C Program Pattern
C Program to Display a Diamond Pattern Using Asterisks
Example:
#include <stdio.h>
int main()
{
int n,a, k;
printf("Enter number of rows\n");
scanf("%d", &n);
for (k = 1; k <= n; k++)
{
for (a = 1; a <= n-k; a++)
printf(" ");
for (a = 1; a <= 2*k-1; a++)
printf("*");
printf("\n");
}
for (k = 1; k <= n - 1; k++)
{
for (a = 1; a <= k; a++)
printf(" ");
for (a = 1 ; a <= 2*(n-k)-1; a++)
printf("*");
printf("\n");
}
return 0;
}
C Program to Display a Diamond Pattern Using Asterisks
Explain Program
Step :1
#include <stdio.h>
input-output use printf() & scanf() function.
int main()
The entry point of the C program. All execution .
int n, a, k;
Three integer variables are declared:
n: Number of rows for the top half of the diamond.
k: Loop counter for rows.
a: Loop counter for columns
printf("Enter number of rows\n");
scanf("%d", &n);
user to enter an integer (n).
numbers determines the height of the top half diamond.
for (k = 1; k <= n; k++)
{
for (a = 1; a <=
n-k; a++)
printf("
");
for (a = 1; a <=
2*k-1; a++)
printf("*");
printf("\n");
}
This loop print the upper half of the diamond
Outer loop (k = 1 to n)
Each iteration of k represents one row.
First inner loop (a = 1 to n - k):Prints leading spaces to center-align the stars.
Example: If k = 1, it prints n - 1 spaces.
Spaces decrease as you move down (k increases).
Second inner loop (a = 1 to 2*k - 1):
Prints the stars on each line.
Stars increase by 2 in each row: 1, 3, 5, 7, ...
Step :6
printf("\n");
After each row
for (k = 1; k <= n - 1; k++)
{
for (a = 1; a <=
k; a++)
printf("
");
for (a = 1 ; a <=
2*(n-k)-1; a++)
printf("*");
printf("\n");
}
Outer loops
(k = 1 to n - 1)
1 to n - 1 to the middles row already
printed to the top part.
First inner loop (a = 1 to k):
Prints leading spaces, which increase with each row.
Second inner loop (a = 1 to 2*(n-k) - 1):
Prints the stars.
Number of stars decreases by 2 in each row: 2*(n-k)-1
C Program to Display a Diamond Pattern Using Asterisks
Output:
Related Post :-
No comments:
Post a Comment