Hi here is my question.
Write a program that uses a do-while statement. It reads in an integer
n from the keyboard. If n is not in the range 1 to 10 it makes an audible
“beep” and asks for another integer. If n is in the correct range, it writes
out “You have input n” and then exits.
Here is my answer.
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
do
{
cout << "Enter an integer." << endl;
cin >> number;
if (!(number >= 1 && number <= 10))
{
Beep(400, 400);
}
}
while (!(number >= 1 && number <= 10));
cout << "You have input " << number << endl;
system("PAUSE");
}
You can see the line
(!(number >= 1 && number <= 10))
is repeated. Is there any workaround for this?
int GetNumber()
{
int number;
cout << "Enter an integer." << endl;
cin >> number;
return number;
}
void main()
{
int n = GetNumber();
while(n < 1 || n > 10)
{
Beep(400, 400);
n = GetNumber();
}
cout << "You have input " << n << endl;
system("PAUSE");
}
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
bool invalid_input = true;
do
{
cout << "Enter an integer." << endl;
cin >> number;
invalid_input = !(number >= 1 && number <= 10);
if (invalid_input)
{
Beep(400, 400);
}
}
while (invalid_input);
cout << "You have input " << number << endl;
system("PAUSE");
}
Perhaps...
int number = 0;
while (true)
{
cout << "Enter an integer." << endl;
if (cin >> number && number >= 1 && number <= 10)
break;
Beep(400, 400);
}
cout << "You have input " << number << endl;
system("PAUSE");
Related
C++ code where a user enters 2 integers, then the program outputs how many numbers were multiples of 3 between those integers, including both numbers, and how many numbers were divisible by 5.
Here is my code. I think I am not calling the if statements correctly. Maybe I need a switch?
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int numb1, numb2;
int sentinel;
int counter = 0;
int mult3 = 0;
int mult5 = 0;
cout << "Enter an integer:";
cin >> numb1;
cout << "Enter another integer:";
cin >> numb2;
cout << endl;
sentinel = (abs(numb2-numb1)+1);
if(numb1 % 3 == 0 && counter <= sentinel) {
mult3++;
numb1++;
counter++;
}
else {
numb1++;
counter++;
}
cout << endl;
counter = 0;
if(numb1 % 5 == 0 && counter <= sentinel) {
mult5++;
numb1++;
}
else {
numb1++;
counter++;
}
cout << endl;
cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
cout << endl;
return 0;
}
A short version for your code is given below. Checkout the while loop(not ran, just from top of my head).
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int numb1, numb2;
int sentinel;
int counter = 0;
int mult3 = 0;
int mult5 = 0;
cout << "Enter an integer:";
cin >> numb1;
cout << "Enter another integer:";
cin >> numb2;
cout << endl;
while(numb1 <= numb2){
mult3 += (numb1%3)==0?1:0; // (numb1%3)?0:1
mult5 += (numb1%5)==0?1:0;
++counter;
++numb1;
}
cout << endl;
cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
cout << endl;
return 0;
}
You're not looping it at all, so this will only execute once.
while(counter < sentinel)
{
//run your tests and increment the appropriate variables if the numbers are divisible by 3 or 5
counter++;
}
start by evaluating the lowest of the 2 entered numbers + counter % 3 == 0
I got it. I had to use 3 separate while loops. One for <, one for >, and one for =. When I just had a <= and >=, the first loop would feed into the second. I took out the sentinel and the counter thanks to Avezan's help. Thanks everyone.
I am a beginner in c++. I wrote a program to separate the digits in an integer entered and display them and their sum. However, when the loop repeats, the program hangs even though it compiled perfectly. I tried a '... while' loop and a while loop but the problem persists. What should I do to have it repeat (ask user for next integer, calculate and display the results) without problems? Any help will be appreciated.
//Preprocessor directives
#include <iostream>
#include <cmath>
//Standard library
using namespace std;
//enter function main
int main()
{
int num;
int digit;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
while (num != 0 )
{
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;
if (num < 0)
num = -num;
//find the highest number of 10 that divides the number
while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
pwr++;
while (num > 0)
{
digit = num / static_cast<int>(pow(10.0, pwr));
cout << digit << " ";
sum = sum + digit;
num = num % static_cast<int>(pow(10.0, pwr));
pwr--;
}
if (pwr != -1) //Either num is 0 or there are trailing zeros in num
while (pwr != -1)
{
cout << 0 << " ";
pwr--;
}
cout << endl;
cout << "The sum of the digits = " << sum << endl;
while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;
}
return 0;
}
//Preprocessor directives
#include <iostream>
#include <cmath>
//Standard library
using namespace std;
//enter function main
int main()
{
while (true )
{
//reset initial values every loop
int num;
int digit;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
//same exit condition
if (num == 0)
break;
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;
if (num < 0)
num = -num;
//find the highest number of 10 that divides the number
while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
pwr++;
while (num > 0)
{
digit = num / static_cast<int>(pow(10.0, pwr));
cout << digit << " ";
sum = sum + digit;
num = num % static_cast<int>(pow(10.0, pwr));
pwr--;
}
if (pwr != -1) //Either num is 0 or there are trailing zeros in num
while (pwr != -1)
{
cout << 0 << " ";
pwr--;
}
cout << endl;
cout << "The sum of the digits = " << sum << endl;
//extraneous
/*while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;*/
}
return 0;
}
I think you should use vector to store the digits... also the logic inside should be a bit smaller (see note 1), (note that I didn't test for negatives, you may use abs from cmath)
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
//Standard library
using namespace std;
//enter function main
int main()
{
int num;
std::vector<int> digits;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
while (num) {
while (num) {
int temp = num % 10;
digits.push_back(temp);
sum += temp;
num /= 10;
}
std::reverse(digits.begin(), digits.end());
cout << sum << endl;
for(auto & a : digits)
{
cout << a << " ";
}
cout << endl;
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;
}
return 0;
}
note 1:
while (num) {
int temp = num % 10;
sum += temp;
num /= 10;
}
I was trying to figure out this task, but so far have been unsuccessful. I think I understand the logic behind it, I just don’t know how to nest loops so it works (if that makes sense). I would very much appreciate your help!
Task:
"Create an application in which a user enters full numbers until they enter number 0 (zero). The application should print out how many even numbers have been entered, how many odd numbers, sum of even numbers and sum of odd numbers, and total sum of numbers."
my code so far:
#include <iostream>
using namespace std;
void main() {
do {
int input1;
cout << "Type in a number";
cin >> input1;
} while (input1 != 0);
cout << "Type in a number";
cin >> input1;
if (input1 % 2 == 0)
{
int even = 0;
while (input1 % 2 == 0 )
cout << even;
even++;
}
else
{
int odd = 0;
while (odd != 0)
{
cout << odd;
odd++;
}
}
}
system("pause");
}
Note: I did not try to do the third part of the task, since the second one won't work :/ I figured out first part, and I did it with do while loop. Thanks again.
Try this:
int oddCount = 0;
int evenCount = 0;
int oddSum = 0;
int evenSum = 0;
int in;
do
{
std::cout << "Type in a number:";
std::cin >> in;
if (0 == in)
break;
if ( in % 2 == 0 )
{
evenCount++;
evenSum += in;
}
else
{
oddCount++;
oddSum += in;
}
} while ( true );
std::cout << "Odd count: " << oddCount << std::endl;
std::cout << "Even count: " << evenCount << std::endl;
std::cout << "Odd sum: " << oddSum << std::endl;
std::cout << "Even sum: " << evenSum << std::endl;
std::cout << "Total sum: " << oddSum + evenSum << std::endl;
Take a look at this piece of code:
#include <iostream>
using namespace std;
int main() {
int input;
int total_sum = 0, odd_sum = 0, even_sum = 0;
int odd_count = 0, even_count = 0;
do {
cout << "Type in a number: ";
cin >> input;
total_sum += input;
if (input % 2 == 0)
{
even_count++;
even_sum += input;
}
else
{
odd_count++;
odd_sum += input;
}
} while (input != 0);
cout << "Total Sum: " << total_sum << endl;
cout << "Even sum: " << even_sum << endl;
cout << "Odd sum: " << odd_sum << endl;
cout << "Even Count: " << even_count << endl;
cout << "Odd Count: " << odd_count << endl;
return 0;
}
See how input is declared outside of the loop. if it was inside it, then you essentially create it each time you enter the loop. that would be fine if you did not want to use its values outside of the loop (like in the loops condition).
Also, notice that the values you need to calculate can be updated within that same loop.
I'm trying to display "invalid option" when the user enters a letter instead of a number. I tried using the isalpha() function but I get an infinite loop showing 0 Invalid option!try again:. The 0 from the output is displayed when entering a letter. When I actually type in the number 0 the message is displayed and the loop is exited.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
cout << "Guess a number 1-100: ";
cin >> userInput;
cout << endl;
if(userInput == answer) {
cout << "Correct!\n\n";
}
while(userInput != answer) {
if(userInput < 1 || userInput > 100 || isalpha(userInput)) {
cout << userInput << " Invalid option!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
cin >> userInput;
cout << endl;
}
}
cout << userInput << " is correct!\n\n";
return 0;
}
When you need to deal with user input differently based on some logic, your best option is to:
Read lines of text. Figure out what to do when there is no more input.
Process each line of text using custom logic.
In your case, you could use:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
std::string line;
cout << "Guess a number 1-100: ";
while ( getline(std:::cout, line ) )
{
// Deal with empty lines.
if ( line.size() == 0 )
{
continue;
}
// If the first character is a letter ...
if(isalpha(line[0])) {
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
// Extract the number from the line using a stringstream.
// If there is a problem extracting the number ...
std::istringstream str(line);
if ( !(str >> userInput ) )
{
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
cout << endl;
// Check the user input against the random answer.
if(userInput == answer) {
cout << "Correct!\n\n";
}
else if(userInput < 1 || userInput > 100 ) {
cout << userInput << " Invalid option!\ntry again: ";
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
}
cout << "Guess a number 1-100: ";
}
cout << userInput << " is correct!\n\n";
return 0;
}
I'm new into programing. I'm working on a program that will tell the odd and even numbers that are less or equal to the user's input (for inputs >=0). How do I make the program run if value is >=0 and ask for the input again if the value is <0.
Here is the program:
> #include <iostream>
using namespace std;
int main() {
cout << "Please enter only a positive value\n";
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;
int number = 1;
while (input >= 0 && number <= input) {
// Print some numbers
cout << "Here are some odd numbers:\n";
while (number <= input) {
cout << number << endl;
number = number + 2;
}
// Print some numbers
cout << "Here are some even numbers:\n";
int number2 = 0;
while (number2 <= input) {
cout << number2 << endl;
number2 = number2 + 2;
}
}
return 0;
}
Correct code:
#include <iostream>
using namespace std;
int main() {
cout << "Please enter only a positive value\n";
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;
while (input < 0) {
cout << "Input is negative. Enter again: \n";
cin >> input;
}
int number = 1;
while (input >= 0 && number <= input) {
// Print some numbers
cout << "Here are some odd numbers:\n";
while (number <= input) {
cout << number << endl;
number = number + 2;
}
// Print some numbers
cout << "Here are some even numbers:\n";
int number2 = 0;
while (number2 <= input) {
cout << number2 << endl;
number2 = number2 + 2;
}
}
return 0;
}
Note that I added this chunk:
while (input < 0) {
cout << "Input is negative. Enter again: \n";
cin >> input;
}
to handle negative inputs.
while (input < 0)
{
cout << "Enter a number:\n";
cin >> input;
if (input < 0)
// Here you can print something to tell that input was not correct
}