Why is an asterisk left?

4

I want the number of rows and columns in the output of my program equal to the given input . Why is the latter left over??

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; }

    }
}

Output:

TELL ME THE NUMBER YOU WANT
4
****
****
****
****
*
    
asked by anonymous 13.12.2016 / 03:06

3 answers

9

I will not even try to solve the problem in this code because it is too confusing and maybe the problem was born of confusion. The simpler you can do, the better. Even if you want to learn some specific concept with this type of code, it is best to learn in a case where it would be needed. If someone asked to do it this way, 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 out of function unnecessarily . Always declare as close as possible to where it will be used. There are people who do not see the value of this, but it creates a greater cognitive ability to do simpler things. If you need the variable just inside the loop, create it inside the loop .

If you have two vectors to consider, create two loops, which is the natural way to do this. This is the structured way to make this code. The original knotted the head. Even a for loop is much more natural for the case.

There was a column variable of type char . Or it makes the line also char and limits the number of asterisks to 127, leaves int in both. I left int because there is no real gain in using char there, even if it only wants low values, which is not even validated, either because 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");
    }
}

See running on ideone and on Coding Ground >.

    
13.12.2016 / 10:27
4

At each while loop, you first start the * and then check if you have reached the limit (row == n). Simply place the print below the end-of-loop checks 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("*");

    }
}
    
13.12.2016 / 03:17
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 pair of nested loops rather than the current logic.

Some other advice:

  • Avoid giving #include in headers if you are not going to use the functions.
  • When executing a function of type scanf() , always check the value returned to make sure the execution was successful.
  • Use comments to make your intentions clearer for anyone reading.
  • Maintain a consistent pattern of indentation:
    • Go up one level after each {
    • Go down one level after each }
  • It is also advisable to 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 output generated:

TELL ME THE NUMBER YOU WANT: 
4
****
****
****
****
    
13.12.2016 / 15:43