0
This c++ code return index of array correct but if value not found then not returning appropriate return what is the problem
#include <iostream> using namespace std; class Search{ public: int arr[6]={16,34,35,58,50,26}; int key=32; int search(){ for(int i=0;i<sizeof(arr);i++){ if(arr[i]==key){ return i; } } return -1; } }; int main() { Search obj; cout<<obj.search()<<endl; return 0; }
1 ответ
+ 2
rajendra , this is because sizeof(arr) will return the amount of memory whole array is taking(6*4(because of int data type)=24) instead of giving the length of the array(which should be 6)
A simple fix is to devide the sizeof(arr) with sizeof(arr[0]) to get the length of the array.
Here👇
https://code.sololearn.com/cGUXz5U2q6J7/?ref=app