Arrays

Confused on how to do this problem with arrays

In this program, the user will enter two digit positive and negative integers (i.e. -99 to +99) but your job is to only count the number of occurrences of each integer between [-9 and +9], inclusive. When the user types 100 or -100 the program should exit and print out the statistic of how many times each integer between [-9 and +9] occurred as well as how many numbers outside the range of [-9 to +9] occurred.

You may assume the user will never type in a number that has magnitude (absolute value) of 101 or more.

Your output should list each number from -9 to +9 on a separate line followed by a colon and a space (:) and then the number of times that number was entered (i.e. number of occurrences). After printing out those 19 lines, you should output a final line that reads Out Of Range: n where n is the actual number of values that were entered but outside the range -9 to +9. You must follow this format or our auto checker will not work and you will lose points.

Hints: Arrays act like tables mapping an index to some desired value. Here we want to map the integer we receive -9 to +9 to the number of times we've entered that value. However, array indexing must be 0 to n-1 (indexes cannot be negative).

Example 1
If the user entered:

-10 -1 5 7 99 5 100
Your program should output exactly the lines:

-9: 0
-8: 0
-7: 0
-6: 0
-5: 0
-4: 0
-3: 0
-2: 0
-1: 1
0: 0
1: 0
2: 0
3: 0
4: 0
5: 2
6: 0
7: 1
8: 0
9: 0
Out Of Range: 2
Hello dms99,

The problem is not that difficult unless you do not understand arrays.

I would suggest not trying to think about how to do the whole program at one time, but to break it down into smaller parts and do one at a time.

To help you get started I was thinking about two arrays "usableNumbers" and "useableNumbersCout". They both could be of type "int". "useableNumbers" would hold the numbers -9 - +9 and "useableNumbersCout" would hold the count of each match in "useableNumbers".

I am also thinking of some "const" variables like "MAXSIZE" for the arrays and "START" and "END" to be used in a for loop. The variables are more for future use than right now, but they will still work.

Next I would deal with user input and follow that with dealing with the input. Do not worry about these parts right now just work on getting the arrays setup.

When you have something post the code and we can go from there.

Hope that helps,

Andy
This is what I have so far, but honestly I'm so confused. I'm new to programming btw.


#include <iostream>
#include <string>
using namespace std;

