Why Loops ?
Loop can be defined as one of the basic logical structures of computer programming. Defining loops allows computers to perform particular tasks repeatedly. The need for defining the loop in a computer program arises for various reasons depending on the tasks to be performed. Computer programming languages require loops so that the codes executive the actions as many times as needed. There are various loops used in computer programming. For loops, while loops and do while loops are the most common loops.We are going to take a look at the for loop.
The for loop is often distinguished by an explicit loop counter or loop variable. This allows the body of the for loop (the code that is being repeatedly executed) to know about the sequencing of each iteration. For loops are also typically used when the amount of iterations is known before entering the loop. For loops are the shorthand way to make loops when the number of iterations is known.
For loop basic structure
for (initial statement; loop condition; update statement){
statements ;
}
For loop basic flowchart
Sample Program
Program to determine the sum of the first n positive integers
#include <iostream>using namespace std;
int main()
{
int counter; //loop control variable
int sum; //variable to store the sum of numbers
int n; //variable to store the number of
//first positive integers to be added
cout << "Line 1: Enter the number of positive "
<< "integers to be added: "; //Line 1
cin >> n; //Line 2
sum = 0; //Line 3
cout << endl; //Line 4
for (counter = 1; counter <= n; counter++) //Line 5
sum = sum + counter; //Line 6
cout << "Line 7: The sum of the first " << n
<< " positive integers is " << sum
<< endl; //Line 7
return 0;
}
The Output
Enter the number of positive integers to be added : 100The sum of the first 100 positive integers is 5050
Understanding the program
The statement in Line 1 prompts the user to enter the number of positive integers to be added.The statement in Line 2 stores the number entered by the user in n, and the statement in Line
3 initializes sum to 0. The for loop in Line 5 executes n times. In the for loop, counter is
initialized to 1 and is incremented by 1 after each iteration of the loop. Therefore, counter
ranges from 1 to n. Each time through the loop, the value of counter is added to sum. The
variable sum was initialized to 0, counter ranges from 1 to n, and the current value of
counter is added to the value of sum. Therefore, after the for loop executes, sum contains
the sum of the first n values, which in the sample run is 100 positive integers.
References
[1] Siddarthe Rao, Sams teach yourself C++ in one hour a day, 7th edition, 800 East 96th Street, Indianapolis, Indiana.[2]Importance of for loops, available at :
http://fareedsiddiqui.expertscolumn.com/article/importance-loops-computer-programming-0[Accessed 8May2014]
[3]D.S Malik, C++ Programming from problem analysis to
problem design, 5th edition, Boston MA 02210.