Displaying Numbers in Ascending and Descending Order using array
Printing numbers in Ascending and Descending Order
import java.util.Scanner; //Calling Scanner Classpublic class Swap
{
public static void main(String []args)
{
//Declaring Variables
int length;
int a=1;
int i=0;
System.out.println("Enter length of array "); //Instruction for user
length= new Scanner(System.in).nextInt(); //Getting value from user
int num[]= new int [length]; //Initializing array
for( i=0; i<length;i++) //loop for getting array from user
{
System.out.println("Enter Value : "+a); //Instruction for user
num[i]= new Scanner(System.in).nextInt(); //Getting value from user
a++; //Increasing value of a
}
//Code to print array in list
System.out.print("List of array :{ ");
for( i=0; i<length;i++)
{
System.out.print(+num[i]);
System.out.print(", ");
}
System.out.print("}");
//Arranging in ascending order
//Loop to swap value and arrange in ascending order
for (int j=0;j<length;j++)
{
for(i=0;i<length;i++)
{
if(num[i]>num[j])
{
int temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
//Printing Result
System.out.println();
System.out.print("List of array in ascending order :{ ");
for( i=0; i<length;i++)
{
System.out.print(+num[i]);
System.out.print(", ");
}
System.out.print("}");
System.out.println();
//Arranging in descending order
//Loop to swap value and arrange in descending order
for (int j=0;j<length;j++)
{
for(i=0;i<length;i++)
{
if(num[i]<num[j])
{
int num= num[i];
num[i]= num[j];
num[j]= temp;
}
}
}
//Printing Result
System.out.println();
System.out.print("List of array in descending order :{ ");
for( i=0; i<length;i++)
{
System.out.print(+num[i]);
System.out.print(", ");
}
System.out.print("}");
}
}
Output:
Comments
Post a Comment