Close
Close

4.Print the following pattern on the screen **** ** * ** ****

   AbhinavBanisetti

practice questions for C programming


Answers

  •   

    Since this question was in the practice section of the first topic, I am assuming you don’t want to use any loop to print the pattern. Hence you can just print the pattern as shown below.

    #include <stdio.h>
    
    int main() {
    	printf("* * * *\n");
    	printf("  * *\n");
    	printf("   *\n");
    	printf("  * *\n");
    	printf("* * * *\n");
    	return 0;
    }
    

    Otherwise, you can print the pattern using the following code.

    #include <stdio.h>
    #include <math.h>
    
    int main(void) {
    	int i, j, k;
    	
    	// printing 1st three rows
    	for(i=0; i<=2; i++) {
    		// printing spaces before first star in each row
    		for(k=i+1; k>0; k--) {
    			if(i>0) {
    				printf(" ");
    			}
    		}
    		// printing stars in each row
    		for(j=pow(2, (2-i)); j>0; j--) {
    			printf("* ");
    		}
    		printf("\n"); 
    	}
    	
    	// printing fourth and fifth rows
    	for(i=1; i>=0; i--) {
    		// printing spaces before first star in each row
    		for(k=i+1; k>0; k--) {
    			if(i>0) {
    				printf(" ");
    			}
    		}
    		// printing stars in each row
    		for(j=pow(2, (2-i)); j>0; j--) {
    			printf("* ");
    		}
    		printf("\n"); 
    	}
    	return 0;
    }
    

     



Ask Yours
Post Yours
Write your answer