Reversing and sorting an array in Java

Problem:

Write a program that reads 10 values of integers from the user store them in an array of integers.
a. Then print the reverse of this array.
Example:

1 6 3 4 2 9 8 10 5 7

Reverse: 7 5 10 8 9 2 4 3 6 1
b.The program writes the array in increasing order. (Using for loops).

Increasing order: 1 2 3 4 5 6 7 8 9 10

Output:

Not applicable.

Solution:

import java.util.Scanner;

public class Prob2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter " + 10 + " numbers: ");
int[] list = new int[10];

for(int i=0; i<10; i++)
{
list[i] = scan.nextInt();
}

System.out.println("The array in reverse is: ");
for(int i=9; i>=0; i--)
{
System.out.print(list[i] + " ");
}

System.out.println();
System.out.println("The array in increassing order is: ");
for(int i=0;i<list.length;i++)
{
int temp = 0;
for(int j=0;j<list.length-1;j++)
{
if(list[j]>list[j+1])
{
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
for(int i=0; i<list.length; i++)
{
System.out.print(list[i] + " ");
}


}



}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact