Find length of string using recursion

Problem statement:- Program to Find the length of the string using recursion.

Data requirement:-

   Input Data:- str

  Output Data:-
StringLength(str,0)

Program in C

Here is the source code of the C Program to Find the length of string using recursion.

Code:

#include<stdio.h>
#include<string.h>
int StringLength(char str[], int i)
{
    if(str[i]=='\0')
        return 0;
    else
        return (1+StringLength(str,i+1));
}
int main()
{
    char str[30];
    printf("Enter your String:");
    scanf("%[^\n]",str);
    printf("Length of the String is: %d",StringLength(str,0));
}

Input/Output:
Enter your String:String recursion Program
Length of the String is: 24

Program in C++

Here is the source code of the C++ Program to Find the length of string using recursion.

Code:

#include<iostream>
using namespace std;
int StringLength(string str, int i)
{
    if(str[i]=='\0')
        return 0;
    else
        return (1+StringLength(str,i+1));
}
int main()
{
    string str;
    cout<<"Enter your String:";
    getline(cin, str);
    cout<<"Length of the String is: "<<StringLength(str,0);
}

Input/Output:
Enter your String:csinfo
Length of the String is: 6

Program in Java

Here is the source code of the Java Program to Find the length of string using recursion.

Code:

import java.util.Scanner;
public class FindStringLength {

static int StringLength(char str[], int i)
{
    if(str[i]=='\0')
        return 0;
    else
        return (1+StringLength(str,i+1));
}
public static void main(String[] args) {
           Scanner cs=new Scanner(System.in);
           String str1;
           System.out.print("Enter your String:");
           str1=cs.nextLine();
           str1+='\0';
           char str[]=str1.toCharArray();
           System.out.print("Length of the String is: "+StringLength(str,0));
        cs.close();
}
}

Input/Output:
Enter your String:Programming string
Length of the String is: 18

Program in Python

Here is the source code of the Python Program to Find the length of string using recursion.

Code:

def StringLength(str, i):
    if (str[i] == '\0'):
        return 0
    else:
        return (1 + StringLength(str, i + 1))
str=input("Enter your String:")
str+='\0'
print("Length of the String is: ",StringLength(str,0))

Input/Output:

Post a Comment

0 Comments