×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

C Program to find the sum of digits of a number until a single digit is occurred (without using recursion or iterative(loop) statements).
Submitted by Abhishek Jain, on April 09, 2017

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

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

#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

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.