In this article, we will show how to write a C program to print the Alphabet K pattern or shape of stars using for loop, while loop, and functions.
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int rows, n;
printf("Enter Rows = ");
scanf("%d",&rows);
n = rows / 2;
for (int i = 0 ; i < rows; i++ )
{
printf("*");
for (int j = 0 ; j <= n; j++ )
{
if (j == abs(n - i))
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Enter Rows = 16
* *
* *
* *
* *
* *
* *
* *
* *
**
* *
* *
* *
* *
* *
* *
* *
Instead of a for loop, this Alphabet K Pattern of stars program uses a while loop to iterate the rows and columns. For more star programs, click here.
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i, j, rows, n;
printf("Enter Rows = ");
scanf("%d",&rows);
n = rows / 2;
i = 0 ;
while ( i < rows )
{
printf("*");
j = 0 ;
while ( j <= n )
{
if (j == abs(n - i))
{
printf("*");
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}
return 0;
}
Enter Rows = 11
* *
* *
* *
* *
* *
**
* *
* *
* *
* *
* *
In this C program, we create an alphabetKPat function that accepts those values and prints the Alphabet K shape or pattern of the given char.
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
void alphabetKPat(int rows, char a)
{
int n = rows / 2;
for (int i = 0 ; i < rows; i++ )
{
printf("%c", a);
for (int j = 0 ; j <= n; j++ )
{
if (j == abs(n - i))
{
printf("%c", a);
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
int rows;
char a;
printf("Enter Alphabet = ");
scanf("%c", &a);
printf("Enter Rows = ");
scanf("%d",&rows);
alphabetKPat(rows, a);
return 0;
}