Thursday, October 11, 2018

What is Loop and type of loop in C++?

Loops and types of loops
  • Loops cause a section of program to be repeated certain number of times.
  • As long as condition remains true, the repetition continues, when the condition becomes false, the loop ends and the control passes to the statement following the loop.

There are three kinds of loops in C/C++.

i)          for loop
ii)         while loop
iii)        do while loop

The for loop
  • The for loop executes a section of code a fixed number of times.
  • “for loop” is used normally when we know, before entering the loop, that how many times we want to execute the code.
Example of for loop with program

 Flow Chart

The While Loop

  • Normally in “for loop” we have an idea that how many times we want to execute a section of code

  • but “while loop” is used when even before starting the loop we have no idea that how many times a section of code will be executed.

  • Like for loop, while loop contains a test expression but there is no initialization or increment/decrement expression etc.
    Example of While Loop
    Flow chart
     While Loop example



    #include <iostream.h>
    #include <conio.h>
    void main(void)
    {  
      clrscr();
    int a=0;
    while(a!=100)
    {
      cout<<a<<"\t"<<(100-a)<<endl;
      a=a+25;
    }
    getch();
      }

The do while loop

  • The do while loop is used when we want to guarantee that the loop body should execute at least once, whatever the initial state of the test expression contains.
    Flow Chart of do while loop
  • In do while loop, the test expression is placed at the end of the loop. 
    Example of do while loop







       

No comments:

Post a Comment