Easy Tutorial
❮ C Standard Library Stdarg H C Recursion ❯

C Practice Example 17

C Language Classic 100 Examples

Title: Input a line of characters and count the number of English letters, spaces, digits, and other characters.

Program Analysis: Use a while loop with the condition that the input character is not '\n'.

Example

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

#include<stdio.h>
int main()
{
    char c;
    int letters=0,spaces=0,digits=0,others=0;
    printf("Please enter some characters:\n");
    while((c=getchar())!='\n')
    {
        if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
            letters++;
        else if(c>='0'&&c<='9')
            digits++;
        else if(c==' ')
            spaces++;
        else
            others++;
    }
    printf("Letters=%d, Digits=%d, Spaces=%d, Others=%d\n",letters,digits,spaces,others);
    return 0;
}

The above example output is:

Please enter some characters:
www.tutorialpro.org 123
Letters=12, Digits=3, Spaces=1, Others=2

C Language Classic 100 Examples

❮ C Standard Library Stdarg H C Recursion ❯