Descending Order in Java Using For Loop

Descending order in java using for loop. To understand the advanced concepts in sorting program in java for new beginners in the java programming language, write a descending order program in java to sort the array the elements in reverse order or descending order.

For Loop in Java Program

Loops are used in computer programming to repeat a piece of code. Let’s assume we wish to broadcast a message 100 times. We may then use a loop instead of writing the print statement 100 times. That was only a simple example; loops may help us attain far more efficiency and sophistication in our applications. This is sample program for loop example for beginners.

Temporary Variable in Java

temp is the name of a local variable in this example. This program loops through the array a. Each repetition, the next value of an is allocated to temp. The value of temp is sent to the console using System.out.println. A temporary array persists only for the period of the data step in which it is defined. A temporary array can be used to store constant values used in calculations. There are no comparable variables to identify the array elements in a temporary array.

If Else Definition in Java

The condition is also tested using the Java if-else expression. If the condition is true, the if block is performed; otherwise, the else block is run. A Java program that shows how to utilize the if-else expression.  A Java program that shows how to utilize the if-else expression. 

Descending Order in Java Using For Loop

import java.util.Scanner;
public class Main
{
public static void main(String[] args) 
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of array");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements");
for (int i = 0; i < n; i++) 
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) 
{
for (int j = i + 1; j < n; j++) 
{
if (a[i] < a[j]) 
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("After sorting");
for (int i = 0; i < n - 1; i++) 
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}

Output:

Enter the size of array 3

Enter the elements

34 56 67

After sorting 67,56,34