Q1) Find the Frequency of Characters
#include <stdio.h>
int main()
{
char str[1000], ch;
int i, frequency = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character to find the frequency: ");
scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
printf("Frequency of %c = %d", ch, frequency);
return 0;
}
Output
Enter a string: This website is awesome. Enter a character to find the frequency: e Frequency of e = 4
In this program, the string entered by the user is stored in variable str.
Then, the user is asked to enter the character whose frequency is to be found. This is stored in variable ch.
Q2)Program to count vowels, consonants etc.
#include <stdio.h>
int main()
{
char line[150];
int i, vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
printf("Enter a line of string: ");
scanf("%[^\n]", line);
for(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'))
{
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
return 0;
}
Output
Enter a line of string: adfslkj34 34lkj343 34lk Vowels: 1 Consonants: 11 Digits: 9 White spaces: 2
This program takes string input from the user and stores in variable line.
Initially, the variables vowels, consonants, digits and spaces are initialized to 0.
When the vowel character is found, vowel variable is incremented by 1. Similarly, consonants, digits and spaces are incremented when these characters are found.
Finally, the count is displayed on the screen.
Q3)Remove Characters in String Except Alphabets
#include<stdio.h>
int main()
{
char line[150];
int i, j;
printf("Enter a string: ");
gets(line);
for(i = 0; line[i] != '\0'; ++i)
{
while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '\0') )
{
for(j = i; line[j] != '\0'; ++j)
{
line[j] = line[j+1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}
Output
Enter a string: p2'r-o@gram84iz./ Output String: programiz
This program takes a string from the user and stored in the variable line.
The, within the for loop, each character in the string is checked if it's an alphabet or not.
If any character inside a string is not a alphabet, all characters after it including the null character is shifted by 1 position to the left.
No comments:
Post a Comment