Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrong results when assigning to int array in c++

#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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading