How to make an array in a function in C++? - c++

What I'm trying to output is the dealer's roll (the numbers are supposed to be stored in an array) but I keep getting an error that int is an invalid type in DealerRoll(dealerRoll[3]);
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
int DealerRoll(int dealerRoll[3]) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
return dealerRoll[3];
}
int main() {
int dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll[3]);
system ("pause");
return 0;
}

Although you can make an array in a function, std::vector provides better flexibility, and deals with resource management for you.
If array size is fixed, you can use std::array<int,3> instead:
void DealerRoll(std::array<int,3>& dealerRoll) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
...
int main() {
std::array<int,3> dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll);
...
}

Change the line int dealerRoll; as int dealerRoll[3];
Reason: You need to pass the array to function but you are declaring the integer variable.
Change the line DealerRoll(dealerRoll[3]); as DealerRoll(dealerRoll);
Reason: Function takes array as input but you have passed the 3rd position of array(Which will decompose to integer) instead of array.

#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
void DealerRoll(int* dealerRoll) //retrieving array in pointer
{
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
int main()
{
int dealerRoll[3]; //syntax for creating array
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll); //passing address of array in function
//As Values are passed by address, values retained in array
cout<<"\nValues in Dealer's Roll : "<<endl;
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
cout << dealerRoll[dealerCount] << " ";
}
system ("pause");
return 0;
}

Related

Swapping two initialized arrays in C++ using Void and Pointers

I need to write a C++ program where it swaps between two 1-dimensional
arrays using pointers and functions. Firstly, a void function named showValues to display both arrays before swapping takes and also a void function named swap to swap the elements between both arrays.
My question is: I'm supposed to swap the function but for some reason it wont run and I am not sure where is the error in my code
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 5;
void showValues(int[],int[]);
void swap(int[],int[]);
int main() {
int array1[SIZE] = {10,20,30,40,50};
int array2[SIZE] = {60,70,80,90,100};
showValues (array1, array2);
swap(array1, array2);
return 0;
}
void showValues(int array1[], int array2[]){
cout<<"The original arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
void swap(int array1[], int array2[])
{
int temp,i;
for(i=0; i<5; ++i)
{
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
}
cout << "\nThe swapped arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
This part of your code doesn't make sense:
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
SIZE is 5. So, you are accessing array1[5] and array2[5], i.e. the 6th element of the array. Yet, your arrays have only 5 elements to begin with (array1[0] to array1[4], same for array2), so you are accessing elements beyond the end of the array, which is undefined behavior that is probably just corrupting memory somewhere!
You probably meant to use i here, not SIZE, then the code makes sense. Instead, it would be useful to replace the "magic number" 5 with SIZE:
for(i = 0; i < SIZE; ++i)
{
temp = array1[i];
array1[i] = array2[i];
array2[i] = temp;
}
The void swap(int array1[], int array2[]) function is where you are having trouble. You actually don't even need to have another function for the swapping. You could just use std::swap() which is defined in the #include <utility> header. Since both arrays have the same size.
For example you could do something along these lines:
#include <iostream>
#include <iomanip>
#include <utility>
const int SIZE = 5;
void showValues(int[], int[]);
void swap(int[], int[]);
int main() {
int array1[SIZE] = { 10,20,30,40,50 };
int array2[SIZE] = { 60,70,80,90,100 };
int n = sizeof(array1) / sizeof(array2[0]);
showValues(array1, array2);
std::swap(array1, array2);
std::cout << "\n\nThe swapped arrays are as shown below:\n ";
std::cout << "\nArray 1 is: ";
for (int i = 0; i < n; i++)
std::cout << array1[i] << ", ";
std::cout << "\nArray 2 is: ";
for (int i = 0; i < n; i++)
std::cout << array2[i] << ", ";
return 0;
}
void showValues(int array1[], int array2[]) {
std::cout << "The original arrays are as shown below: " << std::endl;
std::cout << "\nArray 1 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array1[i] << " ";
}
std::cout << "\nArray 2 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array2[i] << " ";
}
}
Also consider not using using namespace std;.

Vector subscript out of range Visual Studio C++

