-->





Translate

Loops in C++, While Loop

9 comments
Loop in C++
It is a statement that is used to repeat set of statements up to a fixed number of times or until a given condition is satisfied.
There are two types of loops:
  • Conditional Loop (while and do-while Loop)
  • Counter Loop (for loop)
Conditional Loop
It is a loop that executes a set of statements as long as a given condition remains true.
Counter Loop
It is used to repeat a set of statements for a specified number of times.
While Loop
It is used to repeat a set of statements until a given condition is satisfied.
Syntax:
while loop
  • When while statement is executed, the compiler checks the given condition written in parentheses.
  • If the given condition is true then the statements enclosed in the braces ( body of loop) are  executed.
  • After the completion of first iteration control is shifted to while and the condition is again tested.
  • This process is repeated until the condition is true.
  • If the condition is false then control is transferred the statement that comes after the body of loop.
Infinite loop
If the condition of loop never false then the loop never ends and called infinite loop
Note: Infinite loop in useful where the programmer does not know in advance how many times the body of loop will be executed.

Loop control variable
A variable whose value control the number of iterations of loop is called loop control variable.
  • Loop control variable always initialized before starting of the loop and incremented and decremented inside the loop body. 
    For example: Program to print first 10 natural numbers

#include<iostream>

using namespace std;

int main()

{

    int a=1;              

    while(a<=10)               // Condition of loop

    {

        cout<<a<<endl;

        a++;                    // increment statement

    }

return 0;

}

 Output

1

2

3

4

5

6

7

8

9

10

9 comments: