Question

Write a program in C++ that defines a two-dimensional array of integers of size 4x4. The...

Write a program in C++ that defines a two-dimensional array of integers of size 4x4. The program will fill the array with values using the equation array_name[j][i] = i+j+2 (j = row index, i = column index). Define a one-dimensional array of size 4. The one-dimensional array should be filled with the values along the main diagonal of the two-dimensional array.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I've written the code in c++ as per requirements of the question. I've also commented it for easy understanding.

Code

#include<iostream>

using namespace std;

int main(){

    //declaring array

    int array_name[4][4];

    //for each row

    for(int row=0;row<4;row++){

        //for each column

        for(int col=0;col<4;col++){

            array_name[row][col]=row+col+2; //set array value as required

            //row and col in c++ start at 0

        }

    }

    //printing the matrix

    cout<<"Array_Names\n";

    for(int row=0;row<4;row++){

        for(int col=0;col<4;col++){

            cout<<array_name[row][col]<<" ";

        }

        cout<<endl;

    }

    //diagonal array to hold elements of main diagonal

    int diagonal[4];

    int index=0;

    int row=0,col=0;

    //while row and column are within limits

    while(row<4 && col<4){

        //set values of diagonal

        diagonal[index]=array_name[row][col];

        //increment index

        index++;

        //row and column both increase since diagonal move require increased row and column

        row++;

        col++;

    }

    //printing the diagonal array

    cout<<"Diagonal\n";

    for(int index=0;index<4;index++)

        cout<<diagonal[index]<<" ";

}

Output

For Indentation Purpose

Add a comment
Know the answer?
Add Answer to:
Write a program in C++ that defines a two-dimensional array of integers of size 4x4. The...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT