Home > Mobile >  Why it shows me the same exact output everytime?
Why it shows me the same exact output everytime?

Time:10-09

Actually, I want to use the TOTAL line in the commented position but everytime I'm trying to do this it shows me the output is 16, no matter what input I give in there.

#include <stdio.h>
int main()
{
    int num_1, num_2, total ;

    // If "total = num_1   num_2 ;" is here then everytime it shows the sum is 16....WHY ?

    printf("Please enter num_1 : ") ;
    scanf("%d", &num_1);

    printf("\nPlease enter num_2 : ") ;
    scanf("%d", &num_2) ;

    printf("\nThe sum is : %d\n", total) ;
    total = num_1   num_2 ;

    return 0 ;
}

CodePudding user response:

When your program starts, total, num_1, and num_2 are uninitialized, containing garbage values.

Your commented line would assign to total before scanf reads values into num_1 and num_2, so it will add those garbage values together.

You currently assign to total after printing it, which also means the program will display a garbage value.

Move the assignment to after both calls to scanf:

#include <stdio.h>

int main(void) {
    int num_1, num_2, total;

    printf("Please enter num_1 : ");
    scanf("%d", &num_1);

    printf("Please enter num_2 : ");
    scanf("%d", &num_2);

    total = num_1   num_2;

    printf("The sum is : %d\n", total);
}
  •  Tags:  
  • csum
  • Related