Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

6.3 Loops - while & for

1 min read
Image result for Loops - while & for 
while loop

The while loop calculates the expression before every loop. If the expression is true then block of statements is executed, so it will not execute If the condition is initially false. It needs the parenthesis like the if statement.

while ( expression )
/* while expression is true do following*/
&nbsp statements... ;

Do While loop
This is equivalent to a while loop, but it have test condition at the end of the loop. The Do while loop will always execute at least once.

do
&nbsp statements ;
while ( expression );
/* while expression is true do...*/

For loop
This is very widely held loop.
For loops work like the corresponding while loop shown in the above example. The first expression is treated as a statement and executed, then the second expression is test or condition which is evaluated to see if the body of the loop should be executed. The third expression is increment or decrement which is performed at the end of every iteration/repetition of the loop.

for (expr1; expr2; expr3)
&nbsp statements...;

In while loop it can happen that the statement will never execute But In the do-while loop, test condition is based at the end of loop therefore the block of statement will always execute at least once. This is the main difference between the while and the do-while loop.

For example, to execute a statement 5 times:

for (i = 0; i < 5; i++)
&nbsp cout << i << endl;

Another way of doing this is:
i = 5;
while (i--)
&nbsp statements;

While using this method, make sure that value of i is greater than zero, or make the test i-->0.

                      6.4 Break and Continue          NEXT >>

You may like these posts

  • You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of argu…
  • Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. C++ exception h…
  • Object Oriented Programming has a special feature called data abstraction. Data abstraction allows ignoring the details of how a data type is represented. While defining a clas…
  •   Encapsulation is the method of combining the data and functions inside a class. This hides the data from being accessed from outside a class directly, only through th…
  • Polymorphism "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of…
  • A file is collection of related records, a record is composed of several fields and field is a group of character. This requires another standard C++ library called fstream which…

Post a Comment