Module 2 C Programming
Module 2 C Programming
Module 2
Decision control and Looping statements
BRANCHING AND LOOPING: Two way selection (if, if-else, nested if-else, cascaded if-else),
switch statement, ternary operator? Go to, Loops (For, do-while, while) in C, break and continue,
programming examples and exercises
The if, if...else and nested if...else statement are used to make one-time decisions in C Programming,
that is, to execute some codes and ignore some codes depending upon the test expression.
1. simple if
This is the simplest form of the conditional branching statements. Here condition is evaluated, if
it evaluate true a statement or group of statement is executed.
Syntax:
       if (expression)
       {
              Statement to be executed if expression is true ;
       }
   -      If the expression is evaluated and found to be true, statements inside the body of if is executed
       but if expression is false, statements inside body of if is ignored.
   -   Usage of braces is optional, when only one statement is there.
   -   Multiple statements should be written in pair of braces { }.
   -   No semicolon is required after if.
{
int n;
printf (“Enter the value of n”);
scanf (“% d”,&n);
if(n% 2==0)                  / / checking w hether number even or not
printf(“number is =% d”,n);
#include<stdio.h>
void main()
{
int n;
Output 1:- When user enters -2 then, the test expression (num<0) becomes true.
Hence, Number = -2 is displayed in the screen.
Output 2 :- When user enters 5 then, the test expression (num<0) becomes false and
Print This will execute always.
Note: Above program is same as to check whether given no is positive or not.
2. if-else
The if...else statement is used if the programmer wants to execute some statements when the test
expression is true and execute some other statement/s if the test expression is false.
It is two way selection statements
If multiple statements have to be executed, it has to be written into pair of braces. If only one statement
has to be executed then use of pair of braces is optional.
Syntax:
if (test expression)
{
   Statements will execute if test expression is true;
}
else
{
 Statements will execute if test expression is false;
}
# include <stdio.h>
void main()
{
      int age;
         printf("Enter the person age");
         scanf("%d",&age);
            if(age>=18)
            {
            else
            printf("person is not eligible to vote");
#include<stdio.h>
void main()
{
int n;
printf(“Enter the value of n”);
scanf(“%d”,&n);
     }
}
3. Program to accept a number and check the given number is Armstrong or not.
# include <stdio.h>
void main( )
{
int n, a, b, c, d;
printf ("Enter a Three Digit Number: ");
b=((n/10)%10); 5
c=n%10; 3
d=a*a*a+b*b*b+c*c*c;
if (n==d)
printf ("The Given Number is Armstrong number");
else
printf ("The Given Number is Not Armstrong number");
if (Expression 1)
{
       if (expression 2)
       {
               Block- A;
               else
               Block –B;
       }
}
else
{
       Block-c;
}
                   Exp1                                     False
                                             Exp2
False True
                                                                    Block-B
                                           Block-A
Block-C
#include <stdio.h>
int main()
{
int a, b, c, ;
          printf("\n a is greater");
      else
          printf("\n c is geater");
  else
      {
           if(c>b)
            printf("\n c is greater");
       else
           printf("\n b is greater");
       }
             return 0;
}
                                                  4. Else- if ladder
The nested if...else statement is used when program requires more than one test expression.
Syntax :-
if (test expression1)
{
    Statements will execute if test expression1 is true;
}
else if(test expression2)
{
Statements will execute if test expression1 is false and expression2 is true;
}
{
Statements to be executed if all conditions are false;
}
Nested if()...else statements take more execution time compared to an if()...else ladder because the
nested if()...else statements      check   all   the   inner   conditional   statements   once   the    outer
conditional if() statement is satisfied,
whereas the if()..else ladder will stop condition testing once any of the if() or the else if() conditional
statements are true.
#include<stdio.h>
void main( )
{
int marks;
if(marks<=34)
        printf(“Grade   Fail”);
else if(marks<=59)
        printf(“Grade   Second”);
else if(marks<=69)
        printf(“Grade   First”);
else if(marks<=79)
        printf(“Grade   Distinction”);
else
        printf(“Grade   out standing”);
int main()
{
int marks;
    if(marks<=34)
       printf("Grade Fail");
    else if(marks<=59)
       printf("Grade Second");
    else if(marks<=69)
       printf("Grade First");
    else if(marks<=79)
       printf("Grade Distinction");
    else
       printf("Outstanding");
    return 0;
}
     2. WAC program to display the output stop, ready, or go based on traffic signal input given
        by user.
#include<stdio.h>
void main( )
{
char s;
printf ("enter the light colour");
scanf("%c",&s);
if (s=='r')
         printf("Red-stop at signal");
else if (s=='g')
         printf("Green-go");
else if(s=='y')
         printf("Yellow- ready to move");
}
3. Write a C program to relate two integers entered by user using = or > or < sign.
#include<stdio.h>
Void main()
{
int n1 ,n2 ;
printf(“enter two numbers to check”);
scanf(%d%d”, n1,n2)
if (n1== n2)
       printf(“entered number are equal”);
else
if (n1>n2)
       printf(“n1 is greater number”);
else
       printf(“n2 is greater number”);
}
5. Switch
A switch statement is a conditional statement, which tests a value between many different
values. (When decision has to made between many alternatives)
Syntax:-
switch( expression )
   {
     case value1: statements1;
     break;
     case value 2: statements2;
     break;
     case value 3: statements3;
     break;
     ……
     ……
     [default : statements4;]
   }
switch (s)
{
case ‘r’ :       printf(“stop at signal”);
break;
case ‘y’ :       printf(“ready to go”);
break;
case ‘g’ :       printf(“go”);
break;
default :        printf(“error in giving input”);
break;
}
int n;
clrscr( );
printf(“enter a number :”);
scanf(“%d “,&n);
         switch(n)
         {
         case 0:      printf(“ZERO”);
         break;
         case 1:      printf(“ONE”);
         break;
         case 2:      printf(“TWO”);
         break;
         case 3:      printf(“THREE”);
         break;
         case 4:      printf(“FOUR”);
         break;
         case 5:      printf(“FIVE”);
         break;
         case 6:      printf(“SIX”);
         break;
         case 7:      printf(“SEVEN”);
         break;
         case 8:      printf(“EIGHT”);
         break;
         case 9:      printf(“NINE”);
         break;
default:
printf(“please enter the number between 0 and 9”);
}
}
# include <stdio.h>
void main( )
{
int n;
#include<stdio.h>
void main()
{
  char operator;
  float num1,num2,result,div;
  printf("Simulation of a Simple Calculator\n");
  printf("*********************************\n");
  printf("Enter two numbers and operator[+,-,*,/] \n");
  scanf("%f %f %c",&num1,&num2,&operator);
  switch(operator)
   {
          case '+': result = num1 + num2;
                    printf("\n %f %c %f = %f\n", num1, operator, num2, result);
  break;
          case '-': result = num1 - num2;
                    printf("\n %f %c %f = %f\n", num1, operator, num2, result);
  break;
          case '*': result = num1 * num2;
                    printf("\n %f %c %f = %f\n", num1, operator, num2, result);
                    break;
          case '/': if(num2!=0)
                    {
                           result = num1 / num2;
                                                     1. break
           1.   used to break any type of loop as well as switch statements
           2.   breaking loop means terminating loops
           3.   break statements will be the last statement.
           4.   In break, control comes out of loop and statement following loop will be executed
           5.   If break appears in the inner loop of nested loop, control comes out of inner loop only, not
                from outer loop
Example:
#include<stdio.h>
void main()
{
int i=1;
    while(i<=8)
    {
    printf("%d\t", i);
        if(i==7)
    break;
    i++;
    }
}
                                                   2. Continue
            int main()
            {
               int i;
                for(i=1;i<=5;i++)
                {
                   if(i==2) continue;
                   printf("%d\t",i);
                }
                return 0;
            }
3. goto
label_name: statements;
disadvantage
       Using goto and writing program is an unstructured programming.
int main()
{
   int i=0, n, sum=0;
    top: sum=sum+i;
       i=i+1;
       if(i<=n)goto top;
    return 0;
}
1. Looping (Repetition)
Looping means Execution of same set of instruction for given number of times OR until a specified
result obtained.
Q        What is pre-test loop?
- If the condition is checked before each iteration of loop, such loops called as pre-test loop.
- Conditional expression is evaluated true or false at the beginning of loop.
Since in pre-test loop, condition is checked at the top of loop so called as top-testing or entry
controlled loop.
Ex: for, while loop.
Body of loop
Body of loop
Loops in ‘c ‘ Language:-
   1. While loop :-
The while loop checks whether the test expression is true or not. If it is true, code inside
the body of while loop is executed, that is, code 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
Syntax:-
while ( expression )
{
  Single statement
  or
  Block of statements;
}
Flowchart:
     BASIS FOR
                                       WHILE                   DO-WHILE
  COMPARISON
} while( Condition );
     BASIS FOR
                                        WHILE                               DO-WHILE
   COMPARISON
Iterations The iterations do not occur if, The iteration occurs at least
       # include <stdio.h>
       Void main( )                                  Output:
       {                                             1 2 3 4 5 6 7 8 9 10
       int i=1;
       while( i<=10)
       {
       printf(“%d\n”,i);
       i=i+1;
       }
   Output:
   1   1
   2   4
   3   9
   4   16
   5   25
#include<stdio.h>
void main()
{
  int a,b,m,n;
                                                 Output:
                                                 Input - m=4 n=2
                                                 Gcd=
    M e thod-1                                        M e thod-2
#include<stdio.h>                              #include<stdio.h>
Void main( )                                   Void main( )
{                                              {
int n, fact=1 ;                                       int n ,temp , fact=1;
printf(“enter the number”);                           printf(“enter the number”);
scanf(“%d”,&n);                                       scanf(“%d”,&n);
while(n>0)                                            temp=n;
{                                                     while (n>0)
fact=fact*n;                                          {
--n;                                                          fact=fact*temp;
}                                                             temp=temp-1;
P rintf(“factorial=%d”,fact);                         }
}                                                     printf(“% d\n”, fact);
                                               }
Output:
Ente r number=5
Factorial=120
    6. WAC program that will generate and print first n Fibonacci numbers.
#include<stdio.h>
Void main( )
{
int i=0, j=0, n , sum=1;
printf(“enter the limit of series”);
scanf(“%d”, &n);
         while(sum<n)
         {
         Printf(“%d”, sum);
         i=j;
         j=sum;
         sum=i+j;
         }
Printf(“sum of series=%d”, sum);
}
Syntax:
do
{
  statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop
in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
do ... while is just like a while loop except that the test condition is checked at the end of the loop
rather than the start. This has the effect that the content of the loop are always executed at least
once.
#include <stdio.h>
#include <stdio.h>
main()
{
  int i = 10;
  do
  {
    printf("Hello %d\n", i );
    i = i -1;
}while ( i > 0 );
}
Hello   10
Hello   9
Hello   8
Hello   7
Hello   6
Hello   5
Hello   4
Hello   3
Hello   2
Hello   1
You can make use of break to come out of do...while loop at any time.
#include <stdio.h>
main()
{
  int i = 10;
     do{
       printf("Hello %d\n", i );
       i = i -1;
       if( i == 6 )
       {
          break;
       }
     }while ( i > 0 );
}
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Ex ample 1 :
int main()
{
    int j=0
    do
    {
       printf("Value of variable j is: %d", j);
       j++;
    } while (j<=5);
}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
Value of variable j is: 4
Value of variable j is: 5
Ex ample 2 :
#include <stdio.h>
main()
{
    int j = -5; // initialization
    do
    {
         printf("%d\n", j);
         j = j + 1;
    }
    while(j <= 0); // condition
    4. Write a C program to add all the numbers entered by a us e r until user e nters
       0.
#include<stdio.h>
Void main()
{
int sum=0,num;
                                                   Output :-
do                                                 Enter number 3
{                                                  Enter number -2
         P rintf(“enter the number”);              Enter number 0
         scanf(“%d”,&num);                         Sum=1
         sum=sum+num;
}
While (num!=0);
P rintf(“sum=%d”,sum);
}
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 exec uted until num equals to zero.
     BASIS FOR
                                        WHILE                        DO-WHILE
   COMPARISON
} while( Condition );
Iterations The iterations do not occur if, The iteration occurs at least
       BASIS FOR
                                          WHILE                       DO-WHILE
     COMPARISON
Syntax:-
for ( initialization ; condition test ; increment or decrement)
{
       statements needs to be repeated;
Example 1 :
#include<stdio.h>
Void main()
{
int i;                                                     Output:
       for (i=1; i<=3; i++)                                hello, World
                                                           hello, World
       {
                                                           hello, World
         printf("hello, World\n");
       }
}
Explanation:
   1. The initial counter value is initialized. This initialization is done only once for the entire
   for loop.
   2. After the initialization, test condition is checked. Test condition can be any relational or
   logical expression. If the test condition is satisfied i.e. true then the block of statement inside
   the for loop is executed
   3. After the execution of the block of statement, increment/decrement of the counter is done.
   After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till
   the test condition returns false.
Example 2 :
#include<stdio.h>
void main()                                                         Output:
{                                                                   1 1 This will be repeated 5 times
    int i;                                                          2 2 This will be repeated 5 times
   for(i=1; i<=5;i++)                                               3 3 This will be repeated 5 times
   {
                                                                    4 4 This will be repeated 5 times
       printf("%d This will be repeated 5 times\n", i);
                                                                    5 5 This will be repeated 5 times
   }                                                                6 End of the program
  printf("End of the program");
     }
In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is
less than or equal to 5.
Example 3 :
Note : It is necessary to write the semicolon in for loop as shown in the below:
Consider, case 1:
    1 for(i=0; i<10;)
    2{
    3 printf(“Interment/decrement not used above”)
    4 i=i+1;
    5}
    In the above program, Increment is done within the body of for loop. Still semicolon is
    necessary after the test condition.
Consider, case 2 :
    1 i=0;
    2 for(; i<10; i++)
    3{
    4 printf(“Interment/decrement not used above”)
5}
In the above program, Initialization is done before the start of for loop. Still semicolon is necessary
before the test condition.
Example 4 :
#include<stdio.h>
Void main()
{
const int max=5;
int i ;
for(i=0 ;i<max ;i++)
printf(%d”,i)
}
Output:- 0 1 2 3 4
Example 5 :
#include<stdio.h>
void main()
{
   int i;
         for(i=0; i<10 ; i++)
         {
         printf("hello\n");
         printf("world \n");
         }
}
Example 5 :
#include <stdio.h>
int main()                                                      Output:
{
  int i;                                                        0123456789
  for(i=0;i<10;i++)
  {
     printf("%d ",i);
  }
}
printf(“%d\n”,i);
}
     3. Program to accept a number and print mathematical table of the given no.
# include <stdio.h>
void main( )
{
int i,t;
printf("which table u want:");
scanf("%d",&t);
for (i=1; i<=10; i++)
printf("\n%d*%d=%d", t ,i , i*t);
}
     4. 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>
void main()
{
int n, i,sum=0;
printf("enter value of n");
scanf("%d",&n);
for(i=1; i<=n ; i++)
{
sum=sum+i;
}
printf("summation=%d",sum);
}O u tpu t:
Write a C program to check whether the number n is prime or not prime using for loop.
#include <stdio.h>
int main()
{
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
     if (n % i == 0) {
       flag = 1;
       break;
     }
 }
     if (flag == 0)
     printf("%d is a prime number.", n);
    else
     printf("%d is not a prime number.", n);