The assignment is:
Write a program that asks the user how many numbers will be entered and then has the user enter those numbers. When this is done, report to the user the position of the first 9 entered and the last 9 entered. By position we mean, for example, that if the first 9 is the 2nd number entered then its position would be 2.
When i run my program i can enter numbers just fine, but when i'm done i get no output that says if i had or had no 9s. Can anyone spot smething I might be doing wrong?
This is my code so far:
#include <iostream>
using namespace std;
int main()
{
int amount;
int count;
int firstPosition;
int lastPosition;
int number;
cout << "How many numbers will be entered? ";
cin >> amount;
for (count = 0; count < amount; count++){
cout << "Enter num: ";
cin >> number;
if (number == 9){
firstPosition = count;
}
else if (number == 9 && firstPosition == count){
lastPosition = count;
}
}
if (firstPosition == count){
cout << "The first 9 was in position " << firstPosition << endl;
cout << "The last 9 was in position " << lastPosition << endl;
}
else if (firstPosition == 0){
cout << "No nines were entered...";
}
system ("PAUSE");
}
Thanks Ahead. If you need more info let me know. This is my first Programming class so i'm sort of a beginner with no previous experience except for the past 4 assignments in this class.
Initialize firstPosition with -1 and check for if ( lastPosition != -1 ) instead of if (firstPosition == count),
count will change in the loop so you shouldn't use its value in comparison with lastPosition
if ( number == 9 )
{
if ( firstPosition == -1 ) // firstPosition equals to -1
{
firstPosition = count; // set firstPosition to the current position
lastPosition = firstPosition; // set last position to current position too as they may not be other 9s
}
else // firstPosition equals to a position
lastPosition = count; // set lastPosition to current position
}