C Loops


C Loops

You may come across circumstances where a block of code needs to be run multiple times.

Different control structures are available in programming languages, allowing for more sophisticated execution routes.

To meet looping requirements, the C programming language provides the following types of loops.

  • While loop - Recurses a statement or set of statements while a condition is true. Before execution of the loop body, it checks out the entire condition.
  • //print numbers from 1 to 5 using while loop. #include<stdio.h> #include<conio.h> void main() { int n=1; //intilization while(n<=5) // condition { printf("%d ",n); // statement n++; // increment getch(); }

    output:

    1 2 3 4 5
  • Do while loops - These loops are similar to while statements in that they test the condition at the end of the loop body.
  • //print numbers from 1 to 5 using do-while loop. #include<stdio.h> #include<conio.h> void main() { int n=1; //intilization do { printf("%d ",n); // statement n++; // increment } while(n<=5) // condition getch(); }

    output:

    1 2 3 4 5
  • For loop - Abbreviates the code that controls the loop variable and executes a sequence of statements numerous times.
  • //print numbers from 1 to 5 using for loop. #include<stdio.h> #include<conio.h> void main() { int n; for(n=1;n<=5;n++)/* initialization,condition,increment */ { printf("%d ",n); //statement } getch(); }

    output:

    1 2 3 4 5
  • Nested loops - You can stack more while, for, or do..while loops inside of one other.
  • #include<stdio.h> #include<conio.h> void main() { int i,j; for(i=1;i<=2;i++) /* initialization,condition,increment */ { for(j=1;j<=3;j++) /* initialization,condition,increment */ { printf("i is %d, j is %d \n",i,j); // statement } } getch(); }

    output:

    i is 1, j is 1 i is 1, j is 2 i is 1, j is 3 i is 2, j is 1 i is 2, j is 2 i is 2, j is 3

Loop Control Statements

Control statements in loops alter the execution sequence.

  • Break statement - Ends the loop or switch statement and moves execution to the statement that comes after it.
  • #include<stdio.h> #include<conio.h> void main() { int i; for(i=0;i<5;i++) { if(i==3) break; printf("%d ",i); } getch(); }

    output:

    0 1 2
  • Continue statement - Causes the loop to skip the rest of its body and recheck its condition before looping again.
  • #include<stdio.h> #include<conio.h> void main() { int i; for(i=0;i<5;i++) { if(i==3) continue; printf("%d ",i); } getch(); }

    output:

    0 1 2 4
  • Goto statement - Control is transferred to the named statement when you use the goto statement command.
  • #include<stdio.h> #include<conio.h> void main() { int num; num=1; repeat: printf("%d\n",num); num++; if(num<=5) goto repeat; getch(); }

    output:

    1 2 3 4 5