-1

I made a program to sum all the integers out of any given number, but when i use zero as the number i get a huge negative number that increases as i keep running the program...for example given 123 for scanf function the program should return 6.

When i input 0 for the scanf function i get -402438064 then i run the program again with 0 and get -294000560. any explanation as to why its working this way?

#include <stdio.h>

int main(void) {
    int num, lnum, last_result;
    printf("ENTER A NUMBER:\n");
    scanf("%i", &num);

    do {
        lnum = num % 10;
        num /= 10;
        last_result += lnum;
    }
    while (num != 0);
    printf("%i\n", last_result);
    return 0;
}

2 Answers2

0

As explained in the comment, last_result was uninitialized. To be clear about this, if you don't manually set it to 0, the value could be anything, and adding it to last_result is undefined since the standard doesn't insist declared variables are 0-initialized.

#include <stdio.h>

int main(void) {
    int num, lnum;
    int last_result = 0; // 0-initialized on a new line to make it clear.
    printf("ENTER A NUMBER:\n");
    scanf("%i", &num);

    do {
        lnum = num % 10;
        num /= 10;
        last_result += lnum;
    } while (num != 0);
    printf("%i\n", last_result);
    return 0;
}
Daniel
  • 854
  • 7
  • 18
0

Compile this and run it:

#include <stdio.h>

int main(void)
{
    int x, y, z;

    printf("%d, %d, %d\n", x, y, z);
    return 0;
}

Output on my machine:

240689618, 32766, -344466744

As others have said, you have to initialize variables before use. A properly configured compiler would warn you about this. I recommend telling your compiler to report all warnings and treat warnings as errors. With GCC, you can use something like

gcc -Wall -Werror -o program program.c