While loops expression - c++

I'm trying to write a program that asks the user to enter digits between 0 and 1000000 and it outputs the occurrence of a certain number (that the user entered as well)
I've wrote this program and I believe it works well, but I have one issue which is if the while expression is not true, I want to cout a certain message but I don't know where to place it.
Here's my program:
#include <iostream>
using namespace std;
int main()
{
int n,j=0,key;
cout << "Pleaser enter digits\n";
cin >> n;
cout << "please enter key number\n";
cin >> key;
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
Thanks in advance!

Use
if(n>0 && n<1000000)
{
while(n)
{
if(n%10==key)
j++;
n= n/10;
}
}
else
cout<<"n is supposed to be between 0 and 1000000";

As there are no breaks (or no other piece of code that can jump) inside the bucle, everything after the while structure is executed because the expression returned false.
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "While expression not anymore true" << endl;
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
UPDATE
Based on the comments, it seems that you want to check if the number entered is valid or not. Simply, just check it before the while:
if(not (n>0 and n<1000000)) cout << "Number must be between 0 and 1000000" << endl;
else {
while (n)
{
if(n%10==key)j++;
n= n/10;
}
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}

Write a if statement before while loop.
if(!(n>0 && n<1000000))
{
cout << "....";
return -1;
}
while(..)

Related

Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0

Add a countdown timer to a math program quiz

I am trying to add a countdown timer to this program. I would like the timer to start when the first math fact question is asked and upon expiration i want the program to give the grade. What's the code to do this in c++ if possible?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
int main(int args, char* argv[])
{
int i;
int result;
int solution;
char fact;
bool done = false;
int correct = 0;
int count = 0;
do {
try {
cout << "Enter (m)ultiplication or "
<< "(a)ddition." << endl; /*or (s)ubstraction. */
cin >> fact;
while (!cin)
throw fact;
if (fact != 'A')
if (fact != 'a')
if (fact != 'M')
if (fact != 'm')
while (!cin)
throw fact;
cout << "Now, enter the number of the fact that
you would like to do." << endl;
cin >> i;
int wrong = 0;
int score = 0;
int j = 0;
while (!cin)
throw i;
switch (fact) {
case 'm':
case 'M':
while (j < 13) {
cout << "What's " << i << " x " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i * j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " x " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " x " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i * j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
case 'a':
case 'A':
while (j < 13) {
cout << "What's " << i << " + " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i + j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " + " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " + " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i + j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
if (j == 13) {
system("pause");
correct = score - wrong;
score = (correct * 100) / 13;
}
if (score >= 80) {
cout << "Excellent!!!!!" << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Keep up the good work." << endl;
} else if (score >= 70) {
cout << "Congratulations!!!!!" << endl
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Let's see if we can score even higher next time." << endl;
} else {
cout << "You scored below 70 which means that you may need some"
<< " more practice." << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "You might want to try the " << i << " facts again."
<< " Goodluck!!!!!" << endl;
}
}
} catch (char fact) {
cout << "Invalid input. You can only enter (m)ultiplication or"
<< " (a)ddition. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (int i) {
cout << "Invalid input0. You can only enter a
number here. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (...) {
cout << "Invalid input2. You can only enter a number here.
Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
}
} while (!done);
return 0;
}
The task is quite hard, but if you dare trying, I suggest doing it in two steps:
Implement inaccurate solution: timer expiration is checked between queries to user.
If there is some time left, next question is asked, otherwise statistics is shown. So program always waits for user input on the last question despite timer has run out. Not what exactly quizzes look like, but good move to start with.
Method: before starting quiz save current time, before each question take delta between saved time and current one and compare with time limit. Example with chrono (starting from C++11), example with oldschool clock
Add middle-question interruption
This part requires function, which will wait for user input not longer, than specified amount of time. So instead of using std::cin() you'll need to calculate amount of time left (time limit minus delta between cur time and start time) and call some sort of cin_with_timeout(time_left).
The hardest thing is implementing cin_with_timeout(), which requires solid knowledge of multithreading and thread synchronization. Great inspiration can be found here, but it is direction to start thinking rather than complete solution.

How do you make a counter to count the number of even and odd numbers entered by user?

I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}

Ending a loop once the user is wrong twice?

I am doing a quiz and testing the user. If the user is wrong he is allowed a second chance or skip, if he chooses 2nd chance and is wrong again, the game is over. How do I break out of this loop to end the game? I tried a do while loop,
do { stuff} while (wrong<2) while counting ++wrong;
every time he's wrong, but didnt work.
I have labeled the ++wrong with // statements below
void player_try (string questions[][5], char answers[])
{
char user_guess;
int m = 0;
srand(time(NULL));
int x;
int choice;
int wrong =0;
for (m=0; m<7; m++)
{
do
{
x = (rand() % 7);
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
if (user_guess != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong; // THIS IS WHERE I COUNT WRONG ONCE
cout << "Skip this question or take a chance at greatness?" << endl;
cout << "Press 1 to skip, press 2 to take a chance at greatness" << endl;
cin >> choice;
if (choice == '1')
{
cout << "we shall skip this question." << endl;
}
else
{
cout << "I applaud your bravery." << endl;
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
}
if (toupper(user_guess) != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong;; // THIS IS WHERE I CANT WRONG TWICE
}
else
{
cout << "correct!" << endl;
}
}
else
{
cout << "correct!" << endl;
}
}
while(wrong < 2);
}
}
Change your function return type to an integer. That simply means changing "void" to "int."
Then, inside the function place a return 0; at the point you want your function to terminate. Be sure you include another return 1; for the case that the user wins too.
This is how the main() function works. Consider:
int main()
{
string tester = "some string";
if(tester == "some string")
return 1;
cout << "Hey!"
return 0;
}
In the above case, main() terminates at the "return 1;" because the if statement was TRUE. Note that "Hey!" is never printed. It'll work the same way for your function.
As a plus, you can use that return value to let OTHER functions (such as main()) know if the function terminated because the user won (it returned 1), or lost (it returned 0).
Yes, a break statement is also a valid way to terminate the loop, but I submit that this method is the safer, cleaner way to go about it. In general, we like to know whether a function or program was successful or not.
You can use a break; statement if the person has gotten the answer wrong twice.
As per comments. You can shed the do while loop in favour of one for loop. Just put a break at the bottom if the wrong guesses are 2
There are several great suggestions for refactoring the code to remove the duplication of effort here, but to get the program functioning immediately, you've got to break out of the for loop surrounding the do { } while(wrong < 2) loop.
A simple way to do this is to modify the for loop to test the wrong variable also. The added benefit is, if I'm reading everything correctly, you'll no longer need the do{ } while(); loop.
for (m=0; m<7 && wrong < 2; m++)

if statements for c++

My program so far, my question is do i have to include the if statements after each cout/cin code or is there a way to generalize it? :
#include <iostream>
using namespace std;
int main ()
{
double watts, hours_per_day, watt_hours, dollars_per_wh, result;
dollars_per_wh= .00008;
cout << " How many Watts for the Air conditioner? ";
cin >> watts;
cout << " How many hours/day do you run the Air Conditioner? ";
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
cout << "How many Watts for the Television? " ;
cin >> watts;
cout << "How many hours/day do you run the Television? " ;
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
cout << "How many Watts for the Washer? " ;
cin >> watts;
cout << "How many hours/day do you run the Washer? " ;
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
return 0 ;
}
You can write a function that takes two parameters:
bool check(int watts, int hours_per_day)
{
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return false;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return false;
}
}
Then in your main function you can replace the two if statements with one:
if(!check(watts, hours_per_day))
{
return 1;
}
If you want to collect all the inputs first and then evaluate them, then maybe use an array for watts and hours_per_day. Then you can run through the array and check each entry.
Yes, you can pull them out into a separate function:
void cinNonNegative(double &x)
{
cin >> x;
if (x< 0)
{
cout << "Error- negative value detected " << endl;
exit(1);
}
}
int main()
{
...
cout << " How many Watts for the Air conditioner? ";
cinNonNegative(watts);
cout << " How many hours/day do you run the Air Conditioner? ";
cinNonNegative(hours_per_day);
...
}
And if you want to be more specific about the error message (e.g. "negative watts" instead of "negative value") you can add another parameter to cinNonNegative for the name of the variable (e.g. "watts").
The following solution gives you a function that:
Returns a boolean that says if the function succeeded/failed
Allows you to name the value that should be received
Allows you to set minimal and maximal values
If needed, you can build other custom functions for getting integers, or other functions for getting any other kind of input. This way you can concentrate all the input tests into a single place.
#include <iostream>
using namespace std;
bool getint(int &result, const char *name, int minValue, int maxValue)
{
bool success = false;
int value = 0;
cout << "Please enter " << name << ": ";
if (!(cin >> value))
{
cout << "Error: bad input detected" << endl;
}
else if (value < minValue)
{
cout << "Error: " << name << " is less than " << minValue << endl;
}
else if (value > maxValue)
{
cout << "Error: " << name << " is more than " << maxValue << endl;
}
else
{
success = true;
result = value;
}
return success;
}
int main()
{
int watts;
getint(watts, "Watts for the AC", 0, 10000);
return 0;
}