Tuesday 27 June 2017

Java code to simulate multiplication by addition.

Problem:

Design an algorithm to simulate multiplication by addition.

Solution:

package com.myprograms;

import java.util.Scanner;

public class MultiplicationByAddition {

int multiplier;
int multiplicand;

public static void main(String[] args) {
MultiplicationByAddition multiplicationByAddition = new MultiplicationByAddition();
multiplicationByAddition.getTheNumber();
multiplicationByAddition.calculateMultiplication();
}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter multiplicand value: ");
multiplicand = s.nextInt();
System.out.println("enter multiplier value: ");
multiplier = s.nextInt();
s.close();
}

public void calculateMultiplication(){
int result = 0;
for(int i = 1; i<= multiplier; i++){
result = multiplicand + result;
}
System.out.println("the result is: " + result);
}

}


Output:

enter multiplicand value:
5
enter multiplier value:
20
the result is: 100

Thursday 22 June 2017

Java Code to find the largest factorial number present as a factor in n.

Problem:

Design an algorithm which, given some integer n, finds the largest factorial number present as a factor in n.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation4 {

int n;

public static void main(String[] args) {

FactorialComputation4 factorialComputation3 = new FactorialComputation4();
factorialComputation3.getTheValues();
factorialComputation3.printTheResult();
}

private void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("enter a  number");
n = s.nextInt();
s.close();
}

private int findFactorial(){
if(n <= 0)
return -1;
int i = 1;
int j = 2;
while(n%j == 0)
{
if(i*j <= n)
i = i*j;
j++;
}
return i;
}

private void printTheResult(){
System.out.println("The largest factorial number as a factor is: " + findFactorial());
}
}


Output:

enter a  number
12
The largest factorial number as a factor is: 6


Wednesday 21 June 2017

Java Code to determine whether or not a number n is a factorial number

Problem:

Design an algorithm to determine whether or not a number n is a factorial number.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation3 {

int n;

public static void main(String[] args) {

FactorialComputation3 factorialComputation3 = new FactorialComputation3();
factorialComputation3.getTheValues();
factorialComputation3.printTheResult();
}

private void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("enter a  number");
n = s.nextInt();
s.close();
}

private int findFactorial(){
if(n <= 0)
return -1;
int i = 1;
int j = 2;
while(n%j == 0)
{
if(i*j <= n)
i = i*j;
j++;
}
return i;
}

private void printTheResult(){
if(n==findFactorial()){
System.out.println("the given number is factorial");
}
else{
System.out.println("the given number is not a factorial");
}
}
}


Output:
enter a  number
3628800
the given number is factorial


Monday 19 June 2017

Java Code to compute the xn(x power n)/n!

Problem:

For a given x and a given n, design an algorithm to compute xn (x power n)/n!.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation2 {

int n;

int x;

int product = 1;

double xPowerN;

public static void main(String[] args) {

FactorialComputation2 factorialComputation2 = new FactorialComputation2();
factorialComputation2.getTheValues();
factorialComputation2.findXPowerN();
factorialComputation2.findFactorial();
factorialComputation2.printTheResult();

}

private void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to do factorial");
n = s.nextInt();
System.out.println("enter x value");
x = s.nextInt();
s.close();
}

private void findFactorial(){
for(int i = 1; i <=n; i++){
product = product * i;
}
}

private void findXPowerN(){
xPowerN = Math.pow(x, n);
}

private void printTheResult(){
System.out.println("the result is: "+ xPowerN/product);
}
}


Output:

enter how many numbers you want to do factorial
5
enter x value
2
the result is: 0.26666666666666666


Java Code to compute the 1/n!

Problem:

For a given n, design an algorithm to compute 1/n!.

Solution:

package com.myprograms;

import java.util.Scanner;

public class ReciprocalsOfFactorialComputation {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to do factorial");
int n = s.nextInt();
int product = 1;
for(int i = 1; i <=n; i++){
product = product * i;
}
System.out.println("1/n! is: " + 1.0/product);
s.close();
}

}


Output:
enter how many numbers you want to do factorial
5
1/n! is: 0.008333333333333333


Sunday 18 June 2017

Java Code to compute the n factorial (n!).

Problem:

Given a number n, compute n factorial (n!).

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to do factorial");
int n = s.nextInt();
int product = 1;
for(int i = 1; i <=n; i++){
product = product * i;
}
System.out.println("the factorial of " + n + " is " + product);
s.close();
}

}


Output:

enter how many numbers you want to do factorial
10
the factorial of 10 is 3628800


Java Code to compute the sum of the first n terms of the series 1-3+5-7+9...

