Loop
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;
}