printf printing strange numbers

Asked

Viewed 28 times

-1

#include <stdio.h>
#include <locale.h>

void main()
{
    int i, n;

    setlocale(LC_ALL, "Portuguese");

    printf("Digite um número: ");
    scanf("%d", &n);
    
    printf("\nSequência decrescente de %d até 1", n);
    for (i=n; i>=1; i--)
    {
        printf("%d\n\n", i);
    }
    printf("Sequência crescente de 1 até %d", n);
    for(i=1; i<=n; i++)
    {
        printf("%d\n\n", i);
    }
}

Exit:

Digite um número: 5

Sequência decrescente de 5 até 15

4

3

2

1

Sequência crescente de 1 até 51  

2

3

4

5

1 answer

0


The problem is in the initial function call printf who does not own the \n at the end to skip the line before starting to display the values to the STDOUT:

printf("\nSequência decrescente de %d até 1", n);

That’s why, when you inserted 5, the message displayed 15, for the first printf called into your loop of repetition for appeared on the same line as printf initial, joining 1 with 5.

Just insert the character \n at the end of their printf outside the loops of repetition, as in the example:

printf("\nSequência decrescente de %d até 1\n", n);

From this, the first printf within the repeat loop will be displayed in a new line.

  • Thank you very much! I let this detail pass

Browser other questions tagged

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