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

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

C Advance Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.