A Number Pattern Program in C is a type of program that generates and displays a specific pattern of numbers based on user-defined input. These patterns can take various forms, such as triangles, squares, or pyramids, and are often used to demonstrate nested loops and formatting in C.
Example: Right-Angled Triangle Number Pattern
Let's explain a simple program that prints a right-angled triangle number pattern. For instance, if the user inputs the number 5
, the output will look like this:
Logic of the Program:
- Take an integer input from the user that represents the number of rows for the pattern.
- Use a nested loop:
- The outer loop will iterate through each row.
- The inner loop will iterate through numbers from
1
to the current row number.
- Print the numbers in the inner loop.
- After each row, print a newline character to move to the next line.
C Program to Generate a Right-Angled Triangle Number Pattern:
Explanation:
Variables:
int rows
: Holds the number of rows for the pattern.int i, j
: Loop counters.
Input:
- The program prompts the user to enter the number of rows for the pattern.
Outer Loop:
- The outer loop (
for (i = 1; i <= rows; i++)
) controls the number of rows. It runs from1
torows
.
- The outer loop (
Inner Loop:
- The inner loop (
for (j = 1; j <= i; j++)
) controls the numbers printed on each row. It runs from1
toi
, ensuring that the number of printed digits increases with each row.
- The inner loop (
Printing:
- Inside the inner loop, the program prints the current value of
j
. - After the inner loop, a newline (
printf("\n")
) is printed to move to the next row.
- Inside the inner loop, the program prints the current value of
Output:
- Finally, the program displays the number pattern based on the user's input.
Sample Output:
Example 1:
Example 2:
Key Points:
- Nested Loops: The program demonstrates the use of nested loops, which are essential for generating patterns.
- Dynamic Input: The number of rows can be changed by the user, making the program flexible.
- Simple Logic: The program has a straightforward logic that can be easily modified to create different patterns, such as pyramids, inverted triangles, etc.