I am supposed to solve the following problem:
Now write a program to calculate the iterated cross sum. This is calculated by iterating the cross sum until you arrive at a single digit number. Example: 4391873 -> 35 -> 8.
Note: You need nested loops and for understanding what a corss sum does suppose you have the number 14 then its cross sum is 5 = 1 4. Another word may be horizontal checksum.
I have the following code for this, which also calculates simple cross sums, but it doesn't work with the example.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int n = 0;
int c = 0;
printf("please give us your number: ");
scanf("%d", &n);
while((c==0) || (c>10)){
while ((n != 0) || (c>10)) {
if (n % 10 != 0) {
c = c n % 10;
n = n / 10;
}
else {
n = n / 10;
}
}
}
printf("%d", c);
return 0;
}
I had thought about linking two while loops, but I can't get it right to calculate the cross sum of the cross sum here. Do you have a tip for this?
Edit: I posted the code.
CodePudding user response:
At each iteration of the outer loop you need to assign C to N and 0 to C. The following solution uses the Ada language.
-- Now write a program to calculate the iterated cross sum.
-- This is calculated by iterating the cross sum until you arrive
-- at a single digit number. Example: 4391873 -> 35 -> 8.
-- Note: You need nested loops.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
Num : Natural;
Temp : Natural;
Sum : Natural := 0;
begin
Put ("Enter an positive integer: ");
Get (Num);
Temp := Num;
loop
while Temp > 0 loop
Sum := Sum (Temp rem 10);
Temp := Temp / 10;
end loop;
exit when Sum < 10;
Temp := Sum;
Sum := 0;
end loop;
Put_Line ("Original number:" & Num'Image & " cross sum:" & Sum'Image);
end Main;
You will have to rethink your outer loop termination so that it works using C syntax. The Ada example exits the outer loop before assigning Sum to Temp and 0 to Sum.
CodePudding user response:
You are using a sentinel value of zero in:
while((c==0) || (c>10))
But if I enter 0
, this will enter an infinite loop. You want to calculate c
from zero from n
, then test if c
is greater then 9. If it is, than you want to replace n
by c
. This is not one of the pre-pakaged loops in C, so you probably need break
or ,
.
while ((n != 0) || (c>10))
The inner loop is just wrong. It should have no dependence on c
; get rid of that c>10
.
if (n % 10 != 0)
This is a redundant test; 0 % 10 == 0
, so this could be simplified.