Home > Software engineering >  Wrong results when assigning to int array in c
Wrong results when assigning to int array in c

Time:11-03

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main(){
    int v[5];
    int a[5][5];
    int i = 0, j = 0;

    for (i = 0; i < 5; i  ){
        v[i] = 0;
        for (j = 0; j < 5; j  ){
            a[i][j] = 0;
            cout << "A[" << i << ", " << j << "] = " << endl;
            cin >> a[i][j];
            v[i] = v[i]   a[i][j];
        }   
        v[i] = v[i] / 5;
    }   

    for (i = 0; i < 30; i  ){
        cout << "v[" << i << "] = " << v[i] << endl;
    }
}

When I remove the v[i] = 0 line just under the first loop the code runs but returns very large numbers. I don't understand how this is happening. Grateful for any help.

Edit: thanks you for all the replies. I think I understand why I got downvotes. To clarify, this is for a beginners course and we were given the bare-bones of the language mostly to train logic. The question itself is pretty nonsensical as it asks us to declare the array as a int despite the fact that the answer is distorted by integer division.

CodePudding user response:

Initializing a value in c like int v[5]; just reserves space. It does nothing to initialize the values to 0 or something. Anything could be in those five indices. Whatever happens to be in that address space.

CodePudding user response:

It's because of garbage values in your array. Your array has a size of 5 but you try to iterate until the 30th value. Hope that helps!

CodePudding user response:

When you remove v[i]=0, that makes v[I]= undefined, and that is what makes v[I] look like really long numbers. Try to initialize every variable which you will use for successive sum.

  •  Tags:  
  • c
  • Related