C++ is one of the most versatile languages in the world. It is used nearly everywhere for everything… systems programming (operating systems, device drivers, database engines, embedded, Internet of Things, etc.)

Enter Header Image Headline Here

Saturday 15 April 2017

C++ for Loop

                                            C++ for Loop


Loops are used in programming to repeat a specific block of code and specific block until some end condition is met. There are three type of loops in C++ programming:

1. for loop
2. while loop
3. do...while loop


for Loop Syntax :









where only testExpression is mandatory.

How for loop works ?  :

1. The initialization statement is executed only unes at the beginning.

2. Then, the test expression is evaluated.

3. If the test expression is false, for loop is executed and update expression is updated.

4. Again, the test expression is evaluated and this process repeats until the test expression is false.


Flowchart of for Loop in C++























Example: for Loop :







































Output:










In the program, user is asked to enter a positive integer which is stored in variable n (suppose user enter 5). Here is the working of for loop :

1.  Initialy i is equal to 1, test expression is true, factorial becomes 1.
2.  i is Updated to 2, test expression is true, factorial becomes 2.
3.  i is Updated to 3, test expression is true, factorial becomes 6.
4.  i is Updated to 4, test expression is true, factorial becomes 24.
5.  i is Updated to 5, test expression is true, factorial becomes 120.
6.  i is Updated to 6, test expression is false, for loop is terminated.

In the above program, variable i is not used outside of the for loop.in such a cases, it is better to declare the variable in for loop (at initialization statement).


0 comments:

Post a Comment

Popular Posts

Recent Posts

Categories

Unordered List

Text Widget