Array-DS


Problem Statement :


An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai.

Reverse an array of integers.

Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this.


Example:
A=[1,2,3]
Return [3,2,1].


Function Description:

Complete the function reverseArray in the editor below.

reverseArray has the following parameter(s):

 1. int A[n]: the array to reverse
Returns
 1 .int[n]: the reversed array


Input Format:

The first line contains an integer, N, the number of integers in A.
The second line contains N space-separated integers that make up A.


Constraints:
1<=N<=10^3
1<=N<=10^4 where A[i] is ith integer in A.



Solution :


                        In C:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

   int n, new_number;
    scanf("%d", &n);
    
    int *p_numbers = (int*)malloc(n * sizeof(int));
    int i = 0;
    while (i < n) {
        scanf("%d", &new_number);
        *(p_numbers + i) = new_number;
        i++;
    }
    
    while (i >= 1) {
        printf("%d ", *(p_numbers + --i));
    }
    free(p_numbers);
    return 0;
}







In C++:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
            int N;
            cin>>N;
    
            vector<int> arr(N);
    
            for (int i=0;i<N;i++)
                cin>>arr[i];
    
            reverse(arr.begin(),arr.end());
    
                for (int i=0;i<N;i++)
                cout<<arr[i]<<" ";
    
            return 0;
}







In Java:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int length = sc.nextInt();
        int[] array = new int[length];
        for (int i = 0; i < length ; i++) {
            array[i] = sc.nextInt(); 
        }
        for (int i = 0; i < length; i++){
            System.out.print(array[length-i-1] + " ");
        }
    }
}







In Python 3:

n = int(input())
m = input().strip().split(' ')
res = m[::-1]
r=""

for i in range(n):
    r = r + str(res[i]) + " "
    
print(r)