-1
long long int a[n][n];
long long int i,j;
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        cin >> a[i][j];
    }
}

long long int s,f=0;
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        s=s+a[j][i];
    }
    cout<<s<<endl;
}

this is my code. to find sum of all columns of a matrix. but it is giving wrong answer for 13*13 matrix

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 3
    You never initialized `s` so it started with a random garbage value and caused Undefined Behavior. – drescherjm Sep 17 '20 at 12:31
  • 2
    `s` is used uninitialized, your code has undefined behavior. Look at your compilers warnings – 463035818_is_not_an_ai Sep 17 '20 at 12:31
  • 4
    also, not the problem, and actually I am not 100% certain if you are using VLAs, but chances are high, so read here: [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). – 463035818_is_not_an_ai Sep 17 '20 at 12:33
  • 2
    if you use `std::vector` and `std::accumulate` many potential mistakes will be gone. Though, unfortunately the mistake you made here you could make as well with `std::vector` + `std::accumulate` (its just a tiny bit harder to make it) – 463035818_is_not_an_ai Sep 17 '20 at 12:36
  • Why do you have the `f` variable? If you deleted `,f` your code would be fixed because it would initialize `s` to zero. – drescherjm Sep 17 '20 at 12:51
  • Turn on compiler warnings, read compiler warnings, understand compiler warnings, fix compiler warnings. – Goswin von Brederlow Sep 17 '20 at 14:26

1 Answers1

0
long long int a[n][n];
long long int i,j;
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        cin >> a[i][j];
    }
}

long long int s=0,f=0;  //Put some value in S otherwise it will get a junk value
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        s=s+a[j][i];
    }
    cout<<s<<endl;
}

A better way would be to use Vectors instead of arrays

vector<vector<int> > a( n , vector<int> (n));
long long int i,j;
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        cin >> a[i][j];
    }
}

long long int s=0,f=0;  //Put some value in S otherwise it will get a junk value
for(i=0; i<n; i++) {
    for(j=0; j<n; j++) {
        s=s+a[j][i];
    }
    cout<<s<<endl;
}
Mohit Sharma
  • 338
  • 2
  • 13
  • thank u! using vector solved my problem. and i had initialised S with 0 , while trying to correct my code but it didnt help using vectors instead helped tho! – SHIVANI SINGH Sep 18 '20 at 15:00