How to Take Input in Array in C++?
Last Updated :
05 Oct, 2023
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++
#include <iostream>
using namespace std;
int main()
{
int size = 5;
int numbers[size];
for ( int i = 0; i < size; i++) {
cout << "Enter a number: " ;
cin >> numbers[i];
}
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++
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int size = 5;
int array[size];
for ( int i = 0; i < size; i++) {
cout << "Enter the element: " ;
scanf ( "%d" , &arr[i]);
}
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
Share your thoughts in the comments
Please Login to comment...