Algorithm to search an element in an array

##An algorithm to search elements in the array and how many times that element occurs in the index counting.
Flowchart given below:



Source Code In C++:

#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
  int a[1000],n,x,flag=0,i,j;
  std::cout << "How many elements:";
  std::cin >> n;
  std::cout << "Take all the elements: " << '\n';
  for (size_t i = 0; i <n; i++) {
    std::cin >> a[i];
  }
  std::cout << "Which element you wanna search: " ;
  std::cin >> x;
  for(i=0;i<n;i++){
    if (a[i]==x) {
      flag=flag+1;
      std::cout << "Element is in the array's "<<i<<"th index" << '\n';
    }
  }
  std::cout << "Element found in "<<flag<<" times" << '\n';
  return 0;
}



Output:
How many elements:5
Take all the elements:
1
2
3
3
3
Which element you wanna search: 3
Element is in the array's 2th index
Element is in the array's 3th index
Element is in the array's 4th index
Element found in 3 times

Press any key to continue . . .


Explanation:
Here the algorithm is about to search an element in an array.So,at first we took an array index.Then we took the input which number we wanna search.Then in the if-else statement, we compared the input with array's all element.Then we printed the index where the input is located and we also printed how many times the element occured in that array.







No comments

Powered by Blogger.