Program to find length of string in C using functions

Here we are going to write a Program to find length of string in C using functions. More over we will also see different methods of finding length of string using functions i.e., find length of string in c using strlen function using functions or c program to find length of string in c using while loop and for loop using functions.

Program to find length of string in C using functions

Example, given string is "codeitwise"

Length of given string - 10

Let's discuss about the approach that we are going to use.

We can use any loop, for loop or while loop, below is the program using for loop or also referred as program to find length of string in c without strlen function.

Now lets code it. But before going down I will suggest you to first try it on your own and then see the solution.

C Program to find length of string using for loop using functions

#include <stdio.h>

void string_length(char c[]){
	int i,l=0;
    for(i=0;c[i]!='\0';i++)
        l++;
    printf("Length of string: %d",l);
}

int main(){
    char c[100];
    printf("Enter Your string: ");
    scanf("%s",&c);
    string_length(c);
    return 0;
}


Output

Enter Your string: codeitwise
Length of string: 10


C program to find length of string using while loop using functions

#include <stdio.h>

void string_length(char c[]){
	int i=0,l=0;
    while(c[i++]!='\0')
        l++;
    printf("Length of string: %d",l);
}

int main(){
    char c[100];
    printf("Enter Your string: ");
    scanf("%s",&c);
    string_length(c);
    return 0;
}


Output

Enter Your string: codeitwise
Length of string: 10

What's happening here is - i is initialized with 0 and this condition in loop c[i]!='\0' checks that whether a character at c[i] is NULL or not if yes then loop will break else it will go on till the condition is true. At the end, it will encounter a NULL character (' \0 ') and condition becomes false and loop will end. Finally we are printing the length.

C program to find length of string using strlen function using functions

For using strlen() function we first need to include string.h header file.

#include <stdio.h>
#include <string.h>

void string_length(char c[]){
	printf("Length of string: %d",strlen(c));
}

int main(){
    char c[100];
    printf("Enter Your string: ");
    scanf("%s",&c);
    string_length(c);
    return 0;
}


Output

Enter Your string: codeitwise
Length of string: 10


More like this

• C program to find length of string without using functions

• C program to check palindrome string  

• C Program to compare two strings


Post a Comment

If you have any doubts, please let me know

Previous Post Next Post