You are here:

C++/analysis of error and update the program where incorrect

Advertisement


Question
Program: Write a program to accept a 2-D array a[4][4]and copy eacch of the element in a 1-D array of b[16]. Example:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1-D ARRAY: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
#include<iostream.h>
#include<conio.h>
void main()
{
   int a[4][4],i,j,k,b[16];
   cout<<"enter array
";
   for(i=0;i<4;i++)
   {
   for(j=0;j<=i;j++)
   {
      cin>>a[i][j];

   }
   }
   for(k=0;k<=15;k++)
   {
      if(i==0)
      {
      if(k==0&&k<=3)
      {
       a[0][j]=b[k];
      }
      }
      else if(i==1)
      {
      if(k==4&&k<=7)
      {
       a[1][j]=b[k]; // 1ST ERROR
      }
      }
      else if(i==2)
      {
      if(k==8&&k<=11)
      {
      a[2][j]=b[k]; //2ND ERROR
      }
      }
      else if(i==3)
      {
      if(k==12&&k<=15)
      {
      a[3][j]=b[k]; //3RD ERROR
      }
      }
   }
   cout<<b[k];
   getch();
}
ERROR 1: INVALID INDIRECTION IN MAIN FUNCTION
ERROR 2: INVALID INDIRECTION IN MAIN FUNCTION
ERROR 3: INVALID INDIRECTION IN MAIN FUNCTION

Answer
#include <iostream>

int main()
{
   int a[4][4] ;

   std::cout << "enter array\n" ;
   for( int row = 0 ; row<4 ; ++row )
       for( int col = 0 ; col < 4 ; ++col )
         std::cin >> a[row][col] ;

   int b[16] ;
   int pos = 0 ;
   for( int row = 0 ; row<4 ; ++row )
       for( int col = 0 ; col < 4 ; ++col )
         b[pos++] = a[col][row] ;

   for( int k = 0 ; k < 16 ; ++k ) std::cout << b[k] << ' ' ;
   std::cout << '\n' ;
}

See: http://ideone.com/g7EJYa  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.