Write a program to add all the digits of a given positive integer until the result has a single digit.

Write a program to add all the digits of a given positive integer until the result has a single digit.

Java Program
import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        int p;
        Scanner s = new Scanner(System.in);
        System.out.print("Input a positive integer: ");
        int n = s.nextInt(); 
        if (n > 0)
        {
            p=(n == 0 ? 0 : (n % 9 == 0 ? 9 : n % 9));
            System.out.print("The single digit number is: " +p);
        }
    }
}	

Output:

Input a positive integer: 1224

The single digit number is: 9

Python Program
def myfun():
    num=int(input("Input a positive integer: "))
    p=(num - 1) % 9 + 1 if num > 0 else 0
    print("The single digit number is: ",p)
    
    
if __name__=="__main__":
    myfun()

Output:

Input a positive integer: 1224

The single digit number is: 9

C Program
#include <stdio.h>
int main() {
    int n,p;
    printf("Input a positive integer: ");
    scanf("%d",&n);
    p=(n == 0 ? 0 : (n % 9 == 0 ? 9 : n % 9));
    printf("The single digit number is: %d",p);
    return 0;
}

Output:

Input a positive integer: 1224

The single digit number is: 9





More Questions


1 . Write a program to add all the digits of a given positive integer until the result has a single digit.
2 . Write a program to calculate the sum of two integers and return true if the sum is equal to a third integer.
3 . Write a program to check given number is Prime Number or not
4 . Write a Program to find Prime Numbers Between given Interval