Java Questions Part4 - Number Program

1. Write a Java program to print an integer value?
Answer:
// Java program to take an integer as input and print it
import java.io.*; 

import java.util.Scanner; 

class ATI { 

    public static void main(String[] args) 

    { 

        // Declare the variables 

        int num; 

        // Input the integer 

        System.out.println("Enter the integer: ");

        // Create Scanner object 

        Scanner s = new Scanner(System.in); 

        // Read the next integer from the screen 

        num = s.nextInt(); 

        // Display the integer 

        System.out.println("Entered integer is:  + num); 

    } 

}

Output:
Output:

Enter the integer: 10

Entered integer is: 10

2. Write a Java program to swap two numbers using third variable?

Answer: 
public class SwapNumbers {

    public static void main(String[] args) {

        float first = 1.20f, second = 2.45f;

        System.out.println("--Before swap--");

        System.out.println("First number = " + first);

        System.out.println("Second number = " + second);

        // Value of first is assigned to temporary

        float temporary = first;

        // Value of second is assigned to first

        first = second;

        // Value of temporary (which contains the initial value of first) is assigned to second

        second = temporary;

        System.out.println("--After swap--");

        System.out.println("First number = " + first);

        System.out.println("Second number = " + second);

    }

}

Output:
--Before swap--

First number = 1.2

Second number = 2.45

--After swap--

First number = 2.45

Second number = 1.2

3. Write a Java program to swap two numbers without using third variable?

Answer: 
public class SwapNumbers {

    public static void main(String[] args) {

        float first = 12.0f, second = 24.5f;

        System.out.println("--Before swap--");

        System.out.println("First number = " + first);

        System.out.println("Second number = " + second);

        first = first - second;

        second = first + second;

        first = second - first;

        System.out.println("--After swap--");

        System.out.println("First number = " + first);

        System.out.println("Second number = " + second);

    }

}

Output
--Before swap--

First number = 12.0

Second number = 24.5

--After swap--

First number = 24.5

Second number = 12.0

4. Write a Java program to add two numbers?

Answer:
public class AddTwoNumbers {

   public static void main(String[] args) {

      int num1 = 5, num2 = 15, sum;

      sum = num1 + num2;

      System.out.println("Sum of these numbers: "+sum);

   }

}

Output:
Sum of these numbers: 20

5. Write a Java program to find the largest number?

Answer:
public class JavaExample{

  public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if( num1 >= num2 && num1 >= num3)

          System.out.println(num1+" is the largest Number");

      else if (num2 >= num1 && num2 >= num3)

          System.out.println(num2+" is the largest Number");

      else

          System.out.println(num3+" is the largest Number");

  }

}

Output:
20 is the largest Number

6. Write a Java program to print the entered number in reverse?

Answer:
import java.util.Scanner;

class ReverseNumber

{

  public static void main(String args[])

  {

    int n, reverse = 0;

    System.out.println("Enter an integer to reverse:");

    Scanner in = new Scanner(System.in);

    n = in.nextInt();

    while(n != 0)

    {

      reverse = reverse * 10;

      reverse = reverse + n%10;

      n = n/10;

    }

    System.out.println("Reverse of the number is: " + reverse);

  }

}

Output:
Enter an integer to reverse:12345

Reverse of the number is:  54321

7. WAP to print Fizz if no. is divisible by 3, if divisible by 5 then print Buzz and divisible by 15 then print FizzBuzz

Answer:
// Java program to print Fizz Buzz 
import java.util.*; 

class FizzBuzz 

{ 

    public static void main(String args[]) 

    {  

        int n = 100; 

        // loop for 100 times 

        for (int i=1; i<=n; i++)                                  

        { 

            if (i%15==0)                                                  

                System.out.print("FizzBuzz"+" ");  

            // number divisible by 5, print 'Buzz'  

            // in place of the number 

            else if (i%5==0)      

                System.out.print("Buzz"+" ");  

            // number divisible by 3, print 'Fizz'  

            // in place of the number 

            else if (i%3==0)      

                System.out.print("Fizz"+" ");  

            // number divisible by 15(divisible by 

            // both 3 & 5), print 'FizzBuzz' in  

            // place of the number

            else // print the numbers 

                System.out.print(i+" ");                          

        } 

    } 

}

Output:
1    2    Fizz    4    Buzz    Fizz    7    8    Fizz    Buzz    11   

Fizz    13    14    FizzBuzz    16    17    Fizz    19    Buzz    

Fizz    22    23    Fizz    Buzz    26    Fizz    28    29    FizzBuzz    

31    32    Fizz    34    Buzz    Fizz    37    38    Fizz    Buzz    41    

Fizz    43    44    FizzBuzz    46    47    Fizz    49    Buzz    Fizz    

