Print the Triangle Pattern Facing Upside Using For Loop in C Programming
This program is written in the C programming language, and it is used to print a right-angled triangle of asterisks (*) with a user-specified number of rows.
- The program starts by including the standard input/output header file, "stdio.h". Then, the main() function is defined. Inside the main function, three variables are declared: "i", "n" are used as counter variables in the nested for loops, and "a" is used to store the user input value.
- The program then prompts the user to enter a number using the printf() function and stores the value in the "a" variable using the scanf() function. The for loop is then used to repeatedly execute the code inside the loop for the number of times specified by the user. The for loop starts with "i" initialized to 0, and the loop continues until "i" is less than or equal to "a".
- The second for loop is nested inside the first for loop, and it is used to create the indentation before the triangle. The loop starts with "n" initialized to 1, and it continues until "n" is less than or equal to (a-i).
- The third for loop is nested inside the first for loop, and it is used to print the asterisks (*) to form the triangle. The loop starts with "n" initialized to 1 and it continues until "n" is less than or equal to i.
- Finally, the program is exited by returning 0 from main. This program will print a right-angled triangle of the user-specified size and the triangle will be made of asterisks(*).
Source Code
#include<stdio.h>
int main()
{
int i,n,a;
printf("\nEnter the value:");
scanf("%d",&a);
for(i=0;i<=a;i++)
{
printf("\n");
for(n=1;n<=(a-i);n++)
{
printf(" ");
}
for(n=1;n<=i;n++)
{
printf(" *");
}
}
return 0;
}
To download raw file
Click Here
Output
Enter the value:5
*
* *
* * *
* * * *
* * * * *