Print the Flag Pattern Using For Loop in C Programming
This program is written in the C programming language and it is used to print a diamond shape of asterisks (*) with user-specified size.
- 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" and "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 first 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 1, and the loop continues until "i" is less than or equal to "a".
- The second and third for loops are nested inside the first for loop, and they are used to repeatedly execute the code inside the loop for the number of times specified by the user. The second loop starts with "n" initialized to 1 and it creates the space indentation before the diamond shape, and the third loop starts with "n" initialized to 1 and it prints the asterisks (*) to form the diamond shape.
- The second set of nested for loop starts with i value 1 and it creates the second line of the diamond shape.
- The third set of nested for loops starts with i value 1 and it creates the lower triangle of the diamond shape. The first nested loop creates the space indentation, and the second nested loop prints the asterisks (*)
- Finally, the program is exited by returning 0 from main. This program will print a diamond shape of the user-specified size and the diamond shape will be made of asterisk(*)
Source Code
#include<stdio.h>
int main()
{
int i,n,a;
printf("\nEnter the value:");
scanf("%d",&a);
for(i=1;i<=a;i++)
{
printf("\n");
for(n=1;n<=a;n++)
{
printf(" ");
}
for(n=1;n<=a+3;n++)
{
printf(" *");
}
}
for(i=1;i<=a;i++)
{
printf("\n");
for(n=1;n<=a;n++)
{
printf(" ");
}
printf(" *");
}
for(i=1;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
**********
**********
**********
**********
**********
*
*
*
*
*
*
***
******
*********
***********