I'm in an introductory c++ course, and am having trouble with this prompt:
"Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by exactly one space. Declare any variables that are needed."
My solution is as follows:
int num = 0;
int evens = 0;
int odds = 0;
int evenSum = 0;
int oddSum = 0;
do {
cin >> num;
if (num % 2 == 0){
evens++;
evenSum += num;
}
else if (num > 0) {
odds++;
oddSum += num;
}
else {
num = -1;
}
}
while (num >= 0);
cout << evenSum << " " << oddSum << " " << evens << " " << odds;
I get no feedback except "Failure: code goes into infinite loop" from the autograder. What am I doing wrong?
You are also processing negative numbers in this if (num % 2 == 0) part(example: this condition when encountered for first negative integer will also be true e.g -6), thereby incrementing evens and adding this negative number to evenSum, which shoudln't have been done as per your question's requirement; Other thing is that the else part is not necessary, I mean why assign -1 to num instead letting it stay the same number you just read(as it is not in your question's requirement).
I think your else if and else part needs to be changed like this:
#include <iostream>
using namespace std;
int main(){
int num;
int evens = 0;
int odds = 0;
int evenSum = 0;
int oddSum = 0;
while (true) {
cin >> num;
if (num < 0){
break;
}
if (num % 2 == 0){
evens++;
evenSum += num;
}
else {
odds++;
oddSum += num;
}
}
cout << evenSum << " " << oddSum << " " << evens << " " << odds;
return 0;
}
Keep taking the numbers from input, if num < 0 then break and show the results, else check for the number being either odd or even and increment the counters accordingly.
You never make num positive in your loop. All your doing is changing other variables. Also you don't need to reassign num to -1 if it's already negative.
You need to add this:
else if (num > 0) {
odds++;
oddSum += num;
num = 1; //becomes positive and breaks the loop.
}
The while part of your loop will keep going until a negative answer is put in. Where are you getting your num from? User input? Your declaration has made it 0, which is making your while loop continue since the condition is >=. If you want user input there should be a cout statement proceeding your cin.
Related
I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.
I was tasked with writing some code that will take a user input and convert the number to its binary number. I have written some code so far, but am having one issue. I have to use a for loop and the quotient-remainder method. When I output the remainder(binary), it is not printing the last digit.
The question I'm asking is: What would I have to change in my for loop to make it print out the last digit of the binary number?
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
for (int i = 0; i <= (num + 1); i++)
{
num /= 2;
rem = num % 2;
cout << rem;
}
_getch();
return 0;
}
Any help is appreciated, Thank you!
You lose the last binary number when you start your algorithm by dividing num by 2. To avoid this issue, you should exchange both instructions num /= 2; and rem = num % 2;
Your loop also iterates too many times: in fact you can stop when num == 0. The following code is not valid for inputs that are <= 0.
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
while (num != 0)
{
rem = num % 2;
num /= 2;
cout << rem;
}
cout << std::endl;
return 0;
}
If you want to write it in the right order, you should first compute the log of your number in base 2. The following solution uses a number index that starts with '1' and that has '0' after:
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
if (num > 0) {
int index = 1;
while (index <= num)
index *= 2;
index /= 2;
do {
if (num >= index) {
cout << '1';
num -= index;
}
else
cout << '0';
index /= 2;
} while (index > 0);
cout << std::endl;
}
else
cout << '0';
cout << endl;
return 0;
}
You need to change your lines from
num /= 2;
rem = num % 2;
to
rem = num % 2;
num /= 2;
This would print the binary number in reverse order. I would recommend changing the for loop to while(num>0) and adding each digit to an array instead of cout. Print the array from left to right later on to get the correct binary order.
The idea is to use math. Convert the base 10 integer to base 2. The other way maybe is to transverse the bits by testing the integer value against powers of 2 up to maximum bit value for integer. I also assume that you are not going to use floating point numbers. Converting to floating point binary values are a headache.
I tried making a program to find the lowest common multiple of any two numbers. I have gotten most of the way there but my program prints all of the common multiples from 1-1000000 instead of just the first one. How do I make it print only the first one
?
#include <iostream>
using namespace std;
int main() {
cout << "Find the lowest common multiple of two numbers, just enter them one after the other" << endl;
int firstNum;
int secondNum;
cin >> firstNum;
cin >> secondNum;
int i;
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
}
}
system("pause");
return 0;
}
You can add a break to end a loop. In your case, you want to add it at the end of your if statement:
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}
Your problem is a break statement as others have mentioned.
But a better solution: lcm is standardized in C++17! So you can just do:
cout << lcm(firstNum, secondNum) << endl;
If you don't have access to C++17 yet this is already available in the namespace experimental: http://en.cppreference.com/w/cpp/experimental/lcm
After finding the first one you need to leave from for loop, that is why it keeps printing other values.
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}
I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)
I know this probably really simple but Im not sure what im doing wrong...
The assignment states:
For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you a value in that range.
After the user has successfully entered a value in that range, you are to display the sum of all the integers from 1 to the value entered.
I have this so far:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
Im just not sure exactly what i'm doing wrong... I keep getting the wrong sum for the total...
Your loop conditions are wrong.
First, you should use a separate variable as your index (in fact you already declared one using "int i" earlier).
Second, your upper limit shouldn't 50, it's whatever the user entered.
So you want to change all "nums" in the loop to "i", and the "50" to "num".
Actually, you can simplify the for loop into:
sum = ((num+1)*num)/2;
Credits to Carl Friederich Gauss. :D
The Corrected code is
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}
Let me make sure I understand this correctly, your assignment asks for a user input for a given number and store it in num and then display a running sum of 1 up to num?
If that's the case, inside your loop you override the user's input of num when you call num = 1. You'll just calculate the running sum of 1-50 every time.
To correct that, you need to use a different variable to keep incrementing, i.e. count or the variable i since it's already been declared. Then you should loop up from i to num as long as i <= num.
Other than that, I cannot see any problems and it should work correctly.
Note to add about a good investment:
It would definitely be worth while to see if the IDE you are developing in has a debugger you can use. Debugging is a great tool to help figure out why your code is not being executing as it is intended to.
If there is no debugger (which would surprise me) might I suggest my go-to alternative method of stepping through the for loop on a sheet of paper and compare the sum to another hand-written solution already solved, i.e. num = 5 sum = 1+2+3+4+5 = 15
Hope this helps.
The for loop should be:
for (int x = 1; x <= num; x++)
{
sum += x;
}
#include <iostream.h>
int main () {
int num, sum; // here you define (but don't initialize) one variable named sum.
[ ... ]
{ // here you start an inner scope.
int i;
int sum = 0; // here you define *another* `sum`, local to the inner scope.
for (num = 1; num <= 50; num ++)
sum = sum + num; // here you add the numbers to the *second* sum.
} // here the second sum goes out of scope.
// and here you print out the first (still un-initialized) sum.
cout << endl << "The sum is " << sum << endl;
Your upper bound is not 50, but the number you entered.
Therefore your summation is from 1 t0 inclusive of your entered number.
Say you enter 10,
logic will be.
You add all the digits from 1 to 10.