Java – While Loop Programs

Program to display the first digit of given number:

import java.util.Scanner;
class Code
{
            public static void main(String[] args)
            {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter Num : “);
                        int n = scan.nextInt();
                        while(n>=10)
                        {
                                    n = n/10;
                        }
                        System.out.println(“First Digit : ” + n%10);
            }
}

Program to Find the Sum of First and Last digits of given number

import java.util.Scanner;
class Code
{
            public static void main(String[] args)
            {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter Num : “);
                        int n = scan.nextInt();
                        int first = n%10;
                        n=n/10;
                        while(n>=10)
                        {
                                    n = n/10;
                        }
                        int last = n%10;
                        System.out.println(“Sum of First & Last Digits : ” + (first+last));
            }
}

Program to reverse the given number

import java.util.Scanner;
class Code
{
            public static void main(String[] args)
            {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter Num : “);
                        int n = scan.nextInt();
                        int rev=0, r;
                        while(n>0)
                        {
                                    r = n%10;
                                    rev = rev*10 + r;
                                    n = n/10;
                        }
                        System.out.println(“Reverse Number is : ” + rev);
            }
}
Scroll to Top