Open In App

How to Take Input in Array in C++?

Last Updated : 05 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Arrays in C++ are derived data types that can contain multiple elements of the same data type. They are generally used when we want to store multiple elements of a particular data type under the same name.

We can access different array elements using their index as they are stored sequentially in the memory. We can also assign some value to these elements using their index and to assign the user-provided input value, we have to use cin or scanf().

But instead of accessing a single element to take input in an array, we use a loop to iterate over the array elements and take input from the user for each element.

C++ Program to Take User Input in an Array

The following C++ program uses a for loop and cin to take input from the user and insert it in the array.

C++




// C++ program to demonstrate how to take input in an array
#include <iostream>
using namespace std;
  
// driver code
int main()
{
    // defining array size
    int size = 5;
    // defining array of size "size"
    int numbers[size];
  
    // using loop to move to every array element and then
    // using either cin to insert the value given by the
    // user to the array element
    for (int i = 0; i < size; i++) {
        cout << "Enter a number: ";
        cin >> numbers[i];
    }
  
    // Print the array elements
    cout << "The array elements are: ";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
  
    return 0;
}


Output

Enter a number: 1 
Enter a number: 1 1
Enter a number: 5 
Enter a number: 8 
Enter a number: 7
Array elements are: 1 11 5 8 7

C++ Program to Take User Input in an Array using scanf()

We can also use scanf() function to take input but then we have to specify the type of data and pass the address of the array element using & operator.

C++




// C++ program to demostrate how to take input to array
// using scanf()
#include <cstdio>
#include <iostream>
  
using namespace std;
  
// driver code
int main()
{
    // creating an array of size "size"
    int size = 5;
    int array[size];
  
    // going to each element and assigning the value entered
    // by the user
    for (int i = 0; i < size; i++) {
        cout << "Enter the element: ";
        scanf("%d", &arr[i]);
    }
  
    // printing the array
    cout << "The Array elements are: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << ' ';
    }
  
    return 0;
}


Output

Enter a number: 6
Enter a number: 1
Enter a number: 22
Enter a number: 99
Enter a number: 8
Array elements are: 6 1 22 99 8



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads