Saturday 10 June 2017

Java Code to Exchange the values of three vaiables

Problem:

Exchange the values of a, b and c as follows:
  1. Exchange the value of a to b.
  2. Exchange the value of b to c.
  3. Exchange the value of c to a.
Algorithm:
  1. Get the values of a, b and c.
  2. Assign the value of b to temporary variable
  3. Assign the value of a to b.
  4. Assign the value of c to a.
  5. Assign the value of temporary variable to c.
  6. Print the result
Solution:
 import java.util.Scanner;
public class ExchangeThreeValues {
   static int a,b,c,t;
   public static void main(String[] args) {
      getTheValues();
      System.out.println("Before exchange the values are " + a + " " + b + " " + c);
      exchangeValues();
      System.out.println("After exchange the values are " + a + " " + b + " " + c);
  }
  private static void getTheValues(){
      Scanner s = new Scanner(System.in);
     System.out.println("Enter the value of a: ");
     a = s.nextInt();
     System.out.println("Enter the value of b: ");
     b = s.nextInt();
     System.out.println("Enter the value of c: ");
     c = s.nextInt();
 }
 private static void exchangeValues(){
     t = b;
     b = a;
     a = c;
     c = t;
  }
output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Before exchange the values are 3 30 300
After exchange the values are 300 3 30

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...