Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program for length of a string using recursion
Given with the string and the task is to calculate the length of the given string using a user defined function or in-built function.
Length of a string can be calculated using two different ways −
- Using user defined function − In this, traverse the entire string until ‘\o’ is found and keep incrementing the value by 1 through recursive call to a function.
- Using user in-build function − There is an in-build function strlen() defined within “string.h” header file which is used for calculating the length of a string. This function takes single argument of type string and return integer value as length.
Example
Input-: str[] = "tutorials point" Output-: length of string is 15 Explanation-: in the string “tutorials point” there are total 14 characters and 1 space making it a total of length 15.
Algorithm
Start Step 1-> declare function to find length using recursion int length(char* str) IF (*str == '\0') return 0 End Else return 1 + length(str + 1) End Step 2-> In main() Declare char str[] = "tutorials point" Call length(str) Stop
Example
#include <bits/stdc++.h>
using namespace std;
//recursive function for length
int length(char* str) {
if (*str == '\0')
return 0;
else
return 1 + length(str + 1);
}
int main() {
char str[] = "tutorials point";
cout<<"length of string is : "<<length(str);
return 0;
}
Output
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
length of string is : 15
Advertisements