c ++递归算法数的计数_C ++程序使用数组中的递归查找数字的首次出现

c ++递归算法数的计数

Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.

给定长度为N的数组和整数x ,您需要找到并返回数组中存在的整数x的第一个索引。 如果数组中不存在,则返回-1 。 First index表示输入数组中x首次出现的索引。 递归执行此操作。 数组中的索引从0开始。

Input Format:

输入格式:

  • Line 1 : An Integer N i.e. size of array

    第1行:整数N,即数组的大小

  • Line 2 : N integers which are elements of the array, separated by spaces

    第2行: N个整数,它们是数组的元素,以空格分隔

  • Line 3 : Integer x

    第3行:整数x

Output Format: first index or -1

输出格式:第一个索引或-1

Constraints: 1 <= N <= 10^3

限制条件: 1 <= N <= 10 ^ 3

Example

    Input:
    4
    9 8 10 8
    8

    Output:
    1

Description:

描述:

Here, we have to find the first occurrence of x. Therefore in this example the first occurrence of 8 happens in index 1, and hence the output is 1.

在这里,我们必须找到x的第一次出现。 因此,在此示例中,第一次出现8发生在索引1中,因此输出为1。

Algorithm:

算法:

Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.

步骤1:要使用递归解决此问题,请使用输入创建递归函数,并使用变量currIndex遍历输入数组。

Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.

步骤2:基本情况:如果currIndex ==输入数组的大小 ,则返回-1,即找不到元素。

Step 3: If x == input[currIndex], then return currIndex.

步骤3:如果x == input [currIndex] ,则返回currIndex 。

Step 4: else return the next call of recursive function with currIndex incremented.

步骤4:否则,返回递归函数currIndex递增的下一个调用。

C ++源代码/功能: (C++ Source Code/Function:)

#include<bits/stdc++.h>

using namespace std;

int firstIndex(int input[], int size, int x, int currIndex){
    if(size==currIndex){
        return -1;
    }

    if(input[currIndex] == x){
        return currIndex;
    }

    return firstIndex(input,size,x,currIndex+1);
    
}

int main(){
    int input[] = {9,8,10,8};
    int x = 8;
    int size = 4;

    cout<<firstIndex(input,size,x,0);

    return 0;
}

Output

输出量

1


翻译自: https://www.includehelp.com/cpp-programs/find-first-occurrence-of-number-using-recursion-in-an-array.aspx

c ++递归算法数的计数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值