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:9 | ISBN:9780321531346 | Edition: 7

Question

Write some C++ code that will fill an array a with 20 values of type int read in from the keyboard. You need not write a full program, just the code to do this, but do give the declarations for the array and for all variables.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

//Header section
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 20; // Size of the array
//main program
int main()
{
    int a[ARRAY_SIZE]; // Declaration of the array
    int value; // Variable to hold the input value
    //Read input from the user
    cout << "Enter " << ARRAY_SIZE << " integer values:\n";
    
    for (int i = 0; i < ARRAY_SIZE; i++) {
        cout << "Value " << i + 1 << ": ";
        cin >> value;
        a[i] = value; // Store the input value in the array
    }
    //Display output
    cout << "Array a:\n";
    for (int i = 0; i < ARRAY_SIZE; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
    
    return 0;
}

OUTPUT OF THE PROGRAM CODE:

Enter 20 integer values:
Value 1: 5
Value 2: 10
Value 3: -3
Value 4: 7
Value 5: 2
Value 6: 0
Value 7: -8
Value 8: 15
Value 9: 4
Value 10: 9
Value 11: 12
Value 12: -6
Value 13: 3
Value 14: -1
Value 15: 20
Value 16: 17
Value 17: -9
Value 18: 6
Value 19: 1
Value 20: -5
Array a:
5 10 -3 7 2 0 -8 15 4 9 12 -6 3 -1 20 17 -9 6 1 -5
0 0

Discussions

Post the discussion to improve the above solution.