I'm working with matrices in C++. The task is to find odd numbers in a matrix. I created a function, but when executed with Debug > Start Without Debugging... I get the error:
Debug assertion failed. Expression: vector subscript out of range.
This is my code:
File MatrixVec.h:
#include "MatrixVec.h"
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
MatrixVec::MatrixVec(int rows, int cols, int range)
{
row.assign(cols, 0);
mat.assign(rows, row);
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++){
mat[i][j] = rand() % range;
}
}
}
void MatrixVec::process()
{
int *oddNum = new int(mat[0].size());
for (int i = 0; i < mat[0].size(); i++) {
oddNum[i] = 0;
}
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
oddNum[j] += mat[i][j] % 2;
}
}
for (int i = 0; i < mat[0].size(); i++) {
cout << i + 1 << ". kolona " << oddNum[i]<< " neparnih elemenata." << endl;
}
//Edit
delete[] oddNum; //forgot this line
}
File MatrixVec.h:
#include "Matrix.h"
#include <vector>
class MatrixVec : public Matrix {
public:
MatrixVec(int rows, int cols, int range);
void print();
void process();
private:
std::vector<int> row;
std::vector<std::vector<int> > mat;
};
File Matrix.h:
class Matrix {
public:
virtual void print() = 0;
virtual void process() = 0;
};
File main.cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include "Matrix1D.h"
#include "Matrix2D.h"
#include "MatrixVec.h"
using namespace std;
#define NUMBER_RANGE 10
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "Niste uneli potrebne argumente za pokretanje programa!" << endl;
cout << "Argumenti komandne linije treba da budu:" << endl;
cout << "1. N dimenzija matrice" << endl;
cout << "2. M dimenzija matrice" << endl;
exit(-1);
}
// inicijalizacija generatora nasumičnih brojeva
srand(unsigned int(time(NULL)));
int rowNum = atoi(argv[1]);
int colNum = atoi(argv[2]);
// a)
cout << endl << endl << "a) Matrix 1D representation" << endl;
Matrix1D mat1(rowNum, colNum, 10);
mat1.print();
mat1.process();
//b)
cout << endl << endl << "b) Matrix 2D representation" << endl;
Matrix2D mat2(rowNum, colNum, 10);
mat2.print();
mat2.process();
//c)
cout << endl << endl << "c) Matrix vector of vector representation" << endl;
MatrixVec mat3(rowNum, colNum, 10);
mat3.print();
mat3.process();
return 0;
}
This line int *oddNum = new int(mat[0].size()); actually creating one int with value of mat[0].size(). You want something like this to create an array of size mat[0].size().
int *oddNum = new int[mat[0].size()];
Note: This still not answer the exact error. Seems like your mat vector is empty.

C++ rand() not working with string array

I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}

C++ How can I shuffle a vector without using the shuffle functions from the standard library?

For some odd reason, I have an assignment to shuffle the contents of a vector without using the shuffle or random_shuffle functions that are available in the C++ standard library. The following is some basic code with a (non-functioning) function to do the job to give you a clearer idea of what I'm getting at:
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
The way I thought to do it is to:
"push_back" the vector to create a temporary spot
randomly assign an index into the temporary spot
randomly assign an index into the newly-empty spot
put the index in the temporary spot into the last remaining empty index
"pop_back" the vector to its original size
(like with switching indexes in arrays)
I don't know how exactly to execute this but also--more importantly--if this would even work or if it's the best way to go about it. How would you do it?
Bam! This was actually pretty fun to figure out!
I used rand and a "for" loop that iterated 100 times to randomize it. I also added a "temporary" index that was deleted after the shuffling was complete.
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
for (int i = 0; i < 100; i++)
{
int randomIndex = rand() % names.size();
int randomIndex2 = rand() % names.size();
if (randomIndex2 == randomIndex) // make sure the two random values aren't the same
{
do {
randomIndex2 = rand() % names.size();
} while (randomIndex2 == randomIndex);
}
names.push_back("temporary"); // create temporary index at the end of the vector
int last_index_number = (names.size() - 1);
names[last_index_number] = names[randomIndex];
names[randomIndex] = names[randomIndex2];
names[randomIndex2] = names[last_index_number];
names.pop_back(); // bring vector back to original size
}
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}

C++ Random number game from set, rand is choosing a number not from the set

For some reason "0" is being outputted even though I didn't assign it to the set of numbers in the array. How can I get rid of the zero?
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
int n;
int size=10;
int setNums[10];
int main()
{
string ans = "";
do {
for (int n=0; n<size;n++ )
{
setNums[size] = n+1;\
cout << setNums[size] << endl;
}
srand (time(NULL));
int choice = rand() % setNums[size];
cout << choice << endl;
cout << "Keep guessing?" << endl;
cin >> ans;
} while (ans == "Y");
cout << "\n\n...Press ENTER to Exit System...";
cin.get();
return 0;
What you want is to find the index, not the value itself. Change this:
int choice = rand() % setNums[size];
to this:
int choice = setNums[rand() % size];
Also, the assignment is always being performed upon the index size. You should have:
...
for (int n=0; n<size;n++ ) {
setNums[n] = n+1;\
cout << setNums[n] << endl;
}
You're misusing setNums, and you don't need it at all. Just do this:
int choice = rand() % size + 1;