Easy Tutorial
❮ C Function Exit C Function Fopen ❯

C Exercise Example 70

C Language Classic 100 Examples

Title: Write a function to calculate the length of a string. Input the string in the main function and output its length.

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int len;
    char str[20];
    printf("Please enter a string:\n");
    scanf("%s", str);
    len = length(str);
    printf("The string has %d characters.", len);
}
// Calculate string length
int length(char *s)
{
    int i = 0;
    while (*s != '\0')
    {
        i++;
        s++;
    }
    return i;
}

The above program execution output is:

Please enter a string:
www.tutorialpro.org
The string has 14 characters.

C Language Classic 100 Examples

❮ C Function Exit C Function Fopen ❯