Loop "while" ending earlier than expected

Asked

Viewed 56 times

0

The question says the following:

Write a program that reads the side of a square and then print the square with asterisks. Your program should work with squares of all sizes between 1 and 20. For example, if your program reads a size 4, it should print out

****
****
****
****

Even that part of the book I’m reading didn’t mention for or do ... while, only while. So I made this code. I’m starting now but I think it should have worked.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int contador=1, linha=1, valor=0;
    printf("entre com o valor:\n\n");
    scanf("%d", &valor);
    
    
    while (contador<=valor && linha<=valor) {
        printf("*");
        contador++;
    }

    printf("\n");
    contador = 1;
    linha++;
    return 0;
}

I don’t understand if I put at the end of the command while which accountant should go back to 1, the loop should not start again?

If you could tell me what I should study to fix this code, I’d appreciate it.

2 answers

1


There are two logic problems in your code:

  1. The while loop only the commands inside the keys, thus the lines where you update the values of the variables contador and linha are not being executed;
  2. When using the condition contador <= valor && linha <= valor, the moment any of the conditions are false, you will leave the while, then will only print a line with asterisks.

One solution is to use two loops while nested:

while (linha <= valor){ // Percorre as linhas
    while (contador <= valor) { // Percorre as colunas
        printf("*");
        contador++;
    }
    printf("\n");
    contador = 1;
    linha++;
}
  • obg for telling where I went wrong. after seeing the problem it seemed very obvious kkk. obg

0

First of all, you’re not putting contador=1 within the while, but within the main. A simple way to do what you want is to use 2 nested loops, this way:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i=1, j=1, valor=0;
    printf("entre com o valor:\n\n");
    scanf("%d", &valor);

    while(i <= valor) {
        j = 1;
        while(j <= valor){
            printf("*");
            j++;
        }
        printf("\n");
        i++;
    }
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.