Pages

Thursday, March 17, 2011

Introduction to Iteration (Loops)

Sometimes in problem solving, we will encounter problems that will require us to repeat our instruction many times or until such a certain value is not met. If we think about these problems, we may end up in doing redundant command just to arrive with a solution. For example, imagine that you are required to display “Good Morning!” in the screen for 3 times, 5 times,  .... or 100 times.

cout<<”Good Morning!”<<endl;
cout<<”Good Morning!”<<endl;
cout<<”Good Morning!”<<endl;

                This will solve the first but then you will modify the program just to it 5 times and so on. C++ offers a program structures that allows us to repeat instruction with just a few line of these program structure. These are called loops.
               
Loops are structures that control repeated executions of a block of statements for a given of a certain conditions/expressions. If these conditions returns false, the loop itself terminates, otherwise it will continue to execute the block of statement. The concept of looping is fundamental to programming. C++ provides three types of loop statements: while loops, do/while loops and for loops.

Notes:
Nesting can be implemented also to any of the three loops as well as combining any of the three loops from one type of loop to another type of loop as long as it follows the rules of syntax.

1 comment:

  1. What are loops and how we can use them?

    In general a loop is a sequence of statements which is specified once but which may be carried out several times in succession. The function of the loop is to repeat the calculation a given number of times until it reaches a certain value. The code inside the loop is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely. We can divide loops into:
    1) Count-controlled loops,
    2) Condition – controlled loops,
    3) Collection - controlled loops,
    4) General iteration,
    5) Infinite loops,
    6) Continuation with the next iteration,
    7) Redo the current interation and
    8) Restart loop

    For more information please visit: http://megacplusplustutorials.blogspot.com

    ReplyDelete