Reverse order of array elements

Reverse order of array elements

describe

Write a function to reverse the order of array elements. Write the main function, define the array, use the previously written function to input the array elements, call the function of this question to reverse the array elements, and call the previously written function to output the array. Let the array elements be integers, no more than 100. ‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

enter

A number of integers separated by spaces or newlines, -9999 means the end. ‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

output

Array elements in reverse order, without trailing spaces. ‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

Notice

Input, output, and reverse order are all realized by calling functions! ! ! A program without functions is meaningless. ‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

Input and output example

insert image description here

#include <iostream>
using namespace std;

void reverse(int arr[], int size) {
    
    
  
    for(int i=0; i<size/2; i++) {
    
    
        int temp = arr[i];
        arr[i] = arr[size-i-1];
        arr[size-i-1] = temp;
    }
}

void print_arr(int arr[], int size) {
    
    
   
    for(int i=0; i<size-1; i++) {
    
    
        cout << arr[i] << " ";
    }
    cout << arr[size-1] << endl;
}

int main() {
    
    
  
    int arr[100];
    int size = 0;

    while(1) {
    
    
        int val;
        cin >> val;
        if(val == -9999) {
    
    
            break;
        }
        arr[size++] = val;
    }

    reverse(arr, size);
    print_arr(arr, size);

    return 0;
}

The reverse order of an array can be achieved by swapping the first and second halves of the array. The reverse function and print_arr function are defined here, which are used for array reverse order and output array respectively. In the main function, a size variable is defined to record the size of the array, and the function of inputting array elements is realized by continuously reading in integers and storing them in the array. Finally, call the reverse and print_arr functions to reverse the array and output it.

Guess you like

Origin blog.csdn.net/YouWan797411/article/details/130816648