The task:
Write a C program which will print (half pyramid) pattern of natural numbers.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
I have tried using this code, but its not giving the output:
#include <iostream>
using namespace std;
int main()
{
int rows, i, j;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i )
{
for(j = 1; j <= i; j )
{
cout << j << " ";
}
cout << "\n";
}
return 0;
}
OUTPUT:
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
CodePudding user response:
j
in your inner loop is the 1 based index of the element in the current row (1,2,3 etc.).
Instead of printing it, you should print a counter that is increased over all the iterations.
Something like:
#include <iostream>
int main()
{
int rows, i, j;
std::cout << "Enter number of rows: ";
std::cin >> rows;
int n = 1;
for (i = 1; i <= rows; i )
{
for (j = 1; j <= i; j )
{
std::cout << n << " ";
n ; // for next iteration
}
std::cout << "\n";
}
return 0;
}
Output example:
Enter number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
A side note: better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.