In this post, we will learn "How to reverse an Array". Let us start by taking an array as input from the user and then we will reverse it. Steps to follow: Move element at the first index to last, and element at last index to first Move element at the second index to second last, and element at second last index to the second and so on Let's have a look at the code, how to do this work: #include<iostream> using namespace std ; int main() { int arr[100], tot, i, j, temp; cout << "Enter the Size for Array: " ; cin >>tot; cout << "Enter " <<tot<< " Array Elements: " ; for (i=0; i<tot; i++) cin >>arr[i]; cout << " \n The Original Array is: \n " ; for (i=0; i<tot; i++) cout <<arr[i]<< " " ; j = tot-1; for (i=0; i<j; i++, j--) { temp = arr[i]; //swaped first element with last element ...
In this post, we will learn "How to search for an element in an array". To search for an element in an array first you have to traverse through all the elements in the given array. This method is known as Linear search. The full code is given below: C++ code to implement the linear search operation Here x is the element you want to search in the given array and we will output the position of that element if it is present otherwise -1. #include <iostream> using namespace std; //Function for linear search int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } int main(void) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); //way to find out how many elements are present in array int result = search(arr, n, x); // Function call (result == -1) ? cout << "-1"; : cout << "Element is present at index " << result; ...