Using pointers, write a program in ‘C’ to count the occurrence of each character in a given string. 10m Dec2006

By | June 23, 2014

Using pointers, write a program in ‘C’ to count the occurrence of each character in a given string. 10m Dec2006

 

#include <stdio.h>
#include <string.h>
void main()
{
char string[100],*ptr;
int c=0,count[26]={0};
clrscr();
printf(“Enter a string\n”);
gets(string);
ptr=string[0];
while (*ptr)
{
/* Consider characters from ‘a’ to ‘z’ only */
if ( ptr >= ‘a’ && ptr <= ‘z’ )
count[string[c]-‘a’]++;
c++;
ptr++;
}
for(c=0;c<26;c++)
{
if(count[c]!=0)
printf(“%c occurs %d times in string.\n”,c+’a’,count[c]);
}
getch();
}

[codesyntax lang=”c”]

#include <stdio.h>
#include <string.h>
void main()
{
char string[100],*ptr;
int c=0,count[26]={0};
clrscr();
printf("Enter a string\n");
gets(string);
ptr=string[0];
while (*ptr)
{
/* Consider characters from 'a' to 'z' only */
if ( ptr >= 'a' && ptr <= 'z' )
count[string[c]-'a']++;
c++;
ptr++;
}
for(c=0;c<26;c++)
{
if(count[c]!=0)
printf("%c occurs %d times in string.\n",c+'a',count[c]);
}
getch();
}

[/codesyntax]

Screen Shots:

C_program_Count_Chars

 

C_program_Count_Chars_Output

Leave a Reply