C Program to Find the Length of a String

C program uses an array of characters (char str[100]) to store the input string. It uses fgets to read the string from the user, ensuring that it doesn’t overflow the array.

The length of the string is then calculated using a while loop that iterates until it encounters the null character ('\0') or a newline character ('\n'). The null character indicates the end of the string in C.

Finally, the program prints the length of the string to the console.

Method 1 :

#include<stdio.h>
void main()
{
int i=0;
char input[20];
printf(“Enter any String :”);
gets(input);
while(input[i]!=’\0′)
{
i++;
}
printf(“Length of given string: %d”,i);
}

Output :

Method 2 :

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char input[80];
int i;
printf(“Enter the string: “);
gets(input);
i=strlen(input);
printf(“The length of the string is : %d”,i);
}

Output :

Leave a Comment

Your email address will not be published.

Shopping Basket
Verified by MonsterInsights