Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to find length of a string without string.h and loop in C?

  • Difficulty Level : Easy
  • Last Updated : 26 Oct, 2020

Find the length of a string without using any loops and string.h in C. Your program is supposed to behave in following way: 

Enter a string: GeeksforGeeks (Say user enters GeeksforGeeks)
Entered string is: GeeksforGeeks
Length is: 13

You may assume that the length of entered string is always less than 100.
The following is the solution. 

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

C




#include <stdio.h>
int main()
{
     
    // entered string
    char ch[50] = "GeeksforGeeks";
   
    // printing entered string
    printf("Entered String is:");
   
    // returns length of string
    // along printing string
    int len
        = printf("%s\n", ch);
   
    printf("Length is:");
   
    // printing length
    printf("%d", len - 1);
}
Output
Entered String is:GeeksforGeeks
Length is:13

The idea is to use return values of printf(). 
printf() returns the number of characters successfully written on output.
In the above program we just use the property of printf() as it returns the number of characters entered in the array string. 
 



Another way of finding the length of a string without using string.h or loops is Recursion. 
The following program does the work of finding a length of a string using recursion. 
 

C




// C program for the above approach
#include <stdio.h>
 
void LengthofString(int n,char *string)
{
    if(string[n] == '\0')
    {
        printf("%i",n);
        return;
    }
     
    LengthofString(n+1,string);
    //printf("%c",string[n]);
}
 
int main()
{
    char string[100];
    printf("Give a string : \n");
    scanf("%s",string);
    printf("Entered string is:%s\n", string);
    LengthofString(0,string);
     
    return 0;
}
Output
Give a string : 
Entered string is:0
1

The Function LengthofString calls itself until the character of string is’nt a null character it calls itself, when it calls itself it increases the value of the variable ‘n’ which stores number of times the function has been called and when it encounters the null character the function prints the value of ‘n’ and returns back in the same direction in which it was executed.
This article is contributed by Sumit Singh Chauhan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!