Hi there! I need some help with getting my code output a certain way.
I want the program to print "Sorry, no eights were entered." ONLY when there actually is not an eight entered. However, it is printing that even when there is an 8 entered. How can I fix that?
(see output below code)
// This program asks how many numbers will be entered, then has the user input those numbers. It then reports to the user the position of the first and last 8 entered.
#include <iostream>
usingnamespace std;
int number=0;
int count=0;
int highestNumber=0;
int firstEight=0;
int lastEight=0;
int main()
{
// This has the user enter the total number of numbers to be entered.
cout << "How many numbers will be entered? ";
cin >> highestNumber;
// This has the user enter each of the eight numbers.
while (count < highestNumber)
{
cout << "Enter num: ";
cin >> number;
count = count + 1;
if (number==8 && firstEight ==0)
firstEight = count;
if (number==8 && firstEight !=0)
lastEight = count;
}
// This displays to the user the positions of the first and last eight's that were entered.
cout << "The first 8 was in position " << firstEight << endl;
cout << "The last 8 was in position " << lastEight << endl;
if(number!=8)
cout<<"Sorry, no eights were entered."<<endl; //THIS IS WHERE I'M HAVING TROUBLE
return 0;
}
OUTPUT:
How many numbers will be entered? 8
Enter num: 5
Enter num: 2
Enter num: 6
Enter num: 8
Enter num: 1
Enter num: 3
Enter num: 7
Enter num: 6
The first 8 was in position 4
The last 8 was in position 4
Sorry, no eights were entered.
Hi, I'm still unable to get the correct output. Anyone else that can help please? I understand I need an if else statement, I just think I'm putting it in the wrong place. When I go to put the else statement, I get an error message saying there is no if statement, which there is...
#include <iostream>
usingnamespace std;
int main()
{
int number=0;
int N=0;
int numEightCount=0;
int firstEight = 0, lastEight = 0;
cout << "How many numbers will be entered? : ";
cin >> N;
for(int i = 0; i < N; i++)
{
cout << "Enter num: ";
cin >> number;
if (number==8)
{
if(++numEightCount == 1) firstEight = i + 1; lastEight = i + 1;
}
}
if(numEightCount==0)
cout<<"Sorry, no eights were entered."<<endl;
else
{
cout << "The first 8 was in position " << firstEight << endl;
cout << "The last 8 was in position " << lastEight << endl;
}
return 0;
}
In your code, you were checking whether number was not equal to 8 to print that statement. However, each input of yours overwrites any existing value on number and hence when you break out of the loop, number would be equal to your 8th input.
To check if any eights were entered at all, it's better to see how many eights were entered (as in the solution above) and display that message if count = 0.