input n space separated integers in c++
Here is the code to input n space-separated integers in C++ along with explanations for each step:
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n; // Step 1: Read the value of n from the user
std::vector<int> numbers(n); // Step 2: Create a vector to store the numbers
for (int i = 0; i < n; i++) {
std::cin >> numbers[i]; // Step 3: Read each number from the user and store it in the vector
}
// Step 4: Print the numbers
for (int i = 0; i < n; i++) {
std::cout << numbers[i] << " ";
}
return 0;
}
Explanation:
Step 1: Read the value of n from the user using the
std::cin >> n
statement. This statement reads an integer value entered by the user and assigns it to the variablen
.Step 2: Create a vector named
numbers
with a size ofn
using the statementstd::vector<int> numbers(n)
. The vector is used to store the input numbers.Step 3: Use a for loop to iterate
n
times. Inside the loop, read each number from the user using the statementstd::cin >> numbers[i]
. The numbers are stored in the vectornumbers
at the corresponding indexi
.Step 4: After reading all the numbers, use another for loop to print the numbers. The loop iterates
n
times, and each number is printed using the statementstd::cout << numbers[i] << " ";
. The numbers are separated by a space.
That's it! The code reads n
space-separated integers from the user and stores them in a vector. Then, it prints the numbers.