star pattern in c
Generating a Star Pattern in C
To generate a star pattern in C, you can use nested loops to control the number of rows and columns. Here's an example of how you can do it:
#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Let's break down the code and explain each step:
The program starts by including the necessary header file
stdio.h
, which provides input/output functions likeprintf
andscanf
.The
main
function is the entry point of the program.Inside the
main
function, we declare three variables:rows
,i
, andj
.rows
will store the number of rows in the star pattern.i
is a loop variable for the outer loop, which controls the number of rows.j
is a loop variable for the inner loop, which controls the number of stars in each row.The program prompts the user to enter the number of rows using
printf
and reads the input usingscanf
.The outer loop runs from
1
torows
and controls the number of rows in the pattern.Inside the outer loop, the inner loop runs from
1
toi
and controls the number of stars in each row. The number of stars in each row is equal to the row number.Inside the inner loop, we use
printf
to print a star followed by a space.After printing all the stars in a row, we use
printf
to print a newline character\n
to move to the next line.Once the loops are finished, the program returns
0
to indicate successful execution.
To run this program, you can compile and execute it using a C compiler.