Sunday, September 16, 2012

Control Statements in C

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Followings are the different conditional statements used in C.

  1.  If Statement
  2.  If-Else Statement
  3.  Nested If-Else Statement
  4.  Switch Case


If Statement :
This is a conditional statement used in C to check condition or to control the flow of execution of statements. This is also called as 'decision making statement or control statement.' The execution of a whole program is done in one direction only.
Syntax:


if(condition)
{
	statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is not necessary to use.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
a=5;
if(a>4)
printf("\nValue of A is greater than 4 !");
if(a==4)
printf("\n\n Value of A is 4 !");
getch();
}

If-Else Statement :
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
	true statements;
}
else
{
	false statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
printf("\n\n Number is even !");
else
printf("\n\n Number is odd !");
getch();
}

Nested If-Else Statement :

It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute.
Syntax:
if(condition)
{
        if(condition)
{
        statements;
          }
else
{
         statements;
            }
}
else
{
      statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
	}
else
{
if(no==0)
	{
	printf("\n\n It is 0 !");
		}
	else
	{
	printf("Number is less than 0 !");
		}
	}
	getch();
}
 
Switch case Statement :
This is a multiple or multi-path branching decision making statement.
When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.

This is the flow chart of the C switch statement:


Syntax:
switch(expression)
{
	case expr1:
		statements;
		break;
	case expr2:
		statements;
		break;
case exprn:
		statements;
		break;						
	default:
		statements;
}

In this syntax
1.in C switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value, which is returned by expression, must be an integer value otherwise the compiler will issue an error message.
2.The case constant expression must be a constant integer value.
3.When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. The break statement is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logic happens.
3.The default statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.

Rules for declaring switch case :

1. The case label should be integer or character constant.
2. Each compound statement of a switch case should contain break statement to exit from case.
3. Case labels must end with (:) colon.

Advantages of switch case :
1. Easy to use.
2. Easy to find out errors.
3. Debugging is made easy in switch case.
4. Complexity of a program is minimized.

Example code:
1.
#include <stdio.h>
main()
{
     int  Grade = 'L';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}

2.
#include <stdio.h>
int main()
{
     char operator;
     float num1,num2;
     printf("Enter operator +, - , * or / :\n");
     operator=getche();
     printf("\nEnter two operands:\n");
     scanf("%f%f",&num1,&num2);
     switch(operator)                              
     {
     case '+':
              printf("num1+num2=%.2f",num1+num2);
              break;
     case '-':
              printf("num1-num2=%.2f",num1-num2);
              break;
     case '*':
              printf("num1*num2=%.2f",num1*num2);
              break;
     case '/':
              printf("num2/num1=%.2f",num1/num2);
              break;
     default:                                 
              printf(Error! operator is not correct");
              break;
     }
     return 0;
}

3.
#include <stdio.h>
#include <conio.h>
int main(){
     char check;
     int i, flag, num,temp,sum=0;
     printf("Enter number: ");
     scanf("%d",&num);
     printf("-----------------------Instructions--------\n");
     printf("Enter 'a' to check for Armstrong number.\n");
     printf("Enter 'p' to check for prime number.\n");
     printf("Enter 'f' to check for Fibonacci sequence.\n");
     printf("------------------------------------------\n");
     printf("Enter a character according to instruction specified: ");
     check=getche();
     switch(check)
     {
     case 'a':
              temp=num;
            while(num!=0){
                 sum+=(num%10)*(num%10)*(num%10);
                 num=num/10;
               }
               if(sum==temp)
                  printf("\n\nResult: %d is Armstrong\n",temp);
               else
                  printf("\n\nResult: %d is not Armstrong\n",temp);
               break;
     case 'p':
              flag=0;
              for(i=2;i<=(num/2);++i){
                  if((num%i)==0){
                    printf("\n\nResult: %d in not prime.",num);
                     flag=1;
                     break;
                  }
              }
              if(flag==0)
                 printf("\n\nResult: %d is prime.",num);
              break;
     case 'f':
          i=0,flag=1;
          while(flag<=num) {
             if (flag==num){
                printf("\n\nResult: %d lies in Fibonacci.",num);
                  break;
               }
                 temp=flag;
                 flag+=i;
                 i=temp;
            }
          if (flag!=num)
            printf("\n\nResult: %d does not lies in Fibonacci.",num);
          break;
    default:
            printf("Error! ");
            break;
     }
     return 0;
}

in this program we can check for, whether a number is a prime number or Armstrong number or lies on Fibonacci sequence according to instruction from user in one program using switch...case statement.

Looping Statements / Iterative Statements :

A loop is a part of code of a program which is executed repeatedly.
A loop is used using condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
           Check condition to start a loop
           Initialize loop with declaring a variable.
           Executing statements inside loop.
           Increment or decrement of value of a variable.
Types of looping statements :
Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.

1. Entry controlled loop
2. Exit controlled loop


1. Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
  • while loop
  • for loop
2.  Exit controlled loop :
In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed at least one time compulsorily.
Some common example of this looping statement is :
  • do-while loop

For loop:

syntax
for(initial expression; test expression; update expression)
{ 
 code/s to be executed; 
}
 
How for loop works in C programming?
This flowchart describes the working of for loop in C programming.

Example program :
#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

While loop:
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
while ( expression )
{
   Single statement 
   or
   Block of statements;
}

Flowchart of while loop:


 Example code:
C program to find the factorial of a number, where the number is entered by user.
#include <stdio.h>
#include <conio.h>
void main()
{
     int number,factorial;
     printf("Enter a number.\n");
     scanf("%d",&number);
     factorial=1;
     while (number>0)
{                  
           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.
Flow chart

Example program :
#include <stdio.h>
#include <conio.h>
int main(){
   int sum=0,num;
   do{                
        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.

Break Statement :

Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.
Syntax
break;

The break statement can be used in terminating all three loops for, while and do...while loops.
Flow chart:
The figure below explains the working of break statement in all three type of loops.


Example program :

#include <stdio.h>
#include <conio.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
 
Continue Statement :
Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this anomaly.
The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. It causes the loop to be continued with next iteration after skipping statements in between. Continue statement simply skips statements and continues next iteration. Just like break, continue is also used with conditional if statement.
Syntax

Flowchart



Goto Statement :
It is a well known as 'jumping statement.' It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used.
Syntax :
goto [expr];

Example program :
Code 1.
#include <stdio.h>
#include <conio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs: ");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       goto jump;             /* control of the program jumps to label jump */ 
       sum=sum+num;
}
jump:
  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
Code 2
#include <stdio.h>
#include <conio.h>

void main()
{
	int i=1, j;
	clrscr();
	while(i<=3)
	{
		for(j=1; j<=3; j++)
		{
			printf(" * ");
			if(j==2)
			goto stop;
		}
		i = i + 1;
	}
	stop:
		printf("\n\n Exited !");
	getch();
}
output:
**
Exited

Some important Questions:

Q.What is the difference between the two operators = and ==  ?
= assignment operator which is used to asign value to the operand.
exp:
a=10;
== equality operator which is used to compare two operands.
exp:
a==b
Q.what is the difference between entry control and exit control statement?
Entry Comtrolled will check the Condition at First and doesn't execute if it is False.
Exit Comtrolled will check the Condition at Last and at least once the statement will execute though it is False .    
Q.What's  the difference between ++i and i++?
++i adds one to the stored value of i and ``returns'' the new, incremented value to the surrounding expression; i++ adds one to i but returns the prior, unincremented value.

No comments:

Post a Comment