Write your question here.
Hi, I am trying to write a code to sum the digits of an integer but it keeps on coming back as a 0:( anything will help, thanks!
#include<iostream>
usingnamespace std;
int main()
{
int num = 0;
int sum = 0;
int temp = 0;
int mod = 0;
cout << "Enter an integer " << endl;
cin >> num;
while (mod != 0)
{
sum = 0;
temp = num / 10;
mod = num % 10;
sum += mod;
}
cout << "adding " << num << " is equal to " << sum << endl;
system("Pause");
return 0;
}
Line 14: You're never going to execute your loop since you initialize mod to 0.
Line 17: You don't want to set sum equal to zero inside the loop. If you do, you will set reset the sum to zero for each iteration.
Line 18: What;s the point of this line? You never use temp.
#include<iostream>
usingnamespace std;
int main()
{
int num = 0;
int sum = 0;
int mod = 1;
cout << "Enter an integer " << endl;
cin >> num;
while (mod != 0)
{
num = num / 10;
mod = num % 10;
sum += mod ;
}
cout << "adding " << num << " is equal to " << sum << endl;
system("Pause");
return 0;
}
#include<iostream>
usingnamespace std;
int main()
{
int num = 0;
int sum = 0;
int temp = 0;
int mod = 1;
cout << "Enter an integer " << endl;
cin >> num;
while (num != 0)
{
mod = num % 10;
num = num / 10;
sum += mod;
}
cout << "sum = " << sum << endl;
temp = sum % 3;
if (temp == 0)
{
cout << num << " is divisible by 3" << endl;
}
else
{
cout << num << " is NOT divisible by 3" << endl;
}
system("Pause");
return 0;
}
thank you, I realize that. However if I move my cout to before the loop then im not gonna have the value for sum, so im not sure how to solve that problem
#include<iostream>
int main()
{
int num = 0;
int sum = 0;
int mod = 1;
std::cout << "Enter an integer " << std::endl;
std::cin >> num;
std::cout << "Adding " << num; // <--------
while (num != 0) //mod != 0)
{
mod = num % 10;
sum += mod ;
num /= 10;
}
std::cout << " is equal to " << sum << std::endl; // <--------
return 0;
}
That's not going to work correctly for the reason I pointed out earlier.
Consider the number 102. The sum should be 3, but your loop will stop because the second digit is 0.