Programming Fundamentals: C++ For Loop
Programming Fundamentals: C++ For Loop
11/10/2019
by
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
SHEHZAD LATIF
Assistant Professor,
Hajvery University – Lahore
Email: [email protected]
1
C++ for Loop
Loops are used in programming to repeat a specific block of code.
11/10/2019
Loops are used in programming to repeat a specific block until some end
condition is met.
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
There are three type of loops in C++ programming:
for loop
while loop
do...while loop
2
C++ for Loop Syntax
11/10/2019
{
// codes
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
}
3
How for loop works?
11/10/2019
• Then, the test expression is evaluated.
• If the test expression is false, for loop is terminated. But if the test
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
expression is true, codes inside body of for loop is executed and update
expression is updated.
• Again, the test expression is evaluated and this process repeats until
4
Flowchart of for Loop in C++
Programming Fundamentals by
11/10/2019
5
11/10/2019
#include <iostream>
using namespace std;
int main()
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
{
int i, n, factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
for (i = 1; i <= n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
6
Output
Factorial of 5 = 120
Enter a positive integer: 5
Programming Fundamentals by
11/10/2019
7
variable n(suppose user entered 5). Here is the working of for loop:
11/10/2019
1. Initially, i is equal to 1, test expression is true, factorial becomes 1.
Programming Fundamentals by
SHEHZAD LATIF (03134797617)
2. i is updated to 2, test expression is true, factorial becomes 2.