meiryo
meiryo

Reputation: 11697

Print a square pattern full of "#" using two while loops

Given an input, I want to print a square like this:

Enter number: 5
#####
#####
#####
#####
#####

My attempt:

int n;
int col=0;
int row=0;
//user input blah blah

    while  (col < n) {
        while (row < n) {
            printf("#");
            row++;
        }
        col++;
        printf("\n");
    }

But it isn't printing what I'm expecting... can anyone fix this?

EDIT: The actual output looks like this (followed by 4 \n characters, SO doesn't seem to display it).

#####

Upvotes: 1

Views: 8524

Answers (5)

James Bear
James Bear

Reputation: 444

Why not simpler? Math expressions are often more precise than controls.

In [1]: n = 5

In [2]: s = ('#'*n+'\n')*n

In [3]: print(s)
#####
#####
#####
#####
#####

Upvotes: 0

Pankaj Prakash
Pankaj Prakash

Reputation: 2428

Here's the code for printing square pattern in C filled with "#"

i=1;
while(i<=n)
{
    j=1;
    while(j<=n)
    {
        printf("#");
        j++;
    }
    printf("\n");
    i++;
}

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340316

typo.pl's answer solves the immediate problem, but I'd like to point out a couple things:

  1. this is the kind of loop control construct that for loops are designed for. The initialization and increment are packaged up in the loop control instead of being scattered wherever you (or that other guy) might decide to put it.

  2. you've switched the logic for row control and col control. That doesn't matter here since you have the same number of each. But when it's time to add rectangle support, it's going to cause a moment of confusion for someone. And if it's homework, it'll probably mean a couple points off.

So:

for (row = 0; row < n; ++row) {
    for (col = 0; col < n; ++col) {
        printf("#");
    }
    printf("\n");
}

Upvotes: 2

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

You need to reset row after the first while loop, otherwise it'll already be n.

Upvotes: 1

typo.pl
typo.pl

Reputation: 8942

while  (col < n) {
    while (row < n) {
        printf("#");
        row++;
    }
    col++;
    printf("\n");
    row = 0; // <<< THIS HELPS
}

Upvotes: 3

Related Questions