Skip to content
Home » C program to find length of string using recursion

C program to find length of string using recursion

Below is the program to find the length of a string using recursion

#include <stdio.h>
int length(char str[],int i){
    if(str[i]=='\0'||str[i]=='\n'){
        return 0;
    }
    else{
        return 1+length(str,i+1);
    }
    
}
int main(){
    char str[1000];
    printf("Enter a sentence: ");
    fgets(str,1000,stdin);
    int j=length(str,0);
    printf("Length of the string is %d",j);
}

Output:

Enter a sentence: Having a good friend is blessed
Length of the string is 31