I am a beginner in c++. I have spent hours trying to figure out loops and the structure of arrays.
GOAL: take a user input and set it to the size allocation of an array. Take another user input and add values to the array. Display an output of the array, backwards. [last index.....first ind`ex]
I have read everywhere and in my textbook that spaces are not counted by cin >> but my code shows me spaces. I have tried testing whether my loop is correctly adding the input values to the loop. Maybe my output loop is wrong? I can't figure out what the issue is.
These are the example outputs I am getting. If I have an array of 5 elements, why did only 3 items output? In the backwards output loop, I am not seeing all of my array items, and it repeats 3.
I have a lot of comments to keep track of my thought process. Thanks for taking a look and helping me out!!
Example Test Case of Mine:
5
1 2 3 4 5
print array
123
backwards array
3 3 2 1
...Program finished with exit code 0
Press ENTER to exit console.
Expected Example: (user enters)5
(user enters)1 2 3 4 5 (hit enter)
Expected Output:
5 4 3 2 1
#include <iostream>
#include <string>
using namespace std;
int main() {
//write your solution here
//define variables
//int sizeofArray;
//need to account for spaces
//no you don't they are accounte for
//int array[sizeofArray];
int num;
int sizeofArray;
int array[sizeofArray];
cin >> sizeofArray;
//think about 2 for loops
//store values to the array
for (int i=0; i < sizeofArray; ++i) {
//for each index, populate the array
cin >> array[i];
}//end of populate array
cout << "\nprint array \n";
//print the array
for (int k=0; k < (sizeofArray); k++) {
cout << array[k];
}//end of print array
//output values of the arrray backwards
cout << "\nbackwards array \n";
for (int j=sizeofArray; j >=0; --j) {
cout << array[j] << " ";
}
return 0;
}//end of main
- tried to print out the array to see what the system sees. I get an incorrect output
- tried to learn and use the right increment/decrement syntax, ++i or i++
- tried to account for spaces by adding a multiplier of 2 to "sizeofArray"