Control Statements in C


Control Statements
            Control statements are used to transfer the control form one place of the program to other place. Generally we use 3 types of operators when working with control statements. They are
1.      Relational operators (< , > , < =, > =)
2.      Equality operators (= =, ! =).
3.      Logical operators (&&,││ ,  !)
‘C’ language provides 3 types of control statements. They are
1.      Conditional statements
2.      Unconditional statements.
3.      Iterative statements.
Conditional statements
These are used to execute a group of statements based on a condition.

Simple- if:
            This statement is used to execute group of statements if the condition is true. Otherwise they are not executed. The syntax of simple if as follows.
if(condition)                                                                           
{
            Statement-1;
            Statement-2;.
 ………..
Statement n;
}
Next statement.
Example:

If-else:
It is used to execute a group of statements if the condition is true otherwise the statements which are related to false block are executed.
Syntax:            if(condition)
                         {
                                    Statements related to true;
                          }
                        else
                        {
                                    Statements related to false;
                        }



Nested if…else:
                        Nested if contains if else statements under and if and another else statements.
/* check whether a year is leap year or not */
#include<stdio.h>
int main() {
    int year;
    printf("Enter the year ?");
    scanf("%d",&year);
    if((year %100) == 0)
    {
          if((year % 400) == 0)
              printf("%d is leap year.",year);
          else
              printf("%d is not leap year.",year);
     }
 else
{
          if((year % 4) == 0)
              printf("%d is leap year.",year);
          else
              printf("%d is not leap year.",year);
    }
    getch();
}

 
Syntax:            if(Condition)
                        {
                        if(condition)
{
                                    Statements;
}
else
{
            Statements;
}         
                        }
                        else
                        {
                                    Statements;
                        }



Flow Chart


if…else…if (Ladder if):
Syntax:  if (condition)
            {
  statements;
            }
            else if (condition)
            {
  statements;
                        }
                        if (condition)
            {
  statements;
            }
            else if (condition)
            {
  statements;
                        }
 
            Ladder if contain more than one if and else statements. If the first condition is false it goes to next condition. If the second condition it goes to next condition, it checks the conditions until one of the condition is true.            















                                                Example:















Switch statement
The switch statement allows us to select from multiple choices based on a set of fixed values for a given expression.
The common switch statement syntax:
switch(expression)
{
        case value1: /* execute unit of code 1 */
            break;
          case value2: /* execute unit of code 2 */
            break;
            ...
        default: /* execute default action */
            break;
}


·         In the 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 case constant expression must be an integer value and all values in case statement are equal.
·         When a break statement is executed, it causes execution to continue with the statement following the closing brace for the switch.
·         The break statement is not mandatory, but if we 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 logics happen.
·         The default statement is the default choice of the switch statement if all cases statement are not satisfy with the expression.
·          The break after the default statements is not necessary unless you put another case statement below it.
Here is an example of using C switch statement






/* program to simulate a simple calculator */
#include<stdio.h>
main( )
{
    float a,b;
    char opr;
    printf("Enter number1 operator number2 : ");
    scanf("%f %c %f",&a,&opr,&b);   
    switch(opr)
    {
        case '+':
             printf("Sum : %f",(a + b));
             break;
        case '-':
             printf("Difference : %f",(a - b));
             break;
        case '*':
             printf("Product : %f",(a * b));
             break;
        case '/':
             printf("Quotient : %f",(a / b));
             break;
        default:
             printf("Invalid Operation!");
    }
getch( );
}

 





























 
Looping control statements
To execute a set of instructions repeatedly until a particular condition is being satisfied.
Three types of looping statements are there
1)      While Loop
2)      Do while Loop
3)      For Loop

While Loop Statement

A loop statement allows you to execute a statement or block of statements repeatedly. The while loop is used when you want to execute a block of statements repeatedly with checked condition before making an iteration.
Syntax of while loop statement:
while (expression) 
{
  // statements
}
 
 

This loop executes as long as the given logical expression between parentheses after while is true. When expression is false, execution continues with the statement following the loop block. The expression is checked at the beginning of the loop, so if it is initially false, the loop statement block will not be executed at all. And it is necessary to update loop conditions in loop body to avoid loop forever. If you want to escape loop body when certain conditions meet, you can use break statement
Here is a while loop statement demonstration program:
#include <stdio.h>
 main( )
{
    int x = 10;
    int i = 0;
     // using while loop statement
Text Box: Output:
1
2
3
4
5
6
7
8
9
10
1...keep finding
2...keep finding
3...keep finding
4...keep finding
number found    while(i < x)
{
        i++;
        printf("%d\n",i);
    }
 // when number 5 found, escape loop body
    int numberFound= 5;
    int j = 1;
    while(j < x)
{
        if(j == numberFound)
{
            printf("number found\n");
            break;
  }
        printf("%d...keep finding\n",j);
        j++;
 }
 }
 

 

Do-while Loop Statement

do while loop statement allows us to execute code block in loop body at least one.
Here is do while loop syntax:
do
 {
  // statements
} 
while (expression);


Example:


Output:
1

2

3

4

5

 
#include <stdio.h>
main()
{
    int x = 5;
    int i = 0;
    // using do while loop statement
    do{
        i++;
        printf("%d\n",i);
    } while(i < x);
 }
The program above print exactly 5 times as indicated in do while loop body



For Loop Statement
Syntax:
for (initialization_expression;  loop_condition;  increment_expression)
{
  // statements
}
There are three parts which is separated by semi-colons in control block of the for loop.
  • initialization_expression is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part.
  • The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration.
  • The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.
 
/* check whether a number is prime or not */
#include<stdio.h>
int main() {
    int n,i,factors = 0;
    printf("Enter a number : ");
    scanf("%d",&n);
    for(i = 1; i <= n; i++) {
       if((n % i)==0)  ++factors;
    }
    if (factors == 2)
       printf("%d is prime number.",n);
    else
       printf("%d is not prime number.",n);
}

 
Example  1:                                                    Example 2
#include <stdio.h>
 main()
{
    // using for loop statement
    int max = 5;
    int i = 0;
    for(i = 0; i < max;i++)
   {
         printf("%d\n",i);
 
    }
}
 

Followers