Learn how to write the C program step-by-step | Lesson -3

Conditions Branching & Looping

In this lesson we are going to discuss the following topics:

  • WHILE
  • DO WHILE
  • FOR
  • IF
  • SWITCH CASE
  • BREAK
  • CONTINUE
  • GOTO

 

Let's learn C program
Learn C Program

Program

Displays first 10 numbers. Using the while loop.

WHILE

Purpose:

Repeats execution

Usage:

While (expression) statement1;

  • statement1 is executed repeatedly as long as the value of  expression remains nonzero. The test takes place before each execution of the statement1.
  • The value of the expression (test statement) enclosed in parentheses is evaluated. If the result is true, the program statement (the body of the loop) is executed. Then the test expression is evaluated again. If it is again true, the statement is executed once more. This process continues until the test expression become false.

Example:

While (x != 0) sum += x;

Program-1

#include<stdio.h>
/* Program to display first 10 numbers. Using the while loop*/
void main ()
{        int num=0
          while (num<=9)
         {        printf("%d\n",num);
                   num++;
                   }
         }
 
 

Program-2

#include<stdio.h>
/* Program to display first 10 odd numbers. Using the while loop*/
void main ()
{        int counter=1, num=1;
         printf("\nFirst 10 ODD Numbers \n");
         while (counter<=10)
         {        printf("\t%d\n",num);
                   counter++;
                   num += 2;
                   }
         }

 

Program-3

#include<stdio.h>
/* Program to display first 10 even numbers. Using the while loop*/
void main ()
{        int counter=1, num=2;
         printf("\nFirst 10 EVEN Numbers \n");
         while (counter<=10)
         {        printf("\t%d\n",num);
                   counter++;
                   num += 2;
                   }
         }

 

Program-4

