mercredi 31 mars 2021

C++: If statement is not accessing the value of an array (using the index) when evaluating the expression

I am supposed to be creating a program that asks a user to populate an array of size 10. There are three functions which by their name are self-explanatory; one fills up the array with elements, the second one displays the array horizontally, and the third array checks to see if a number entered by the user is an element in the array.

That last function, which is a bool function, is not performing the way I thought it would. Here is my code:

#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);

int main(){
  int s = 10; //size of array
  int A[s]; //array A with size s
  int num; //search number
  
  fillUpArray(A, s);

  std::cout <<"\n";

  displayArray(A, s);

  std::cout << "\n";

  std::cout << "Enter a number to check if it is in the array:\n";
  std::cin >> num;

  std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;

  return 0;
  
}

void fillUpArray(int array[], int size)
{
  std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
  for(int i = 0; i < size; i++){
    
    std::cin >> array[i];

  }

}
void displayArray(int array[], int size)
{
  for(int j = 0; j < size; j++){
    std::cout << array[j] << "\t";
  }
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
  bool isPresent;
  for(int k = 0; k < size; k++){
    if(array[k] == SearchNum)
      isPresent = true;
    else
      isPresent = false;
  }
  return isPresent;
}

I thought by doing array[k] whatever index k is then it should spit out the element in the array and then with the expression if(array[k] == SearchNum) it should then work as if(element == SearchNum) but that doesn't seem to be the case and the output is always false.

Aucun commentaire:

Enregistrer un commentaire