C program to count the number of occurrences of a character in a word

C program to count the number of occurrences of a character in a word


#include <stdio.h>

int main(){
	
	// declare string (character array) to hold the input string
	char inputString[100];
	
	// prompt the user to enter a string
	printf("Enter a single word: ");
	
	// get the input
	scanf("%s\n", inputString);
	
	// declare character to hold the character to count
	char charToCount;
	
	// prompt the user to enter the character to be counted
	printf("Enter the character to be counted: ");
	
	// get the character
	scanf("%c", &charToCount);
	
	// initialise loop variables for counting the input character
	int i = 0;
	int count = 0; 
	
	// Use a loop to iterate through the input string 
	while(inputString[i] != '\0'){
		
		// check if input character is found in the string
		// if found, increment the count variable
		if(inputString[i] == charToCount) count++;
		i++;
		}  
		
		if(count > 0){ 
			if(count == 1) printf("%c appears once in '%s'", charToCount, inputString);
			
			else printf("%c appears %d times in '%s'", charToCount, count, inputString);
			}
		else printf("%c did not appear in %s", charToCount, inputString);
			
			return 0;
			
	}