C++ || Snippet – How To Input Numbers Into An Integer Array & Display Its Contents Back To User
This snippet demonstrates how to place numbers into an integer array. It also shows how to display the contents of the array back to the user via cout.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; // const int allocating space for the array const int ARRAY_SIZE = 100; int main() { // declare variables int numElems = 0; int myArray[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements // ask user how many items they want to place in array cout << "How many items do you want to place into the array?: "; cin >> numElems; // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { cout << "nEnter item #" << index +1<< " : "; cin >> myArray[index]; } // display data to user cout << "nThe current items inside the array are: "; // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { cout << "nItem #" << index +1<< " : "; cout << myArray[index]; } cout<<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
How many items do you want to place into the array?: 5
Enter item #1 : 45Enter item #2 : 7
Enter item #3 : 34
Enter item #4 : 8
Enter item #5 : 2
The current items inside the array are:
Item #1 : 45
Item #2 : 7
Item #3 : 34
Item #4 : 8
Item #5 : 2
Leave a Reply