0% found this document useful (0 votes)
5 views

Unit 3 String Excercise 1

Uploaded by

tv5874
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 3 String Excercise 1

Uploaded by

tv5874
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

School of Computing Science and Engineering

Course Code : R1UC101B Name: Programming for Problem Solving-C

UNIT III
String: Exercise:-1

Program Name: B.Tech. (CSE)


Ex-1 : String Examples in C Programming

C Program to Find the Frequency of Characters in a String


Find the Frequency of a Character
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

printf("Enter a character to find its frequency: ");


scanf("%c", &ch);
Continue…

for (int i = 0; str[i] != '\0'; ++i) {


if (ch == str[i])
++count;
}

printf("Frequency of %c = %d", ch, count);


return 0;
}
Output
Enter a string: This website is awesome.
Enter a character to find its frequency: e
Frequency of e = 4
Ex-2: C Program to Count the Number of Vowels, Consonants
and so on
In this example, the number of vowels, consonants, digits, and white-
spaces in a string entered by the user is counted:
#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;

vowels = consonant = digit = space = 0;

printf("Enter a line of string: ");


fgets(line, sizeof(line), stdin);
Cont…
for (int i = 0; line[i] != '\0'; ++i) {
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U') {
++vowels;
} else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i]
<= 'Z')) {
++consonant;
} else if (line[i] >= '0' && line[i] <= '9') {
++digit;
} else if (line[i] == ' ') {
++space;
}
}
Cont…
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}
Output
Enter a line of string: adfslkj34 34lkj343 34lk
Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2
References

 http://kirste.userpage.fu-berlin.de/chemnet/use/info/libc/libc_7.html
 Let Us C by Yashavant Kanetkar : Authentic Guide to C PROGRAMMING Language 17th
Edition, BPB Publications
 C in Depth by by S.K.Srivastava and Deepali Srivastava, BPB Publications

You might also like