How to perform array frequency count?

Hi, I need to write a program to read, group, and total up the survey marks entered by a respondent. I need to use an array to store the frequency counts and I'm new to frequency counts. There are 10 survey questions and the
respondent will key in the response which is the mark to each question.
The responses are from 0(very bad) to 4(excellent).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

main(void) {
	int i, total, response;
	int frequencyVB = 0, frequencyB = 0, frequencyG = 0, frequencyVG = 0, frequencyE = 0;
	int totalVB, totalB, totalG, totalVG, totalE;

	printf("Please enter the survey marks below: \n");
	printf("Question         Response(0-4)\n");
	for (i = 1; i <= 10; i++)
	{
		printf("Q %d          : ", i);
		scanf("%d", &response);

			switch (response) {
			case 0: frequencyVB++;
				break;
			case 1: frequencyB++;
				break;
			case 2: frequencyG++;
				break;
			case 3: frequencyVG++;
				break;
			case 4: frequencyE++;
				break;
			}

			totalVB = 0 * frequencyVB;
			totalB = 1 * frequencyB;
			totalG = 2 * frequencyG;
			totalVG = 3 * frequencyVG;
			totalE = 4 * frequencyE;

			total = totalVB + totalB + totalG + totalVG + totalE;
	}


	printf("RESULTS\n");
	printf("========\n");
	printf("Response          frequency\n");
	printf("--------          ---------\n");
	printf("0-Very Bad        %d\n", frequencyVB);
	printf("1-Bad             %d\n", frequencyB);
	printf("2-Good            %d\n", frequencyG);
	printf("3-Very Good       %d\n", frequencyVG);
	printf("4-Excellent       %d\n", frequencyE);
	printf("Total mark=       %d\n", total);
	system("pause");
}


The code above did not use array frequency counting, so I need to modify some coding in order to perform frequency counting.

The output is like below:
Please enter the survey marks below:
Question Response(0-4)
Q 1 : 2
Q 2 : 3
Q 3 : 2
Q 4 : 2
Q 5 : 2
Q 6 : 1
Q 7 : 0
Q 8 : 0
Q 9 : 3
Q10 : 3
RESULTS
=========
Response frequency
-------- ---------
0-Very Bad 2
1-Bad 1
2-Good 4
3-Very Good 3
4-Excellent 0
Total mark = 18

Hope someone can guide me with this, thank you for reading and guiding me.
to use an array for it..
int counts[5] {}; //initializes array to all zeros.

...
get a response... ensure that it is 0-4 or you will have a bad problem.
counts[response]++; //total them up.

...
number of very bad responses is counts[0]
... number of excellents is counts[4]
it is also useful to have an enum here,
enum responses_e {very_bad, bad, good, very_good, excellent, total_responses}
and say
int counts[total_responses]{};
and..
counts[very_good] //more readable with the enums

if this is supposed to be pure C, the {} may not work (not sure). you can set it to zeros another way in that case, that is a C++ syntax.
Last edited on
A frequency count is simply the number of times something happens.
An array frequency count is just a table printing both the element and the number of times it occurs, exactly as in your sample "Response frequency" output.

That's it. If you are feeling underwhelmed by the lack of complexity of this task, don't feel bad.

Lines 30-36 of your code are entirely unnecessary. You don't need to gather any other information.

However, I should point out that this is an array frequency count, and you are not using an array...

 
  int responses[5] = { 0, 0, 0, 0, 0 };

This makes your code easy. The user inputs a response == index into the array (but make sure that 0 <= response <= 4) and you need a simple loop to print the resulting table (n and responses[n], for n in 0..4).

Because the results expect you to name the elements of the array, it is helpful to have an additional array with those names:
1
2
3
4
5
6
  const char* response_names[5] =
  {
    "Very Bad",
    "Bad",
    ...
  };

Then when you loop through the array to print the responses you can also print the very useful names:
 
  printf("%d-%s %d\n", n, response_names[n], responses[n] );


Finally, the total (total mark) is nothing more than the sum of the elements of the array. You can gather this by simply adding the inputted response to total each time.

Don't forget, the purpose of this assignment is to use arrays and loops together, and to index elements of the array.

Hope this helps.
Last edited on
Hi @Duthomhas, sorry for the disturbance, I went and changed some of my codings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

