Pattern 10
Objective
Write a C++ program to print a right half pyramid with identical odd numbers on each row.
Algorithm / Approach
- Use outer loop
ifrom 0 to 3. - Use inner loop
jup toi. - Print the mathematical formula for odd numbers based on the row:
(2 * i) + 1.
main.cpp
#include<iostream>
using namespace std;
int main() {
int i,j;
for(i = 0; i< 4; i++) {
for(j = 0; j<=i; j++) {
cout<< (2*i)+1<<" ";
}
cout<< endl;
}
return 0;
}
Expected Output
1 3 3 5 5 5 7 7 7 7
Explanation of the Program
- Because all numbers on a specific row are identical, the number printed must be tied directly to the outer loop variable (
i). - Using the math formula
2n + 1, we convert the row indexes (0, 1, 2) into sequential odd numbers (1, 3, 5).
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)