Wednesday, November 12, 2014

C Programming break and continue Statement

C Programming break and continue Statement

There are two statements built in C programming, break; and continue; to alter the normal flow of a program. Loops perform a set of repetitive task until text expression becomes false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop immediately without checking the test expression. In such cases, break and continue statements are used. The break; statement is also used in switch statement to exit switch statement.

break Statement

In C programming, break is used in terminating the loop immediately after it is encountered. The break statement is used with conditional if statement.

Syntax of break statement

break;
The break statement can be used in terminating all three loops for, while and do...while loops.
Flowchart of break statement in C programming.
The figure below explains the working of break statement in all three type of loops.
working of break statement in C programming in for, while and do...while loops

Example of break statement

Write a C program to find average of maximum of n positive numbers entered by user. But, if the input is negative, display the average(excluding the average of negative input) and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative number*/
# include <stdio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs\n");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       break;                     //for loop breaks if num<0.0
       sum=sum+num;
}
  average=sum/(i-1);       
  printf("Average=%.2f",average);
  return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using break statement with executing the statement below it i.e., without executing sum=sum+num.
In C, break statements are also used in switch...case statement. You will study it in C switch...case statement chapter.

continue Statement

It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.

Syntax of continue Statement

continue;
Just like break, continue is also used with conditional if statement.
Flowchart of continue statement in C programming
For better understanding of how continue statements works in C programming. Analyze the figure below which bypasses some code/s inside loops using continue statement.
Working of continue statement in  C programming language

Example of continue statement

Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.

//program to demonstrate the working of continue statement in C programming 
# include <stdio.h>
int main(){
    int i,num,product;
    for(i=1,product=1;i<=4;++i){
        printf("Enter num%d:",i);
        scanf("%d",&num);
        if(num==0)
            continue;  / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */
        product*=num;
}
    printf("product=%d",product);
return 0;
}

Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

C programming while and do...while Loop

C programming while and do...while Loop

C programming loops

Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming.
Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one time and repeat the execution 10 times using loop.
There are 3 types of loops in C programming:
  1. for loop
  2. while loop
  3. do...while loop

Syntax of while loop

while (test expression) {
     statement/s to be executed.  
}
The while loop checks whether the  test expression is true or not. If it is true, code/s inside the body of while loop is executed,that is, code/s inside the braces { } are executed. Then again the test expression is checked whether test expression is true or not. This process continues until the test expression becomes false.
Flowchart of while loop in C programming

Example of while loop