void main()
{
        int responses[5] = { 0, 1, 2, 3, 4 };
		const char* response_names[5] =
		{
		  "Very Bad",
		  "Bad",
		  "Good",
		  "Very Good",
		  "Excellent"
		};
		int i, n, total, frequencyVB = 0, frequencyB = 0, frequencyG = 0, frequencyVG = 0, frequencyE = 0;

		printf("Please enter the survey marks below: \n");
		printf("Question         Response(0-4)\n");
		for (i = 1; i <= 10; i++)
		{
			printf("Q %d          : ", i);

			for (n = 0; n < 5; n++)
			{
				scanf("%d", &responses[n]);
			}

			switch (responses[n]) {
			case 0: frequencyVB++;
				break;
			case 1: frequencyB++;
				break;
			case 2: frequencyG++;
				break;
			case 3: frequencyVG++;
				break;
			case 4: frequencyE++;
				break;
			}

			total = 0*frequencyVB + 1*frequencyB + 2*frequencyG + 3*frequencyVG + 4*frequencyE;
		}


		printf("RESULTS\n");
		printf("========\n");
		printf("Response          frequency\n");
		printf("--------          ---------\n");
		for (n = 1; n < 5; n++)
		{
			printf("%d-%s %d\n", n, response_names[n], responses[n]);
		}
		printf("Total mark=       %d\n", total);
		system("pause");
}


However, I have a little problem, first of all, I can't print out
Q 1 : 2
Q 2 : 3
Q 3 : 2
Q 4 : 2
Q 5 : 2
Q 6 : 1
Q 7 : 0
Q 8 : 0
Q 9 : 3
Q10 : 3

I used the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
for (i = 1; i <= 10; i++)
		{
			printf("Q %d          : ", i);

			for (n = 0; n < 5; n++)
			{
				scanf("%d", &responses[n]);
			}

			switch (responses[n]) {
			case 0: frequencyVB++;
				break;
			case 1: frequencyB++;
				break;
			case 2: frequencyG++;
				break;
			case 3: frequencyVG++;
				break;
			case 4: frequencyE++;
				break;
			}

			total = 0*frequencyVB + 1*frequencyB + 2*frequencyG + 3*frequencyVG + 4*frequencyE;
		}

but it kept looping like this
Please enter the survey marks below:
Question         Response(0-4)
Q 1          : 2
2
2
2
2
Q 2          : 2
2
2
2
2
Q 3          : 2
no, do not read into responses.
read into a temporary variable.
increment responses.
1
2
3
4
5
6
7
8
9
10
for (i = 1; i <= 10; i++)
		{
			printf("Q %d          : ", i);

		
				scanf("%d", &tmp); //tmp MUST be 0-4 though, better force that on user
   		         responses[tmp] ++;		

			total = 0*frequencyVB + 1*frequencyB + 2*frequencyG + 3*frequencyVG + 4*frequencyE;
		}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
   const int Nmarks = 10, MaxMark = 4;
   int freq[MaxMark+1] = { 0 };
   const char *desc[] = { "Very Bad", "Bad", "Good", "Very Good", "Excellent" };
   int response, total = 0;
   cout << "Please enter " << Nmarks << " survey marks (0-" << MaxMark << ")\n";
   for ( int n = 0; n < Nmarks; n++ )
   {
      cin >> response;
      freq[response]++;
      total += response;
   }

   for ( int i = 0; i <= MaxMark; i++ ) cout << i << " (" << desc[i] << "): " << freq[i] << '\n';
   cout << "Total: " << total << '\n';
}


Please enter 10 survey marks (0-4)
1 2 3 4 0 1 2 3 4 1
0 (Very Bad): 1
1 (Bad): 3
2 (Good): 2
3 (Very Good): 2
4 (Excellent): 2
Total: 21
When using an input value as an array element, it's important to check that the input is in a valid range - otherwise there's invalid memory access. Using a function for this simplifies the main code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <type_traits>
#include <limits>