52    53    Fizz    Buzz    56    Fizz    58    59    FizzBuzz    61    

62    Fizz    64    Buzz    Fizz    67    68    Fizz    Buzz    71    

Fizz    73    74    FizzBuzz    76    77    Fizz    79    Buzz    Fizz    

82    83    Fizz    Buzz    86    Fizz    88    89    FizzBuzz    91    

92    Fizz    94    Buzz    Fizz    97    98    Fizz    Buzz


8. Write a Code to generate Random numbers.

Answer:
// A Java program to demonstrate random number generation 
// using java.util.Random;
import java.util.Random; 

public class generateRandom{ 

    public static void main(String args[]) 

    { 

        // create instance of Random class 

        Random rand = new Random(); 

        // Generate random integers in range 0 to 999 

        int rand_int1 = rand.nextInt(1000); 

        int rand_int2 = rand.nextInt(1000); 

        // Print random integers 

        System.out.println("Random Integers: "+rand_int1); 

        System.out.println("Random Integers: "+rand_int2); 

        // Generate Random doubles 

        double rand_dub1 = rand.nextDouble(); 

        double rand_dub2 = rand.nextDouble(); 

        // Print random doubles 

        System.out.println("Random Doubles: "+rand_dub1); 

        System.out.println("Random Doubles: "+rand_dub2); 

    } 

}

Output:
Random Integers: 547

Random Integers: 126

Random Doubles: 0.8369779739988428

Random Doubles: 0.5497554388209912

9. WAP to print Fibonacci series from 1 to 10.

Answer: A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.
public class Fibonacci {

    public static void main(String[] args) {

        int n = 10, t1 = 0, t2 = 1;

        System.out.print("Upto " + n + ": ");

        while (t1 <= n)

        {

            System.out.print(t1 + " + ");

            int sum = t1 + t2;

            t1 = t2;

            t2 = sum;

        }

    }

}

Output:
Upto 10: 0 + 1 + 1 + 2 + 3 + 5 + 8 +

10. Verify if a given number is a palindrome or not.

Answer: A palindromic number is a number (in some base ) that is the same when written forwards or backwards, i.e., of the form . The first few palindromic numbers are therefore are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111 etc.
public class Palindrome {

    public static void main(String[] args) {

        int num = 121, reversedInteger = 0, remainder, originalInteger;

        originalInteger = num;

        // reversed integer is stored in variable 

        while( num != 0 )

        {

            remainder = num % 10;

            reversedInteger = reversedInteger * 10 + remainder;

            num  /= 10;

        }

        // palindrome if orignalInteger and reversedInteger are equal

        if (originalInteger == reversedInteger)

            System.out.println(originalInteger + " is a palindrome.");

        else

            System.out.println(originalInteger + " is not a palindrome.");

    }

}

Output:
121 is a palindrome number.

11. Write a Java Armstrong number program.

Answer:  Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. Let's try to understand why 153 is an Armstrong number.
class ArmstrongExample{  

  public static void main(String[] args)  {  

    int c=0,a,temp;  

    int n=153;//It is the number to check armstrong  

    temp=n;  

    while(n>0)  

    {  

    a=n%10;  

    n=n/10;  

    c=c+(a*a*a);  

    }  

    if(temp==c)  

    System.out.println("armstrong number");   

    else  

        System.out.println("Not armstrong number");   

   }  

}  

Output:
armstrong number

12. Write a code to print the triangle of numbers.

Answer: 
public class Tpattern

{

    public static void main(String[] args)

    {

        int i=0,j=0,n=4,k=1;

        for(i=1; i<n+1; i++)

        {

            for(j=0; j<i; j++)

                System.out.print(" "+k++);

            System.out.println(" ");

        }

    }

}

Output:
1

 2 3

 4 5 6

 7 8 9 10

13. Calculate power of a number using a while loop

Answer: 
public class Power {

    public static void main(String[] args) {

        int base = 3, exponent = 4;

        long result = 1;

        while (exponent != 0)

        {

            result *= base;

            --exponent;

        }

        System.out.println("Answer = " + result);

    }

}

Output:
Answer = 81

14. Write a Java program for printing the even numbers between 1 and 100 using for loop? 

Answer: 
class JavaExample {

   public static void main(String args[]) {

 int n = 100;

 System.out.print("Even Numbers from 1 to "+n+" are: ");

 for (int i = 1; i <= n; i++) {

    //if number%2 == 0 it means its an even number

    if (i % 2 == 0) {

  System.out.print(i + " ");

    }

 }

   }

}

Output:
Even Numbers from 1 to 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 

30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 

78 80 82 84 86 88 90 92 94 96 98 100

