Back to C++
2026-04-296 min read

Example 2: Take Inputs from User and Store Them in an Array

Learn Example 2: Take Inputs from User and Store Them in an Array step by step with clear examples and exercises.

Why This Matters

In this lesson, we will delve into an essential aspect of C++ programming: taking user inputs and storing them in an array. This skill is crucial for various applications, including data processing, interactive programs, and more. By learning how to handle user input and manage arrays effectively, you will be well-prepared for tackling real-world projects.

Prerequisites

Before proceeding with the core concept, ensure a solid understanding of the following topics:

  1. C++ basics (variables, operators, control structures)
  2. Standard Input/Output (std::cin, std::cout)
  3. Basic data types (int, float, char, etc.)
  4. Understanding of arrays and their basic operations
  5. Familiarity with conditional statements (if-else, switch)
  6. Knowledge of mathematical functions (e.g., pow, sqrt)
  7. Comprehension of string manipulation (std::string, std::getline)

Core Concept

Arrays in C++ are collections of elements of the same data type stored in contiguous memory locations. They can be declared using square brackets []. Here's an example:

int numbers[5]; // Declare an array named 'numbers' with 5 elements

To store user input into the array, we can use a loop to read data from standard input (std::cin) and assign it to each element in the array. Here's a more detailed example:

#include <iostream>
using namespace std;

int main() {
int numbers[5]; // Declare an array named 'numbers' with 5 elements
int n; // Variable to store the number of elements in the array

cout << "Enter the number of integers you want to enter: ";
cin >> n; // Read user input for the number of elements

if (n > 5) {
cout << "Array size cannot exceed 5.\n";
return -1;
}

cout << "Enter " << n << " integers, one at a time:\n";
for (int i = 0; i < n; ++i) {
cout << "Number " << i + 1 << ": ";
cin >> numbers[i]; // Read user input and store it in the array
}

cout << "\nThe numbers you entered are:\n";
for (int i = 0; i < n; ++i) {
cout << "Number " << i + 1 << ": " << numbers[i] << '\n'; // Print the stored values
}

return 0;
}

In this example, we first declare an array numbers and a variable n to store the number of elements. We then ask the user for the number of elements they want to enter and check if it's within the array size limit. If so, we read user input and store it in the array. After that, we print out the stored values.

Array Initialization

It's also possible to initialize arrays with specific values during declaration:

int numbers[5] = {1, 2, 3, 4, 5}; // Declare an array named 'numbers' with 5 elements and initial values

Worked Example

Let's explore a more complex worked example that calculates the sum of the squares of the numbers entered by the user:

#include <iostream>
#include <cmath> // Include header file for mathematical functions like pow and sqrt
using namespace std;

int main() {
int numbers[5]; // Declare an array named 'numbers' with 5 elements
int sum = 0; // Initialize a variable to store the sum of squares
int n; // Variable to store the number of elements in the array

cout << "Enter the number of integers you want to enter: ";
cin >> n; // Read user input for the number of elements

if (n > 5) {
cout << "Array size cannot exceed 5.\n";
return -1;
}

cout << "Enter " << n << " integers, one at a time:\n";
for (int i = 0; i < n; ++i) {
cout << "Number " << i + 1 << ": ";
cin >> numbers[i]; // Read user input and store it in the array

sum += pow(numbers[i], 2); // Calculate the square of each number and add to the sum
}

cout << "\nThe sum of the squares of the numbers you entered is: " << sum << '\n'; // Print the calculated sum

return 0;
}

In this example, we first declare an array numbers, a variable sum, and another variable n. We then ask the user for the number of elements they want to enter and check if it's within the array size limit. If so, we read user input, calculate the square of each number, add it to the sum, and print out the calculated sum.

Common Mistakes

  1. Forgetting to initialize the array before reading user input:
int numbers[5]; // Declare an array named 'numbers' with 5 elements
cin >> numbers; // This will not work!

To fix this, make sure you initialize each element in the array before trying to read data into it.

  1. Reading more input than there are elements in the array:
int numbers[5];
for (int i = 0; i < 10; ++i) { // Read 10 integers, but we only have an array of 5!
cin >> numbers[i];
}

To fix this, make sure the loop counter does not exceed the number of elements in the array.

  1. Forgetting to include the header file ``:
#include <stdio.h> // This includes C-style I/O functions instead of C++ ones!
int main() {
int numbers[5];
cin >> numbers; // This will not work!
}

To fix this, make sure to include the correct header file for mathematical functions.

Common Mistakes (continued)

  1. Not handling invalid user inputs (e.g., non-numeric values):
int numbers[5];
for (int i = 0; i < 5; ++i) {
cin >> numbers[i]; // This will not work if the user enters a non-numeric value!
}

To fix this, you can use error checking and handle invalid inputs appropriately. For example, you could loop until valid input is provided.

  1. Not considering negative numbers:
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += pow(numbers[i], 2); // This will give incorrect results if there are negative numbers!
}

To fix this, you can calculate the absolute value of each number before squaring it.

Practice Questions

  1. Write a program that takes user input of 3 integers and stores them in an array. Then, find and print the largest number among them.
  2. Write a program that takes user input of 5 integers and stores them in an array. Calculate and print the average of the numbers.
  3. Write a program that takes user input of 10 integers and stores them in an array. Find and print the second-largest number among them.
  4. Write a program that takes user input of 5 strings and stores them in an array. Sort the strings alphabetically and print them out.
  5. Write a program that takes user input of 10 integers, stores them in an array, and calculates the median (middle value) of the numbers. If there is no middle value (i.e., an odd number of inputs), calculate the average of the two middle values.

FAQ

Question: What happens if I try to read more input than there are elements in the array?

Answer: If you try to read more input than there are elements in the array, you will encounter a runtime error (segmentation fault) because you're trying to access memory that doesn't belong to your program.

Question: Can I declare an array with a size that is not a power of 2?

Answer: Yes, you can declare an array with any positive integer size. The size does not have to be a power of 2.

Question: What if I don't know the size of the array in advance? How can I handle dynamic arrays?

Answer: To handle dynamic arrays (arrays whose size is not known at compile time), you can use dynamic memory allocation functions like new and delete. We will cover that topic in a future lesson.

Question: What's the difference between an array and a vector?

Answer: An array is a contiguous block of memory with a fixed size, while a vector is a dynamic array-like data structure that can grow or shrink as needed. Vectors are more flexible than arrays but have some performance overhead due to their dynamic nature.

Question: How do I find the index of an element in an array?

Answer: To find the index of a specific value in an array, you can use the std::find algorithm or write your own linear search function. We will cover these topics in future lessons.

Example 2: Take Inputs from User and Store Them in an Array | C++ | XQA Learn