Hello. I'm going through a C++ book on my own and am having a hard time writing a program for this exercise:
An integer is divisible by 9 if the sum of its digits is divisible by 9.Write a program that prompts the user to input an integer.The program should then output the number and a message stating whether the number is divisible by 9. It does so by first adding the digits and then checking whether the sum of the digits is divisible by 9.
I know the solution is probably pretty simple and I can get a 2 digit integer to calculate fine but any more and I get an infinite loop. I know the looping structure is required but I'm not to sure about the formatting of it. Any help would be appreciated. Thank you.
#include <iostream>
#include <conio.h>
usingnamespace std;
int main()
{
//Declare and initialize variables
int integer = 0;
int dividedBy = 0, remainder = 0;
int sum = 0;
//Ask for an integer
cout << "Give me an integer: ";
cin >> integer;
cout << endl;
//Split the integer into separate digits
dividedBy = integer / 10;
remainder = integer % 10;
sum = divisor + remainder;
//Keep splitting te number up until the remainder is 0
while (dividedBy >= 10)
{
dividedBy = dividedBy / 10;
remainder = dividedBy % 10;
sum = dividedBy + remainder;
}//Closes while*/
//Display output
if (sum == 9)
cout << "The integer is divisble by 9." << endl;
else
cout << "The integer is not divisible by 9." << endl;
//Close program on user input
getch();
return 0;
}
OK, read the thread on console closing down. getch() is a nonstandard and crappy solution. But at least you aren't using void main, which is, IMO, worse.
If you know how to use stringstreams (they are quite esoteric though, so I don't blame you if you don't) then you can convert the int to a string, cycle through the string's chars and add them up. Too much casting though. It's a bit messy.
I am not sure what your condition should be. Maybe >0? I can't analyze this theoretically for some reason, my brain's all addled up today...
I know what you mean about the addled brain... and thanks for the info on getch(). I'll follow your suggestion and read the thread as an alternative to bludgeoning myself with the keyboard lol.
So I figured it out. Basically I needed to use a while loop to apply the modulus operator to the integer provided by the user and then make the integer equal to itself divided by 10. Here is the updated code:
#include <iostream>
usingnamespace std;
int main()
{
//Declare and initialize variables
int integer = 0;
int digit = 0;
int sum = 0;
//Ask for an integer
cout << "Give me an integer: " << endl;
//Split the integer into digits and add them together
if (cin >> integer)
{
while (integer != 0)
{
digit = integer % 10;
integer /= 10;
sum += digit;
cout << digit << " ";
}
}
//Display output
if (sum == 9)
cout << "\nThe integer is divisble by 9." << endl;
else
cout << "\nThe integer is not divisible by 9." << endl;
return 0;
}