Skip to content

Instantly share code, notes, and snippets.

@RahulBRB
Created September 13, 2022 08:58
Show Gist options
  • Save RahulBRB/a7c963a86b579cd6f5d41ae1d43520d6 to your computer and use it in GitHub Desktop.
Save RahulBRB/a7c963a86b579cd6f5d41ae1d43520d6 to your computer and use it in GitHub Desktop.
Use this code to find the position of an element inside the array.
#include<iostream>
int myIndex(int numbers[], int size, int element);
int main(){
int numbers[] = {1,2,3,4,5,6,7,8,9,0};
int size = sizeof(numbers)/sizeof(numbers[0]);
int index;
int element;
std::cout << "Enter a number to search: \n";
std::cin>>element;
index = myIndex(numbers, size, element);
if(index != -1){
std::cout << element << " is present at the position of " << index << std::endl;
} else{
std::cout << "Your element is not in the array. \n";
}
return 0;
}
int myIndex(int numbers[], int size, int element){
for(int i = 0; i<size; i++){
if(numbers[i]==element){
return i;
}}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment