-2
#include <stdio.h>

int main()
{
    //initialize the array
    int arr[7] = {8, 8,6,5,34,57,6};
    //initialize the sum of the array 
    int sum;
    for (int t = 0; t < 7; t++){
        printf("%i", arr[t]);
        printf("\n");
        sum = sum + arr[t];
        printf("The sum of the array is: %i", sum);
        printf("\n");
    }

    return 0;
}

outcome is a bunch of arbitrary gigantic numbers. im trying to basically show the sum of the array at different points within the array.,

Jt Carter
  • 9
  • 2
  • If you compile your code with warnings enabled, your compiler will have told you that `sum` is uninitialized... if you had used lint, likewise... or any good static analyser! – Andrew Apr 14 '22 at 06:16
  • 2
    Stop wasting your time searching for bugs that the compiler has already found for you, by setting up your compiler correctly: [What compiler options are recommended for beginners learning C?](https://software.codidact.com/posts/282565) – Lundin Apr 14 '22 at 06:18
  • 1
    You may also want to read this: [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) – Andreas Wenzel Apr 14 '22 at 06:21
  • 1
    @Lundin: You may also want to add `-Wshadow` to that answer of yours, which you linked to. In my experience, unintentionally declaring variables multiple times in different scopes is a common beginner's mistake. In gcc and clang, `-Wshadow` is not included in `-Wall` or `-Wextra`. Debugging such errors is very hard for a beginner, which makes the compiler warning even more important. – Andreas Wenzel Apr 14 '22 at 06:35

1 Answers1

2

You must initialize sum to 0.

#include <stdio.h>

int main()
{
    int arr[7] = { 8, 8, 6, 5, 34, 57, 6 };

    int sum = 0;

    for (int t = 0; t < 7; t++)
    {
        printf( "%i", arr[t] );
        printf( "\n" );
        sum = sum + arr[t];
        printf( "The sum of the array is: %i", sum );
        printf( "\n" );
    }

    return 0;
}

This program now has the following output:

8
The sum of the array is: 8
8
The sum of the array is: 16
6
The sum of the array is: 22
5
The sum of the array is: 27
34
The sum of the array is: 61
57
The sum of the array is: 118
6
The sum of the array is: 124
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • ooooh its because it doesn't initially have a value, so im adding the number to something thats unknown, thanks so much! – Jt Carter Apr 14 '22 at 06:01
  • 1
    @JtCarter: It does initially have a value, but this value is "indeterminate", to use the official terminology. So yes, you are adding to something that's unknown. You should never rely on a variable having a certain initial value, unless you explicitly initialize it to that value. There are only a few cases in C (such as global variables) in which you can rely on variables being implicitly initialized to `0`. – Andreas Wenzel Apr 14 '22 at 06:05