Saturday, December 13, 2014

Number of Occurrence of a c pgm



Check whether a given Character is present in a String, Find Frequency & Position of Occurrence

#include 
#include 
#include 
 
int main()
{
    char a, word[50];
    int i, freq = 0, flag = 0;
    clrscr();
    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; 
 getch();
}

Output
 
Enter character: r
Now enter the word: programming
Positions of 'r' in programming are: 2  5  
Character 'r' occured for 2 times.


Count the Number of Occurrence of each Character Ignoring the Case of Alphabets & Display them

#include 
#include 
#include 
#include 
 
struct detail
{
    char c;
    int freq;
};
 
int main()
{
    struct detail s[26];
    char string[100], c;
    int i = 0, index;
    clrscr();
    for (i = 0; i < 26; i++)
    {
       s[i].c = i + 'a';
       s[i].freq = 0;
    }
    printf("Enter string: ");
    i = 0;
    do
    {
        fflush(stdin);
        c = getchar();
        string[i++] = c;
        if (c == '\n')
        {
            break;
        }
        c = tolower(c);
        index = c - 'a';
        s[index].freq++;
    } while (1);
    string[i - 1] = '\0';
    printf("The string entered is: %s\n", string);
 
    printf("*************************\nCharacter\tFrequency\n*************************\n");
    for (i = 0; i < 26; i++)
    {
        if (s[i].freq)
        {
            printf("     %c\t\t   %d\n", s[i].c, s[i].freq);
        }
    }
 
    return 0;
getch();
}

Output
 
Enter string: A quIck brOwn fox JumpEd over a lazy dOg
The string entered is: A quIck brOwn fox JumpEd over a lazy dOg
*************************
Character           Frequency
*************************
     a                       3
     b                       1
     c                       1
     d                       2
     e                       2
     f                        1
     g                       1
     i                        1
     j                        1
     k                       1
     l                        1
     m                      1
     n                       1
     o                       4
     p                       1
     q                       1
     r                        2
     u                       2
     v                       1
     w                      1
     x                       1
     y                       1
     z                       1

No comments:

Post a Comment