SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Arrays
Exercise:
Self-test Exercises
Question:21 | ISBN:9780321531346 | Edition: 7

Question

Write code that will fill the array a (declared below) with numbers typed

in at the keyboard. The numbers will be input five per line, on four lines

(although your solution need not depend on how the input numbers are

divided into lines).

int a[4][5];

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

//Header section
#include <iostream>

using namespace std;

int main() 
{
    // Declare the 2D array 'a' with dimensions 4 rows and 5 columns.
    int a[4][5];

    // Nested loops to iterate through each element of the array.
    // Outer loop for rows, and inner loop for columns.
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            // Prompt the user to input a number and store it in the array.
            cout << "Enter a number for row " << (i + 1) << ", column " << (j + 1) << ": ";
            cin >> a[i][j];
        }
    }

    // Output the filled array to verify the input.
    cout << "Array 'a' after input:" << endl;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            // Output each element, separated by a space, in the same row.
            cout << a[i][j] << " ";
        }
        // Move to the next row after finishing a row.
        cout << endl;
    }

    return 0;
}

OUTPUT:

Enter a number for row 1, column 1: 10
Enter a number for row 1, column 2: 29
Enter a number for row 1, column 3: 30
Enter a number for row 1, column 4: 40
Enter a number for row 1, column 5: 50
Enter a number for row 2, column 1: 70
Enter a number for row 2, column 2: 99
Enter a number for row 2, column 3: 1
Enter a number for row 2, column 4: 8
Enter a number for row 2, column 5: 9
Enter a number for row 3, column 1: 10
Enter a number for row 3, column 2: 200
Enter a number for row 3, column 3: 50
Enter a number for row 3, column 4: 45
Enter a number for row 3, column 5: 90
Enter a number for row 4, column 1: 88
Enter a number for row 4, column 2: 66
Enter a number for row 4, column 3: 33
Enter a number for row 4, column 4: 22
Enter a number for row 4, column 5: 11

Array 'a' after input:
10 29 30 40 50 
70 99 1 8 9 
10 200 50 45 90 
88 66 33 22 11 

 

0 0

Discussions

Post the discussion to improve the above solution.