Write a C program to find the factorial of a number, where the number is entered by user. (Hints: factorial of n = 1*2*3*...*n

/*C program to demonstrate the working of while loop*/
#include <stdio.h>
     int main(){
     int number,factorial;
     printf("Enter a number.\n");
     scanf("%d",&number);
     factorial=1;
     while (number>0){      /* while loop continues util test condition number>0 is true */
           factorial=factorial*number;
           --number;
}
printf("Factorial=%d",factorial);
return 0;
}
Output
Enter a number.
5
Factorial=120

do...while loop

In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.

Syntax of do...while loops

do {
   some code/s;
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside body of do are executed again and the process continues until test expression becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Flowchart of working of do...while loop in C programming.

Example of do...while loop

Write a C program to add all the numbers entered by a user until user enters 0.

/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
   int sum=0,num;
   do             /* Codes inside the body of do...while loops are at least executed once. */
   {                                    
        printf("Enter a number\n");
        scanf("%d",&num);
        sum+=num;      
   }
   while(num!=0);
   printf("sum=%d",sum);
return 0;
}

Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is again executed until num equals to zero.

C while Loops Examples

C Programming for Loop

C Programming for Loop

C Programming Loops

Loops cause program to execute the certain block of code repeatedly until test condition is false. Loops are used in performing repetitive task in programming. Consider these scenarios:
  • You want to execute some code/s 100 times.
  • You want to execute some code/s certain number of times depending upon input from user.
These types of task can be solved in programming using loops.
There are 3 types of loops in C programming:
  1. for loop
  2. while loop
  3. do...while loop

for Loop Syntax

for(initialization statement; test expression; update statement) {
       code/s to be executed; 
}

How for loop works in C programming?

The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.
This flowchart describes the working of for loop in C programming.
Flowchart of for loop in C programming language

for loop example

Write a program to find the sum of first n natural numbers where n is entered by user. Note: 1,2,3... are called natural numbers.
 
#include <stdio.h>
int main(){
    int n, count, sum=0;
    printf("Enter the value of n.\n");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  //for loop terminates if count>n
    {
        sum+=count;    /* this statement is equivalent to sum=sum+count */
    }
    printf("Sum=%d",sum);
    return 0;
}

Output
Enter the value of n.
19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then,  count is initialized to 1 at first. Then, the test expression in the for loop,i.e.,  (count<= n) becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the expression ++count is executed and again the test expression is checked, which becomes true. Again, the body of for loop is executed which makes sum to 3 and this process continues. When count is 20, the test condition becomes false and the for loop is terminated.

C for Loop Examples

Note: Initial, test and update expressions are separated by semicolon(;).

C Programming if, if..else and Nested if...else Statement

C Programming if, if..else and Nested if...else Statement

The if, if...else and nested if...else statement are used to make one-time decisions in C Programming, that is, to execute some code/s and ignore some code/s depending upon the test expression.

C if Statement

if (test expression) {
       statement/s to be executed if test expression is true;
}
The if statement checks whether the text expression inside parenthesis ( ) is true or not. If the test expression is true, statement/s inside the body of if statement is executed but if test is false, statement/s inside body of if is ignored.

Flowchart of if statement


Branching in C programming language using if statement

Example 1: C if statement

Write a C program to print the number entered by user only if the number entered is negative.

#include <stdio.h>
      int main(){
      int num;
      printf("Enter a number to check.\n");
      scanf("%d",&num);
      if(num<0) {      /* checking whether number is less than 0 or not. */ 
            printf("Number = %d\n",num); 
      }  
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
      printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number = -2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s inside body of if is skipped and only the statement below it is executed.

C if...else statement

The if...else statement is used if the programmer wants to execute some statement/s when the test expression is true and execute some other statement/s if the test expression is false.

Syntax of if...else

if (test expression) {
     statements to be executed if test expression is true;
}
else {
     statements to be executed if test expression is false;
}

Flowchart of if...else statement

Flowchart of if...else statement in C Programming

Example 2: C if...else statement

Write a C program to check whether a number entered by user is even or odd
#include <stdio.h>
int main(){
      int num;
      printf("Enter a number you want to check.\n");
      scanf("%d",&num);
      if((num%2)==0)          //checking whether remainder is 0 or not.
           printf("%d is even.",num);
      else
           printf("%d is odd.",num);
      return 0;
}
Output 1
Enter a number you want to check.
25
25 is odd.
Output 2
Enter a number you want to check.
2
2 is even.

Nested if...else statement (if...elseif....else Statement)

The nested if...else statement is used when program requires more than one test expression.

Syntax of nested if...else statement.

if (test expression1){
     statement/s to be executed if test expression1 is true;
     }
     else if(test expression2) {
          statement/s to be executed if test expression1 is false and 2 is true;
     }
     else if (test expression 3) {
         statement/s to be executed if text expression1 and 2 are false and 3 is true;
     }
         .
         .
         .
     else {
            statements to be executed if all test expressions are false;
       }
How nested if...else works?
The nested if...else statement has more than one test expression. If the first test expression is true, it executes the code inside the braces{ } just below it. But if the first test expression is false, it checks the second test expression. If the second test expression is true, it executes the statement/s inside the braces{ } just below it. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the nested if...else
The ANSI standard specifies that 15 levels of nesting may be continued.

Example 3: C nested if else statement

Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){ 
     int numb1, numb2;
     printf("Enter two integers to check\n");
     scanf("%d %d",&numb1,&numb2); 
     if(numb1==numb2) //checking whether two integers are equal.
          printf("Result: %d = %d",numb1,numb2); 
     else 
        if(numb1>numb2) //checking whether numb1 is greater than numb2. 
          printf("Result: %d > %d",numb1,numb2); 
        else 
          printf("Result: %d > %d",numb2,numb1); 
return 0; 
} 
Output 1
Enter two integers to check.
5
3
Result: 5 > 3
Output 2
Enter two integers to check.
-4
-4
Result: -4 = -4

More Examples on if...else Statement

C Programming Introduction Examples

C Programming Introduction Examples

This page contains example and source code on very basic features of C programming language. To understand the examples on this page, you should have knowledge of following topics:
  1. Variables and Constants
  2. Data Types
  3. Input and Output in C programming
  4. Operators

C Introduction Examples

C Programming Introduction Examples
C Program to Print a Sentence
C Program to Print a Integer Entered by a User
C Program to Add Two Integers Entered by User
C Program to Multiply two Floating Point Numbers
C Program to Find ASCII Value of Character Entered by User
C Program to Find Quotient and Remainder of Two Integers Entered by User
C Program to Find Size of int, float, double and char of Your System
C Program to Demonstrate the Working of Keyword long
C Program to Swap Two numbers Entered by User

C Programming Operators

C Programming Operators

Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition.
C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators

Arithmetic Operators

OperatorMeaning of Operator
+addition or unary plus
-subtraction or  unary minus
*multiplication
/division
%remainder after division( modulo division)
Example of working of arithmetic operators

/* Program to demonstrate the working of arithmetic operators in C.  */
#include <stdio.h>
int main(){
    int a=9,b=4,c;
    c=a+b;
    printf("a+b=%d\n",c);
    c=a-b;
    printf("a-b=%d\n",c);
    c=a*b;
    printf("a*b=%d\n",c);
    c=a/b;
    printf("a/b=%d\n",c);
    c=a%b;
    printf("Remainder when a divided by b=%d\n",c);
    return 0;
}
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1
Explanation
Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4 equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So, the output is also integer and the compiler neglects the term after decimal point and shows answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.
Suppose a=5.0, b=2.0, c=5 and d=2
In C programming,
a/b=2.5    
a/d=2.5
c/b=2.5      
c/d=2
Note: % operator can only be used with integers.

Increment and decrement operators

In C, ++ and -- are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example:
Let a=5 and b=10
a++;  //a becomes 6
a--;  //a becomes 5
++a;  //a becomes 6
--a;  //a becomes 5 
Difference between ++ and -- operator as postfix and prefix
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main(){
    int c=2,d=2;
    printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
    printf("%d",++c);   //this statement increments 1 to c then, only c is displayed. 
    return 0;
}

Output
2
4

Assignment Operators

The most common assignment operator is =. This operator assigns the value in right side to the left side. For example:
var=5  //5 is assigned to var
a=c;   //value of c is assigned to a
5=c;   // Error! 5 is a constant.
OperatorExampleSame as
=a=ba=b
+=a+=ba=a+b
-=a-=ba=a-b
*=a*=ba=a*b
/=a/=ba=a/b
%=a%=ba=a%b

Relational Operator

Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
OperatorMeaning of OperatorExample
==Equal to5==3 returns false (0)
>Greater than5>3 returns true (1)
<Less than5<3 returns false (0)
!=Not equal to5!=3 returns true(1)
>=Greater than or equal to5>=3 returns true (1)
<=Less than or equal to5<=3 return false (0)

Logical Operators

Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators:
OperatorMeaning of OperatorExample
&&Logial AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.
||Logical ORIf c=5 and d=2 then, ((c==5) || (d>5)) returns true.
!Logical NOTIf c=5 then, !(c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.

Conditional Operator

Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

Bitwise Operators

A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
OperatorsMeaning of operators
&Bitwise AND
|Bitwise OR
^Bitwise exclusive OR
~Bitwise complement
<<Shift left
>>Shift right
Bitwise operator is advance topic in programming . Learn more about bitwise operator in C programming.

Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:
int a,c=5,d;

The sizeof operator

It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc. For example:

#include <stdio.h>
int main(){
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%d bytes\n",sizeof(a));
    printf("Size of float=%d bytes\n",sizeof(b));
    printf("Size of double=%d bytes\n",sizeof(c));
    printf("Size of char=%d byte\n",sizeof(d));
    return 0;
}
Output
Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

Conditional operators (?:)

Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false.

Syntax of conditional operators

conditional_expression?expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.

Example of conditional operator

#include <stdio.h>
int main(){
   char feb;
   int days;
   printf("Enter l if the year is leap year otherwise enter 0: ");
   scanf("%c",&feb);
   days=(feb=='l')?29:28;
   /*If test condition (feb=='l') is true, days will be equal to 29. */
   /*If test condition (feb=='l') is false, days will be equal to 28. */ 
   printf("Number of days in February = %d",days);
   return 0;
}
Output
Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29
Other operators such as &(reference operator), *(dereference operator) and ->(member selection) operator will be discussed in pointer chapter.

C Programming Input Output (I/O)

C Programming Input Output (I/O)

ANSI standard has defined many library functions for input and output in C language. Functions printf() and scanf() are the most commonly used to display out and take input respectively. Let us consider an example:

#include <stdio.h>      //This is needed to run printf() function.
int main()
{
    printf("C Programming");  //displays the content inside quotation
    return 0;
}
Output
C Programming
Explanation of How this program works
  1. Every program starts from main() function.
  2. printf() is a library function to display output which only works if #include<stdio.h>is included at the beginning.
  3. Here, stdio.h is a header file (standard input output header file) and #include is command to paste the code from the header file when necessary. When compiler encounters printf() function and doesn't find stdio.h header file, compiler shows error.
  4. Code return 0; indicates the end of program. You can ignore this statement but, it is good programming practice to use return 0;.

I/O of integers in C


#include<stdio.h>
int main()
{
    int c=5;
    printf("Number=%d",c);
    return 0;
}
Output
Number=5
Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this conversion format string matches with remaining argument,i.e, c in this case, value of c is displayed.

#include<stdio.h>
int main()
{
    int c;
    printf("Enter a number\n");
    scanf("%d",&c);  
    printf("Number=%d",c);
    return 0;
}
Output
Enter a number
4
Number=4
The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and value is stored in that address.

I/O of floats in C


#include <stdio.h>
int main(){
    float a;
    printf("Enter value: ");
    scanf("%f",&a);
    printf("Value=%f",a);    //%f is used for floats instead of %d
    return 0;
}

Output
Enter value: 23.45
Value=23.450000
Conversion format string "%f" is used for floats to take input and to display floating value of a variable.

I/O of characters and ASCII code

#include <stdio.h>
int main(){
    char var1;
    printf("Enter character: ");
    scanf("%c",&var1);     
    printf("You entered %c.",var1);  
    return 0;
}
Output
Enter character: g
You entered g.
Conversion format string "%c" is used in case of characters.

ASCII code

When character is typed in the above program, the character itself is not recorded a numeric value(ASCII value) is stored. And when we displayed that value by using "%c", that character is displayed.

#include <stdio.h>
int main(){
    char var1;
    printf("Enter character: ");
    scanf("%c",&var1);     
    printf("You entered %c.\n",var1);  
/* \n prints the next line(performs work of enter). */
    printf("ASCII value of %d",var1);  
    return 0;
}
Output
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.
You can display character if you know ASCII code only. This is shown by following example.

#include <stdio.h>
int main(){
    int var1=69;
    printf("Character of ASCII value 69: %c",var1);
    return 0;
}
Output
Character of ASCII value 69: E
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.
Click here to learn about complete reference of ASCII code.

More about Input/Output of floats and Integer

Variations in Output for integer an floats

Integer and floating-points can be displayed in different formats in C programming as:
#include<stdio.h>
int main(){
    printf("Case 1:%6d\n",9876);      
/*  Prints the number right justified within 6 columns  */
    printf("Case 2:%3d\n",9876);      
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right justified  */
    printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
    printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
    printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation(scientific notation) */
    return 0;
}
Output
Case 1:  9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002

Variations in Input for integer and floats

#include <stdio.h>
int main(){
    int a,b;
    float c,d;
    printf("Enter two intgers: ");
/*Two integers can be taken from user at once as below*/
    scanf("%d%d",&a,&b);
    printf("Enter intger and floating point numbers: ");
/*Integer and floating point number can be taken at once from user as below*/
    scanf("%d%f",&a,&c);
    return 0;
}
Similarly, any number of input can be taken at once from user.