How can I use ASCII to loop through an array and count the characters in that array?

How can I use ASCII to loop through an array and count the characters in that array? So I have an array of char (c string) called message that I need to loop through to count each occurrence of a letter or symbol using ASCII and then fill an array with the frequency of each occurrence. Not sure how to do that? I got somewhat of a start but I'm kind of lost on how to do it.

ASCII_SIZE is defined in a .h file that is an int of 128
MESSAGE_SIZE is defined in a .h file that is an int of 1000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  
int counts[ASCII_SIZE]; 
 
	for (int i = 0; i < ASCII_SIZE; i++)	{
	
	counts[i] = 0;
	
	}

		for (int i = 0; i < MESSAGE_SIZE; i++) {
				for (int j = 0; j < ASCII_SIZE; j++) {
		
					if (counts[(char) j] ==  message[i]) {
	
						counts[(int) j] += 1;
						cout << counts[(int) j] << endl;
			
					}
				}	

			}
Last edited on
No need for nested loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <iostream>
using namespace std;

const int ASCII_SIZE = 128;

int main ()
{   int counts[ASCII_SIZE]; 
    string message = "Some Message";
    
    //  Clear the array
	for (int i = 0; i < ASCII_SIZE; i++)	
	    counts[i] = 0;

    //  Count the characters
	for (unsigned i = 0; i < message.size(); i++) 
	   counts[message[i]]++; 
	   
    //  Output the results
    for (int i=0; i<ASCII_SIZE; i++)
        cout << i << " = " << counts[i] << endl;
}
Topic archived. No new replies allowed.