My professor is saying that The while loop runs provided n>=1. But I did not put any value into the variable n so depending on its “default” value, the loop may not be entered. And I'm not sure how to fix what he is talking about!?
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
int n, count;
double sum;
while (n >=1)
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
return 0;
}
Here is the line where n is declared
int n, count;
In this case the value of n is unspecified as it is left uninitialized. You should initialize it
int n = 1;
If you always want a loop to run at least once then you want a do...while(); loop. It will always enter the loop on the first iteration and execute the loop body then it will check the while condition to determine if it loops again or exits. A do...while(); has the form of
do
{
statements
} while (condition);
In this case it would save you from having to initialize n before you get the input from the user.
In this case though that doesn't seem like exactly what you want as you want nothing to happen if the user enters a number less than 1. One way you can solve that is to put your output and input into the while loop along with the check for n. This will stop anything from happening if the user enters less than 1 but still allowing you to prompt the usr and get the input on each iteration.
while (cout << "Enter a positive integer N (<1 to stop): " && cin >> n && n >= 1)
{
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0 / count);
cout << "Sum = " << sum << endl;
}
The problem is that n has not been initialized. Unlike in other languages like Java or C#, primitive variables do not have any pre-defined "default" value. The simply occupy whatever stack space was there previously; for all intents and purposes, the default value of uninitialized variables can be considered "random".
To fix this, simply initialize the variable before entering the loop.
n = 1;
Set n to a value greater than or equal to 1 so the loop is guaranteed to enter. Since you aren't setting it yourself, the default value can be something less than 1 meaning that the look has a chance, but isn't guaranteed to fire.
int n = 1
Also, you should set count = 0 in your for loop, because if n and count is equal to each other, the for loop automatically breaks and doesn't execute at all, leaving sum at 0.
To make sure your dividing by 0, set count to count + 1.
for (count = 0; count <= n; count++)
sum = sum + (1.0 / (count + 1) );
You need simply to use another kind of loop that is the do-while loop. For example
do
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
} while ( n > 0 );
cout << "Bye! ";
And instead of the declaration
int n, count;
you should use declaration
unsigned int n, count;
You could else check whether the input is valid. For example
if ( !( cin >> n ) || n == 0 ) break;
Taking this into account you could use also the following kind of loop
while ( true )
{
cout << "Enter a positive integer N (<1 to stop): ";
unsigned int n;
cin >> n;
if ( !( cin >> n ) || n == 0 ) break;
sum = 0;
for (unsigned int count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
Related
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.
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'm starting learning C++ on my own and I'm confused with one assignment which I'm trying to complete. User shoud type in natural numbers as long as he wants until he types in 0. After that my program should find the largest sum of digits which were typed and print it out. It shoud also print out a number from which it took the sum.
Here is what I tried to do:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int input = 0;
int digit;
int sum = 0;
int largest = 0;
do
{
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
while (input > 0)
{
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
largest = sum;
} while (input);
cout << "Max sum of digits was " << largest << "for" << endl;
}
When I'm running the programm it counts sum of digits from only first typed in number and stop working. When I take while (input > 0) away, it makes a loop, but doesn't count digits.
I'll be very grateful for help and explanation.
P.S. Sorry for my English, I'm not a native speaker.
You seem to have three problems here:
1 - You are trying to use a variable that you essentially set to zero in your while loop
2 - You seem to be looking for the input that is for the largest sum
3 - You are not resetting your sum variable for each input
The solution for the first problem is to "backup" the input into another variable before modifying it and using that variable for the while loop.
That also allows for you to get what the largest number inputted is and store it.
int input = 0;
int inputBackup = 0;
int digit;
int sum = 0;
int largest = 0;
int largestInput = 0;
To add in the inputBackup variable, put it after the cin.
Then set the largestInput in your sum > largest if statement to set the largestInput if it is the largest.
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
inputBackup = input;// This line
sum = 0; // and this line
while (input > 0)
{
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
{
largest = sum;
largestInput = inputBackup;// Store largest input
}
Then change while(input) to while(inputBackup) to check the inputBackup variable instead of the input one.
Change your cout to be like this to add the largestInput variable into it
cout << "Max sum of digits was " << largest << " for " << largestInput << endl;
And your code should be fixed!
Happy Coding!
do
{
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
//more code
} while (input);
To make this work correctly, input may not change between the cin and the loop condition.
But
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
does change input.
Replace it with something like
int input2 = input;
while (input2 > 0) {
digit = input2 % 10;
sum = sum + digit;
input2 = input2 / 10;
}
In this part:
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
while input is not zero it'll repeat, so when get out the loop the value of input is 0. Use a auxiliary variable or enclose this code on a function:
int getDigitsSum(int input) {
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
return sum;
}
Try that instead
If we do not zero sum value, it accumulate sum of all input digits and the sum will always be larger than than largest value, bacause it stores largest + sum of current values digits. So, if we zero sum value it only contains sum of digits of current input and can be simple compared with previous one wich was largest.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
int input = 0;
int digit;
int sum = 0;
int largest = 0;
do
{
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
largest = sum;
sum = 0; // set to 0 current sum
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
} while (input);
cout << "Max sum of digits was " << largest << " for" << endl;
_getch();
return 0;
}
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.