Problem:

Develop an algorithm to compute the sum of the first n terms of the series 1-3+5-7+9....

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SumOfFirstNTermsOfTheSeries {

static int n = 0;

public static void main(String[] args) {

Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in sequence : ");
n = s.nextInt();
findTheSumOfTheSequence();
s.close();
}

private static void findTheSumOfTheSequence(){
int sum = 0;
List<Integer> series  = new ArrayList<Integer>();
series.add(1);
for(int i = 0; i<n-1; i++){
series.add(series.get(i) + 2);
if((i%2) != 0){
series.set(i, -series.get(i));
}
else {
series.set(i, series.get(i));
}
}
for(Integer k: series){
sum = sum + k;
}
System.out.println("the series is: " + series);

System.out.println("The series sum is: " + sum);
}
}


Output:
Enter the No. of terms in sequence :
5
the series is: [1, -3, 5, -7, 9]
The series sum is: 5

Enter the No. of terms in sequence : 
10
the series is: [1, -3, 5, -7, 9, -11, 13, -15, 17, 19]
The series sum is: 28

Saturday 17 June 2017

Java Code to prints out n values of the sequence 1 -1 1 -1 1 -1...

Problem:

Develop an algorithm that prints out n values of the sequence 1 -1 1 -1 1 -1 ...

Solution:
package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PrintOutSequence {

static int n = 0;

public static void main(String[] args) {

Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in sequence : ");
n = s.nextInt();
generateTheSequence();
s.close();
}

private static void generateTheSequence(){
List<Integer> series  = new ArrayList<Integer>();
System.out.print("The series is: ");
for(int i = 0; i<n; i++){
if((i %2) == 0){
series.add(1);
}
else{
series.add(-1);
}

}
System.out.print(series + " ");

}
}

Output:

Enter the No. of terms in sequence :
10
The series is: [1, -1, 1, -1, 1, -1, 1, -1, 1, -1] 

Friday 16 June 2017

Java Code to generate the first n terms of the sequence

Problem:

Generate the first n terms of the sequence 1 2 4 8 16 32 .... without using multiplication.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//This class is defined to generate
//the sequence 1 2 4 8 16 32 .... without using multiplication
public class GeneratingTheFirstNTermsOfSequence {

static int n = 0;

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in series : ");
n = s.nextInt();
generateTheSequence();
s.close();
}

private static void generateTheSequence(){
List<Integer> series  = new ArrayList<Integer>();
series.add(1);
System.out.print("The series is: ");
for(int i = 1; i<=n; i++){
series.add(series.get(i-1) + series.get(i-1));

}
System.out.print(series + " ");

}

}

Output:
Enter the No. of terms in series :
10
The series is: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] 

Java Code to compute the sums for the first n terms.

Problem:

Develop an algorithm to compute the sums for the first n terms of the following series:
  a. s = 1+2+3+.......
  b. s = 1+3+5+.......
  c. s = 2+4+6+......
  d. s = 1+1/2+1/3+.....

Solution:

package com.myprograms;

import java.util.Scanner;

//This class is defined to find the sum of following series
//1. s = 1+2+3+.....
//2. s = 1+3+5+.....
//3. s = 2+4+6+.....
//4. s = 1+1/2+1/3+...
public class SunOfFirstNTerms {

static int n = 0;

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in series : ");
n = s.nextInt();
findTheSumOfSequenceNumbers();
findTheSumOfOddNumbers();
findTheSumOfEvenNumbers();
findTheSumOfReciprocals();

s.close();
}

private static void findTheSumOfSequenceNumbers(){
int sum = 0;
for(int i = 1; i<=n; i++){
sum = sum + i;
}
System.out.println("The sum of 1+2+3+... is: " + sum);
}

private static void findTheSumOfOddNumbers(){
int sum = 0;
for(int i = 1; i<=n; i=i+2){
sum = sum + i;
}
System.out.println("The sum of 1+3+5+... is: " + sum);

}

private static void findTheSumOfEvenNumbers(){

int sum = 0;
for(int i = 2; i<=n; i=i+2){
sum = sum + i;
}
System.out.println("The sum of 2+4+6+... is: " + sum);
}

private static void findTheSumOfReciprocals(){
double sum = 1.0;
for(int i = 2; i<=n; i++){
sum = sum + (1.0/i);
}
System.out.println("The sum of 1+1/2+1/3+... is: " + sum);

}
}


Output:

Enter the No. of terms in series :
10
The sum of 1+2+3+... is: 55
The sum of 1+3+5+... is: 25
The sum of 2+4+6+... is: 30
The sum of 1+1/2+1/3+... is: 2.9289682539682538


