阅读358 返回首页    go 阿里云 go 技术社区[云栖]


递归判断元素是否在数组中

#include <iostream>
using namespace std;
//if it is found, return the index of the array
//if not fount, return -1
void findInArray(char arr[],  char x, int index, int size, int& pos);

int main()
{
char arr[] = "abcdefghijk";
int size = sizeof(arr) / sizeof(char);
    int pos;
char x;
cout << "Enter the element you want to find: " ;
cin >> x;

    findInArray(arr, x, 0, size, pos);
if ( pos == -1)
    cout << x << " is not found in the array!" << endl;
    else
        cout << x << " is found in the " << pos << "th index of the array!" << endl;
    return 0;
}
void findInArray(char arr[], char x, int index, int size, int& pos)
{
if (x == arr[index])
pos = index;
else if (index >= size)
        pos = -1;
else
        findInArray(arr, x, index+1, size, pos);
}

最后更新:2017-04-02 18:14:51

  上一篇:go eclipse中如何修改编码格式
  下一篇:go 递归求集合的所有子集的程序