template<typename T = int>
typename std::enable_if_t< std::is_integral_v<T>, T>
getInp(const std::string& prm)
{
	T n {};

	while ((std::cout << prm) && (!(std::cin >> n))) {
		std::cout << "Invalid input. Not a(n) " << typeid(T).name() << '\n';
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	return n;
}

template<typename T = int>
typename std::enable_if_t< std::is_integral_v<T>, T>
getInp(const std::string& prm, T low, T upper = std::numeric_limits<T>::max())
{
	T num {};

	do {
		num = getInp<T>(prm);
	} while ((num < low || num > upper) && (std::cout << "Input not in range\n"));

	return num;
}

int main()
{
	constexpr const char* desc[] {"Very Bad", "Bad", "Good", "Very Good", "Excellent"};
	constexpr unsigned NoMrks {10};
	constexpr unsigned MxMrk {std::size(desc) - 1};
	unsigned freq[MxMrk + 1] {};

	std::cout << "Please enter " << NoMrks << " survey marks (0 - " << MxMrk << "): ";
	for (unsigned n {}; n < NoMrks; ++n)
		freq[getInp("", 0U, MxMrk)]++;

	unsigned total {};

	for (unsigned i {}; i <= MxMrk; ++i) {
		std::cout << desc[i] << ": " << freq[i] << '\n';
		total += freq[i] * i;
	}

	std::cout << "Total: " << total << '\n';
}



Please enter 10 survey marks (0 - 4): 1 2 3 4 0 1 2 3 4 1
Very Bad: 1
Bad: 3
Good: 2
Very Good: 2
Excellent: 2
Total: 21

Last edited on
@seeplus
LOL, man, you just went waaaaaaaaaaaaaaaaaAAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaaaaaaay over OP's head...

Though, I suppose if OP is getting code off the interweebs for his homework, he can expect it, heh.

Also, no one seems to have noticed that OP is using C. Well, except jonnin
Last edited on
@Duthomhas
Hi, i have my own code already and I'm using c not c#, I should have mentioned it in the question because I saw some users suggested me to use c# coding or variable.
prove:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

main(void) {
	int i, n, total, response, frequency[5] = { 0 };
	int total0, total1, total2, total3, total4;

	printf("Please enter the survey marks below: \n");
	printf("Question         Response(0-4)\n");
	for (i = 1; i <= 10; i++)
	{
		printf("Q %d          : ", i);
		scanf("%d", &response);

		switch (response) {
		case 0: frequency[0]++;
			break;
		case 1: frequency[1]++;
			break;
		case 2: frequency[2]++;
			break;
		case 3: frequency[3]++;
			break;
		case 4: frequency[4]++;
			break;
		}

		total0 = 0 * frequency[0];
		total1 = 1 * frequency[1];
		total2 = 2 * frequency[2];
		total3 = 3 * frequency[3];
		total4 = 4 * frequency[4];
		total = total0 + total1 + total2 + total3 + total4;
	}

	printf("\nRESULTS\n");
	printf("========\n");
	printf("Response         \tfrequency\n");
	printf("--------         \t---------\n");
	printf("0-Very Bad       \t%d\n", frequency[0]);
	printf("1-Bad            \t%d\n", frequency[1]);
	printf("2-Good           \t%d\n", frequency[2]);
	printf("3-Very Good      \t%d\n", frequency[3]);
	printf("4-Excellent      \t%d\n", frequency[4]);
	printf("Total mark=      \t%d\n", total);
	system("pause");
}

Latest code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

main(void) {
	int i, n, total = 0, response, frequency[5] = { 0 };
	

	printf("Please enter the survey marks below: \n");
	printf("Question         Response(0-4)\n");
	for (i = 1; i <= 10; i++)
	{
		printf("Q %d          : ", i);
		scanf("%d", &response);

		frequency[response]++;
		total += response;

		
	}

	printf("\nRESULTS\n");
	printf("========\n");
	printf("Response         \tfrequency\n");
	printf("--------         \t---------\n");
	printf("0-Very Bad       \t%d\n", frequency[0]);
	printf("1-Bad            \t%d\n", frequency[1]);
	printf("2-Good           \t%d\n", frequency[2]);
	printf("3-Very Good      \t%d\n", frequency[3]);
	printf("4-Excellent      \t%d\n", frequency[4]);
	printf("Total mark=      \t%d\n", total);
	system("pause");
}

The coding is completely different from @seeplus.
I'm not as lazy as some people who just ask for answers when I really don't know how to solve it, I'll ask the reason why my program won't run, and I'll learn from my mistakes, sorry but the sentence here "I suppose if OP is getting code off the interweebs for his homework, he can expect it, heh" really offended me. I know the consequences of getting answers from those people who are professional in both c and c#(I read it from the forum rules), and also I have to face exams without any aid from people so I cant' just get answers from people like that, sorry if I made you think that I only get an answer from interweebs, this programming skill is very important to me as when I graduated, I need to find a job that's related to the field, I might become a game programmer or app developer, there are some people who just posted question and expect people like you all to help them answer. Sorry again if I cause confusion between you and me. That's all from me and hope you have a great day :) Cheers!
Last edited on
@OP
Many opportunities to simplify and get rid of repetition by using simple array data model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>

