w3resource

C Exercises: Reads the side of a square and prints square using hash (#) character


Print a filled square of size nnn using #

Write a C program that reads the side (side sizes between 1 and 10 ) of a square and prints square using hash (#) character.

Sample Input: 10

Sample Solution:

C Code:

#include<stdio.h>
int main()
{
    int size, i, j; // Declare variables for size and loop counters
    
    // Prompt user for the size of the square
    printf( "Input the size of the square: \n" );
    scanf( "%d", &size );
    
    // Check if the size is within the valid range
    if(size < 1 || size > 10) {
        printf("Size should be in the range 1 to 10\n"); // Print error message
        return 0; // Exit the program
    }
    
    // Loop for rows
    for(i=0; i<size; i++) {
        // Loop for columns
        for(j=0; j<size; j++) {
            printf(" #"); // Print a space and a #
        }
        printf("\n"); // Move to the next line after completing a row
    }

    return 0; // Indicate successful program execution
}

Sample Output:

Input the size of the square: 
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #
 # # # # # # # # # #

Pictorial Presentation:

C Programming: Reads the side of a square and prints square using hash character.


Flowchart:

C Programming Flowchart: Reads the side of a square and prints square using hash character.


For more Practice: Solve these Related Problems:

  • Write a C program to print a filled square of a given size using nested loops and formatted output.
  • Write a C program to print a filled square pattern with a border of asterisks and the inside filled with hashes.
  • Write a C program to generate a square pattern of a user-specified size with alternate rows filled with '#' and '*'.
  • Write a C program to print a filled square using recursive function calls to draw each row.

Go to:


PREV :Generate a table with x,x+2,x+4 using loops.
NEXT : Print a hollow square of size nnn using #.

C programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.