Array/Reversing Arrays

This program is supposed to have the user enter in 15 values, put them into an array, and then reverse that array. The output is putting a zero in the fourteenth place and cutting off the last number.
EX)
1 2 3 4...14 15--> 0 15 14...4 3 2

I'm really stuck. Some help would be much appreciated!


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
#include <iostream>
#include <string>
#include<vector>
#include<ctime>
#include<cstdlib>
using namespace std;

void fillarray(vector <int> &fill)
{
    int val, count=1;   
        for (int i=0; i<fill.size(); i++)
        {
            cout<<"Enter value "<<count<<":  ";
            cin>>val;
            fill[i]= val;
            count++;
            cout<<endl;
        }
         

}

void backwards(vector <int> inputs)
 {
     cout<<"The array in reverse order is: ";
     for(int i=inputs.size(); i>0; i--)
     {
         cout<<inputs[i]<<" ";
     }
     
   
 }



 int main()
 {
     vector <int> fifteen (15);
     cout<<"Please enter 15 numbers, this program will reverse their order."<<endl;
     cout<<endl;
     fillarray(fifteen);
     backwards(fifteen);
     
     
return(0);
}





The problem in your code is in the loop of backwards() function. The indexes of vector start from 0 and end with inputs.size()-1, so the loop you're looking for would be:
1
2
3
4
5
6
7
8
9
 void backwards(vector <int> inputs) {
     cout<<"The array in reverse order is: ";
     for(int i=inputs.size()-1; i>=0; i--)
     {
         cout<<inputs[i]<<" ";
     }
     
   
 }

Pay attention to int i= inputs.size()-1 and i>= 0; the last element in vector is inputs[inputs.size()-1] and the first one is inputs[0]
Last edited on
Topic archived. No new replies allowed.