To Print Triangle & Pyramid by using for loops
In the realm of C programming, understanding loops is crucial for creating intricate patterns. In this article, we'll explore two programs that utilize for loops to print triangle and pyramid patterns. Let's dive into the code and visualize the patterns it generates.
Program for Triangle
#include<stdio.h>
main()
{
int n, i, j;
printf("Enter how many lines you want : ");
scanf("%d", &n);
for(i = 1; i < = n; i++)
{
for(j = 1; j < = i; j++)
printf("%d \t", i);
printf(" \n ");
}
}
Input: Enter how many lines you want: 4
This program creates a triangle pattern where each line displays the line number, repeating the number of times corresponding to the line number.
Program for Pyramid
#include<stdio.h>
main()
{
int n, i, j, k;
clrscr();
printf("Enter how many lines you want : ");
scanf("%d", &n);
for(i = 1; i < = n; i++)
{
for(k = 0; k < = n - i; k++)
printf(" ");
for(j = 1; j < = i; j++)
printf(" %6d ", i);
printf(" \n ");
}
}
Input: Enter how many lines you want: 4
This program generates a pyramid pattern with each line displaying the line number, and the numbers are right-aligned for aesthetic appeal.
Conclusion:
Understanding loop structures allows programmers to create fascinating patterns. These C programs provide insights into printing triangle and pyramid patterns using for loops. Experiment with different input values to observe variations in the generated patterns. Happy coding!
'
0 Comments