number pattern in c
Number Pattern in C
To create a number pattern in C, you can use loops and conditional statements to generate the desired sequence of numbers. Here's an example of a number pattern in C:
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", number);
number++;
}
printf("\n");
}
return 0;
}
In this example, the program prompts the user to enter the number of rows they want in the pattern. It then uses nested loops to print the numbers in the pattern. The outer loop controls the number of rows, and the inner loop controls the number of elements in each row. The number
variable keeps track of the current number to be printed.
Let's break down the code and explain each step:
The program includes the necessary header file
stdio.h
for input/output operations.The
main()
function is the entry point of the program.Inside the
main()
function, we declare the variablesrows
,i
,j
, andnumber
.rows
stores the number of rows in the pattern.i
is used as a loop counter for the outer loop.j
is used as a loop counter for the inner loop.number
keeps track of the current number to be printed.The program prompts the user to enter the number of rows using the
printf()
function and reads the input using thescanf()
function.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 elements in each row. The loop prints the current value ofnumber
followed by a space and incrementsnumber
by1
.After printing all the elements in a row, the program moves to the next line using the
printf("\n")
statement.Once all the rows and elements are printed, the
main()
function returns0
to indicate successful execution of the program.
You can modify this code to create different number patterns by changing the logic inside the loops.