15. Write a Java program to find the sum of first 100 numbers using for loop? 

Answer: 
public class SumNatural {

    public static void main(String[] args) {

        int num = 100, sum = 0;

        for(int i = 1; i <= num; ++i)

        {

            // sum = sum + i;

            sum += i;

        }

        System.out.println("Sum = " + sum);

    }

}

Output:
Sum = 5050

16. Write a for loop which prints numbers from 1 to 100. But if the number is divisible by 5, then it should print ‘divisible by 5 followed by that number’? 

Answer:
public class NumberPrint {

 public static void main(String[] args) {

  for (int i = 1; i < 100; i++) {

   if (i % 5 == 0)

    System.out.println("divisible by 5: " + i + ", ");

   else {

    System.out.println(i + ", ");

   }

  }

 }

Output:
1, 2, 3, 4, divisible by 5: 5, 6, 7, 8, 9, divisible by 5: 10, 11, 12, 13, 14, divisible by 5: 15, 16,....

17. How to reverse an integer?

Answer: // Java program to reverse a number
class ATI

{ 

    /* Iterative function to reverse 

    digits of num*/

    static int reversDigits(int num) 

    { 

        int rev_num = 0; 

        while(num > 0) 

        { 

            rev_num = rev_num * 10 + num % 10; 

            num = num / 10; 

        } 

        return rev_num; 

    } 

    // Driver code 

    public static void main (String[] args)  

    { 

        int num = 4562; 

        System.out.println("Reverse of no. is " 

                           + reversDigits(num)); 

    } 

}

Output:
6985

18. Write a Java program to find odd and even numbers ?

Answer:
import java.util.Scanner;

public class Odd_Even 

{

    public static void main(String[] args) 

    {

        int n;

        Scanner s = new Scanner(System.in);

        System.out.print("Enter the number you want to check:");

        n = s.nextInt();

        if(n % 2 == 0)

        {

            System.out.println("The given number "+n+" is Even ");

        }

        else

        {

            System.out.println("The given number "+n+" is Odd ");

 }

    }

}

Output:
Enter the number you want to check:15

The given number 15 is Odd

19. Write a Java program for printing the prime numbers?

Answer: A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
public class PrimeExample{    

 public static void main(String args[]){    

  int i,m=0,flag=0;      

  int n=3;//it is the number to be checked    

  m=n/2;      

  if(n==0||n==1){  

   System.out.println(n+" is not prime number");      

  }else{  

   for(i=2;i<=m;i++){      

    if(n%i==0){      

     System.out.println(n+" is not prime number");      

     flag=1;      

     break;      

    }      

   }      

   if(flag==0)  { System.out.println(n+" is prime number"); }  

  }//end of else  

}    

}   

Output:
3 is prime number

20. Write a Java program to demonstrate creating factorial of a number using recursion?

Answer:  Factorial, in mathematics, the product of all positive integers less than or equal to a given positive integer and denoted by that integer and an exclamation point. Thus, factorial seven is written 7!, meaning 1 × 2 × 3 × 4 × 5 × 6 × 7.
import java.util.Scanner;

public class Factorial

{

    public static void main(String[] args) 

    {

        int n, mul;

        Scanner s = new Scanner(System.in);

        System.out.print("Enter any integer:");

        n = s.nextInt();

        Factorial obj = new Factorial();

        mul = obj.fact(n);

        System.out.println("Factorial of "+n+" :"+mul);

    }

    int fact(int x)

    {

        if(x > 1)

        {

            return(x * fact(x - 1));

        }

        return 1;

    }

}

Output:
Enter any integer:8

Factorial of 8 :40320

21. Write a Java program to verify whether a number is perfect number or not?

Answer: Perfect number, a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8,128.

import java.util.Scanner;

public class Perfect

{

    public static void main(String[] args) 

    {

        int n, sum = 0;

        Scanner s = new Scanner(System.in);

        System.out.print("Enter any integer you want to check:");

        n = s.nextInt();

        for(int i = 1; i < n; i++)

        {

            if(n % i == 0)

            {

                sum = sum + i;

            }

        }

        if(sum == n)

        {

            System.out.println("Given number is Perfect");

        }

        else

        {

            System.out.println("Given number is not Perfect");

        }    

    }

    int divisor(int x)

    {

       return x;

    }

}

Output
Enter any integer you want to check:6

Given number is Perfect

22. Write a Java program to check whether a given number is Armstrong ?

Answer: Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. Let's try to understand why 371 is an Armstrong number.
public class Armstrong {

