Wednesday, June 19, 2013

Loops

Motivation : Suppose you want to print 1 to 10 on the screen on a single line.
what will you do??
easy right??? just use 'cout' to print them on screen(huh!!! childs play).
Now, imagine the same scenario but this time instead of 1 to 10 try to print 
1 to 1000. Not so easy right!!!!!
So, what i want to say is, if you want to execute the same block of code a no. of times than c++ provides what is known as a loop.
There are 3 different loops that c++ provides 
1> for loop
2> while loop
3> do while loop

Now let's have a look at each of them in details :
1> for loop : 
                   general Syntax :  
                   for(initialization; condition checking; increment or decrement) {
                                               //repeating block of code
                   }
note : if the loop's body contains one statement than it is not necessary to give the curly brackets(for all types of loops).

let's take an example to understand the syntax more clearly :




















                                   




*in the previous picture the output : 0 1 2 3 4 5 6 7 8 9 
(sorry for the silly mistake)

The picture below depicts the flow of control in the for loop :

let's look at the following code to find the sum of n entered numbers : 


Explanation :  we have taken the loop variable as i. we have initialized 'i' to 1(as you may have noticed from the flow chart that the initialization is  done only once ). Now 1<= 10 condition is checked. which is found to be true.
so, control enters the loop body and it takes a number as input from user.
Add this number with sum(which is 0 initially) now sum = 0+10 = 10. Then i is incremented 2<=10 condition is checked and found true. Again a number is taken as input from the user and  added to sum.  so, sum = 10 + 20 = 30 and so on.............


look at the following diagram for more clarity(it is assumed that the user gives same input as in the program shown above)


























the general syntax of the for header can be varied the following program illustrates this none of the parts of the for loop header are compulsory.
 Explanation :  you can easily see from the above program, that for loop can be used in various ways. You can skip the initialization part, the increment decrement part, the condition checking part or you can skip all. This gives us flexibility to write our code. The break will be explained shortly.

2> while loop :
                         general syntax : 
                          while(condition) {
                                             //repeating code block
                          }
the following figure depicts the particular pattern for a while loop





look at the following code snippet to understand various ways of using while loop :




























Explanation :  in the 2. standard loop i have used post increment so it prints first and then increments the value. In the 3. standard loop i have post incremented the value during condition checking so that first condition is checked and then it is incremented, (i-1) is used since the value is already incremented and i want to print the previous value.


Entry Control loop :  upto this point whatever loop we have studied is known as entry control loop. Because the condition checking is done prior to getting entry in the loop body(much like buying ticket at the entry of a fair to enter it).

2> do while loop : 
                              Syntax :
                               do {
                                  //repeating code block
                                 
                                } while(condition) ;
look at the following code to understand the syntax of do while loop properly
look at the following code to understand the syntax of do while loop properly :

Explanation : by observing the output one can easily say that this loop behaves a little differently than the others because the condition checking is after the loop body it executes one time more than the value of n(in 1 and 3).
I encourage you to find out what is happening in the 2nd version where exactly 6 numbers are getting printed.


break : this is a instruction that is used to break out of the current active loop
body without executing any further iterations.

continue : this instruction is used to skip any c++ statements in the current iteration after the continue statement   and go to the next iteration.

look at the code for more clarity :
Explanation : 
                      continue : the control enters the if's body for odd values of i and then encounters the increment so in cases where the value of i is odd the cout is not executed
                  break : user is prompted for a input at each iteration of the loop and then the if is used to check the choice if found to be true break is used to exit the loop body.
 here is the output :

the while loop part of the above program which uses break can be done by do while loop i encourage you to do it as an exercise.



                      Nested Loops

Motivation : Sometimes we require that for each iteration of the outer loop there is some work that we need to do that occurs a fixed no. of times.
For these kind of situations nested loop is used

Syntax : 
ini -> initialization
cndchk -> condition checking
inr/dcr -> increment/decrement
                for(ini; cndchk; inr/dcr) {//outer loop body
                                    for(ini; cndchk; inr/dcr) {//inner loop body
                                                               //repeatable code block  
                                    }
                    }
                    while(cndchk) {//outer loop body
                                    while(cndchk) {//inner loop body
                                                               //repeatable code block 
                                                                inr/dcr
                                     }
                                     inr/dcr
                   
                     }
                     do {/outer loop body
                                     do {/inner loop body
                                                //repeatable code block 
                                                inr/dcr
                                     } while(cndchk)
                                     inr/dcr
                     } while(cndchk)


let's have a look at the following snippet to understand the nested loops better :
output : 1 2 3 4 5 6 7 8 9 10
               1 2 ..................10
               1
             .
             .
             .
               1 2 3 ...............10  (no. of rows 10 and no. of columns 10)

let's look at a few programs to print patterns :

1>

2>

3>
note :
Enter patterns :  means Enter n : i don't know why i wrote it please bear with it.
I encourage you to program all these patterns using while loop and try several other patterns by yourself. you can find a lot of these patterns on the internet or in basic books of c++.
 as with all other posts i have uploaded the source code of all the programs here in google drive here : Learning c++







No comments:

Post a Comment