Populating an array - c++

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; }

Related

How to check two arrays, a random generated and user inputed array in c++

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.

How To Print Values Stored in an Array

I am working to create a function where I take in 6 values (3 strings, 3 ints), store those values in arrays, then print out each of those values in pairs of 2
Here is what I have:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int SIZE = 3;
int time[SIZE] = {};
string name[SIZE] = {};
for (int a = 0; a < 3; a++)
{
cout << "Enter runner name: ";
getline (cin, name[+1]);
cout << "Enter runner time: ";
cin >> time[+1];
cin.ignore();
}
for (int a = 0; a < 3; a++)
{
cout << name << " finished in " << time << "\n";
}
return 0;
}
I would like my output to look like this:
name1 finished in time1
name2 finished in time2
name3 finished in time3
Currently, my output looks like this:
0x22fdf0 finished in 0x22fe10
0x22fdf0 finished in 0x22fe10
0x22fdf0 finished in 0x22fe10
How can I get the inputs to be stored in the arrays then output those values to the user?
If this has been answered already, apologies. I haven't been able to find an example where the arrays are populated with user input values and then returned to the display.
You need to actually index the array using the [] subscript operator. Likewise, when printing, you should attempt to index an element in the array. Since when you attempt to print the array itself, the compiler will implicitly convert the array to a pointer, which, when printed, will print the memory address of the first element in that array, rather than the element itself.
So you could dereference the arrays to get the first value in each, but a better way is to index it by the a variable in your for loop, like so:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int SIZE = 3;
int time[SIZE] = {};
string name[SIZE] = {};
for (int a = 0; a < 3; a++) {
cout << "Enter runner name: ";
getline(cin, name[a]);
cout << "Enter runner time: ";
cin >> time[a];
cin.ignore();
}
for (int a = 0; a < 3; a++) {
cout << name[a] << " finished in " << time[a] << "\n";
}
return 0;
}
Alternatively, if you wanted to not index it, you could use your original approach, but then you would have to dereference the pointer using the * dereference operator:
for (int a = 0; a < 3; a++) {
cout << *name << " finished in " << *time<< "\n";
}
However, now you would simply print the first element three times. So to remedy this, you need to employ some pointer arithmetic, and increase the value by a, to get the elements, 0, 1, and 2 past the first element respectively:
for (int a = 0; a < 3; a++) {
cout << *(name + a) << " finished in " << *(time + a)<< "\n";
}
So some things to look up:
* Dereferncing
* Subscripting
* Implicit array to pointer conversion

C++: How to output data into columns from an iteration loop

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).

Run Time Check Failure #2, AND array values swapped with outputs incorrectly

I've been struggling with this piece for a while now. I've googled run time check failure and I have no idea what to do. From what I get, it's because I declared swapEven and swapOdd to have an array of size 0? I initially had this set up as a pointer array, but that just didn't work. Can anybody point me in the right direction please? Thanks in advance!
void arrangeArrayJesseRagsdale(int* ary1, int* ary2, int arraySize1, int arraySize2) {
int i, j;
int temp;
int swap = 0;
int* swapEven = 0;
int* swapOdd = 0;
swapEven = new int[arraySize1];
swapOdd = new int[arraySize2];
cout << " Original Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
for (i = 0; i < arraySize1; i++) {
for (j = 0; j < arraySize2; j++) {
if (ary1[i] % 2 != 0) {
if (ary2[j] % 2 == 0) {
temp = swapOdd[i] = ary1[i];
ary1[i] = swapEven[i] = ary2[j];
ary2[j] = temp;
swap++;
}
}
}
}
cout << "\n Updated Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
if (swap > 0) {
cout << "\n Swapping info -\n";
for (i = 0; i < swap; i++) {
cout << " Array #1 value " << swapOdd[i] << " swapped with Array #2 value " << swapEven[i] << endl;
}
}
cout << "\nThere is/are " << swap << " swap(s)." << endl << endl;
delete[] swapEven;
delete[] swapOdd;
return;
}
First, your arrays here:
int swapEven[] = {0};
int swapOdd[] = {0};
Have 1 element each.
Second, your loops use arraySize1 and arrraySize2 to index into the arrays above. There is no check whatsoever in your code to ensure that the indexing into these arrays are within bounds. More than likely, this is where your error occurs, and that is accessing the array out-of-bounds.
If your goal is to create arrays with the same number of elements, use std::vector:
#include <vector>
//...
std::vector<int> swapEven(arraySize1, 0);
std::vector<int> swapOdd(arraySize2, 0);
The rest of the code stays the same.
swapEven and swapOdd do not have zero size, they are arrays containing the single integer element, 0. These arrays therefore have length 1.
However, from what I can tell from your code, you need to declare swapOdd to have at least as many elements as does ary1. Similarly, swapEven needs to have at least as many elements as does ary2. This is because you are storing values in those arrays using the indices of ary1 and ary2. Writing to unallocated memory may cause the crash that you see.
Also use of the indices of the 2 arrays will result in non-contiguous storage of the swapped values in swapOdd and swapEven. The affect of this is that the swap reporting code will use the wrong array elements when generating the report.
You might be better off using a dynamic "list" data structure for accumulating the swapped elements. C++ has a few alternatives there such as list and vector and these could be used instead of the swap arrays.
One other thing, rather than use pointer arithmetic to access the elements of arrays ary1 and ary2, it's more readable to use array indexing, i.e.
ary[i]
instead of
*(ary1 + i)

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.