CurlyKid
CurlyKid

Reputation: 13

Output numbers in reverse - c++

Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a space, including the last one. Assume that the list will always contain less than 20 integers.

Input : 5 2 4 6 8 10

Expected output: 10 8 6 4 2

My output is:

0 4196464 0 4196944 0 0 0 0 0 4197021 0 2 0 4196929 10 8 6 4 2

I have the answer at the very end, but I don't know how to get rid of the numbers in front. I'm guessing that its looping 20 times and that's why my answer is weird. I changed my max to fit the number of input but that's cheating for my assignment.

My Code:

#include <iostream>
using namespace std;

int main() {
  const int MAX_ELEMENTS = 20;  // Number of input integers
  int userVals[MAX_ELEMENTS];   // Array to hold the user's input integers
  int i;

  for (i = 0; i < MAX_ELEMENTS; ++i) {
    cin >> userVals[i];
  }
  for (i = MAX_ELEMENTS - 1; i >= 1; --i) {
    cout << userVals[i] << " ";
  }
  cout << endl;
  return 0;
}

Upvotes: 1

Views: 15688

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596121

You are not following the instructions you were given, in particular this sentence:

The input begins with an integer indicating the number of integers that follow.

As you surmised, you are indeed reading and printing out exactly 20 values, even if the user actually enters fewer values (and the instructions provide). The 1st number given specifies the count of subsequent numbers. Read that number first and store it in a variable that you can then use to control your loops.

And speaking the loops, your output loop is skipping the 1st element of the array. The loop condition needs to be i >= 0 instead of i >= 1.

Try this instead:

#include <iostream>
using namespace std;

int main() {
  const int MAX_ELEMENTS = 20;  // Number of input integers
  int userVals[MAX_ELEMENTS];   // Array to hold the user's input integers
  int i, count; // <-- ADD count!

  cin >> count; // <-- ADD THIS!

  for (i = 0; i < count; ++i) { // <-- use count, not MAX_ELEMENTS!
    cin >> userVals[i];
  }

  for (i = count - 1; i >= 0; --i) { // <-- use count, not MAX_ELEMENTS!
    cout << userVals[i] << " ";
  }

  cout << endl;
  return 0;
}

Live Demo

Upvotes: 1

Related Questions