Array with User Input

I am working on a simple program to ask the user to input 4 numbers, print those numbers in an array back to the user
I am stuck on trying to put the numbers into an array. It only prints out the 2nd number entered. I don't understand. This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>

using namespace std; 

	
int main()
{
	int val;				//declare val
	int array[4];				//declare array 
	cout <<"Enter 4 numbers: "<<endl;	//user input, 4 numbers 
	
	for (int val = 0; val<4; val++)
	{
		cin >> array[val];
		
	}
	cout <<array[val]; 	//prints out the 4 numbers the user entered
	return 0; 
}
Last edited on
Well You have used a loop to ask for input and now there are 4 elements in array right? So you gotta use a loop again,which iterates 4 times,to print those numbers. Also avoid declaring same variable(s) multiple times like you did with int val

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include<iostream>
using namespace std;
int main()
{
    int val ,arr[4] ;
    cout<<"\nEnter The Numbers For The Array (4) : \n " ;
    for (val = 0 ; val < 4 ; ++val)
    {
        cout<<"Enter Number " << val + 1 ;
        cin>>arr[val] ;
        cout<<endl;
    }
    for (val = 0 ; val < 4 ; ++val)
    {
        cout<<"\t"<<arr[val];
    }
    return 0 ;

}
You can print your array like this:
1
2
  for (int i: array)
    cout << i << "\t";


Last edited on
Thank you so much, I was able to use this to get it working. I appreciate the help :)
closed account (E0p9LyTq)
C++11 introduced the range-based for loop for sequence containers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

int main()
{
   int arr[4];

   std::cout << "Enter The Numbers For The Array (4) :\n";

   for (int val = 0; val < 4; ++val)
   {
      std::cout << "Enter Number " << val + 1 << ": ";
      std::cin >> arr[val];
   }
   std::cout << '\n';

   for (auto val : arr)
   {
      std::cout << val << ' ';
   }
   std::cout << '\n';
}

Enter The Numbers For The Array (4) :
Enter Number 1: 5
Enter Number 2: 10
Enter Number 3: 52
Enter Number 4: 900

5 10 52 900
Topic archived. No new replies allowed.