Java Programs


Absolute Value of a number


  • Program to determine the absolute value of a given number.

Program

import java.util.Scanner;

public class Absolute {

            private static Scanner sc;
            public static void main(String[] args) {
                        int num;
                        sc=new Scanner(System.in);
                        System.out.print("Enter the number:");
                        num=sc.nextInt();
                        System.out.print("The absolute value of "+num+" is ");
                        if(num<0) {
                                    System.out.println(-1*num);
                        }
                        else {
                                    System.out.println(num);
                        }
            }
}


Output

Enter the number:-67
The absolute value of -67 is 67


----------------------------------------------------------------------------------------

Sum of Digits


  • Program to find the sum of the digits of a given number.

Program

import java.util.Scanner;


public class AddInt {
            public void revInt(int num) {
                        int j,f=0;
                        while(num>0) {
                                    j=num%10;
                                    f=f+j;
                                    num=num/10;
                        }
                        System.out.println("Sum of the digits = "+f);
            }

            private static Scanner sc;
            public static void main(String[] args) {
                        sc=new Scanner(System.in);
                        System.out.print("Enter an integer:");
                        int num=sc.nextInt();
                        AddInt ob=new AddInt();
                        ob.revInt(num);

            }

}

Output

Enter an integer:784
Sum of the digits = 19

-----------------------------------------------------------------------------------------------

No comments:

Post a Comment