0

Problem in result of two version of C code

What's difference between result of these codes : #include <stdio.h> int main() { int n = 10; int a, S, i; i = 0; S = 0; while(i<n) { printf("Enter a number: "); scanf("%d",&a); S+=a; i++; } printf("\nSum of numbers = %d\n\n",S); return 0; } ------------------------------------------------------------------------------------------------------ #include <stdio.h> int main() { int n = 10; int a, S, i; i = 0; while(i<n) { printf("Enter a number: "); scanf("%d",&a); S+=a; i++; } printf("\nSum of numbers = %d\n\n",S); return 0; } ------------------------------------------------------------------------------------------------------ for example if you give 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 to "a" : code #1 give you 55. code #2 give you 57 or another number. in other word what changes when there is "S = 0;" in code?

28th Dec 2018, 6:24 PM
Hemmat
Hemmat - avatar
3 Respostas
+ 1
Since S in first code in not initialized that means it could be filled with a garbage value. So there's a change that S is not start from 0. Thats why we need to initialize the variable
28th Dec 2018, 6:37 PM
Taste
Taste - avatar
0
thank you but what's garbage value ? How is S filled when we did not initialize it?
29th Dec 2018, 10:08 AM
Hemmat
Hemmat - avatar
0
Its just leftover from another procress in memory
29th Dec 2018, 10:26 AM
Taste
Taste - avatar