Why is there an asterisk left?

Asked

Viewed 216 times

4

I want the number of rows and columns to be equal to input data. Why is this last *?

Code:

#include<stdio.h>
#include<math.h>
int row = 0;
char column = 0;
int n;


int main ( void )
{
    printf("TELL ME THE NUMBER YOU WANT: \n");
    scanf("%d", &n);

    while ( column <= n ){
        printf("*");
        column = column + 1;

        if ( column == n ){
            printf("\n");
            row = row + 1;
            column = column - n;
        }
        else if ( row == n ){
            break; }

    }
}

Exit:

TELL ME THE NUMBER YOU WANT
4
****
****
****
****
*

3 answers

9


I’m not even going to try to solve the problem in this code because it’s too confusing and maybe the problem was born out of confusion. The simpler you can do it, the better. Even if you want to learn a specific concept from this type of code, it is best to learn in a case where it would be necessary. If someone asked to do so, the person did a disservice to you. It would be a useless and unproductive requirement. and I would argue that this form is disadvantageous.

Do not declare variables outside the function without need. Always state as close as possible to where it will be used. Some people don’t see the value of this, but it creates a greater cognitive capacity to do simpler things. If you only need the variable inside the loop, create it inside the loop.

If you have two vectors to consider, create two loops, it’s the natural way to do this. This is the structured form to make this code. The original knots in the head. Including a loop for is much more natural to the case.

There was a column variable of type char. Or make the line char and limits the number of asterisks to 127, int in both. I left int because there is no real gain in using char there, even if only want low values, which in fact is not even validated, because the scanf() is not very suitable for this. Be consistent.

I gave an organized one. It is very difficult to understand what the code does in written form.

Once this is done, the code becomes too simple.

#include<stdio.h>

int main(void) {
    printf("TELL ME THE NUMBER YOU WANT: \n");
    int n;
    scanf("%d", &n);
    for (int row = 0; row < n; row++) {
        for (int column = 0; column < n; column++) printf("*");
        printf("\n");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Man, thank you so much! I am a beginner and am learning on my own, your advice will help me a lot... I myself realized that " aesthetically" was strange what I had done, but I could not do otherwise, unfortunately...

4

With each while "loop", you first print the * and then check if you reached the limit (Row == n). Simply place the print below the end checks of the loop that your problem solves.

#include<stdio.h>
#include<math.h>
int row = 0;
char column = 0;
int n;


int main ( void )
{
    printf("TELL ME THE NUMBER YOU WANT: \n");
    scanf("%d", &n);

    while ( column <= n ){

        column = column + 1;

        if ( column == n ){
            printf("\n");
            row = row + 1;
            column = column - n;
        }
        else if ( row == n ){
            break; }

        printf("*");

    }
}

3

The question code does not take into account that, in this algorithm, the value of row changes less frequently than column. Therefore, it would be better to use a couple of nested loops instead of the current logic.

Some other advice:

  • Avoid giving #include in headers if you will not use the functions.
  • When performing a function of type scanf(), always check the value returned to make sure the execution was successful.
  • Use comments to make your intentions in code clearer to anyone reading.
  • Maintain a consistent indentation pattern:
    • Climb a level after each {
    • Descend one level after each }
  • Is also advisable avoid global variables in most cases. And also initialize your local variables.

Code:

#include <stdio.h>   // scanf(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE
//#include <math.h>

// usar um valor definido dá significado à "números mágicos" no seu código
// e facilita mudar os valores mais tarde, se necessário
#define MAX_COLUMNS (80)

int main ( void )
{
    size_t n = 0;  

    printf("TELL ME THE NUMBER YOU WANT: \n");
    if( 1 != scanf("%lu", &n) )  // se um valor < 0 não for permitido, use unsigned int
    {
        perror( "scanf não registrou um unsigned int" );
        exit( EXIT_FAILURE );
    }

    // else implícito, com scanf bem-sucedido

    // verifique o valor de entrada. Nunca confie que o usuário sabe o que está fazendo
    if( MAX_COLUMNS < n )
    {
        printf( "O valor de entrada deve ser %lu. Você usou: %lu\n", (size_t)MAX_COLUMNS, n );;
        exit( EXIT_FAILURE );
    }

    // else implícito, valor inserido menor que o máximo permitido

    for( size_t row = 0; row < n; row++ )
    {
        for( size_t column = 0; column < n; column++ )
        {
            printf("*");
        }

        printf("\n");
    }
} // fim de função: main

This is the generated output:

TELL ME THE NUMBER YOU WANT: 
4
****
****
****
****
  • 4

    I translated the post to Portuguese but I must say that, as in the question, I do not know very well how I feel about the English excerpts in the code (within the printfs, for example). So I translated the new ones here, and left some old ones that were already in the question

Browser other questions tagged

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