C Programming Code Examples C > Strings Code Examples C program to count occurrences of a character in a string C program to count occurrences of a character in a string Write a C program to count all occurrences of a character in a string using loop. How to find total occurrences of a given character in a string using for loop in C programming. Input a string from user, store it in some variable say str. Input character to search occurrences, store it in some variable say toSearch. Initialize count variable with 0 to store total occurrences of a character. Run a loop from start till end of string str. The loop structure should look like while(str[j] != '\0'). Inside the loop if current character of str equal to toSearch, then increment the value of count by 1. #include <stdio.h> #define maxsize 100 // Maximum string size int main() { char str[maxsize]; char toSearch; int j, count; /* Input string and search character from user */ printf("Enter any string: "); gets(str); printf("Enter any character to search: "); toSearch = getchar(); count = 0; j=0; while(str[j] != '\0') { /* * If character is found in string then * increment count variable */ if(str[j] == toSearch) { count++; } j++; } printf("Total occurrence of '%c' = %d", toSearch, count); return 0; }