Tag: java loop program

  • Java Program to Create a Calculator using Switch Case

    The program shows how to Create a Calculator using Switch Case in java. The program uses a scanner class to take the inputs from the user. The switch case is mostly used when it is necessary to give options to the users.

    As we all have used a basic calculator before and we know how it works. It basically lets you input two numbers (operands) and one operator in between. The operator could be one of the following:

    • + = Addition
    • = Subtraction
    • * = Multiplication
    • / = Division

    Similarly, the program below gives you an option for the operation to perform on operands.

    If you do not know about the operators in java and the switch case statements then click the link below.


    Java Program to Create a Calculator using Switch Case

    //Making Calculator in java
      
     import java.util.Scanner;
    
     public class CalculatorJava 
     {
       public static void main(String[] args) 
       {
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter first numbers: ");
        double num1 = reader.nextDouble();
        
        System.out.print("Enter second numbers: ");
        double num2 = reader.nextDouble();
        
        System.out.print("Choose an operator (+, -, *, /): ");
        char operator = reader.next().charAt(0);
        double result;
        
        //switch case 
        switch(operator)
        {
         case '+':
          result = num1 + num2;
          break;
        
         case '-':
          result = num1 - num2;
          break;
        
         case '*':
          result = num1 * num2;
          break;
        
         case '/':
          result = num1 / num2;
          break;
        
         default:
          System.out.printf("Error! operator is not correct");
          return;
        }
        //Displaying result
        System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2, result);
      }
     }

    Output:

    Enter first numbers: 5
    Enter second numbers: 3
    Choose an operator (+, -, *, /): -
    5.0 - 3.0 = 2.0


  • Java Program to Convert Fahrenheit to Celsius and Vice-Versa

    The program shows how to convert Fahrenheit to Celsius and Vice-Versa in java using a switch statement. The program uses a scanner class to take the inputs from the user.

    Switch case is mostly used when it is necessary to give options to the users. The Java program below gives you two options to choose from case 1 and case 2 that calculate the conversion of Fahrenheit to Celsius and Celsius to Fahrenheit respectively.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Convert Fahrenheit to Celsius and Vice-Versa using Switch Case

     //convert Fahrenheit to Celsius and vice-versa using switch in java
    
     import java.util.Scanner;
    
     class FahrenheitCelsius
     {
       public static void main(String args[])
       {
          Scanner sc = new Scanner(System.in);
          
        
          System.out.println("Press 1 to convert Celsius into Fahrenheit");
          System.out.println("Press 2 to convert Fahrenheit into Celsius");
        
          System.out.println("Enter your Choice:");
          int ch = sc.nextInt();
    
          switch(ch)
          {
            case 1:  System.out.println("Enter temperature in Fahrenheit:");
                      float F = sc.nextFloat();
                      float C = ((5/9.0f)*(F-32));
                      System.out.println("Temperature in Centigrade degrees:"+C);
                      break;
    
            case 2: System.out.println("Enter temperature in Celsius:");
                    float c = sc.nextFloat();    
                    float f = ((c - 32)*5)/9;
                    System.out.println("Temperature in Fahrenheit degrees:"+f);
                    break;
    
                        
    
            default:System.out.println("Invalid Input");
                    break;
        }
       }
     }

    Output:

    Press 1 to convert Celsius into Fahrenheit
    Press 2 to convert Fahrenheit into Celsius
    Enter your Choice:
    2 
    Enter temperature in Celsius:
    41
    Temperature in Fahrenheit degrees:5.0

  • Java Program to Calculate Simple Interest, Amount and Compound Interest using a Switch

    The program shows how to Calculate Simple Interest, Amount, and Compound Interest using a Switch in java. The program uses a scanner class to take the inputs from the user.

    The switch case is mostly used when it is necessary to give options to the users. The following program gives users 3 different options to choose from and it displays results accordingly.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Calculate Simple Interest, Amount and Compound Interest

     //calculate Simple Interest, Amount in java
     //and Compound Interest using switch 
    
     import java.util.Scanner;
     import java.io.*;
     
     class InterestAmountCI
     {
      public static void main(String args[])
      {
            Scanner sc = new Scanner(System.in);
            
          
            System.out.println("Press 1 to find Simple Interest");
            System.out.println("Press 2 to find the Amount");
            System.out.println("Press 3 to find the Compound Interest");
            
            System.out.print("Enter your Choice: ");
            int ch = sc.nextInt();
    
            switch(ch)
            {
              case 1:  System.out.println("Enter Principal, Rate and Time:");
                       float principal = sc.nextFloat();
                       float rate = sc.nextFloat();
                       float time = sc.nextFloat();
                        
                       float SI =principal*rate*time/100;
                       System.out.println("Simple Interest: "+SI);
                       break;
    
              case 2: System.out.println("Enter principal and Interest:");
                      float P = sc.nextFloat(); 
                      float I = sc.nextFloat();
                      
                      float Amount =P + I;
                      System.out.println("Amount: "+Amount);
                      break;
              case 3: System.out.println("Enter principal, Rate and Time:");
                      float Pr = sc.nextFloat(); 
                      float r = sc.nextFloat();
                      float t = sc.nextFloat();
                      double CI = Pr *  Math.pow( 1.0 + r, t);
    
                      System.out.println("Compound Interest: "+CI);
                      break;
    
                          
    
              default:System.out.println("Invalid Input");
                      break;
            }
      }
     }

    Output:

    Press 1 to find Simple Interest
    Press 2 to find the Amount
    Press 3 to find the Compound Interest
    Enter your Choice: 1
    Enter Principal, Rate and Time:
    1000
    5
    2
    Simple Interest: 100.0

  • Java Program to Calculate the Area of Different Geometric Figures

    The program shows how to Calculate the Area of Different Geometric Figures in java using a switch statement. The program uses a scanner class to take the inputs from the user.

    The switch case is mostly used when it is necessary to give options to the users. The following program gives users seven cases or options to choose from and it displays results accordingly.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Calculate the Area of Different Geometric Figures using Switch Case

     //area of different geometric figures using switch case in java
    
     import java.util.Scanner;
    
     public class AreasSwitch
     {
      public static void main(String args[])
      {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("To find the areas of following press:");
        System.out.println("1 for the Area of a Circle");
        System.out.println("2 for the Area of a Square");
        System.out.println("3 for the Area of a Right Angled Triangle");
        System.out.println("4 for the Area of a Rectangle");
        System.out.println("5 for the Circumference of a Circle");
        System.out.println("6 for the Perimeter of a Square");
        System.out.println("7 for the Perimeter of a Rectangle");
        System.out.println("Enter your Choice:");
        int ch = sc.nextInt();
    
        switch(ch)
        {
          case 1: System.out.println("Enter radius for the circle:");
                  float r = sc.nextFloat();
                  float area = 3.14f*r*r;
                  System.out.println("Area:"+area);
                  break;
    
          case 2: System.out.println("Enter side for square:");
                  int s = sc.nextInt();
                  int ae = s*s;
                  System.out.println("Area:"+ae);
                  break;
    
          case 3: System.out.println("Enter height and base for traingle:");
                  float h = sc.nextFloat();
                  float bs = sc.nextFloat();
                  float ar = 0.5f*h*bs;
                  System.out.println("Area:"+ar);
                  break;
    
          case 4: System.out.println("Enter length and breadth for rectangle:");
                  int l = sc.nextInt();
                  int b = sc.nextInt();
                  int aa = l*b;
                  System.out.println("Area:"+aa);
                  break;
    
          case 5: System.out.println("Enter radius for circle:");
                  float rad = sc.nextFloat();
                  float cir = 3.14f*2f*rad;
                  System.out.println("Circumference:"+cir);
                  break;
    
    
          case 6: System.out.println("Enter side for square:");
                  int side = sc.nextInt();
                  int peri = 4*side;
                  System.out.println("Perimeter:"+peri);
                  break;
          
          case 7: System.out.println("Enter length and breadth for rectangle:");
                  int lg = sc.nextInt();
                  int br = sc.nextInt();
                  int per = 2*(lg+br);
                  System.out.println("Perimeter:"+per);
                  break;             
    
          default:System.out.println("Invalid Input");
                  break;
        }
      }
     }

    Output:

    To find the areas of following press:
    1 for the Area of a Circle
    2 for the Area of a Square
    3 for the Area of a Right Angled Triangle
    4 for the Area of a Rectangle
    5 for the Circumference of a Circle
    6 for the Perimeter of a Square
    7 for the Perimeter of a Rectangle
    Enter your Choice:
    4
    Enter length and breadth for rectangle:
    5
    8
    Area:40

  • Java Program to Check for the Negative Number

    The program shows how to Check for the Negative Number in java. This program is also a good demonstration to know the working process of the if-else statement.

    If you do not understand the program, perhaps you may want to learn about the if-else statement first.


    Java Program to Check for the Negative Number

     //check for the negative number using if-else statement in java
    
     public class IfElseNegNumber
     {
       public static void main(String[] args) 
       {
         int num = 5;
          
          if(num < 0)  //checking condition for true
          { 
            System.out.println("Number is negative");
          }
          else //executed if the condition is false
          { 
            System.out.println("Number is positive");
          }
            
          System.out.println("Always executed");
       }
       
     }

    Output:

    Number is positive
    Always executed


  • Java Program to List Even Numbers within a Range

    The program shows how to List Even Numbers within a Range in java. The program uses a scanner class to take the input of the last number(n) from the user.

    Therefore it displays all the even numbers between 1 to n using for loop and if statement.

    If you do not know the working process of for loop and if statement then click the link below.


    Java Program to List all the Even Numbers within a Range

     //list even numbers using for loop
    
     import java.util.Scanner;
    
     public class ListOfEvenNumbers
     {
      
       public static void main(String[] args) 
       {
         
         Scanner scanner = new Scanner(System.in);
         
         System.out.println("Enter the last number:");
         int num = scanner.nextInt();
     
         System.out.println("Displaying even numbers between 1 to " +num);
         
         for(int i=1; i <= num; i++)
         {
          // if the number is divisible by 2 then it is even
          if( i % 2 == 0)
          {
            System.out.print(i + " ");
          }
         }
       }
     }

    Output:

    Enter the last number:
    50
    Displaying even numbers between 1 to 50
    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 

  • Java Program to Calculate Average of Elements in an Array

    The program shows how to Calculate the Average in an Array element in java. The program uses a scanner class to take the input from the user. It takes the size of an array and the array elements and adds those elements and displays them accordingly.

    If you do not know the working process of for loop then click the link below.


    Java Program to Calculate Average of Elements in an Array

     //calculate the average in an array element using for loop
    
     import java.util.Scanner;
    
     public class AverageForLoop
     {
        public static void main(String args[])
        {
          int num, sum = 0;
          float average;
          Scanner s = new Scanner(System.in);
          
          System.out.print("Enter the number of elements for an array: ");
          num = s.nextInt();
          
          int a[] = new int[num];
          
          System.out.println("Enter elements of array:");
          for(int i = 0; i < num; i++)
          {
              a[i] = s.nextInt();
          }
             
         
         for(int i=0; i < a.length ; i++)
           sum = sum + a[i];
         
         //calculate average value
         average = sum / num;
         
         System.out.println("Average value of array elements is : " +average);
            
        }
     }

    Output:

    Enter the number of elements for an array: 5
    Enter elements of array:
    1
    2
    3
    4
    5
    Average value of array elements is : 3.0


  • Java Program to Generate First n Whole Numbers using a do-while loop

    The program shows how to Generate First n Whole Numbers in java. The program is pretty simple n is already defined in a program. Although you can use the scanner class to take the inputs from the user.

    If you do not know the working process of do-while loop then click the link below.


    Java Program to Generate First n Whole Numbers

     //generate first n whole numbers using do-while loop 
    
     public class DoWhileNNumbers 
     {
        public static void main(String args[]) 
        {
          int num = 0;
          int N = 10;
        
          System.out.println("First 5 whole Number ");
          do
          {
           System.out.print(num + " ");
           num++; // Incrementing 
          } while ( num <= N );
        }
     }

    Output:

    First 5 whole Number
    0 1 2 3 4 5 6 7 8 9 10


  • Java Program to Count Backward of a Number using a do-while loop

    In this tutorial, we will write a program to count the number backward in java. The program uses a scanner class to take the input from the user and with a do-while loop, it counts backward and displays the result.

    If you do not know the working process of do-while loop then click the link below.


    Java Program to Count Backward of a Number

     //count backward of a number using do-while loop in java
    
     import java.util.Scanner;
    
     public class CountBackNumber
     {
       public static void main(String args[])
       {
         int n = 5;
         Scanner scanner = new Scanner(System.in);
    
         System.out.println("Enter the number from where you want to back count: ");
         n = scanner.nextInt();
    
         do {
           System.out.print(n + " ");
           n--;  // Decrementing N by 1 in each iteration
         } while (n >= 0);
       }
     }

    Output:

    Enter the number from where you want to back count:
    10
    10 9 8 7 6 5 4 3 2 1 0


  • Java Program to Find the Greatest of Three numbers using if-elseif statement

    The following program takes three integers from the user and finds the largest of those three numbers. The program uses if..else if statement to check the greatest of three and print them accordingly.

    Before we start, click on the links below to have a proper working idea of if..else if statement that this program uses.


    Java Program to Find the Greatest of Three Numbers

     //greatest of three numbers using if-elseif statement in java
    
     import java.util.Scanner;
    
     public class GreatestNumber 
     {
         public static void main(String[] args) 
         {
            int num1, num2, num3;
            
            Scanner s = new Scanner(System.in);
            System.out.println("Enter the first number:");
            num1 = s.nextInt();
            
            System.out.println("Enter the second number:");
            num2 = s.nextInt();
            
            System.out.println("Enter the third number:");
            num3 = s.nextInt();
            
            
            if(num1 > num2 && num1 > num3)
            {
                System.out.println("Largest number is:"+num1);
            }
            else if(num2 > num3)
            {
                System.out.println("Largest number is:"+num2);
            }
            else
            {
                System.out.println("Largest number is:"+num3);
            }
    
         }
     }

    Output:

    Enter the first number:
    34
    Enter the second number:
    89
    Enter the third number:
    23
    Largest number is:89