#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows\n");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
/* Print spaces before stars in a row */
for (j = 0; j < i; j++) {
printf(" ");
}
/* Print rows stars after spaces in a row */
for (j = 0; j < rows; j++) {
printf("*");
}
/* jump to next row */
printf("\n");
}
return 0;
}
And if i want to add more rows?
Now it shows 8 columns and 8 rows, if i would need 10?
Well, if that's a permanent change then change the 8 to a 10. If it can vary then you WILL need to ask (or refactor to take a command-line argument).
If you need to flush the input buffer after printf then just add fflush(stdout);
after your first printf statement in the original code. Or rewrite it in c++, not c.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
constint DEFAULT_ROWS = 8;
int rows = 0;
printf("Enter the number of rows (0 for default):");
scanf("%d", &rows);
if (rows == 0)
{
rows = DEFAULT_ROWS;
}
printf("\n");
for (int i = 0; i < rows; i++)
{
/* Print spaces before stars in a row */
for (int j = 0; j < i; j++)
{
printf(" ");
}
/* Print rows stars after spaces in a row */
for (int j = 0; j < rows; j++)
{
printf("*");
}
/* jump to next row */
printf("\n");
}
return 0;
}
If you want a different number of rows compared to columns then you would need to enter a number for columns. You would also have to adjust the 2nd inner for loop.
Notes:
Do not define variables like "i" and "j" outside the for loops. Define them in the for loops and keep those variables local to the for loop. The only reason to define for loop variables outside the for loop is if you need them later for something else, which you do not.
I added line 18 to make the display look a bit nicer.
A few blank lines makes the code much easier to read.
Something else to consider is that for rows and or columns you may want to have a minimum number. As is the program will display 1 line of 1 star, but it looks like it should be more.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
int rows;
cout << "Enter the number of rows: "; cin >> rows;
string line( rows, '*' );
for ( int i = 0; i < rows; i++ ) cout << setw( i + rows ) << line << '\n';
}