C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Q. Program to print the elements of an array in reverse order.ExplanationIn this program, we need to print the elements of the array in reverse order that is; the last element should be displayed first, followed by second last element and so on. Above array in reversed order: Algorithm
SolutionPython#Initialize array arr = [1, 2, 3, 4, 5]; print("Original array: "); for i in range(0, len(arr)): print(arr[i]), print("Array in reverse order: "); #Loop through the array in reverse order for i in range(len(arr)-1, -1, -1): print(arr[i]), Output: Original array: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1 C#include <stdio.h> int main() { //Initialize array int arr[] = {1, 2, 3, 4, 5}; //Calculate length of array arr int length = sizeof(arr)/sizeof(arr[0]); printf("Original array: \n"); for (int i = 0; i < length; i++) { printf("%d ", arr[i]); } printf("\n"); printf("Array in reverse order: \n"); //Loop through the array in reverse order for (int i = length-1; i >= 0; i--) { printf("%d ", arr[i]); } return 0; } Output: Original array: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1 JAVApublic class ReverseArray { public static void main(String[] args) { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; System.out.println("Original array: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("Array in reverse order: "); //Loop through the array in reverse order for (int i = arr.length-1; i >= 0; i--) { System.out.print(arr[i] + " "); } } } Output: Original array: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1 C#using System; public class ReverseArray { public static void Main() { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; Console.WriteLine("Original array: "); for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); Console.WriteLine("Array in reverse order: "); //Loop through the array in reverse order for (int i = arr.Length-1; i >= 0; i--) { Console.Write(arr[i] + " "); } } } Output: Original array: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1 PHP<!DOCTYPE html> <html> <body> <?php //Initialize array $arr = array(1, 2, 3, 4, 5); print("Original array: <br>"); for ($i = 0; $i < count($arr); $i++) { print($arr[$i] . " "); } print("<br>"); print("Array in reverse order: <br>"); //Loop through the array in reverse order for ($i = count($arr)-1; $i >= 0; $i--) { print($arr[$i] . " "); ; } ?> </body> </html> Output: Original array: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1
Next Topic#
|