Home > Back-end >  Recursive Function return ordered vector
Recursive Function return ordered vector

Time:11-16

I have a problem with the return of that function, it should return the vector with the typed sequence, but it's returning an ordered sequence, could you tell me where I'm going wrong?

Create a recursive function that takes a string as input and also its length. This function should return how many times the character the substring “hi” 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 of maximum length equal to 5000 characters

Exit

The output consists of n lines, each containing an integer that indicates the number of times the string “hi” occurs in the input string. All strings are written in lowercase letters.

Example

Prohibited

4
hipotenuse hipothermia hilux hifi
hi
hihihi
xavante hey

Exit

4
1
3
0

My code:

#include <stdio.h>
#include <string.h>
#define MAX 5000

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

int main() {
    int n,i;
    scanf("%d",&n);

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

CodePudding user response:

For starters the for loops like this

for(i=0; i<=n; i  ){
         ^^^^^

are wrong.

You need to write

for(i=0; i < n; i  ){
         ^^^^^^

The function ocorrencias should be declared either like

size_t ocorrencias( const char *palavra );

or like

size_t ocorrencias( const char *palavra, const char *st );

instead of

int ocorrencias(const char *palavra, size_t len) ;

because it deals with strings and the function is able to determine lengths of passed strings.

It can be defined for example the following way

size_t ocorrencias( const char *palavra ) 
{
    const char *st = "hi";
    const char *p = strstr( palavra, st );
 
    return p == NULL ? 0 : 1   ocorrencias( p   strlen( st ) );
}

So in main you should write

size_t re[n];

//...

for ( i = 0; i < n; i   )
{
    printf( "%zu\n", re[i] );
}

Otherwise if you want to count substrings either "hi" or "hy" (according to your comment to the question) then the function can look the following way

size_t ocorrencias( const char *palavra ) 
{
    const char *p = strchr( palavra, 'h' );
 
    return p == NULL ? 0 : ( p[1] == 'i' || p[1] == 'y' )   ocorrencias( p   1 );
}
  • Related