Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}
Related
I have written a small program which compares two arrays with custom array size. Whenever I set the array size to 4, the program does not work correctly on comparing the fourth member of each array.
(when I set x to 4, the fourth array members does not get compared correctly)
This is the code:
#include <iostream>
using namespace std;
int main()
{
int x;
std::cin >> x;
int i =1;
int arr[x];
int arr2[x];
while(i <= x)
{
std::cout << "Enter row " << i << " of arr\n";
std::cin >> arr[i];
i++;
}
i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
}
You have an out of bound access, which yields undefined behavior. Recall that indices into raw arrays start with zero, not with one. Hence,
int i = 0;
is the correct initialization of the index, while the first loop must be changed to
while (i < x) { /* ... */ }
Then, the assignment of i needs again to be adjusted to
i = 0;
and the two remaining loops to
while (i < x) { /* ... */ }
for (int a = 0; a < x; a++) { /* ... */ }
As a side note, you are using variable length arrays (arr and arr2), which is non-standard C++ (see this thread for more info). Prefer std::vector for a simple container with runtime-dependant size.
i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
you are storing element in array starts with 1 index
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
But comparing by starting from 0 index.
keep consistency either start from 0 or 1
for(int a = 1;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
it will work..
I want to cout an array as a row vector but when I write:
int main() {
int B[3]={0};
for (int w = 0; w <2; w++) {
cout <<"B="<<" "<< B[w] << " ";
}
cout << endl;
return 0;
}
The output is B=0 B=0
But I want output to be like:
B=(0 0)
For a fixed size array of only I would probably even prefer a oneliner like this, because I can read it at first glance:
cout << "B=(" << B[0] << " " << B[1] << " " << B[2] << ")\n";
For a container B with a dynamic or very high number of elements n, you should probably do something like this:
cout << "B=(";
if(n > 0)
{
cout << B[0];
// note the iteration should start at 1, because we've already printed B[0]!
for(int i=1; i < n; i++)
cout << ", " << B[i]; //I've added a comma here, so you get output like B=(0, 1, 2)
}
cout << ")\n";
This has the advantage, that no matter what number of elements, you don't end up with trailing commas or unwanted whitespace.
I'd reccommend making a generic (template) function for the purpose of printing array/std::vector content anyways - it's really useful for debugging purposes!
int main() {
int B[3] = { 0 };
cout << "B=(";
for (int w = 0; w < 3; w++) {
cout << B[w];
if (w < 2) cout << " ";
}
cout << ")" << endl;
return 0;
}
Output should be now:
B=(0 0 0)
The simplest way to do this is:-
#include<iostream>
using namespace std;
int main()
{
int B[3]={0};
cout << "B=(";
for (int w = 0; w < 3; w++)
{
cout << B[w] << " ";
}
cout << ")" << endl;
return 0;
}
the output will be B= (0 0 0 )
You can try this one if you want:
#include <iostream>
using namespace std;
int main() {
int B[3]={0};
cout << "B=(";
for (int w = 0; w <2; w++) {
cout << B[w];
if(w != 1) cout << " ";
}
cout << ")" << endl;
cout << endl;
return 0;
}
The output is:
B=(0 0)
The line if(w != 1) checks whether you 've reached the last element of the array. In this case the last index is 1, but in general the if statement should be: if(w != n-1) where n is the size of the array.
I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.
I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}
I am Having Problem with Passing a 2D array to a c++ Function. The function is supposed to print the value of 2D array. But getting errors.
In function void showAttributeUsage(int)
Invalid types for int(int) for array subscript.
I know the problem is with the syntax in which I am passing the particular array to function but I don't know how to have this particular problem solved.
Code:
#include <iostream>
using namespace std;
void showAttributeUsage(int);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
int attVal[qN][aN];
cout << "\nEnter Attribute Usage Values" << endl;
for(int n = 0; n < qN; n++) { //for looping in queries
cout << "\n\n***************** COLUMN " << n + 1 << " *******************\n\n";
for(int i = 0; i < aN; i++) { //for looping in Attributes
LOOP1:
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if((attVal[n][i] > 1) || (attVal[n][i] < 0)) {
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
goto LOOP1; //if wrong input value
}
}
}
showAttributeUsage(attVal[qN][aN]);
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
getch();
return 0;
}
void showAttributeUsage(int att)
{
int n = 0, i = 0;
while(n != '\0') {
while(i != '\0') {
cout << att[n][i] << " ";
i++;
}
cout << endl;
n++;
}
}
I really suggest to use std::vector : live example
void showAttributeUsage(const std::vector<std::vector<int>>& att)
{
for (std::size_t n = 0; n != att.size(); ++n) {
for (std::size_t i = 0; i != att.size(); ++i) {
cout << att[n][i] << " ";
}
cout << endl;
}
}
And call it that way:
showAttributeUsage(attVal);
Looking at your code, I see no reason why you can't use std::vector.
First, your code uses a non-standard C++ extension, namely Variable Length Arrays (VLA). If your goal is to write standard C++ code, what you wrote is not valid standard C++.
Second, your initial attempt of passing an int is wrong, but if you were to use vector, your attempt at passing an int will look almost identical if you used vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
typedef std::vector<int> IntArray;
typedef std::vector<IntArray> IntArray2D;
using namespace std;
void showAttributeUsage(const IntArray2D&);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
IntArray2D attVal(qN, IntArray(aN));
//... Input left out ...
showAttributeUsage(attVal);
return 0;
}
void showAttributeUsage(const IntArray2D& att)
{
for_each(att.begin(), att.end(),
[](const IntArray& ia) {std::copy(ia.begin(), ia.end(), ostream_iterator<int>(cout, " ")); cout << endl;});
}
I left out the input part of the code. The vector uses [] just like a regular array, so no code has to be rewritten once you declare the vector. You can use the code given to you in the other answer by molbdnilo for inputing the data (without using the goto).
Second, just to throw it into the mix, the showAttributeUsage function uses the copy algorithm to output the information. The for_each goes throw each row of the vector, calling std::copy for the row of elements. If you are using a C++11 compliant compiler, the above should compile.
You should declare the function like this.
void array_function(int m, int n, float a[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0.0;
}
where you pass in the dimensions of array.
This question has already been answered here. You need to use pointers or templates. Other solutions exists too.
In short do something like this:
template <size_t rows, size_t cols>
void showAttributeUsage(int (&array)[rows][cols])
{
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
You're using a compiler extension that lets you declare arrays with a size determined at runtime.
There is no way to pass a 2D array with such dimensions to a function, since all but one dimension for an array as a function parameter must be known at compile time.
You can use fixed dimensions and use the values read as limits that you pass to the function:
const int max_queries = 100;
const int max_attributes = 100;
void showAttributeUsage(int array[max_queries][max_attributes], int queries, int attributes);
int main()
{
int attVal[max_queries][max_attributes];
int qN = 0;
int aN = 0;
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
cout << "\nEnter Attribute Usage Values" << endl;
for (int n = 0; n < qN; n++)
{
cout << "\n\n***************** COLUMN " << n + 1 <<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad_input = true;
while (bad_input)
{
bad_input = false; // Assume that input will be correct this time.
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad_input = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal, qN, aN);
getch();
return 0;
}
void showAttributeUsage(int att[max_queries][max_attributes], int queries, int attributes)
{
for (int i = 0; i < queries; i++)
{
for (int j = 0; j < attributes; j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
For comparison, the same program using std::vector, which is almost identical but with no size limitations:
void showAttributeUsage(vector<vector<int> > att);
int main()
{
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
vector<vector<int> > attVal(qN, vector<int>(aN));
cout << "\nEnter Attribute Usage Values"<<endl;
for (int n = 0; n < qN; n++)
{
cout<<"\n\n***************** COLUMN "<<n+1<<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad = true;
while (bad)
{
bad = false;
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal);
getch();
return 0;
}
void showAttributeUsage(vector<vector<int> > att);
{
for (int i = 0; i < att.size(); i++)
{
for (int j = 0; j < att[i].size(); j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
The Particular Logic worked for me. At last found it. :-)
int** create2dArray(int rows, int cols) {
int** array = new int*[rows];
for (int row=0; row<rows; row++) {
array[row] = new int[cols];
}
return array;
}
void delete2dArray(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
delete [] ar[row];
}
delete [] ar;
}
void loadDefault(int **ar, int rows, int cols) {
int a = 0;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
ar[row][col] = a++;
}
}
}
void print(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
cout << " | " << ar[row][col];
}
cout << " | " << endl;
}
}
int main () {
int rows = 0;
int cols = 0;
cout<<"ENTER NUMBER OF ROWS:\t";cin>>rows;
cout<<"\nENTER NUMBER OF COLUMNS:\t";cin>>cols;
cout<<"\n\n";
int** a = create2dArray(rows, cols);
loadDefault(a, rows, cols);
print(a, rows, cols);
delete2dArray(a, rows, cols);
getch();
return 0;
}
if its c++ then you can use a templete that would work with any number of dimensions
template<typename T>
void func(T& v)
{
// code here
}
int main()
{
int arr[][7] = {
{1,2,3,4,5,6,7},
{1,2,3,4,5,6,7}
};
func(arr);
char triplestring[][2][5] = {
{
"str1",
"str2"
},
{
"str3",
"str4"
}
};
func(triplestring);
return 0;
}