Thursday 15 June 2017

Java code to compute the Harmonic Mean of n values

Problem:

Develop an algorithm to compute the harmonic mean of n data values.

Algorithm:

1. Prompt the number of terms in a series
2.  Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
     a. compute current sum by adding the harmonic series (i.e 1/number) to the most recent sum.
4. Divide the number of terms in a series by sum
5. Print the output

Solution:

package com.myprograms;

import java.util.Scanner;

public class HarmonicMean {

public static void main(String[] args) {
System.out.println("Enter the No. of terms in series : ");
Scanner s = new Scanner(System.in);
int n = s.nextInt();

double sum = 0.0;
for(int i = 1; i <= n; i++){
sum = sum + 1.0/i;
}
System.out.println("the harmonic mean  is: " + n/sum);

s.close();
}
}


Output:

Enter the No. of terms in series :
5
the harmonic mean  is: 2.18978102189781


Java Code to find the sum of squares of numbers

Problem:

Design an algorithm to compute the sum of the squares of n numbers.

Algorithm:

1. Prompt and read in the number of numbers to be summed.
2. Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
      a. read in next number
      b. compute current sum by adding the square of the number read to the most recent sum.
4. Write out sum of squares of n numbers.


Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SumOfSquaresOfNNumbers {

List<Integer> numbers = new ArrayList<Integer>();

public static void main(String[] args) {

SumOfSquaresOfNNumbers sumOfSquaresOfNNumbers = new SumOfSquaresOfNNumbers();
sumOfSquaresOfNNumbers.getTheNumbers();
sumOfSquaresOfNNumbers.findTheSumOfSquares();

}

private void getTheNumbers(){
System.out.println("how many numbers you want to find out the squares sum");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 0; i< n;i++){
System.out.println("enter the number");
numbers.add(s.nextInt());
}
}

private void findTheSumOfSquares(){
int sum = 0;
for(Integer i: numbers){
sum = sum + (i * i);
}
System.out.println("the sum is: " + sum);
}
}


Output:
how many numbers you want to find out the squares sum
3
enter the number
1
enter the number
3
enter the number
5
the sum is: 35


Wednesday 14 June 2017

Java Code to compute the average of n numbers

Problem:

     Design an algorithm to compute the average of n numbers.

Algorithm:

1. Prompt and read in the number of numbers to find average.
2. Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
      a. read in next number
      b. compute current sum by adding the number read to the most recent sum.
4. Divide the sum by number of numbers to find out average.
4. Write out average of  n numbers.

Solution:

package com.myprograms;

import java.util.Scanner;

public class AverageOfNNumbers {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to find average");
int n = s.nextInt();
int sum = 0;
for(int i = 0; i< n; i++){
System.out.println("enter the number");
sum = sum + s.nextInt();
}
System.out.println("the average is " + sum/n);
s.close();
}
}


Output:
enter how many numbers you want to find average
3
enter the number
1
enter the number
2
enter the number
3
the average is2


Java Implementation of Computing the Summation of a set of numbers

Problem:

Given a set of n numbers design an algorithm that adds these numbers and returns the resultant sum. Assume n is greater than or equal to zero.


Algorithm:

1. Prompt and read in the number of numbers to be summed.
2. Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
      a. read in next number
      b. compute current sum by adding the number read to the most recent sum.
4. Write out sum of n numbers.


Solution:

package com.myprograms;

import java.util.Scanner;

public class SummationOfNNumbers {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to sum");
int n = s.nextInt();
int sum = 0;
for(int i = 0; i <n; i++){
System.out.println("enter the number");
sum = sum + s.nextInt();
}
System.out.println("the sum is" + sum);
s.close();
}

}

Output:

enter how many numbers you want to sum
5
enter the number
100
enter the number
200
enter the number
300
enter the number
400
enter the number
500
the sum is 1500

Java Code to find the Student Pass count when the variable counter initialized to the total number of students n

Problem:

Given a set of n students examination marks (in the range 0 to 100) make a count of the number of students that passed the examination. A pass is awarded for all marks of 50 and above.

Condition is the variable counter should be initialized to the total number of students n.

Algorithm:

1. Prompt then read the number of marks to be processed.
2. Initialize count to the total number of students n.
3. While there are still marks to be processed repeatedly do
     a. read next mark
     b. if it is a pass (i.e >=50) then subtract one from count.
4. Write out total number of passes

Solution:

package com.myprograms;

import java.util.Scanner;

