0% found this document useful (0 votes)
19 views

Loop

- Loops repeat a section of code a specified number of times or as long as a condition is true. There are three types of loops in C++: for, while, and do loops. - The for loop is easiest to understand as it contains the initialization, test, and increment expressions together. It is commonly used when the number of repetitions is known. - The while loop repeats as long as a test condition is true. It is used when the number of repetitions isn't known beforehand. - The do loop guarantees the loop body executes at least once since the test condition is at the end, differing from while which tests at the beginning.

Uploaded by

osama.20en714
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Loop

- Loops repeat a section of code a specified number of times or as long as a condition is true. There are three types of loops in C++: for, while, and do loops. - The for loop is easiest to understand as it contains the initialization, test, and increment expressions together. It is commonly used when the number of repetitions is known. - The while loop repeats as long as a test condition is true. It is used when the number of repetitions isn't known beforehand. - The do loop guarantees the loop body executes at least once since the test condition is at the end, differing from while which tests at the beginning.

Uploaded by

osama.20en714
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Loops

• Loops cause a section of your program to be repeated a certain number of


times.
• The repetition continues while a condition is true.
• When the condition becomes false, the loop ends and control passes to the
statements following the loop.
There are three kinds of loops in C++:
• for loop,
• while loop,
• do loop.
The for Loop
• The for loop is the easiest C++ loop to understand. All its loop
control elements are gathered in one place.
Here’s an example that displays the squares of the numbers from 0
to 14:
#include <iostream>
using namespace std;
int main()
{
int j; //define a loop variable
for(j=0; j<15; j++) //loop from 0 to 14,
cout << j * j << “ “; //displaying the square of j
return 0;
} Here’s the output:
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196
The for statement. It consists of the keyword for, followed by parentheses that contain three expressions
separated by semicolons ;. These three expressions are the initialization expression, the test expression, and the
increment expression, as shown in Figure.
for( j=0; j<15; j++)
In the for statement j is called the loop variable
• The initialization expression is executed only once, when the loop first starts. In above statement it sets j to 0
• The test expression. It is evaluated each time through the loop, just before the body of the loop is executed. It
determines whether the loop will be executed again.
• The increment expression changes the value of the loop variable. It is always executed at the end of the loop,
after the loop body has been executed.
The increment expression doesn’t need to increment the loop variable; it can perform any operation
it likes.
In the next example it decrements the loop variable. This program, FACTOR, asks the user to type in a
number, and then calculates the factorial of this number. (The factorial is calculated by multiplying the original
number by all the positive integers smaller than itself. Thus the factorial of 5 is 5*4*3*2*1, or 120.)
#include <iostream>
using namespace std;
int main()
{
unsigned int numb;
unsigned long fact=1; //long for larger numbers
cout << “Enter a number: “;
cin >> numb;
for(int j=numb; j>0; j--) //multiply 1 by
fact *= j; //numb, numb-1, ..., 2, 1
cout << “Factorial is “ << fact << endl;
Note: The loop variable j is defined inside the for statement.
return 0; Variables defined in the loop statement this way are visible
} in the loop body only
Multiple Statements in the Loop Body
The next example uses three statements in the loop body. It prints out the cubes of the numbers from 1 to 10,
using a two-column format.
// cubelist.cpp
// lists cubes from 1 to 10
#include <iostream>
#include <iomanip> //for setw
using namespace std;
int main()
{
int numb; //define loop variable
for(numb=1; numb<=10; numb++) //loop from 1 to 10
{
cout << setw(4) << numb; //display 1st column
int cube = numb*numb*numb; //calculate cube
cout << setw(6) << cube << endl; //display 2nd column
}
return 0;
}
Multiple Initialization and Test Expressions
• You can put more than one expression in the initialization part of the for statement, separating the different
expressions by commas.
• You can also have more than one increment expression. separating the different expressions by commas.
• You can have only one test expression.
Here’s an example:
for( j=0, alpha=100; j<50; j++, beta-- )
{
// body of loop
}
Actually, you can leave out some or all of the expressions if you want to. Such as
for(;;)
The while Loop
• The for loop does something a fixed number of times.
• What happens if you don’t know how many times you want to do something before you start the loop? In
this case a different kind of loop may be used: the while loop.
Example: the following program asks the user to enter a series of numbers. When the number entered is 0,
the loop terminates. Notice that there’s no way for the program to know in advance how many numbers will
be typed before the 0 appears; that’s up to the user.
#include <iostream>
using namespace std;
int main()
{
int n = 99; // make sure n isn’t initialized to 0
while( n != 0 ) // loop until n is 0
cin >> n; // read a number into n
cout << endl;
return 0;
}
Figure: Syntax of the while loop

• Although there is no initialization expression,


• the loop variable (n) must be initialized before the loop begins.
• The loop body must also contain some statement that changes the value of the loop variable; otherwise the loop
would never end. In the above program it’s
cin>>n;
Multiple Statements in a while Loop

Example: Write a program that compute the sum of numbers 1-100 Using while.
#include<iostream>
using namespace std;
main()
{ int sum,i;
sum=0;i=1;
while(i<=100)
{ sum=sum+i;
i++;
}
cout<<“sum=”<<sum;
return 0;
}
The do Loop
• In a while loop, the test expression is evaluated at the beginning of the loop. If the test expression is
false when the loop is entered, the loop body won’t be executed at all.
• Sometimes you want to guarantee that the loop body is executed at least once, no matter what the
initial state of the test expression. When this is the case you should use the do loop, which places the
test expression at the end of the loop.
Our example, invites the user to enter two numbers: a dividend (the top number in a division) and a divisor
(the bottom number). It then calculates the quotient (the answer) and the remainder, using the / and %
operators, and prints out the result. Following each computation, the program asks if the user wants to do
another division.
#include <iostream>
using namespace std; Here’s an output:
int main() Enter dividend: 11
{ Enter divisor: 3
long dividend, divisor; Quotient is 3, remainder is 2
char ch; Do another? (y/n): y
do //start of do loop Enter dividend: 222
{ //do some processing Enter divisor: 17
cout << "Enter dividend: "; cin >> dividend; Quotient is 13, remainder is 1
cout << "Enter divisor: "; cin >> divisor; Do another? (y/n): n
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is " << dividend % divisor;
cout << "\nDo another? (if yes enter y): "; //do it again?
cin >> ch;
}
while( ch == 'y' ); //loop condition
return 0;
}

You might also like