How to check how many times a number has been entered - c++

I'm trying to solve one of the questions on a task sheet I've been received, to help me further in my understanding of C++ code from my class.
The question is (and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen
Creates a second array of size 5 and fills it with zeros
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
The problem is how to go about checking how many times a number was entered. I was thinking of a for loop, but the way I wrote it is fundamentally incorrect, so I find myself struggling to see the mistake I am having. Perhaps I am missing something simple? Any help would be great.
Here is my (terrible) for loop attempt, so you can see my error.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}

Put
COUNT[ input[i]-1 ]++;
in your first loop (after validation). Once you do that, you don't need a second loop to tally up the results.
This works from the inside out by first getting what input[i] is, then using it to modify the (input[i]-1)'th location in the COUNT array. If the user enters 4 on the first run of the loop, then i == 0 and input[i] == 4. Since arrays are 0-based, it will increment COUNT[input[i]-1] which in this case is COUNT[4-1] == COUNT[3].
After your initial loop runs the number of 1's will be in COUNT[0], the number of 2's will be in COUNT[1] and so on.

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
//declare a constant values
int input[10];
int count = 10; //all constant MUST be in capital letters
//second array filled with zeros
const int MAX_NO = 5;
int COUNT[5] = { 0, 0, 0, 0, 0 };
//ask user for 10 input values
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
//check if input numbers are between 1 and 5 inclusive
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
/* show how many times 1 number appears.
this section should be in the main loop which would enable the program to check how many times a
number is entered so that it is stored in the second array. changed i to secondCount because this is the counting index of the second array not the first which you've called i (one of the reason you'd all zero as output when u ran your code)*/
for (int secondCount = 1; secondCount <= MAX_NO; secondCount++)
{
if (input[i] == secondCount)
{
COUNT[secondCount-1]+= 1; //use minus 1 from i and increment. += 1 is the same as COUNT++
}
}
}
//display number entered in the first array
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
//display how many times a number is entered.
for (int secondCount = 0; secondCount < MAX_NO; secondCount++)
{
cout << secondCount + 1 << " appears " << COUNT[secondCount]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
OUTPUT:
Please enter a number for value 1 = 1
Please enter a number for value 2 = 1
Please enter a number for value 3 = 1
Please enter a number for value 4 = 2
Please enter a number for value 5 = 3
Please enter a number for value 6 = 2
Please enter a number for value 7 = 4
Please enter a number for value 8 = 4
Please enter a number for value 9 = 3
Please enter a number for value 10 = 2
You entered: 1 1 1 2 3 2 4 4 3 2
1 appears 3 times in the input
2 appears 3 times in the input
3 appears 2 times in the input
4 appears 2 times in the input
5 appears 0 times in the input

for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
Let's examine what this is doing. It starts by checking input[1]. (This should be input[0] as array indices start at 0). Then it checks if input[1] is equal to 1. If it is, then it increments COUNT[1].
Next, it checks input[2]. Then it checks if input[2] is equal to 2. If it is, it increments COUNT[2]. And so on until it has gone through input[5].
Do you see the problem with this? You're only checking the first 5 inputs and only checking them against a single value.

Related

how to make this number shape?

Write a program to display the below pattern with n rows, where n is
in the range between 1 and 100. The variable n should be entered by
the user. If the user input is between 1 and 100 then output the
pyramid as given below, otherwise prompt the user to enter n again.
Here is the sample output: Enter the number of rows: 6
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
6 7 8 9 10 11
(enter image description here)
this is my code it shows a close answer but not correct.
int num=1 , counter=1;
cout << "Enter the number of rows: " ;
cin>>num;
for(int i=0;i<=num;i++)
{
for(int j=0;j<=i;j++)
{
cout<<counter<<" ";
counter++;
}
cout<<endl;
}
int num = 1, counter = 1, temp = 1;
cout << "Enter the number of rows: ";
cin >> num;
for (int i = 0; i < num; i++)
{
for (int j = 0; j <= i; j++)
{
cout << temp << " ";
temp++;
}
counter++;
temp = counter;
cout << endl;
}
The variable temp serves as a counter for the rows, meanwhile the variable counter is responsible for the starter numbers in the first column.
you should either set counter in each run of outer loop, right before entering the inner one with something like counter = i+1, the way you wrote this code value of this variable carries over to the next iteration and keeps going only upwards.
Alternate solution would be to print j instead and work on inner loop, it should then start with i and the first number that wouldn't qualify would be 2*i this way for i equal 2 the sequence would be 2 3,
either way you should also rework your outer loop, as right now it starts with 0 and ends with num meaning it goes through num+1 iterations
int rows, i, j = 0, number = 0, counter = 0;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++)
{
while (j != 1 * i)
{
if (counter <= rows)
{
cout << i+j << " ";
counter++;
}
++j;
}
number=counter=j=0;
cout << endl;
}

total the even numbers and product the odd