#include<stdio.h>
/* Program to accept a line from user & convert it to upper-case. Using the while loop*/
void main ()
{        char text[80]
          int flag, counter=0
          while((text[counter] = getchar()) != "\n')
                 ++counter;
          flag=counter;
          counter = 0;
          while(counter < flag)  
         {        putchar(toupper(text[counter])); 
                   ++counter;
                   }
         }

 

Program-5

#include<stdio.h>
/* Program to calculate average of n numbers. Using the while loop*/
void main ()
{        int num, counter=1, x, avg, total=0;
          printf("\nHow Many Numbers To Be Averaged ? ");
          scanf("%d", &num);
          while(counter <= num)
          {              printf("x = ");
                         scanf("%d", &x);
                         total += x;
                         ++counter;  
                        }
          avg=total/num; 
            printf("\nThe Average Is : %d\n",avg);  
                 
                   }
        

 Program-6

#include<stdio.h>
/* Program to reverse a digit. Using while loop*/
void main ()
{        int n, sum=0, r_digit;
          printf("Enter a number : ");
          scanf("%d", &n);
          r_digit = n % 10 ;
          printf("%d", r_digit);
          n /= 10;
          while(n>0)
                    r_digit = n % 10 ;
                       printf("%d", r_digit);
                       n /= 10;             }       
                       
         

DO WHILE

Purpose:
Repeats execution
 
Usage:
do statement1  while (expression);
 
Explanation:
  • statement1 is executed repeatedly as long as the value of expression remains non-zero. The test takes place after each execution of the statement1.
  • Here the condition is not tested until the body of the loop has been executed once. i.e. Even if the condition is false, the body of the loop is executed at least once.

Example: 

do printf("x= %d\n",i++);
     while ( i <= 5);

Program-1

#include<stdio.h>
/* Program to display first 10 numbers. Using do while loop*/
void main ()
{        int num=0;
          do  printf("%d\n", num++);while (num<=9);    }
       

Program-2

#include<stdio.h>
/* This is a program to sum up all the digits in a given number. Using do while loop */
void main ()
{        int n, sum=0,  r_digit;
          printf("Enter a number : ");
          scanf("%d",&n);
          do    {        r_digit = n % 10 ;
                            sum += r_digit;
                            n /= 10;            }
           while(n>0);
            printf("The sum of this number is %d\n",sum);        }
  

Program-3

#include<stdio.h>
/* Program to accept a line from user & convert it to upper-case. Using do while loop */
void main ()
{        char text[80];
          int flag, counter=-1;
          do ++counter;
          while ((text[counter] = getchar() != '\n');
          flag=counter;
          counter = 0;
          do    {        putchar(toupper(text[counter]));
                            ++counter;                                    }
           while(counter < flag);            }
            
   
Program-4
#include<stdio.h>
/* Program to calculate average of n numbers. Using do while loop */
void main ()
{        int num, counter=1, x, avg, total=0;
          printf("\nHow Many Numbers To Be Averaged ? ");
          scanf(%d",&num);
          do    {        printf("x = "); 
                            scanf("%d",&x);
                            total += x;
                            ++counter;                   }
           while (counter < = num);    
           avg=total/num;
           printf("nThe Average Is : %d\n",avg);            


FOR

Purpose:
 
Usage:
for  ([export1] ; [expr2] ; [expr3] ) 
            statement1 ;

Explanation :
  • exprt1 is the initialization expression, usually an assignment, which is performed once before the loop actually begins execution. This expression can be omitted if the variable is initialized outside the loop.
  • expr2 is the test expression, which is evaluated before each iteration of the loop and which determines whether the loop should continue or be terminated.
  • expr3 is the modifier statement , which changes the value of the variable used in the test. This expression is executed at the end of each iteration, after the body of the loop is executed. This expression can also be omitted.
  • If one or more expressions are omitted from the for loop, the two semicolons (;) still must appear.  

Example:

for (i=1; i<=100; i++)
            printf("This will print 100 times \n");
 
Program-1 
 
#include<stdio.h>
/* Program to display first 10 numbers. Using for loop */
void main ()
{        int num;
          for(num=0;num<=9;++num)
          printf("%d\n", num);        }
        

Program-2
 
#include<stdio.h>
/* Program to display first 10 numbers. Using for loop. Initializing of variable is done outside the loop & incrementing the variable is done within the printf statement. Still we see that the two semicolons (;) appear in the for loop */
void main ()
{        int num=0;
          for( ; num<=0;num<=9;)
          printf("%d\n", num++);        }

         

Program-3
 
#include<stdio.h>
/* Program to display first 10 even numbers. Using the for loop */
void main ()
{        int counter, num=0;
          printf("\nFirst 10 EVEN Numbers \n");       
          for( counter=1; counter<=10;counter++)
          printf("\t%d\n",num+=2);         

         }

 

Program-4
 
#include<stdio.h>
/* Program to display table of a given number. Using the for loop */
void main ()
{        int counter, num=0;
          printf("\nEnter a digit : ");       
          scanf(%d",&num);
          for(counter=1; counter<=10;counter++)
          printf("%3d * %3d  = %4d\n",num,counter,num*counter);     }

      

Program-5
 
#include<stdio.h>
/* Program to accept a line from user & convert it to upper-case. Using the for loop */
void main ()
{       char text[80];
         int flag, counter;
         for(counter=0; (text[counter]=getchar()) != "\n'; ++counter)
         flag=counter;
         for(counter=0; counter <= flag; counter++)
         putchar(toupper(text[counter]));             }

       

Program-6
 
#include<stdio.h>
/* Program to calculate average of n numbers. Using the for loop */
void main ()
{       int num, counter, x, avg, total=0;
         printf("\nHow Many Numbers To Be Averaged ? ");
         scanf("%d",&num);
         for(counter=1; counter <= num; ++counter)
         (         printf("x = ");
         scanf(%d",&x);
        total += x;
avg=total/num;
printf("\nThe Average Is : %d\n",avg);            }
     

 

Program-7
 
#include<stdio.h>
/* Program to calculate average for several different list of numbers. Using nested for loop */
void main ()
{       int num, counter, list, listcnt, x, avg, total;
         printf("\nHow Many List : ");
         scanf("%d",&list);
         for(listcnt=1; listcnt <= list; ++listcnt)
         {         total=0;
                    printf("\nList number %d\nHow Many Numbers To  Be Averaged ?", listcnt);
         scanf(%d",&num);
         for(counter=1;counter <= num; ++counter)
         {    printf("x, = ");
         scanf(%d",&x);
        total += x;
avg=total/num;
printf("\nThe Average Is : %d\n",avg);            }
     

Program-8
 
#include<stdio.h>
/* Program to accept several lines from user & convert it to upper-case. Using nested for loop */
void main ()
{       
         char text[80];
         int flag, counter;
         while((text[0] = getchar() != '*' )
{
         for(counter=1; (text[counter]=getchar()) !="\n'; ++counter);
         flag=counter;
         for(counter=0; counter <= flag; ++counter)
         putchar(toupper(text[counter]));
         printf("\n\n");
           

printf("Good Bye. \n");       }

    

IF   

Purpose:
The if statement is used to carry out a logical test and then take one of two possible actions, depending on the outcome of the test.
 
Usage:
if (expression)     or    if (expression)        or         if (expression1)
     statement1;                  statement1;                          statement1;                                                                                                                                      else if (expression2)
                                                                                     statement2; 
                                                                       else if (expression3)
                                                                                     statement3;  
                                                                       else
                                                                                statement    n; 
 
Explanation:
  • If expression is nonzero  when evaluated, then statement1 is executed. In the second case, statment2 is executed if the expression is 0.
  • The outcome of a logical or relational expression allows the program execution to branch to a statement or group of statements with the help of IF.
  • An optional else can follow an if statement, but no statements can come between an if statement and an else. 
Examples:        if (count <50) count++;
                            if (x < y)
                             z = x ;
                             else
                            z = y ;
                               
 
The following program is an example of if. scanf accepts marks of an entrance test and allows the if syntax to checks the marks scored. printf displays a message if the expression evaluates to be true.


 

Program-1
 
#include<stdio.h>
/* Example of if statement */
void main ()
      
{       int mks;
         printf("n\Enter Marks Scored in Entrance Test : ");
         scanf("d",&mks);
         if(mks>35)
                printf("\nAdmission Granted "); 
       }
  • The following program is an example of if else. scanf accepts marks of an entrance test and allows the if syntex to check the marks scored. If the expression evaluates to be true, the first message is displayed else the second message is displayed.

 

 Program-2

 #include<stdio.h>
/* Example of if else */
 main ()
      
{       int mks;
         printf("n\Enter Marks Scored in Entrance Test : ");
         scanf("d",&mks);
         if(mks>35)
                printf("\nAdmission Granted "); 
        else
             
                printf("\nAdmission Denied ");
       }

 

  • The following program is an example of if else. scanf accepts a number and allows the if syntex to check that the number divided by 2 does not returns a zero (0) remainder. If the expression evaluates to true, the first message is displayed else the second message is displayed.

 

 Program-3
 #include<stdio.h>

/* Example of if else */
void main ()
      
{       int numb;
         printf("n\Enter a Number : ");
         scanf("d",&numb);
         if(numb%2 !=0)
                printf("\n%d is Odd",numb); 
        else
                printf("\n%d is Even",numb);         }

 

  • The following program is an example of nested if else. Accepts a number and displays whether the number is between 5 and 10 using nested if-else.

Program-4
 #include<stdio.h>

/* Example of nested if else */
void main ()
      
{       int a;
         printf("n\Enter a Number between 5 and 10 : ");
         scanf("d",&a);
         if(a <= 10)
         if(a >= 5)
                printf("\n%d is between 5 and 10",a); 
        else
                printf("\n%d is not between 5 and 10" ,a);      
    }

The following program is an example of if-else. scanf() accepts a year and aloows the if syntax to check the following 3 conditions :

  • year divided by 4 returns a zero (0) remainder, and
  • year divided by 100 does not returns a zero (0) remainder, or
  • year divided by 400 returns a zero (0) remainder


If the expression evaluates to be true, the first message is displayed else the second message is displayed.

 

Program-5
 #include<stdio.h>

/* Example of if-else */
void main ()
      
{       int year;
         printf("n\Enter A Year : ");
         scanf("d",&year);
         if(year%4 = = 0 && year%100 !=0 || year%400 = = 0)
                  printf("\n%d Is A Leap Year ",year);
      
    }
  • The following program is an example of nested if-else. Program No.5 is modified to highlight 2 points :
  • && (AND) operator can be replaced with an if statement nested within an if clause.
  • || (OR) operator can be replaced with an if statement nested within an else clause.


Program-6
 #include<stdio.h>

/* Example of nested if else */
void main ()
      
{       int year;
         printf("n\Enter A Year : ");
         scanf("%d",&year);
         if(year%4 = = 0)
         if(year%100 != 0)
                printf("\n%d Is A Leap Year" , year); 
        else
        if(year%400 = = 0)
                printf("\n%d Is A Leap Year",year);  
        else
               printf("\n%d Is Not A Leap Year",year); 
       else
               printf("\n%d Is Not A Leap Year",year); 
       }

 

SWITCH CASE

Purpose:

  • Branches control
  • Causes control to branch to one of a list of possible statement in the block defined by statement.
  • The switch statement causes a particular group of statements to be chosen from several available groups.

Usage:

 switch (variable)

{

    case constant1 :     statement1;

                                  break;

    case constant2 :     statement2;

                                  break;

   default                    statement(n);

    }

Explanation:

  • The branched-to statement is determined by evaluating expression, which must return an integral type. The list of possible branch points within  statement is determined by preceding sub-statements with case constant-expression : where constant-expression must be an int and must be unique.
  • Once a value is computed for expression, the list of possible constant expression values determined from all case statements is searched for a match.
  • If a match is found, execution continues after the matching case statement and continues until a break statement is encountered or the end of statement is reached.
  • If a match is not found and this statement prefix is found within statement, default : execution continues at this point. Otherwise, statement is skipped entirely.      

 

Example:
switch(choice=toupper(getchar())  )
{                   case    'D'   :
                                   printf("DOS");
                                   break;
                    case 'U'    :    
                                    printf("UNIX");
                                    break;
                    case 'O'    :    
                                    printf("OS/2");
                                    break;
                   default    :
                                    printf("Not Found");
                }
 
The following program displays a range of marks, allows user to enter a choice, and displays appropriate message.  
 

Program-1
 #include<stdio.h>

        /* Example of switch, case, break */
void main ()
      
{       int mks;
         printf("\n\n    Marks Scored ");
         printf("\n1.    70 and above ");
         printf("\n2.     60 - 70"); 
         printf("\n3.     50 - 60");  
         printf("\n4.     below 50");  
         printf("\n5.     Quit");    
         printf("\n\nEnter choice : ");   
         scanf("%d",&mks);   
 
 
switch(mks)
{          case    1    :      printf("\nDistinction");
                                    break; 
            case    2    :          printf("\nFirst Class");
                                    break; 
            case    3    :          printf("\nPass");
                                    break; 
            case    4    :          printf("\nFail");
                                    break; 
            case    5    :          break;
            default:            printf("\nChoice Not Valid");
            }
}
  
 

BREAK    

Purpose:
Passes control.
 
Usage:
break ;
 
Explanation:
  • The break statement causes control to pass to the statement following the innermost enclosing white, do, for, or switch statement.
  • The following program displays a message on the screen for 100 times. If use presses any key it dis-continues with the help of a break statement.
  • kbhit() is an inbuilt function found in conio.h. It checks for currently available keystrokes, kbhit is unique to DOS . If a keystroke is available, kbhit returns a nonzero integer; if not, it returns 0.                            
Program-1
#include<stdio.h>
#include<conio.h>
/* Example of break */
void main ()
      
{       int counter=1;
         while(counter<=100)
        {       printf("\nl Love You");
        counter++
        if(kbhit() != 0)
        break;
             }
        printf("\nl Loved You %d Time        s", counter);
        }
 
 

CONTINUE    

 
Purpose:
Passes control
 
Usage:
continue ;
 
Explanation:
  • Causes control to pass to the end of the innermost enclosing white, do , or for statement, at which point the loop continuation condition is re-evaluated.
  • It is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. But the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop.
  • The following program inputs any numbers (negative or positive). But only positive numbers are averaged.
            
Program-1
#include<stdio.h>
/* Example to calculate average of all positive numbers. Using continue */
void main ()
      
{       int num, counter, flag=0, x, avg, total=0;
         printf("\nEnter, how many numbers to be averaged ");
        scanf("%d",&num);
        for(counter=1; counter <= num; ++counter)
 
 
 
 
 
        {        printf("x= ");
                  scanf("%d",&x);
                  if(x<0)
                  continue;
                  total += x;
                  ++flag;
                 }
    avg=total/flag;
    printf("\nThe Average Is %d\n",avg);
    }
 
 

GOTO   

Purpose:
Transfers control
 
Usage:
goto label;
 
 
Explanation:
  • Control is unconditionally transferred to the location of a label specified by identifier.
  • It is used to alter the normal sequence of program execution by transferring control to some other part of the program.
  • The labeled statement within the program must have a unique label name.
  • The following program is a simple division program, that accepts 2 numbers from user, if denominator is 0, it prompts with an error message, and allows the user to re-enter the vale for the 2nd number.

 Program-1
#include<stdio.h>
/* Example of goto */
void main ()
      
{       int x,y;
         printf("\nEnter 1st Number : ");
         scanf("%d",&x);
        again : printf("Enter 2nd Number : ");
        scanf("%d",&y);
        if(y= =0)
        {        printf("\n2nd Number Cannot Be Zero, Try Again\n");
                 goto again;
                 }
        printf("\nThe Division Is :%d",x/y);
        }
 
      
             
 
 
Thank you for visit my site. If you find this article informative, please share the post to your friends.
Learn how to write the C program step-by-step | Lesson -3 Learn how to write the C program step-by-step | Lesson -3 Reviewed by Neel Kamal on November 11, 2020 Rating: 5

No comments:

For More Details Subscribe & Comment..!

Powered by Blogger.