This is a C program to check whether a given character is present in a string, find frequency & position of occurrence.
This C Program checks whether a given character is present in a string, find frequency & position of occurrence.
This C Program checks whether a given character is present in a string, it also displays it occurrence and frequency as shown in the program below.
Here is a source code of the C program to check if a given character is present in a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Check whether a given Character is present in a * String, Find Frequency & Position of Occurrence */ #include <stdio.h> #include <string.h> int main() { char a, word[50]; int i, freq = 0, flag = 0; printf("Enter character: "); scanf("%c", &a); printf("Now enter the word: "); scanf("%s", word); printf("Positions of '%c' in %s are: ", a, word); for (i = 0; i < strlen(word); i++) { if (word[i] == a) { flag = 1; printf("%d ", i + 1); freq++; } } if (flag) { printf("\nCharacter '%c' occured for %d times.\n", a, freq); } else { printf("None\n"); } return 0; }
In this C program, we are reading the character and the word to check the position of occurrence using ‘a’ and ‘word’ variables respectively. In for loop initialize the value of ‘i’ variable as 0. Check the length of the string is greater than the value of ‘i’ variable.
Nested if else condition statement is used to check whether a given character is present in a string using the word[] variable is equal to the value of ‘a’ variable. If the condition is true then execute the statement. Initialize the value of ‘flag’ variable as 1 and increment the value of ‘freq’ variable. Print the characters, frequency & position of occurrence in a string.
$ cc charfrequency.c $ ./a.out Enter character: r Now enter the word: programming Positions of 'r' in programming are: 2 5 Character 'r' occured for 2 times.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Watch Advanced C Programming Videos
- Apply for C Internship
- Practice Computer Science MCQs
- Practice BCA MCQs
- Check Computer Science Books