    public static void main(String[] args) {

        int number = 371, originalNumber, remainder, result = 0;

        originalNumber = number;

        while (originalNumber != 0)

        {

            remainder = originalNumber % 10;

            result += Math.pow(remainder, 3);

            originalNumber /= 10;

        }

        if(result == number)

            System.out.println(number + " is an Armstrong number.");

        else

            System.out.println(number + " is not an Armstrong number.");

    }

}

Output:
371 is an Armstrong number.

23. Write a Java program to print Floyd’s triangle?

Answer:
import java.util.Scanner;

public class FloyidsTriangle {

   public static void main(String args[]){

      int n,i,j,k = 1;

      System.out.println("Enter the number of lines you need in the FloyidsTriangle");

      Scanner sc = new Scanner(System.in);

      n = sc.nextInt();



      for(i = 1; i <= n; i++) {

         for(j=1;j <= i; j++){

            System.out.print(" "+k++);

         }

         System.out.println();

      }

   }

}

Output:
Enter the number of lines you need in the FloyidsTriangle
9

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

16 17 18 19 20 21

22 23 24 25 26 27 28

29 30 31 32 33 34 35 36

37 38 39 40 41 42 43 44 45

24. Write a Java program to find find the biggest number among 1,2,3,4,5,65,76,5,4,33,4,34,232,3,2323?

Answer:
package NumberPackge;

 public class MaximumInArray {

 public static int arr[] = { 1,2,3,4,5,65,76,5,4,33,4,34,232,3,2323};

 // Method to find maximum in arr[]

 static int biggest() {

  int i;

  // Initialize maximum element

  int max = arr[0];

  // Traverse array elements from second and

  // compare every element with current max

  for (i = 1; i < arr.length; i++)

   if (arr[i] > max)

    max = arr[i];

  return max;

 }

 public static void main(String[] args) {

  System.out.println("Biggest number in given array is: " + biggest ());

 }

}

Output:
Biggest number in given array is: 2323

25. Write a Java Program to print the below output: * 1 * 12 * 123 * 1234 * 12345 * 123456 * 1234567.

Answer: 
public class JavaProgram {

 public static void main(String[] args) {



  printPattern();

 }

 static void printPattern() {

  int i, j;

  for (i = 1; i <= 7; i++) {

   System.out.print(" * ");

   for (j = 1; j <= i; j++)

    System.out.print(j);

  }

 }

}

Output:
* 1 * 12 * 123 * 1234 * 12345 * 123456 * 1234567

26. Java Program: Write 0 and 1 separately from 10011101101 and find the frequency of each?

Answer:
import java.util.Scanner;

public class FrequencyOfDigits

{   

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in); 

        //Taking inputNumber from the user 

        System.out.println("Enter the number :"); 

        int inputNumber = sc.nextInt(); 

        //Creating an Array object to hold the frequency of corresponding digits i.e

        //frequency of 0 at index 0

        //frequency of 1 at index 1

        //frequency of 2 at index 2 and so on....

         

        int[] digitCount = new int[10];

         

        while (inputNumber != 0)

        {

            //Get the lastDigit of inputNumber

             

            int lastDigit = inputNumber % 10;

             

            //incrementing the lastDigit's count

             

            digitCount[lastDigit]++;

             

            //Removing the lastDigit from inputNumber

             

            inputNumber = inputNumber / 10;

        }

         

        //Printing digits and their frequency

         

        System.out.println("===================");

         

        System.out.println("Digits : Frequency");

         

        System.out.println("===================");

         

        for (int i = 0; i < digitCount.length; i++)

        {

            if(digitCount[i] != 0)

            {

                System.out.println("   "+i+"   :   "+digitCount[i]);

            }

        } 

         

        sc.close();

    }

}

Output:
Enter the number :

10011101101

===================

Digits : Frequency

===================

1      :      7

0      :      4

27. Write a Java program to check whether an year is leap year or not?

Answer: A leap year is a year in which an extra day is added to the Gregorian calendar, which is used by most of the world. While an ordinary year has 365 days, a leap year has 366 days. ... A leap year comes once every four years. Because of this, a leap year can always be evenly divided by four.
import java.util.Scanner;
public class Check_Leap_Year 

{

    public static void main(String args[])

    {

        Scanner s = new Scanner(System.in);

        System.out.print("Enter any year:");

        int year = s.nextInt();

        boolean flag = false;

        if(year % 400 == 0)

        {

            flag = true;

        }

        else if (year % 100 == 0)

        {

            flag = false;

        }

        else if(year % 4 == 0)

        {

            flag = true;

        }

        else

        {

            flag = false;

        }

        if(flag)

        {

            System.out.println("Year "+year+" is a Leap Year");

        }

        else

        {

            System.out.println("Year "+year+" is not a Leap Year");

        }

    }

}

Output:
Enter any year:1800

Year 1800 is not a Leap Year


2 comments: