I keep getting random numbers using scanf and printf when i run my programm and i dont know why

0 votes
asked Oct 28, 2019 by Tarek Abla (130 points)
im working on simple structure of a Programm that is supposed to sum the digits of a given number.

im using scanf  so that the user can put the values himself in the following form:

int x;

printf("put the first Digit if the number : %d",x);

scanf("%d",&x);

but i keep getting random values sometimes negative sometimes positive and i dont know why

can someone please help me

thanks in advanced

1 Answer

0 votes
answered Oct 28, 2019 by gameforcer (2,950 points) 1 flag

That"s because you're first trying to print out a variable that has no value assigned to it and only then you try to put some value in it. Before scanf line in your code x has no value so it just prints out garbage from memory turned into some bizarre value.

 Depending on what you need do either one of these:

    int x;
    
    scanf("%d",&x);
    printf("put the first Digit if the number : %d",x);

    int x = 0;
    
    printf("put the first Digit if the number : %d",x);
    scanf("%d",&x);

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...