A program to reverse an Array or String

Reading Time:- 1 min 12 scec

Reading Time:- 1 min 12 scec


Avatar

 BY TEJAS





First, we have created an array and stored that array in the variable arr. Then we store the size of the arr in the variable n. In this program, we have created two functions which are reverseArray() and printArray().

Reverse An Array

In the reverseArray() function, we have passed the parameters arr[], start, end. In that function, we have created another variable called temp. In which we have used a while loop. In which arr[start] is saved in temp variable, arr[end] is in arr[start], and temp is saved in arr[end]. And after that increment the start and decrement the end. And here the reverseArray() function ends.



ADVERTISEMENT




Now printArray() function accepts two parameters in which arr[] and size as n passed. In it, we have used for loop from which we have printed the reversed array.



ADVERTISEMENT




C Program

                        
    #include<stdio.h>

    void rvereseArray(int arr[], int start, int end)
    {
        int temp;
        while (start < end)
        {
            temp = arr[start];   
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }   
    }     

    void printArray(int arr[], int size)
    {
    int i;
    for (i=0; i < size; i++)
        {
            printf("%d ", arr[i]);
        }
    printf("\n");
    } 

    int main() 
    {
        int arr[] = {1, 2, 3, 4, 5, 6};
        int n = sizeof(arr) / sizeof(arr[0]); 
        printArray(arr, n);
        rvereseArray(arr, 0, n-1);
        printf("Reversed array is \n");
        printArray(arr, n);    
        return 0;
    }
 
                    


ADVERTISEMENT




Java Program

                        
   public class reverse {
      static void rvereseArray(int arr[],
                      int start, int end)
      {
          int temp;
          while (start < end)
          {
              temp = arr[start]; 
              arr[start] = arr[end];
              arr[end] = temp;
              start++;
              end--;
          } 
      }    

      static void printArray(int arr[], int size)
      {
          for (int i = 0; i < size; i++)
            {
               System.out.print(arr[i] + " ");
            }
          System.out.println();
      } 

      public static void main(String args[]) {
          int arr[] = {1, 2, 3, 4, 5, 6};
          printArray(arr, 6);
          rvereseArray(arr, 0, 5);
          System.out.print("Reversed array is \n");
          printArray(arr, 6);   
      }
  }
 
                    


ADVERTISEMENT







COMMENTS




Search
Advertisement
Advertisement
Share With
Follow us on
Advertisement
Advertisement