int main()
{
int usableNumbers[19];
int usableNumbersCout;
const [MAXSIZE];

cin >> usableNumbers;

for(int i = 0; i < 19; i++)
{
if(usableNumbers > 99 || usableNumbers < -99)
{
break;
}

}
Hello dms99,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

You have a good start, but the code is lacking. Look at the comments in the following code. Some places I have shown you how it should be done and others what needs to be done.

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 <iostream>
#include <string>

using namespace std;

int main()
{
	const size_t MAXSIZE{ 19 };

	int usableNumbers[MAXSIZE]{};  // <--- {} initializes the array to zeros. You should always initialize your variables.
	int usableNumbersCout[MAXSIZE]{};  // <---Should be an array to store the count of each time the input number is between -9 and 9 inclusive.

	// Here you need to put the numbers -9 through 9 into the "useableNumbers" array. I used a for loop along with a variable called "index" for the subscript to do this. Also used the "const" variables "START" and "END" in the for loop.

	//  Next line not need here and will not work the way you think it is.
	cin >> usableNumbers;  // <--- Did this inside a do/while loop.

	// This for loop is useful, being used the wrong way and to soon.
	for (int i = 0; i < 19; i++)
	{
		// This condition is using the wrong costaants. Needs to check the numbers  of the "usableNumbers" array.
		if (usableNumbers > 99 || usableNumbers < -99)
		{
			// Here based on "i" for the subscript you need to add to the corsponding element of the " usableNumbersCout" array b"efore the break.
			break;
		}

	}

	//  Used this part to print the two arrays to look like your sample output.

	return 0;
}


"size_t" is another name for "unsigned int". Since "MAXSIZE" needs to be a positive number this is all that is needed. It could also be an int.

At line 13 you could use a for loop to put the numbers -9 - 9 into the array or initialize the array when it is defined. I recommend the for loop because you can change the range of numbers used.

If you have any problems with this we can work on them.

Hope that helps,

Andy
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
#include <iostream>
#include <string>

using namespace std;

int main()
{
	const size_t MAXSIZE{ 19 };

	int usableNumbers[MAXSIZE]{-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};  
	int usableNumbersCout[MAXSIZE]{};  // <---Should be an array to store the count of each time the input number is between -9 and 9 inclusive.

    for(int index = 0; index < 19; i++)
    {
        usableNumbers[i];
    }

	while(
	cin >> usableNumbers;  

	// This for loop is useful, being used the wrong way and to soon.
	for (int i = 0; i < 19; i++)
	{
		// This condition is using the wrong costaants. Needs to check the numbers  of the "usableNumbers" array.
		if (usableNumbers > 9 || usableNumbers < -9)
		{
			// Here based on "i" for the subscript you need to add to the corsponding element of the " usableNumbersCout" array b"efore the break.
			break;
		}

	}

    cout << usableNumbers[i] << ':' << ' ' << usableNumbersCout[i];

	return 0;
}


This is what I have now. I'm not sure what to initialize the usableNumbersCout array to. Also not sure what to put into the while loop or for loops lol. But is this the structure? for loop followed by a while loop then another for loop? or do I need more? Thanks for your help
Hello dms99,

Getting better.

Line 10 is fine it will work this way. the numbers between the {} will initialize each element of the array.

Line 11 the empty {} will initialize each element of the array to zero. Nothing else is needed.

The for loop in lines 13 - 16 is wrong and will do nothing. for(int index = 0; index < 19; i++). "index" is set to zero. In the middle it would "0 < 19", this will always be true because the value of index never changes. At the end you increase "i" by one. What is this for and what good does it do to increase "i"?

What I used looks lie this:
1
2
for (int lc = START; lc <= END; lc++)
	usableNumbers[index++] = lc;

Where "START" is defined as "-9" and "END" is defined as "9". "index" was defined and set to zero. This puts the numbers "-9" - "9" into the "usebleNumbers" array,, but allow you to change the numbers to whatever you would want just be changing three const variables "MAXSIZE", "START" and "END" at the beginning of the program. This just makes it easier to change than what you did on line 10. Although there is nothing wrong with what you did.

Line 18 the while condition is incomplete. You are missing the condition and the closing ")" along with the {} to define the block of the while loop. See:
http://www.cplusplus.com/doc/tutorial/control/
The while loop will work, but for what it is worth I used a do/while loop. read the difference between the two.

Line 19 will not work. "usablenumbers" is the starting address of the array. Not a variable to put something in. What you need to do is create a variable to put the "cin" into.

Line 22 is OK, but you could use "MAXSIZE" in place of the 19 that is what it is there for.

Line 25 is not what you want in the (). The comparison here needs to be with each individual element of the "usableNumbers" array and the number input from the keyboard. If the comparison is equal you add one to the "usableNumbersCount" array: usableNumbersCount[i]++;. This keeps track of how many times each number, -9 - 9 is entered. Also in the if statement I added one to "totalUsable" to know how how many numbers fell in the range.

Before the for loop and after the "cin" I added one to "totalEntered" to know how many numbers were entered. The difference between"totalEntered" and "totalUsabel" left the numbers out of range.

Line 33 will not work because you have no value for "i". "i" lost scope when the for loop ended. This needs its own for loop to print all of both arrays.

You have taken some of what I showed you and used it correctly, but do you understand how it works? If not we can work on what you do not understand just let me know.

Hope that helps,

Andy

Edit:
This works cout << usableNumbers[i] << ':' << ' ' << uableNumbersCout[i];
but could be shortened to: cout << usableNumbers[i] << ": " << usableNumbersCout[i];
Last edited on
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
#include <iostream>
#include <string>

using namespace std;

int main()
{
	const size_t MAXSIZE{ 19 };

	int usableNumbers[MAXSIZE]{-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};  
	int usableNumbersCount[MAXSIZE]{};
    int START = 9;
    int END = -9;
    int number;
    int totalUsable = 0;
    int totalEntered = 0;
    
    for(int i = START; i <= END; i++)
    {
        usableNumbers[i++] = i;
    }

	do {
	    cin >> number;
	    totalEntered++;
	} while( number < 100 || number > -100 ); 
	
	
	for (int i = 0; i < 19; i++)
	{
		if (usableNumbers[i] = numbers)
		{
			usableNumbersCount[i]++;
			totalUsable++;
		}
        
	}

    cout << usableNumbers[i] << ': ' << usableNumbersCout[i];

	return 0;
}


I'm confused on how to define usableNumbers[i]. You said it was lost in the for loop, so how do I print out both arrays using a for loop. The do while loop may not be correct either. Do I have all the variables I need?
Hello dms99,

Much better. Getting there.

Lines 8 - 16 are almost there. This is what I did with comments on what you have wrong and the bold is what I changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
	const size_t MAXSIZE{ 19 };
	// These to are backwards
	const int START = 9;  // <--- -9.
	const int END = -9;  // <--- 9.

	int usableNumbers[MAXSIZE]{};  // <--- Empty {} are all you need here with the for loop.
	int usableNumbersCount[MAXSIZE]{};
	int number;  // <--- Needs initialized.
	int index{};  // <--- Need to add.
	int totalUsable = 0;
	int totalEntered = 0;

	for (int i = START; i <= END; i++)
	{
		usableNumbers[index++] = i;
	}


This way by changing the three "const" variables you can change the set of numbers used to whatever you may need and the for loop will fill the array with the numbers that you need. By using the for loop initializing the array on line 10 the way you have is not needed.

The do/while loop is right, but not complete. The for loop lines 29 - 37 should be inside the do/while. In the for loop "19" should be replaced with "MAXSIZE" I hope you can see why. If not let me know. After you add to "totalUsable" this needs a "break" statement to end the for loop because once you find a match there is no need to continue.

In the if statement loose the "s" on "numbers". That is not what you defined earlier.

What I found is after the do/while loop I had to put in "totalEntered--;" for the math to work correctly. A quick fix for something I should have done differently.

Line 39 needs to be in a for loop. "i" is only defined in the previous for loop and looses its scope when the for loop ends. So in line 39 "i" is not defined and has no value.

After the for loop for line 39 you need to deal with printing "Out Of Range: 2".

Hope that helps,

Andy
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
57
58
#include <iostream>
#include <string>

using namespace std;

int main()
{
	const size_t MAXSIZE{ 19 };
    const int START = -9;
    const int END = 9;
    
	int usableNumbers[MAXSIZE]{};
	int usableNumbersCount[MAXSIZE]{};
    int number = 0;
    int index{};
    int totalUsable = 0;
    int totalEntered = 0;
    
    for(int i = START; i <= END; i++)
    {
        usableNumbers[index++] = i;
    }

	do {
	    for (int i = 0; i < 19; i++)
	{
		if (usableNumbers[i] == number)
		{
			usableNumbersCount[i]++;
			totalUsable++;
		}
        
	}
	    cin >> number;
	    totalEntered--;
	} while( number < 100 || number > -100 ); 
	
	
	for (int i = 0; i < 19; i++)
	{
		if (usableNumbers[i] == number)
		{
			usableNumbersCount[i]++;
			totalUsable++;
			break;
		}
        
	}

    for(int i = 0; i < MAXSIZE; i++)
    {
    cout << usableNumbers[i] << ':'  << ' ' << usableNumbersCount[i];
    }

    cout << "Out Of Range: " << number;
    
	return 0;
}



Everything seems to work except that in the last for loop it says warning: comparison between signed and unsigned integer expressions. That is why i changed it to 19, but idk. Are there any other errors you see?

I haven't gotten it to compile or print what I want yet
Last edited on
Hints: Arrays act like tables mapping an index to some desired value. Here we want to map the integer we receive -9 to +9 to the number of times we've entered that value. However, array indexing must be 0 to n-1 (indexes cannot be negative).


Think of this:
1
2
3
4
5
std::cin >> number;
if ( START <= number and number <= END )
{
  std::cout << "index " << (number - START) << " value " << number << '\n';
}
Hello dms99,

I see you can copy and paste well, but do you understand what is going on and how it works?

Line 35 my bad what I meant to say is that it should be after the while loop.

Lines 39 - 48 is the correct for loop that should be inside the do/while loop. You made an attempt to do that , but missed the break statement.

Lines 39 - 48 I do not believe you understand what this is doing. If you did you would have figured out it should not be there.

After line 48 the for loop is correct, but watch the indenting.

Line 55 is a good start. You print the words, but the wrong answer.

Hope that helps,

Andy
Is it better to use a boolean variable in a while loop instead of the do/while? or is that the same thing
I'm sorry if it seems like I'm copying and pasting but it seems like this program could be a lot simpler and I'm struggling grasping your concepts
Do While loops are typically used for thing that need to happen at least once (one or more times). While loops are used for things that need to happen 0 or more times. It is also possible to make a while loop behave for one or more times by setting up the logic but often a do while is the better way to go.
Not quite the same thing:
The do..while evaluates its body at least once.
The while might evalueta its body, if the condition is false to begin with.

In the body of a loop one can naturally evaluate additional conditions with if-statements and use break or continue. (and use loops and call functions and ...)


Do you realize that you need only two loops in your program?
1. Read input.
2. Print result.
No nested loops required.


You already had
1
2
3
4
do {
	cin >> number;
	totalEntered++;
} while( number < 100 || number > -100 );

Whether you know it or not, this one contains a very important feature:
number < 100 || number > -100
Put in more general terms:
boolean-expression-1 || boolean-expression-2
A boolean expression is and expression that returns a bool. For example, the number < 100 is such expression.

The || is logical OR operator that combines two boolean expressions into a larger boolean expression. One can actually combine many subexpressions with multiple logical operators into one condition. The && is logical AND.


A really useful thing is that std::cin can be used as boolean expression.
Do you know whether std::cin >> number is an expression that returns a value?
If it returns a value, what that value is?
this program could be a lot simpler and I'm struggling grasping your concepts
Ok, no panic :-)
Write a little piece of code and test it immediately: don’t write a lot of code without testing it. You’ve decided to use arrays: that’s good. To start, declare your array and immediately write the procedure to display its content on screen, even if in an output that doesn’t comply with your assignment.
This way, as you write, you can verify your results.

I’m afraid my English is terrible, but I hope this can push you in the right direction:

1) In this program, the user will enter two digit positive and negative integers (i.e. -99 to +99)
2) You may assume the user will never type in a number that has magnitude (absolute value) of 101 or more.
3) a) When the user types 100 or -100 the program should exit...
That means:
- you need a loop where the user is asked to input numbers
- that loop will stop when the user types 100 or -100
- the user will NOT type 101 or more (or -101 or less)
So: you only need to check for 100 or -100 to appear: the user will do anything right.
(of course, if you create a loop that runs as long as the user types values greater than -100 and lower than 100 that’s also fine)

