Explore solved C++ while loop exercises, including a multiplication table, algorithm analysis, dry run, complete code, code explanation, and sample output.
for Loops – Printing a Rectangle PatternProblem: Write a C++ program using nested for loops to print a rectangular pattern of stars (*).
Requirements:
for loop to control the rows.for loop to print the stars in each row.Understanding the problem:
Think of the output as a rectangle:
cout << endl; moves the cursor to the next line after each row.i = 1.i <= 4.j = 1.j <= 5.* during each iteration.j by 1.endl.i by 1.START
FOR i = 1 TO 4
FOR j = 1 TO 5
PRINT "* "
END FOR
PRINT NEW LINE
END FOR
STOP
The outer loop controls the rows, while the inner loop controls the stars printed in each row.
| Outer loop (i) | Inner loop (j) | Output |
|---|---|---|
| 1 | 1, 2, 3, 4, 5 | * * * * * |
| 2 | 1, 2, 3, 4, 5 | * * * * * |
| 3 | 1, 2, 3, 4, 5 | * * * * * |
| 4 | 1, 2, 3, 4, 5 | * * * * * |
Total iterations:
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 5; j++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
#include <iostream>
cout to display output on the screen.using namespace std;
cout and endl without writing std:: before them.int main()
main() function is the starting point of the program.int indicates that the function returns an integer value.{
main() function body.for (int i = 1; i <= 4; i++)
This loop controls the number of rows.
It contains three parts:
| Part | Explanation |
|---|---|
int i = 1 |
Initializes the row counter at 1. |
i <= 4 |
Continues the loop while i is less than or equal to 4. |
i++ |
Increases the value of i by 1 after each iteration. |
How it works:
i = 1 (Row 1).i = 2 (Row 2).i = 3 (Row 3).i = 4 (Row 4).The outer loop executes 4 times, so the program prints 4 rows.
{
for (int j = 1; j <= 5; j++)
This loop controls the number of stars in each row.
It also contains three parts:
| Part | Explanation |
|---|---|
int j = 1 |
Initializes the star counter at 1. |
j <= 5 |
Continues the loop while j is less than or equal to 5. |
j++ |
Increases the value of j by 1 after each iteration. |
How it works:
j = 1 (First star).j = 2 (Second star).j = 3 (Third star).j = 4 (Fourth star).j = 5 (Fifth star).The inner loop executes 5 times for every iteration of the outer loop.
cout << "* ";
*) on the screen.}
cout << endl;
}
i and starts the next row.return 0;
main() function.0 to indicate successful program execution.}
main() function.* * * * *
* * * * *
* * * * *
* * * * *
| Concept | Purpose |
|---|---|
Outer loop (i) |
Controls the number of rows. |
Inner loop (j) |
Controls the number of stars in each row. |
cout << "* "; |
Prints one star. |
cout << endl; |
Moves to the next line. |
| Nested loops | A loop inside another loop. |
Remember this simple rule:
endl = Move to the next row.