I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.
I get to put in the first number but then the for loop does not work.
#include <iostream>
#include <vector>
int main() {
int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;
std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";
for (int i = 1; i <= totalNum; i++){
std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];
if (numbers[i] % 2 == 0) {
total_even = total_even + numbers[i];
} else {
product_odd = product_odd * numbers[i];
}
}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}
First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).
Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out (0 + a + b == a + b, 1 * a * b == a * b). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.
By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):
#include <iostream>
int main() {
int numCount, thisNum, sumEven = 0, productOdd = 1;
std::cout << "How many numbers would you like to enter? ";
std::cin >> numCount;
std::cout << "\n";
for (int i = 1; i <= numCount; i++) {
std::cout << "Please enter number #" << i << ": ";
std::cin >> thisNum;
if (thisNum % 2 == 0) {
sumEven += thisNum;
} else {
productOdd *= thisNum;
}
}
std::cout << "\nSum of even: " << sumEven << "\n";
std::cout << "Product of odd: " << productOdd << "\n";
}
A sample run:
How many numbers would you like to enter? 6
Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6
Sum of even: 12
Product of odd: 15

How to cycle through 2 arrays and determine if values in each array are the same?

I am programming a guessing game where the user will define the first array to scale from 1 to whatever number inputed. I have a function that will randomise the numbers, then the second array will be the user input guesses. I am trying to make a for loop that will cycle through both arrays and print "O" if array values match, and "X" if they do not. It looks like the first iteration of the loop works and prints "O" but then prints a lot of X's after that.
#include <iostream>
using namespace std;
void createArray() {
int n;
int counter = 0;
cout << "Enter total number: ";
cin >> n;
// for loop to generate array to scale from 1 -
user input.
int *arr1 = new int[n];
for (int i = 1; i < n + 1; i++){
arr1[i] = i;
// Counter is used to track the size of array
counter++;
}
// for loop used to print the values of array (just for development and my reference)
for (int i = 1; i < n + 1; i++){
cout <<"[" << arr1[i] << "]";
}
cout << endl;
cout << counter << endl << "Number Guessing" << endl;
cout << "Enter " << counter << " digits (1-" << counter << ")" << endl;
// initialize user input array to be the same size as first array
int arr2[counter];
for (int i =0; i < counter; i++){
cin >> arr2[i];
}
cout << endl;
// here I am trying to cycle through both arrays and print "O" if the values match in each array.
for (int i = 0; i < n; i++){
arr1[i] = i;
bool correct = true;
for (int j = 0; j < n; j++){
arr2[j] = j;
if (arr1[i] != arr2[j]){
correct = false;
cout << "X";
}
if (correct){
cout << "O";
}
}
}
cout << endl;
}
int main(){
createArray();
}
This is the output:
Enter total number: 6
[1][2][3][4][5][6]
Number Guessing Enter 6 digits (1-6)
1 2 3 4 5 6
OXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Your loops are not comparing the arrays side by side but rather every element in array 1 is being compared to every element in array 2.
Since both arrays are reset by arr[i]=i & arr2[j]=j then they both are {0,1,2,3,4,5}.
The first innerloop will net a 'O' if(0==0) where i=0 & j=0, the next 5 innerloops if(0==1..5) where i=0 & j=1..5, are an 'X'.
The problem is on the next outerloop. Correct is reset to true by the outerloops second pass of i=1, but immediately the innerloop tests if(1==0) where i=1 & j=0, which is false and thus sets Correct to false.
So on the second pass thru the innerloop if(1==1) is true where i=1 & j=1, BUT there is no statement in the inner loop to set **Correct back to true.
Also, where as the X is printed as the result of the equality test, the O is outputted only when Correct is still true, which it is not. In fact, for every outloop after the first one, there will be an innerloop equality test which sets Correct to false before any a subsequent true equality tests.
The results are one 'O' followed by a 30 'X'. One 'X' for every false; 6 outerloops, and foreach, 5 of the six innerloops will be false. Five of the 'O's will simply not print because the 'O' does not print as a result of the equality test.
You dont need two loops
for (int i = 0; i <= n; ++i) {
if (arr1[i] == arr2[i]) {
std::cout << "0";
}
else {
std::cout << "X";
}
}
You should put your expected output for us to know what you want

opening stream using a 2d array

Can anyone fix this sample code that will print a file in 2D array. Here is the code and the output.
while (!file.eof())
{
int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
The output is not in table form.
The output is:
Index Size Weight (lb/ft) Diameter (in) 0 2 0.167 0.250 1 3 0.376 0.375 2 4 0.668 0.500 3 5 1.043 0.625 4 7 1.502 0
6 9 2.670 1.000 7 12 3.400 1.128 8 14 4.303 1.270 1.270
Press any key to continue . . .
Two options:
Define coutner as static
while (!file.eof())
{
static int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
or have it define external to the while loop:
int counter = 0;
while (!file.eof())
{
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
If you define it and initialized it to 0 in ever iteratoin of the while loop - it will never reach 5 to print endl;
It seems to be that not only the counter is initialized in every loop, as others pointed out before me, but moreover, it is never actually increased. The only increase I see is within the condition that it is equal to five. As it is never increased outside the condition, it never reaches five (even if it is declared as static or outside the loop), hence the condition is never met.
You have an uneven number of opening and closing curly braces, too.
I am not exactly sure what you want to achieve. If you want a line break after every fifth iteration, the following should work:
int counter = 0;
cout << setw(4) // suffice to set once
while (!file.eof())
{
file >> n;
cout << n << " ";
if (++counter == 5) // increase here before checking condition
{
cout << endl;
counter = 0;
// do not increase here again
}
}

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)