3) b) ...and print out the statistic of how many times each integer between [-9 and +9] occurred as well as how many numbers outside the range of [-9 to +9] occurred.
That means:
- As soon as the loops end, you need to have all your values ready to display.
So: everything must happen inside the loop (except for the display on screen step).

4) your job is to only count the number of occurrences of each integer between [-9 and +9], inclusive.
That means:
- inside your loop, you need to check if any values are greater than -10 and lower than +10.
- If yes, you need to increment a specific variable which stores that piece of information (the number ‘x’ has been inserted again: let’s increment the variable for ‘x’).
Hints: in your code, you already have an array. An array is no more than a bunch of variables which lie one next to the other, in order. The values you are selecting are in the same situation: they are contiguous; there’re no ‘interruptions’ between -9 and 9.

Let’s assume the user types -9. You want to increment the value for "how many time -9 has been typed in?". You have an array with a ‘row’ of variables (you decide how many you need) which can store any piece of information you need to save.
So...

Now, your teacher has set a trap for you ;-)
You apparently need to manage only values from -9 and 9, but that’s false.
When the program finishes, you also need to state how many ‘not-in-range’ numbers have been typed in. So, you don’t need room only for 19 values from -9 to 9, but also one further variable which stores the frequency of all other numbers.
Topic archived. No new replies allowed.