public class StudentPassCountWithCounterAsNValue {
int a[];
static Scanner s = null;
static int counter = 0;

public StudentPassCountWithCounterAsNValue(int n){
a = new int[n];
counter = n;
}

private void initializeMarks(){
for(int i = 0; i< a.length; i++){
System.out.println("enter the marks");
a[i] = s.nextInt();
}
}

private void findPassedStudents(){
for(int i = 0; i< a.length; i++){
if(a[i] >= 50){
counter = counter - 1;
}
}
}


public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("How many students marks you want to verify??");
StudentPassCountWithCounterAsNValue sp = new StudentPassCountWithCounterAsNValue(s.nextInt());
sp.initializeMarks();
sp.findPassedStudents();
System.out.println("the count of passed students is: "+counter);
}

}


Output:

How many students marks you want to verify??
5
enter the marks
12
enter the marks
56
enter the marks
99
enter the marks
45
enter the marks
6
the count of passed students is: 3


Tuesday 13 June 2017

Java Code to find out the student pass count , pass percentage and total number of marks where the data comes from a file

Problem:


Given a set of n student marks in a file. For this set of marks determine the total number of marks, the number of passes, and the percentage pass rate.

Algorithm:

1. Read the number of marks to be processed  from a file.
2. Initialize the count to zero.
3. While there are still marks to be processed repeatedly do
     a. if it is a pass (i.e >= 50) then add one to count.
4. To find the pass percentage divide the counter value with number of marks.
5. To find the total number of marks
    a. Initialize the sum to zero.
    b. loop the marks to add sum value to each mark.
6. Print the result of passed count, pass percentage and total number of marks

Solution:

package com.myprograms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StudentMarksOperations {
static int counter = 0;
List<Integer> numbers = new ArrayList<Integer>();

public StudentMarksOperations(){
}

private void findPassedStudents(){
for(Integer n: numbers){
if(n >= 50){
counter = counter + 1;
}
}
}

private  void  getTheNumbersFromFile() throws IOException{
File file = new File("D:\\MarksList.txt");
BufferedReader bufferedReader = null;
FileReader fileReader = null;
try {
int number = 0;
fileReader = new FileReader(file);
bufferedReader= new BufferedReader(fileReader);
while((number = bufferedReader.read()) != -1){
numbers.add(number);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(bufferedReader != null){
bufferedReader.close();
}
if(fileReader != null){
fileReader.close();
}
}

}

private double findThePassPercentage(){

return (counter * 100 )/numbers.size();
}

private int findTheTotalNumberOfMarks(){
int sum = 0;
for(Integer n: numbers){
sum = sum + n;
}
return sum;
}

public static void main(String[] args) throws IOException {
StudentMarksOperations studentMarksOperations = new StudentMarksOperations();
studentMarksOperations.getTheNumbersFromFile();;
studentMarksOperations.findPassedStudents();
System.out.println("the count of passed students is: "+counter);
System.out.println("the percentage of pass rate is: " + studentMarksOperations.findThePassPercentage());
System.out.println("the total number of marks is: " + studentMarksOperations.findTheTotalNumberOfMarks());
}
}


Output:

the count of passed students is: 9
the percentage of pass rate is: 64.0
the total number of marks is: 701

Monday 12 June 2017

Java Code to count Negative and Positive Numbers in a set

Problem:

Design an algorithm that reads a list of numbers and makes a count of the number of negatives and the number of non-negative members in the set.

Algorithm:

1. Prompt then read the number of elements in the list.
2. Initialize both positive and negative counters to zero.
3. while there are still numbers to be processed repeatedly do
    a. Check the number is greater than zero. If it is then increment the positive number counter to one.
    b. Check the number is less than zero. If it is then increment the negative number counter to one.
4. Print both counters.

Solution:

package com.myprograms;

import java.util.Scanner;

public class CountOfNegativeAndPositive {

static int a[];
static int positiveNo = 0;
static int negativeNo = 0;
static Scanner s;

public CountOfNegativeAndPositive(int n) {
a = new int[n];
}

private void getTheNumbers(){

for(int i = 0; i<a.length; i++){
System.out.println("enter number :" + i);
a[i] = s.nextInt();
}
}

private void countPositiveAndNegative(){
for(int i = 0; i< a.length; i++){
if(a[i] > 0){
positiveNo = positiveNo + 1;
}
else if(a[i] < 0){
negativeNo = negativeNo + 1;
}
}
}

public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("How many numbers you want to hold in the set");
CountOfNegativeAndPositive countOfNegativeAndPositive = new CountOfNegativeAndPositive(s.nextInt());
countOfNegativeAndPositive.getTheNumbers();
countOfNegativeAndPositive.countPositiveAndNegative();
System.out.println("The Number of positive numbers entered: " + positiveNo);
System.out.println("The Number of negative numbers entered: " + negativeNo);

s.close();
}
}

