Академический Документы
Профессиональный Документы
Культура Документы
11/10/2019
C++ do...while Loop
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
by
SHEHZAD LATIF
Assistant Professor,
Hajvery University – Lahore
Email: Shehzadch49@yahoo.Com
1
Syntax of C++ while Loop
while (testExpression)
11/10/2019
{
// statement
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
}
2
How while loop works?
11/10/2019
• If the test expression is true, codes inside the body of while loop is
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
evaluated.
• Then, the test expression is evaluated again. This process goes on until
3
Flowchart of while Loop in C++
Programming Fundamentals by
11/10/2019
4
11/10/2019
#include <iostream>
using namespace std;
int main()
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
{
int number, i = 1, factorial = 1;
Factorial of 4 = 24
Enter a positive integer: 4
Programming Fundamentals by
11/10/2019
6
11/10/2019
Then, the while loop starts executing the code. Here's how while loop works:
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
1. Initially, i = 1, test expression i <= number is true and factorial becomes 1.
terminated.
7
C++ do...while Loop
11/10/2019
• The do...while loop is a variant of the while loop with one
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
important difference. The body of do...while loop is executed once
8
The syntax of do…while loop is:
11/10/2019
do
{
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
// codes;
while (testExpression);
9
How do...while loop works?
• The codes inside the body of loop is executed at least once. Then,
11/10/2019
only the test expression is checked.
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
• If the test expression is true, the body of loop is executed. This
10
Flowchart of do...while Loop
Programming Fundamentals by
11/10/2019
11
11/10/2019
using namespace std;
int main()
{
float number, sum = 0.0;
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
do {
cout<<"Enter a number: ";
cin>>number;
sum += number;
}
while(number != 0.0);
return 0; 12
}
Output
Enter a number: 2
11/10/2019
Enter a number: 3
Enter a number: 4
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
Enter a number: -4
Enter a number: 2
Enter a number: 2
Enter a number: 0
13