I have a homework assignment for my beginner's C programming class:
Additive persistence is a property of the sum of the digits of an integer. The sum of the digits is found, and then the summation of digits is performed on the sum, repeating until a single integer digit is reached. The number of such cycles is that integer’s additive persistence. Consider the following example:
● The beginning integer is 1234
● Sum its digits is 1+2+3+4 = 10
● The integer is now 10
● The sum of its digits is 1 + 0 = 1
● The integer is 1. When the value reaches a single digit, we are finished. This final integer is the additive root
The number of cycles is the additive persistence. The integer 1234 has an additive persistence of 2 (first sum was 10, then the second sum was 1). The final digit reached is called the integer’s additive digital root. The additive digital root of 1234 is 1. Write a program that:
● Ask the user for a positive integer.
● If the given integer is a single digit, report it’s additive persistence and multiplicative persistence as 0 and both its additive root as itself.
● If the integer is less than 0, that is a signal to quit the program.
● Otherwise, find the additive persistence and additive root of the given integer and report the results to the user
● Continue by prompting the user until they quit
This is the code I came up with:
#include <stdio.h>
int main()
{
int num;
int pers = 0;
int res = 0;
int sig = 0;
int sum = 0;
int sum1 = 0;
for (sig = 0;sig >= 0;) {
printf("Please enter a positive integer to find the additive persistence, and the integer's additive digital root: ");
scanf_s("%d", &num);
if (num < 0) {
sig--;
break;
}
res = num;
sum = 0;
while((res>0)){
sum = sum + (res % 10);
res = num / 10;
if (res == 0) {
if (sum >= 10) {
res = sum;
sum = 0;
}
if (sum < 10)
pers++;
}
}
printf("\nThe additive persistence is %d and the additive root is %d\n", pers, sum);
}
return 0;
}
Whenever I (successfully) compile and run the code, after the scanf statement the program does nothing. Why is this happening? And any advice for successfully completing this assignment? Thank you so much for your help
Consider this line:
res = num / 10;
What's the value of res
after the first run through the loop? And after the second run? If you put a print there to debug your program, you'll see that res
always has the same value and doesn't change. It's an infinite loop and will probably go on until you have undefined behavior when sum
overflows. You probably wanted this instead:
res = res / 10;