How to Reverse an Array In C++?

9 minutes read

To reverse an array in C++, you can use the following method:

  1. Declare an array of the desired type and size.
  2. Calculate the length of the array using the sizeof() operator.
  3. Declare two variables, start and end, to keep track of the start and end indices of the array.
  4. Use a while loop where start is less than end: Swap the elements at start and end indices of the array. Increment start and decrement end.
  5. The array will be reversed after completing the loop.


Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

void reverseArray(int arr[], int length) {
    int start = 0;
    int end = length - 1;

    while (start < end) {
        // Swap elements at start and end indices
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        // Increment start and decrement end
        start++;
        end--;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = sizeof(arr) / sizeof(arr[0]);

    cout << "Original Array: ";
    for (int i = 0; i < length; i++) {
        cout << arr[i] << " ";
    }

    reverseArray(arr, length);

    cout << "\nReversed Array: ";
    for (int i = 0; i < length; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}


In this example, the reverseArray() function takes an array and its length as parameters. It uses a while loop to swap the elements from the start and end indices until they meet in the middle. The main() function initializes an array, calculates its length, and then calls reverseArray() to reverse the array. Finally, it prints the original and reversed arrays.

Best C++ Books to Read in 2024

1
C Programming Language, 2nd Edition

Rating is 5 out of 5

C Programming Language, 2nd Edition

2
Effective C: An Introduction to Professional C Programming

Rating is 4.9 out of 5

Effective C: An Introduction to Professional C Programming

3
C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)

Rating is 4.8 out of 5

C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)

4
Learn C Programming: A beginner's guide to learning the most powerful and general-purpose programming language with ease, 2nd Edition

Rating is 4.7 out of 5

Learn C Programming: A beginner's guide to learning the most powerful and general-purpose programming language with ease, 2nd Edition

5
The C Programming Language

Rating is 4.6 out of 5

The C Programming Language

6
C: The Complete Reference, 4th Ed.

Rating is 4.5 out of 5

C: The Complete Reference, 4th Ed.

7
C Programming For Dummies (For Dummies (Computer/Tech))

Rating is 4.4 out of 5

C Programming For Dummies (For Dummies (Computer/Tech))


How to reverse words in a sentence using an array in C++?

To reverse words in a sentence using an array in C++, you can follow the steps below:

  1. Include the necessary header files:
1
2
3
#include <iostream>
#include <string>
using namespace std;


  1. Define a function to reverse the words in a sentence:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void reverseWords(string &sentence) {
   int len = sentence.length();

   // Reverse the entire sentence using two pointers approach
   int start = 0, end = len - 1;
   while (start < end) {
      swap(sentence[start], sentence[end]);
      start++;
      end--;
   }

   // Reverse individual words in the sentence using two pointers approach
   int wordStart = 0;
   for (int i = 0; i < len; i++) {
      if (sentence[i] == ' ') {
         int wordEnd = i - 1;
         while (wordStart < wordEnd) {
            swap(sentence[wordStart], sentence[wordEnd]);
            wordStart++;
            wordEnd--;
         }
         wordStart = i + 1;
      }
   }

   // Reverse the last word in the sentence (if any)
   int wordEnd = len - 1;
   while (wordStart < wordEnd) {
      swap(sentence[wordStart], sentence[wordEnd]);
      wordStart++;
      wordEnd--;
   }
}


  1. Create a main function and utilize the reverseWords function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
int main() {
   string sentence;

   // Read the sentence from the user
   cout << "Enter a sentence: ";
   getline(cin, sentence);

   // Reverse the words in the sentence
   reverseWords(sentence);

   // Display the reversed sentence
   cout << "Reversed sentence: " << sentence << endl;

   return 0;
}


  1. Compile and run the program.


Now, you can enter a sentence and the program will reverse its words. For example:

1
2
Enter a sentence: Hello world!
Reversed sentence: world! Hello



How to reverse an array by swapping elements in C++?

To reverse an array by swapping elements in C++, you can use the following approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

void reverseArray(int arr[], int start, int end) {
    while (start < end) {
        // Swapping elements
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        
        start++;
        end--;
    }
}

int main() {
    int size;
    std::cout << "Enter the size of the array: ";
    std::cin >> size;

    int arr[size];
    std::cout << "Enter the elements of the array: ";
    for (int i = 0; i < size; i++) {
        std::cin >> arr[i];
    }

    std::cout << "Original array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    reverseArray(arr, 0, size - 1);

    std::cout << "\nReversed array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}


This program asks the user to enter the size and elements of an array. It then calls the reverseArray function with the array, starting index, and ending index as arguments. Inside the reverseArray function, a while loop is used to swap the elements at the start and end indices. The loop continues until the start index becomes greater than or equal to the end index, ensuring that all elements are swapped. Finally, the reversed array is printed in the main function.


How to reverse an array of strings in C++?

To reverse an array of strings in C++, you can follow these steps:

  1. Include the necessary header file for input and output () and for string manipulation ().
  2. Create a function named reverseArray that takes an array of strings as a parameter.
  3. Inside the function, declare two integer variables named start and end. Initialize start with 0 and end with the length of the array minus 1.
  4. Use a loop to swap the strings at the start and end indices while incrementing start and decrementing end. Continue the loop until start becomes greater than or equal to end.
  5. After the loop, the array will be reversed.


Here is the complete example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

void reverseArray(std::string arr[], int length) {
    int start = 0;
    int end = length - 1;

    while (start < end) {
        std::swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

int main() {
    std::string arr[] = { "Hello", "World", "This", "Is", "Reversed" };
    int length = sizeof(arr) / sizeof(arr[0]);

    reverseArray(arr, length);

    for (int i = 0; i < length; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}


This code will reverse the strings in the array "arr" and output the reversed array: "Reversed Is This World Hello".

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To insert a blank array into a multidimensional array in Matlab, you can follow these steps:Determine the size of the multidimensional array you want to insert the blank array into.Create a blank array of the desired size using the zeros or NaN functions in Ma...
To convert a NumPy array to a PyTorch tensor, you can follow these steps:Import the necessary libraries: import numpy as np import torch Create a NumPy array: numpy_array = np.array([[1, 2, 3], [4, 5, 6]]) Convert the NumPy array to a PyTorch tensor: tensor = ...
In order to add a string to the start of an array in MATLAB, you can follow these steps:Define your array with elements.Create a new string variable that you want to add at the beginning.Use the concatenation operator [ ] to combine the string with the existin...