Professional Documents
Culture Documents
Looping in C++ Final.
Looping in C++ Final.
Group members:
3. The initialization part sets the starting value for the loop counter, the condition part checks if the loop should
continue, and the increment/decrement part updates the loop counter after each iteration.
Flowchart of the For Loop:
1 Initialization
The loop starts by initializing a counter variable, which is used to track the number
of iterations.
2 Condition
The loop checks the condition, which determines whether the loop should continue
or terminate.
3 Execution
If the condition is true, the code inside the loop is executed.
Syntax of the For Loop:
for( initialization; condition; increment/decrement)
1 2 3 4
Output:
Code:
1 2 3 4 5 6 7 8 9 10
for( int i=1; i<=10; i++) { cout<< i<< " "; }
Example 2: Printing Table Using a For Loop
1. The for loop can be used to print the multiplication table of any given number.
2. The loop initializes a counter variable, usually i, to the starting value (e.g., 1).
3. The condition checks if the counter is less than or equal to the desired number of iterations (e.g., 10 for a 10x
table).
4. Inside the loop, the code prints the product of the given number and the current value of the counter.
5. The increment expression updates the counter variable after each iteration, usually by adding 1 (i++).
Example 2:
Code:
3. Inside the loop, the code calculates the square of the current value of `i` and prints it to the console.
Example 3:
Code: Output:
for (int i = 1; i <= number; i++) { cout << number; Square of 5= 25
if (i != number) { cout << " + "; } } cout << " = " <<
(number * number) << endl;
Example 4: Printing Star Patterns Using For
Loops
1. The for loop can be used to print various star patterns on the console.
2. The loop initializes a counter variable, usually i, and checks if it meets the desired condition.
3. Inside the loop, the code prints the appropriate star symbol, space, or newline character to create the desired
pattern.
Example 4:
Output:
The star pattern will be displayed.
Code:
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++)
{ cout<< "*"; } cout <<endl; }