To find string length using recursion

To find string length using recursion

Question:

Write a program to find string length using recursion.

Logic:

  • Get the input string from the user.
  • Then count the characters in the string.
  • String length found when reach the \0.

Algorithm:

  1. Get the input string from the user.
  2. Pass the string as an argument.
  3. Then count the number of characters in the string.
  4. The string length is found by passing string recursively.
  5. Then return the count value by reaching \0.

Program:

#include<stdio.h>
void main()
{
	char a[30];
	clrscr();
	printf("enter the string:");
	gets(a);
	printf("the length of string is %d",len(a));
	getch();
}
int len(char a[])                  //gets the string as an argument
{
	static int count=0;        //it initializes the i value for first time only
	if(a[count]!='\0')         //checks every position in the string
	{
		count++;
		len(a);           // passes the string recursively
	}
	else
	{
		return count;     //returns the length of string
	}
}

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x