Search code examples
c++arraysfunctionparametersprogram-entry-point

Array and Function


I am trying to make functions to call in the main function, trying to keep "main" as clean as possible. so I made a function to get the size array from the user then the user enters the elements of the function, but I got stuck at the linear search function, so want help "Still absolute beginner"

#include <iostream>
using namespace std;
int* Array_Elements () {
    static int arr [5] {}, i, size;
    cout << "Enter Array size: ";
    cin >> size;
    cout << "Enter Array Elements: " << endl;
    for (i=0; i<size; i++) {
        cin >> arr[i];
    }
    return arr;
}
void Array_Search (int arr [], int n) {
    int temp = -1;
    for (int i = 0; i < 5; i++) {
        if (arr [i] == n) {
            cout << "Element found at position: " << i + 1 << endl;
            temp = 0;
            break;
        }
 }
 
  if (temp == -1) {
    cout << "No Element Found" << endl;
  }    
    }
int num () {
    cout << "Please enter an element to search" << endl;
    int num;
    cin >> num;
    return num;
}

int main () {
    Array_Search (Array_Elements(), num());
    return 0;
}

Solution

  • Lets jump right in, my suggestion to keep the main as clean as possible is to use a class then instantiate its object then use the object to call class methods in the main. This is best practice.

    Your code confuses the compiler, in that the function num() precedes the function Array_Elements() in terms of order of evaluation. And I believe you want it the other way around.

    Here's how to fix it: Remove the function num(), and make the following changes to your code

    
    int* Array_Elements(int size) {
        int* arr, i;
        cout << "Enter Array Elements: " << endl;
        arr = new int[size];
        for (i=0; i<size; i++) {
            cin >> arr[i];
        }
        return arr;
    }
    
    void Array_Search (int *arr, int size) { 
        int temp = -1, num;
        cout << "Please enter an element to search" << endl;
        cin >> num;
        for (int i = 0; i < size; i++) {
            if (arr [i] == num) {
                cout << "Element found at position: " << i + 1 << endl;
                temp = 0;
                delete [] arr;
                break;
            }
        }
        if (temp == -1) {
        cout << "No Element Found" << endl;
        }    
    }
    
    int main () {
        int size;
        cout << "Enter Array size: ";
        cin >> size;
        Array_Search(Array_Elements(size),size);
        return 0;
    }