w3resource

C Exercises: Find the length of a string without using the library function

C For Loop: Exercise-58 with Solution

Write a C program to find the length of a string without using the library function.

This C program takes a string as input and iterates through each character until it encounters the null terminator '\0', incrementing a counter variable for each character. After iterating through the entire string, it prints the count of characters as the length of the string.

Visual Presentation:

Print a string in reverse order

Sample Solution:

C Code:

#include <stdio.h>   // Include the standard input/output header file. 
#include <string.h>
void main()
{
    // Variable declarations
char str1[50];
int i, l = 0;
    // Prompting user for input
printf("\n\nFind the length of a string:\n ");
printf("-------------------------------------\n");
    // Getting user input
printf("Input a string : ");
scanf("%s", str1);
    // Loop to count characters in the string
for (i = 0; str1[i] != '\0'; i++)
    {
l++;
    }
    // Printing the length of the string
printf("The string contains %d number of characters. \n", l);
printf("So, the length of the string %s is : %d\n\n", str1, l);
}

Output:

Find the length of a string:                                                                                  
 -------------------------------------                                                                        
Input a string : welcome                                                                                      
The string contains 7  number of characters.                                                                  
So, the length of the string welcome is : 7 

Flowchart:

Flowchart :  Find the length of a string without using the library function.

C Programming Code Editor:

Previous: Write a program in C to print a string in reverse order.
Next: Write a program in C to check Armstrong number of n digits.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/for-loop/c-for-loop-exercises-58.php