OutPut:

How many numbers you want to hold in the set
3
enter number :0
-1
enter number :1
0
enter number :2
1
The Number of positive numbers entered: 1
The Number of negative numbers entered: 1

  

Sunday 11 June 2017

Java Code to find out Student Pass Count

Problem:

Given a set of n students examination marks (in the range 0 to 100) make a count of the number of students that passed the examination. A pass is awarded for all marks of 50 and above.

Algorithm:

1. Prompt then read the number of marks to be processed.
2. Initialize count to zero.
3. While there are still marks to be processed repeatedly do
     a. read next mark
     b. if it is a pass (i.e >=50) then add one to count.
4. Write out total number of passes


Solution:

package com.myprograms;
//Algorithm 2.2
import java.util.Scanner;

public class StudentPassCount {
int a[];
static Scanner s = null;
static int counter = 0;

public StudentPassCount(int n){
a = new int[n];
}

private void initializeMarks(){
for(int i = 0; i< a.length; i++){
System.out.println("enter the marks");
a[i] = s.nextInt();
}
}

private void findPassedStudents(){
for(int i = 0; i< a.length; i++){
if(a[i] >= 50){
counter = counter + 1;
}
}
}


public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("How many students marks you want to verify??");
StudentPassCount sp = new StudentPassCount(s.nextInt());
sp.initializeMarks();
sp.findPassedStudents();
System.out.println("the count of passed students is: "+counter);
}
}


Output:
How many students marks you want to verify??
3
enter the marks
56
enter the marks
78
enter the marks
35
the count of passed students is: 2


Saturday 10 June 2017

Java Code to Exchange the values of two variables without using temporary variable

Problem:

Exchange the values of two variables without using temporary variable.

Algorithm:

1. Get the values of a and b.
2. Calculate the sum of a and b and assign to a.
3. Calculate the difference of a and b and assign to b.
4. Calculate the difference of a and b and assign to a.
5. Print the values.

Solution:

import java.util.Scanner;

public class ExchangeTwoValuesWithoutUsingTempVariable {

         static int a,b;

         public static void main(String[] args) {
             getTheValues();
             System.out.println("Before exchange the values are " + a + " " + b);
              exchangeValues();
            System.out.println("After exchange the values are " + a + " " + b);
         }

         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();
        }

        private static void exchangeValues(){
               a= a+b;
               b = a -b;
               a= a-b;
        }
}

Output:

Enter the value of a:
30
Enter the value of b:
3
Before exchange the values are 30 3
After exchange the values are 3 30

Java Code to Exchanging the values of four variables

Problem:

Exchange the values of four variables as follows:
1. Exchange the value of b to a
2. Exchange the value of c to b
3. Exchange the value of d to c
4. Exchange the value of a to d.

Algorithm:
1. Get the values of a,b,c and d.
2. Assign the value of a to temporary variable.
3. Assign the value of b to a.
4. Assign the value of c to b.
5. Assign the value of d to c.
6. Assign the value of temporary variable to d.

Solution:
public class ExchangeFourValuesInReverseOrder {
     static int a,b,c,d,t;
     public static void main(String[] args) {
          getTheValues();
          System.out.println("Before exchange the values are " + a + " " + b + " " + c + " " + d);
          exchangeValues();
          System.out.println("After exchange the values are " + a + " " + b + " " + c + " " + d);
     }
     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();
        System.out.println("Enter the value of d: ");
        d = s.nextInt();
   }
   private static void exchangeValues(){
       t = a;
       a = b;
       b = c;
      c = d;
      d = t;
   }
}

output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Enter the value of d:
3000
Before exchange the values are 3 30 300 3000
After exchange the values are 30 300 3000 3

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

Java Code to Exchanging the values of two variables


Problem: Given two variables, a and b, exchange the values assigned to them.

Algorithm:
1.Get the values of a and b.
2.Save the original value of a to temporary variable.
3.Save the value of b in a.
4.Save the value of temporary variable in b.
5.Print the exchanged values of a and b.

Solution:

import java.util.Scanner;

public class ExchangeTwoValues {
     static int a,b,t;

public static void main(String[] args) {
    getTheValues();
    System.out.println("Before exchange the values are " + a + " " + b);
    exchangeValues();
    System.out.println("After exchange the values are " + a + " " + b);
}

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();
}
private static void exchangeValues(){
    t = a;
    a = b;
    b = t;
}
}
Output:
Enter the value of a:
3
Enter the value of b:
2
Before exchange the values are 3 2
After exchange the values are 2 3

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...