how do i translate this in c++???

int main()
{
int n,r,sum=0;
printf("Enter your number: ");
scanf("%d",&n);
while(n<0)
{
r=%10;
sum= sum+r;
n=n/10;

}
printf("Sum of digits= %d",sum);
getch();


return 0;
}
Replace printf with std::cout and scanf with std::cin.
https://www.geeksforgeeks.org/basic-input-output-c/
wont run T_T
You have to include iostream.
wont run T_T

You're lucky Computergeek01 is psychic!
ahhh then why do you use 10 here? why not other number???
why do you use 10 here? why not other number???


because the number is decimal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sum = 0
n= "456"

loop pass 1:
r=n%10            -> 6
sum= sum+r     -> 6
n=n/10;            -> 45

loop pass 2:
r=n%10            -> 5
sum= sum+r     -> 11
n=n/10;            -> 4

loop pass 3:
r=n%10            -> 4
sum= sum+r     -> 15
n=n/10;            -> 0


as you only ever evaluate the units column (which is correct) dividing y 10 will move all the digits to the right. as in 4560 / 10 = 456

what i did above is called "dry running" its a skill you should try to develop. its a pen and paper task, but it will really help you understand what code is doing. Just pretend you are the computer and make notes of variable values as you go.
Topic archived. No new replies allowed.