# Thread: Problem with sentinel controlled loop

1. ## Problem with sentinel controlled loop

So far I have written a code to find the reverse of a number as well as the sum of the digits for an integer. The program is meant to keep asking the user for a new integer so that it will find the sum and reverse of that new integer again. However when the program asks the user for a new integer it just adds it to the original one how can I separate the operation. For example this is what came out:

Enter an integer:
123
The sum of the digits is: 6
The reverse of the number is : 321
1 <------------ (at this part it didn't even go back to the original printf statement)
The sum of the digits is: 7
The reverse of the number is : 3211

Code:
```#include <stdio.h>
int main()
{

int n, sum=0, r, reverse=0;

printf("Enter an integer:\n");
scanf("%d", &n);

while(n!=-1)
{
while(n!=0)
{
r=n%10;
sum=sum+r;

reverse=reverse*10;
reverse=reverse+n%10;
n=n/10;
}

printf("The sum of the digits is: %d\n", sum);
printf("The reverse of the number is : %d\n", reverse);

scanf("%d", &n);

}
return 0;
}```

By the way I am new with this so please bear with me, thank you in advance.

2. That's because the original printf statement is not part of your loops.

Jim

3. You failed to reset sum and reverse inside the outer loop.

4. I have reset the sum and reverse but how do I get the printf statement to be part of the loop?

5. Originally Posted by n.jimenez
I have reset the sum and reverse but how do I get the printf statement to be part of the loop?
You change sum and reverse inside the inner loop, you do not change the variables (exclusively) in the outer loop (the one controlled by "while (n != -1)").

6. Originally Posted by n.jimenez
I have reset the sum and reverse but how do I get the printf statement to be part of the loop?
Same way you got any of those other statements to be part of the loop. Simply put it between the opening and closing curly brace of the loop you want. Where exactly in the loop you put it depends on where/when you want the print statement to appear relative to other statements in your loop. I recommend right before you ask for user input.

Popular pages Recent additions