Calculate length of string - C Program

Q. C program to read a string and find its length using for loop.

Solution:

#include <stdio.h>
int main()
{
    char s[1000];
    int i=0;
    printf("Enter String: ");
    scanf("%s", s);
    /* After the for loop semicolon is there to calculate total length of string and after this for no statement to execute*/
    for(i = 0; s[i] != '\0'; i++);
    printf("Length of String: %d", i);
    return 0;
}


Q. C program to read a string and find its length using while loop.

Solution:

#include <stdio.h>
int main()
{
    char s[1000];
    int i=0;
    printf("Enter String: ");
    scanf("%s", s);
    /* After the for loop semicolon is there to calculate total length of string*/
    for(i = 0; s[i] != '\0'; i++);
    printf("\nLength of String: %d", i);
    return 0;
}


Q. C program to read a string and find its length using strlen() function.

Solution:

#include <stdio.h>
#include <string.h>
int main()
{
    char s[1000];
    int i=0;
    printf("Enter String: ");
    /* We can use gets function instead of scanf */
    gets(s);
    i=strlen(s);
    printf("\nLength of String: %d", i);
    return 0;
}


Output:

string length