Q:

C program to find the sum of digits of a number until a single digit is occurred

0

C program to find the sum of digits of a number until a single digit is occurred

In general , we use loop or recursion to traverse each digit of the number and to add them .But it is a complex method (with time complexity O(n)) in comparison to the method describe below (with time complexity O(1)).

Input: 987654
Output:  3

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#include <stdio.h>

int main()
{
    int x;

    printf("Enter an integer number: ");
    scanf("%d", &x);

    if (x == 0)
        printf("%d", 0);
    else if (x % 9 == 0)
        printf("%d", 9);
    else
        printf("%d", x % 9);

    printf("\n");
 
   return 0;
}

Output:

RUN 1:
Enter an integer number: 123
6

RUN 2:
Enter an integer number: 98751
3

RUN 3:
Enter an integer number: 13
4

RUN 4:
Enter an integer number: 19082
2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now