Split an integer and find the largest sum C++ - c++

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;
}

Related

C++ How to convert decimal number to binary?

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.

How to assure the loop is entered (C++)

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! ";

i have this example in my textbook, i want to solve it with any loop method

I have an example in my textbook with following code and input
/* A program that takes a four digits integer from user and shows the digits on the
screen separately i.e. if user enters 7531, it displays 7,5,3,1 separately. */
#include <iostream.h>
main()
{
// declare variables
int number, digit;
// prompt the user for input
cout << "Please enter 4-digit number:";
cin >> number;
// get the first digit and display it on screen
digit = number % 10;
cout << "The digits are: ";
cout << digit << ", ";
// get the remaining three digits number
number = number / 10;
// get the next digit and display it
digit = number % 10;
cout << digit << ", ";
// get the remaining two digits number
number = number / 10;
// get the next digit and display it
digit = number % 10;
cout << digit << ", ";
// get the remaining one digit number
number = number / 10;
// get the next digit and display it
digit = number % 10;
cout << digit;
}
A sample output of the above program is given below.
Please enter 4-digit number: 5678
The digits are: 8, 7, 6, 5
How can i solve it with loop method.
A loop executes the same section of code zero or more times, depending on the loop's conditional.
If you carefully examine your code, you see that you are repeating essentially the same code, four times: calculate the remainder of a division by ten, integer division by ten, and some output.
So, it seems logical to simply write a loop that executes the same exact code, which only executes these operations one, but have the loop execute this section of code four times.
And that's how you do it.
To get an equivalent output You can use for example do-while loop
cout << "The digits are: ";
do
{
cout << number % 10;
} while ( ( number /= 10 ) && cout << ", " );
Or
do
{
cout << number % 10;
number /= 10;
if ( number ) cout << ", ";
} while ( number );
If you want to output exactly four digits provided that the number indeed has four digits then you can write
int i = 0;
do
{
cout << number % 10;
number /= 10;
if ( number ) cout << ", ";
} while ( ++i < 4 && number );
First you need to recognise part of code which repeat itself more times and that code put inside some loop(for,while,do-while) and declare how many times it will execute,mostly it is some bool expresion. In you case this part of code you need to put inside for,while or do-while loop:
digit = number % 10;
cout << digit << ", ";
number = number / 10;
for example:
for(int i=0;i<4;i++){
digit = number % 10;
if(i!=3)
cout << digit << ", ";
else
cout << digit;
number = number / 10;
}
Is there any specific reason you need to perform division on an integer? If you accept the user's input as a string it is possible to simply iterate over the characters contained e.g
string val;
cin >> val;
int len = val.length();
for(int i = len-1; i >= 0; --i){
cout << val[i]<<",";
}
Of course if you know the number of digits beforehand you can easily do this using an int
int val;
cin >> val;
for(int i = 0; i < 4; ++i){
int digit = val % 10;
val /= 10;
cout << digit << ",";
}
If you need to extend the solution to cover any arbitrary length int you would need a while loop with this condition
while(val > 0){
int digit = val % 10;
val /= 10;
cout << digit << ",";
}

Adding a series of input number in c++

Hi can anyone help me in creating a code for the sum of input number in C++.
e.g.
Input: 535
Output: 13
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int i = 0,sum = 0;
int numarray[50];
void calc(int c,string num) {
do {
numarray[i] = num.at(i);
/*sum = sum + numarray[i];*/
sum = sum + num.at(i);
cout << numarray[i] << endl;
i++;
} while(i != c);
cout << sum << endl;
}
int main() {
string num;
int i,charlen;
int numar[50];
int sum=0;
cout << "Input numbers: ";
cin >> num;
charlen = num.length();
calc(charlen,num);
}
While characters are numbers, their values are often not the same as the character they represent. The most common encoding scheme is ASCII encoding.
As you can see in the linked table, the digits don't have the value 1 or 2 etc. Instead they have values like 49 and 50 etc. The characters '5' and '3' have the ASCII values 53 and 51 respectively, adding e.g. "535" will give you the result 157.
But as you can see in the ASCII table, all numbers are consecutive, that means we can use a very simple trick to get the digits value from its ASCII value, simply subtract the ASCII value of '0'. For example '5' - '0' will give you the value 5.
Without testing:
#include <iostream>
int main()
{
unsigned long long x;
std::cout << "Enter a non-negative number: ";
std::cin >> x;
unsigned long long sum = 0;
do { sum += x % 10; } while ( x /= 10 );
std::cout << "\nThe sum of digits of the number is " << sum << std::endl;
}
For the sake of readability, it might help to not pass in the charlength into the function, and just do that inside the method. Besides that, a for loop seems like a better option in this case as well.
void calc(string num) {
int sum = 0, int i = 0;
//for loop run from num.length - 1 to 0 {
/*numarray[i] = stoi(num.at(i));*/
/*sum = sum + numarray[i];*/
sum = sum + stoi(num.at(i));
cout << numarray[i] << endl;
i++;
}
cout << sum << endl;
}

C calculating sum correctly

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. ;-)