Home > Software engineering >  Return in a recursive function in C
Return in a recursive function in C

Time:11-14

I'm having a problem with the result of this problem, apparently it only returns the first use case, where am I going wrong?

Problem:

Create a recursive function that takes a string as input and also its length. This function should return how many times the character 'x' appears in the string.

Prohibited

The first line in the input contains the number n of test cases. Next, n lines occur, each containing a string with a maximum length of 5000 characters.

Exit

The output consists of n lines, each containing an integer that indicates the number of times the letter 'x' occurs in the input. All strings are written in lowercase.

Example

Prohibited:

3
open cadabra
chess taxi bacaxi rate box pulls sandpaper
syrup xxx

Expected Return:

0
7
4

My code

#include <stdio.h>
#define MAX 5000

int ocorrencias(char palavra[], char letra, int i) {
    if (palavra[i] == '\0') return 0;
    return (letra == palavra[i])   ocorrencias(palavra, letra, i   1);
}

int main() {
    char palavra[MAX];
    char letra = 'x';
    int i,j,n;
    int re[MAX];

    scanf("%d",&n);

    for(i=0;i<n;i  ){
        scanf("%s", palavra);
    }
    for(j=0;j<n;j  ){
        re[j] = ocorrencias(palavra, letra, 0);
    }

    printf("%d \n",re[j]);
}

CodePudding user response:

  1. ocorrencias() works but doesn't satisfy your requirement that it has to accept a length of the string.
  2. scanf("%d", ...) will leave the trailing newline so append a space to the format string to flush it.
  3. It's better to use fgets() to read a string with spaces. It doesn't matter here but fgets() will return a string with a newline.
  4. re should hold n results (1 per string) not MAX.
#include <stdio.h>
#define MAX 5000

int ocorrencias(const char *palavra, size_t len) {
    return len ?
        ('x' == *palavra)   ocorrencias(palavra   1, len - 1) :
        0;
}

int main() {
    int n;
    if(scanf("%d ", &n) != 1) {
        printf("scanf failed\n");
        return 1;
    }

    char palavra[MAX];
    int re[n];
    for(int i=0; i<n; i  ){
        fgets(palavra, MAX, stdin);
        re[i] = ocorrencias(palavra, strlen(palavra));
    }
    for(int i=0; i<n; i  ){
        printf("%d\n", re[i]);
    }
}

and here is an example run:

3
open cadabra
chess taxi bacaxi rate box pulls sandpaper
syrup xxx
0
3
3
  • Related