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.

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);
}

Sample 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.



Follow us on Facebook and Twitter for latest update.