I'm having trouble figuring how to output the data generated by running a loop twice, into two columns.
I'm generating 100 random dice rolls, and outputting the count of how many times each roll gets. And I do this twice through.
My goal is to get two sets of the count and output it so that it looks like:
"one: (count of first set) (count of second set)
two: (count of first set) (count of second set)
three: (count of first set) (count of second set)
and so on...
This is my code below:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int seed, random, count_one (0), count_two(0), count_three(0), count_four(0), count_five(0), count_six(0);
cout<<"Input the random seed: ";
cin>> seed;
srand(seed);
for(int i=0; i<2; i++) {
for (int i=0; i<100; i++) {random=(rand()%6)+1;
if (random==1)
count_one++;
if (random==2)
count_two++;
if (random==3)
count_three++;
if (random==4)
count_four++;
if (random==5)
count_five++;
if (random==6)
count_six++;
}
cout<<"First Set"<<"\t"<<"Second Set "<<endl;
cout<<"one "<<count_one<<endl;
cout<<"two "<<count_two<<endl;
cout<<"three "<<count_three<<endl;
cout<<"four "<<count_four<<endl;
cout<<"five "<<count_five<<endl;
cout<<"six "<<count_six<<endl;
cout<<" Set 1 Avg."<<"\t"<<"Set 2 Avg. "<<endl;
}
return 0;
}
Any help will be appreciated!! Thank you so much :)
You need to a count variable for each set and number. Then you can simply put the output after your for loops and thus generate the appearance of columns.
Probably you want to use for that a two dimensional array, since this has two direct benefits for you:
Definition of Variables is shorter
You don't need your if instructions.
This would then look similar to this:
int seed;
int count[2][6] = {{0,0,0,0,0,0},{0,0,0,0,0,0}};
cout<<"Input the random seed: ";
cin>> seed;
srand(seed);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 100; ++j) {
count[i][rand() % 6]++;
};
};
cout << "First Set" << "\t" << "Second Set " << endl;
cout << "one " << count[0][0]<< "\t" << count[1][0] << endl;
cout << "two " << count[0][1]<< "\t" << count[1][1] << endl;
...
Further improvements would be two put the Strings of the numbers names in an Array, too. Thus you could put most of the output
Since you are in c++, you can use vectors too. I would move the loop that loops to a hundred into a function. That function runs and fills a vector with the counts calculated, and then just call that function twice. After that you can run your printing routine:
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
float getCounts (vector<int> &counts) {
float average = 0.0f;
// Initialize all counts to be output to zero
counts.clear();
for (int idxDieNumber=0; idxDieNumber<6; idxDieNumber++) {
counts.push_back(0);
}
// The run the loop you already had, but instead of printing here,
// just save the results in the vector passed
for (int i=0; i<100; i++) {
int random=(rand()%6)+1;
// instead of the original code: if (random==1) counts_one++; , etc
counts[random-1]++; // counts[0] corresponds to die face 'one', etc
average += random;
}
return average/100;
}
int main()
{
// we substitute count_one, count_two, etc in your code
// by two vectors, each stores the count in each loop
vector<int> countsPass1;
vector<int> countsPass2;
float averagePass1, averagePass2;
int seed;
cout<<"Input the random seed: ";
cin>> seed;
srand(seed);
// Instead of the two loops, call the function twice, passing the
// desired vector and the average for each pass
averagePass1 = getCounts (countsPass1);
averagePass2 = getCounts (countsPass2);
cout<<"First Set"<<"\t"<<"Second Set "<<endl;
cout<<"one "<< countsPass1[0] << "\t" <<countsPass2[0] << endl;
cout<<"two "<< countsPass1[1] << "\t" <<countsPass2[1] << endl;
cout<<"three "<< countsPass1[2] << "\t" <<countsPass2[2] << endl;
cout<<"four "<< countsPass1[3] << "\t" <<countsPass2[3] << endl;
cout<<"five "<< countsPass1[4] << "\t" <<countsPass2[4] << endl;
cout<<"six "<< countsPass1[5] << "\t" <<countsPass2[5] << endl;
cout<<" Set 1 Avg. " << averagePass1 << "\t"<<"Set 2 Avg. "<< averagePass2 <<endl;
return 0;
}
Note that your averages might be skewed away from 3 if RAND_MAX in your system is not an exact multiple of 6 (which most likely it will not be).
Related
Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.
I need some advice on how to echo the input from the user. A bit of background on the program that this is needed first. I created this program so that it asks the user how many values they would like to enter and then they enter the number in positive integers. Then the program computes to figure out if the numbers are even, odd, or zero and displays said information. I'm stuck on how I can create something that can output all of the enter values on the same line. For example, if the user chooses to enter in 4 values, being 1,2,3, and 4, with my current program it will read, Enter a number on one line and the next would be the number 1. Then it would ask to enter a number again and on another line the number 2. When I want it to read, The values you entered are 1,2,3,4. I'm confused as to how it works to display all the input on one line with a call by reference. Any advice or explanation would be greatly appreciated!
Code below
#include<iostream>
using namespace std;
void initialize(); //Function declarations
void get_number(int x);
void classify_number(int, int& zero_count, int& even_count, int& odd_count);
void print_results();
int N; //The number of values that the user wants to enter
//variables declared so that all functions can access it
int even_count;
int odd_count;
int zero_count;
int main()
{
cout << "Enter number of values to be read, then press return.\n"; //Prompting the user for how many values they will want to input
cin >> N;
get_number(N);
return 0;
}
void initialize() //This function is making sure that all the variables being used are initialized
{
even_count = 0;
odd_count = 0;
zero_count = 0;
}
void get_number(int N) //This function is getting the input from the user and then calling upon the previous function
{
int count = 0;
int x;
initialize(); //Calling upon the previous function to uses the variables
do {
cout << "Enter a positive whole number, then press return.\n";
cin >> x; //The number the user enters
//call the funtion and increment their count
classify_number(x, zero_count, even_count, odd_count); //Calling upon the function classify to update
count++;
} while (count < N);
//then print the count
print_results(); //Calling upon the print function
}
void classify_number(int x, int& zero_count, int& even_count, int& odd_count) //This function determines if it's an even,odd, or zero
{
if (x == 0)
zero_count++;
else if (x % 2 == 0)
even_count++;
else
odd_count++;
}
void print_results() //This is printing the results on the screen of the number of even, odds, and zeros.
{
cout << "There are " << even_count << " number of evens.\n";
cout << "There are " << zero_count << " number of zeros.\n";
cout << "There are " << odd_count << " number of odds.\n";
}
I believe that this much code will be sufficient :
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::size_t n;
std::cout << "Enter number of elements : ";
std::cin >> n;
std::vector<int> v(n);
std::cout << "Enter the numbers now : ";
for (auto &i : v) std::cin >> i;
std::cout << "The values you entered are : [ ";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "\b ]\n";
auto odd = std::count_if(v.begin(), v.end(), [](auto i) { return i % 2; });
auto zero = std::count(v.begin(), v.end(), 0);
auto even = v.size() - (odd + zero);
std::cout << "There are " << even << " even number(s).\n"
<< "There are " << zero << " zero(s).\n"
<< "There are " << odd << " odd number(s). \n";
}
Sample Run :
Enter number of elements : 6
Enter the numbers now : 0 1 2 3 4 6
The values you entered are : [ 0,1,2,3,4,6 ]
There are 3 even number(s).
There are 1 zero(s).
There are 2 odd number(s).
Ref. :
std::vector
Range-based for loop
How to print out the contents of a vector?
std::count, std::count_if
You could simply use an array of integers.
#include<iostream>
int main(int argc, char *argv[]){
/* Declare an array great enough to store all possible user values. */
/* Or use dynamic memory allocation when you are more experienced. */
int my_array[16];
int my_array_length = sizeof my_array / sizeof my_array[0];
/* As your code only uses positive integers, we use this information */
/* to our advantage and initialize our array with negative numbers. */
for(int i = 0; i < my_array_length; i++){
my_array[i] = -1;
}
/* Here is your own input program routine. I'll use some example values. */
for(int i = 0; i < my_array_length; i++){
if(i > 4){
break;
}
my_array[i] = i;
}
/* Here is your output program routine. */
for(int i = 0; i < my_array_length; i++){
if(my_array[i] == -1){
break;
}
std::cout << my_array[i] << std::endl;
}
return 0;
}
Or you could just count the amount of inputs in the first place.
I'm trying to check each value of two arrays that contain 5 values to see if there are any matches.
For example, a random array of {3,5,2,6,8} and a user generated array of {3,2,2,5,9}. In this case there would be two matches.
The Goal of this program is to check a random array and compare it to a user generated array and return the number of matches.
The Problem: I am able to generate a random array, but I am stuck on trying to check for any matched numbers and output that number in the main function
Here is my code so far:
#include <iostream>
#include <ctime> //for time() function
using namespace std;
void generateNumbers(int arrLotto[], int arrSize) {
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < arrSize; i++) {
int rnum = (rand() % (10));
arrLotto[i] = rnum;
cout << arrLotto[i] << " ";
}
}
int findMatches(const int arrLotto[], const int arrUser[], int arrSize)
{
int matchCount = 0;
for (int i = 0; i < arrSize; i++) {
if (arrLotto[i] == arrUser[i]) {
matchCount++;
}
return matchCount;
}
}
int main() {
int rnum;
int arrLotto[5];
int arrUser[5];
int arrSize = 5;
int matchCount = findMatches(arrLotto, arrUser, arrSize);
//prompt user for lotto numbers
cout << "Enter your 5 lottery number picks (0-9)\n" << endl;
for (int i = 0; i < 5; i++) {
cout << "Number " << i+1 << ": ";
cin >> arrUser[i];
}
//display Lotto numbers
cout << "\nLottery Numbers" << endl;
generateNumbers(arrLotto, arrSize);
//display array user numbers
cout << "\nYour Numbers" << endl;
for (int i = 0; i < 5; i++) {
cout << arrUser[i] << " ";
}
cout << endl;
//display matches
cout << "\nYou matched " << matchCount << " numbers" << endl;
if(matchCount == 5)
cout << "You are a grand winner" << endl;
return EXIT_SUCCESS;
}
A few issues with the code:
You are calling the findMatches function before populating the user inputted array and populating the random generated array.
So the matches (if any) will be random and unpredictable. Not to mention that your program has undefined behavior due to accessing uninitialized variables.
Call findMatches after you have populated the user inputted array and the random generated array.
The below statement:
int matchCount = findMatches(arrLotto, arrUser, arrSize);
should be after the second for loop in main.
You should also pass a reference to array instead of the array itself so that you will preserve the randomly generated numbers in the array after the funtion returns. So you have to change the prototype of generateNumbers function to this:
void generateNumbers(int (&arrLotto)[5], int arrSize)
And within the function, you have to return after the completion of the for loop and not after the first iteration. So move the return statement
return matchCount;
after the closing brace of the for loop.
Convert each of the input arrays into std::set (or sort them via std::sort). Then you can use set intersection algorithm. https://en.cppreference.com/w/cpp/algorithm/set_intersection
If the output is empty, there are no matches and the size of the output indicates number of matches.
You are calling findMatches() method before array is populate, so it always return 0 bcz when you call findMatches() method at that time both array are empty.
So the solution is first populate the user attay then call generateNumbers() to populate random array then call findMatches() then it will give you a perfect count.
I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}
Can you help me with a problem on populating an array of 5 circles with random numbers.
The random number would be the radius of the circles.
Here is my code:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Array 2, below section is to populate the array with random radius
float CircleArrayTwo [5]; // store the numbers
const int NUM = 5; // Display 5 random numbers
srand(time(NULL)); // seed the generator
for(int i = 0; i < NUM; ++i)
{
CircleArrayTwo[i] = rand()%10;
}
cout << "Below is the radius each of the five circles in the second array. " << endl;
cout << CircleArrayTwo << endl;
system("PAUSE");
return 0;
}
Currently is output the following:
Below is the radius each of the five circles in the second array.
002CF878
Where am I going wrong?
Any help is much appreciated
You are printing the address of the first element of the array.
You could loop over the array and print each element:
for(int i = 0; i < NUM; ++i)
{
std::cout << CircleArrayTwo[i] << ", ";
}
std::cout << "\n";
Or, if you have C++11 support,
for (auto& x : CircleArrayTwo) {
std::cout << x << ", ";
}
std::cout << "\n";
The way you populated the array is correct, however you cannot print an array like that. You need to write a loop to output the values one by one.
In C(and C++) arrays are almost equivalent to pointers to the beginning of memory location. So you're just outputting the adress of the first element;
To output all elements introduce another loop:
for(int i = 0; i < NUM; ++i)
{
cout << CircleArrayTwo[i] << endl;
}
CircleArrayTwo is a pointer. When you print a pointer, it prints a memory address, like the one you provided. In order to print the values of an array, you need to use the [] notation that you have for the insert.
You could loop over the values in the array and print each one:
for (int i = 0; i < NUM; ++i) { cout << CircleArrayTwo[i] << endl; }