Java program to print sum of the given number

 Java program to print sum of the given number

Java program  to print sum of the given number by using Do While loop

Example 1


import java.util.Scanner;
class SumofDigits
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int n=sc.nextInt();
int sum=0;
do{
int a=n%10;
sum=sum+a;
n=n/10;
}while(n!=0);
System.out.println("Sum of Digits is: "+sum);
}
}



Example 2
To calculate the sum of the digits of any given number with the help of Java Programs by using
 Static Method

class SumOfDigits
{
public static void main(String arg[])
{
    long n,s;
                  Scanner sc=new Scanner(System.in);
    System.out.println("Enter a number ");
                   n=sc.nextLong();
    s=sum(n);
    System.out.println("Sum of digits of a number is "+s);
                      
}
static int sum(long num)
{
int sum=0;
    while(num!=0)
    {
sum+=num%10;
num/=10;
    }
return sum;
}
}

Comments

Popular posts from this blog

Java Program for shop Bill to Calculate total amount of product with discount

RCM|Consequences of imbalanced Nutrition|WHO share daily need

Learn Data structures and algorithms concepts free online with certificate