Loop which are used in C Language With Syntax And Example - Computer Free Knowlege Loop which are used in C Language With Syntax And Example | Computer Free Knowlege

0
Loops:
         A loop makes possible repeated execution of one or more statements,This repetition must be controlled so that these statements are executed only a finite number of lines.C provides three statements to implement loop strecture.These three statements are:

  1. The For statement
  2. The While statement 
  3. The Do-While statement.

The For Loop:
                        The for loop is primarily used for executing a statement or block of statements a predetermined number of times.You control a for loop using three expressions separated by semicolon,which are placed between brackets following the keyboard for.
Syntax:
            The General form of the for statement is
 for(exp1;exp2;exp3)  
 {  
    Body of the loop (block of statements)  
 }  

Example:
             
 #include 
 #include 
 main ()  
 {  
 int j;  
 for (j=1;j<=3;J++)  
 printf("\nj=%d",j);  
 }  


The While Loop:
                            The while loop uses a logical expression to control execution of the loop body.The loop will continue as long as the value is non-zero.If the condition controlling the loop produces an integer,Any non-zero integer means the condition is ture and only a zero means it is false.
 Syntax:
               The while statement has the general form
  while (expression)  
        {  
           body of the loop  
          }  
Example:
  #include <stdio.h>   
          #incluse  
          main()  
          {  
           int count;  
           float marks,sum,avg  
           sum=0;  
           count=0  
          printf("\nenter marks:");  
          scanf("%f",&amp;marks);  
          while (marks&gt;=0)  
        {  
          sum=sum+marks;  
          count=count+1  
          printf("\nEnter marks:")"  
          scanf("%f",&amp;marks);  
         }  
         avg=sum/count;  
        printf("\nagverage marks=%6.2".avg);  
        printf("\n no.of marks in the list=%2d",count);  

The Do While Loop:
                                  The do while loop is similar to the while loop in that loop continues as long as the specified loop condition remains true.However,the difference is that the loop condition is checked at the end of the do while loop,rather then at the begining,so the loop body is always executed at least once.

Syntax:
              This sort of loop takes a form that is easy to understand:
  do  
       {  
          body of the loop  
          }  
         while (expression);  
Example:


  #include   
          #include   
          main(),  
         {  
           char ch:  
           ch='A';  
           do  
          {  
          printf("%c",ch);  
          ch=ch+1;  
        }  
        while(ch<='Z');  
       }  
If you have any questions/queries,feel free to ask.

Post a Comment

 
Top