int main()
{
    const int NO_QUESTIONS{4};
    
    int frequency[5]{ 0 };
    
    std::string label[]
    {"0-Very Bad", "1-Bad","2-Good","3-Very Good","4-Excellent"};
    
    printf("Please enter the survey marks below: \n");
    printf("Question         Response(0-4)\n");
    
    int response{0};
    int total{0};
    for (int i = 0; i <= NO_QUESTIONS; i++)
    {
        printf("Q %d          : ", i);
        scanf("%d", &response);
        
        frequency[response]++; // SHOULD CHECK RESPONSE IN RANGE
        total += response;
    }
    
    printf("\nRESULTS\n");
    printf("========\n");
    printf("Response         \tfrequency\n");
    printf("--------         \t---------\n");
    
    for(int i = 0; i < 5; i++)
    {
        std::cout << label[i] << '\t' << frequency[i] << '\n';
    }
    std::cout << "Total: " << total << '\n';
}



Please enter the survey marks below: 
Question         Response(0-4)
Q 0          : 0
Q 1          : 1
Q 2          : 2
Q 3          : 3
Q 4          : 4

RESULTS
========
Response         	frequency
--------         	---------
0-Very Bad	1
1-Bad	1
2-Good	1
3-Very Good	1
4-Excellent	1
Total: 10
Program ended with exit code: 0
againtry, now do it in C like the OP said.
hi @The Grey Wolf @againtry, I already got my solution, thank you so much for your help!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

main(void) {
	int i, n, total = 0, response, frequency[5] = { 0 };
	

	printf("Please enter the survey marks below: \n");
	printf("Question         Response(0-4)\n");
	for (i = 1; i <= 10; i++)
	{
		printf("Q %d          : ", i);
		scanf("%d", &response);

		frequency[response]++;
		total += response;

		
	}

	printf("\nRESULTS\n");
	printf("========\n");
	printf("Response         \tfrequency\n");
	printf("--------         \t---------\n");
	printf("0-Very Bad       \t%d\n", frequency[0]);
	printf("1-Bad            \t%d\n", frequency[1]);
	printf("2-Good           \t%d\n", frequency[2]);
	printf("3-Very Good      \t%d\n", frequency[3]);
	printf("4-Excellent      \t%d\n", frequency[4]);
	printf("Total mark=      \t%d\n", total);
	system("pause");
}

@OP
All the best - good to see the simplification I suggested helped. It's fun what can be done with simple C-style arrays notwithstanding STL containers when the big guns are a better choice.

FWIW I used cout because I've forgotten most of the printf codes and I was in a hurry. But sometimes printf is not a bad move instead of cout with <iomanip> functionality.
AkiraC, againtry did put an important comment in his code [// SHOULD CHECK RESPONSE IN RANGE ]. Always tread use input with suspicion and sanitise or discard invalid input.
When I was taught programming at uni, we were initially provided with input routines to use so while we were concentrating on the language and programming concepts we weren't distracted by issues such as this. Later we learnt how to do input etc correctly when we could understand it.

IMO For c++ learners it would be help if some easy to use input routines were available to be used until the student is ready to code their own.
seeplus, I hear what you're saying. I guess my experience of Uni was different. If we only stuck to the happy path we wouldn't get much more that a passing mark. We were encouraged to do error checking and handling very early on.
Ours was only for the first few exercises (3 I think?) that we could. Then the access to the library was removed and we couldn't use them. We didn't see the source and then we had to write and use our own. And then yes, we had to do input checking and handling and were heavily penalised in marking if we didn't do it and do it right. But not having to really bother about input during the first few weeks was a great help in that we could concentrate on the programming concepts etc.

Well, I suppose that on the internet you can offend anyone with anything.

AkiraC, you took offense to something that was not directed at you. And even if it were, people in the programming world need thicker skin if they wish to survive.

It is very common for learners to come and get code here and simply plagiarize it for their homework. Whether or not you are doing it is unknown to me, hence my usage of the word "if".

It does appear to me that you are actually trying to understand this without simply copying code, which is awesome of you. You have still failed to completely understand the idea of using loops and array indices together, but you are closer, and that is all that matters. Keep learning.

And don't get all bent out of shape when a stranger on the internet says something the wrong way. Even if he is actually trying to be an a**hole.
Topic archived. No new replies allowed.