Swaroop Sampath Swaroop Sampath - 1 month ago 14
C++ Question

The values are getting stored in "arr" correctly but garbage values are getting stored in "str". I do not understand why

The values are getting stored in "arr" correctly but garbage values are getting stored in "str". I do not understand why. I checked it many times and it seems right to me.

#include <iostream>
using namespace std;

int main() {
int test,n,arr[50],str[20][20],i,j,k;
t = 0;
j = 0;
cin>>test; //test cases
while(test>0){
cin>>n; //number of elements in a test case
for(i=0;i<n;i++)
cin>>arr[i]; //array of elements
for(i=0;i<n;i++){
cout<<"arr = "<<arr[i]<<"\n";
str[i][j] = arr[i]; // storing arr in str
}
cout<<"\n";
str[i+1][j] = 0;
j++;
test--;
}
for(i=0;i<j;i++){
for(k=0;str[i][k]!=0;k++)
cout<<<<str[i][k]; // printing str
cout<<"\n";
}
return 0;
}

Answer Source

There are a lot of mistakes but the main one is the indexing of a 2d array

A two dimensional array is like this arr [row] [column] and you have been using it like arr [column] [row]

 str[i][j] = arr[i];

see what u are doing is storing a number at every row

maybe this image will clear things out

enter image description here

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

int main() {
    int test,n,arr[50],str[20][20],i,j,k;
    j = 0;
    cin>>test; //test cases
    int temp = test ;
    while(test>0)
    {
        cin>>n; //number of elements in a test case 

        for(i=0;i<n;i++)
            cin>>arr[i]; //array of elements

        for(i=0;i<n;i++)
        {
            cout<<"arr = "<<arr[i]<<"\n";
            str[j][i] = arr[i]; // storing arr in str
        }

        str[j][i] = '\0';
        cout<<"\n";

        j++;
        test--;
    }

    for ( int i = 0 ; i < temp ; i++ )
    {
        j=0 ;
    while ( str[i][j] != '\0')
       {
           cout<<str[i][j];  // printing str
            j++ ;
        }
        cout<<"\n";
    }
    cin.ignore(5) ;
    return 0;
}