Print dynamic star pattern using C
Question
Print dynamic star pattern for the given number as given below.
Logic
- Here you can see that star expands in all direction based on the input.
- We must print the star and also the blank spaces to get the desired result.
- Using two functions, we are printing the blanks spaces and gap between stars.
- Try to work out by giving any input. It’s very simple.
Program
#include<stdio.h>; void space();// declaration of function void gap(); void main() { int in=0,len,i,sp,j,p,m,l; printf("enter input"); scanf("%d",&in); len=(in*2)-1;// length of each row/column sp = in-2 ; /*sp ->number of blank spaces 3->1 5 ->2 */ p =sp;// blank spaces starting with sp l=1;// used to print blank spaces // top half of pattern for(i=0;i<len/2;i++) { if(i!=0) // no gap in first row { gap(l); l++; } printf("*"); space(p); printf("*"); space(p); printf("*\n"); p--; } for(m=0;m<len;m++) // center of pattern , print len n0. of stars printf("*"); printf("\n"); p=sp; l=1; //bottom half of pattern for(i=0;i<len/2;i++) { space(p); p--; printf("*"); if(i!=0) { gap(l); } printf("*"); if(i!=0) { gap(l); l++; } printf("*\n"); } } void space(int sp) { // decreasing gap pattern int k; for( k=sp;k>0;k--) { printf(" "); } } void gap(int sp) { int k; // increasing gap pattern for(k =0;k<sp;k++) { printf(" "); } }