i wanna ask is that any statement can calculate number of occurrence of each letter (A-Z) instead of using switch statement or if statement to compare.

Recommended Answers

You want single instruction ???
I dont think thr are any such instructions which can calculate number of occurances..

But you want a program to calculate it

Count alphabets

Jump to Post

*sigh*

Okay, here's a better example. Instead of trying to cram letters into a smaller array, I've used an array that covers the whole range of the char type and then filter the output. It should be easier to follow:

#include <stdio.h>
#include <ctype.h>
#include <limits.h>

int main(void) …
Jump to Post

All 7 Replies

You want single instruction ???
I dont think thr are any such instructions which can calculate number of occurances..

But you want a program to calculate it

Count alphabets

which mean i only have one way to do with it..
i have to compare one by one from lower 'a' to upper 'Z'.

yeah.. but i dont understand why ch - 'A'...

To count the alphabets we need respective counters.
we have array to keep count of alphabets.
so array[0] keeps count of 'A' whose ASCII value is 65
array[1] keeps count of 'B; whose ASCII value is 66 and so on

by subtracting 'A' from current char we get index of the array and increment perticular counter..
But it has some portibility issue as explained by expert on that thread..
Hopes its clear..
If any doubt ask i'll get to help

*sigh*

Okay, here's a better example. Instead of trying to cram letters into a smaller array, I've used an array that covers the whole range of the char type and then filter the output. It should be easier to follow:

#include <stdio.h>
#include <ctype.h>
#include <limits.h>

int main(void)
{
    char freq[CHAR_MAX] = {0};
    int ch;
    int i;

    while ((ch = getchar()) != '\n' && ch != EOF)
        ++freq[ch];

    for (i = 0; i < CHAR_MAX; i++) {
        /* Only print the letters that were found */
        if (freq[i] > 0 && isalpha(i))
            printf("%c: %d\n", i, freq[i]);
    }

    return 0;
}

The idea of a character frequency table is that the character itself is used as an index into an array, and the array contains a count of how many times that character was found. So if the letter 'A' is in your string three times, freq would have a value of 3.

commented: Amazing!! +1

wooww Cool ..
and portable too ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.