C++ function and array homework - c++

Create a function that prints the array to the screen as a table with the appropriate rows and columns. Use setw() to ensure the numbers have enough room. You may assume the numbers are no more than 3 digits each. Include the row and column labels.
In main, ask the user to supply a row and column and a value (no more than 3 digits), then put the value into the array at that row and column. Print the result and ask the user for another row, column and value. Repeat until the user is finished.
Once finished, compute and print the total of the values in the array.
#include <iostream>
#include <iomanip>
using namespace std;
const int ROWS= 4;
const int COLS = 3;
const int WIDTH = 4;
const char YES = 'y';
int total = 0;
void print(int arr[ROWS][COLS]);
int main()
{
int arr[ROWS][COLS];
char ans = YES;
int val;
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++)
arr[r][c] = 0;}
while (tolower(ans) == YES){
int row = -1;
int col = -1;
cout << "Row? ";
cin >> row;
cout << "Columns? ";
cin >> col;
while (row < 0 || row >=ROWS){
cout << "Only value under " << ROWS << " is accepted, try again: ";
cin >> row;
}
while (col < 0 || col >= COLS){
cout << "Only value under " << COLS << "is accepted, try again: ";
cin >> col;
}
cout << "Value? ";
cin >> val;
arr[row][col] = val;
print(arr);
cout << "Again (y/n)? ";
cin >> ans;
}
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++){
total += arr[r][c];
}
}
cout << "Sum of all values is " << total << endl;
// Print array with labels
// get input from user
// print array again - repeat until user wishes to quit
return 0;
}
void print (const int arr[ROWS][COLS])
{
cout << endl << endl;
for (int i = 0 ; i < COLS; i++)
cout << setw(WIDTH) << i;
cout << endl;
for (int r = 0; r < ROWS; r++)
cout << setw(WIDTH) << r << "|";
for (int r = 0; r < ROWS; r++)
for (int c = 0; c< COLS; c++)
cout << setw(WIDTH) << arr[r][c];
cout << endl << endl;
}
I dont know where I did wrong on this one but when I complie, I got the LD return 1 exit status error, Can you please help?

The definition and the declaration of your print function are different.

Change the declaration of your print() function.
void print(int arr[ROWS][COLS]);
to
void print(const int arr[ROWS][COLS]);

Related

I want to display all entries of 2D array in c++

I want to create a program that take size of rows and columns of 2D array from user, and then take all entries of array from user. And Finally display all the entries from array[0][0] to array[size][size].
My code is:
#include <iostream>
using namespace std;
int main()
{
int rows, columns;
int tom[rows][columns];
cout << "Size of array rows: ";
cin >> rows;
cout << "Size of array columns: ";
cin >> columns;
for(int count1 = 0; count1 < rows; count1++)
{
for(int count2 = 0; count2 < columns; count2++)
{
cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
cin >> tom[count1][count2];
}
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
cout << tom[i][j] << endl;
}
}
return 0;
}
Output is:
Size of array rows: 2
Size of array columns: 3
Enter entry of row 0 and column 0: 1
Enter entry of row 0 and column 1: 2
Enter entry of row 0 and column 2: 3
Enter entry of row 1 and column 0: 12
Enter entry of row 1 and column 1: 13
Enter entry of row 1 and column 2: 14
12
13
14
12
13
14
It should give output:
1
2
3
12
13
14
What is the problem?
Please help.
You can't dynamically create an array like this. This shouldn't even compile. And even if it did, you are creating the array before letting the user input the dimension. For the proper Approach use std::vector:
#include <iostream>
#include <vector>
int main()
{
int rows, columns;
std::cout << "Size of array rows: ";
std::cin >> rows;
std::cout << "Size of array columns: ";
std::cin >> columns;
std::vector<std::vector<int>> tom(rows, std::vector<int>(columns));
for (int count1 = 0; count1 < rows; count1++)
{
for (int count2 = 0; count2 < columns; count2++)
{
std::cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
std::cin >> tom[count1][count2];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
std::cout << tom[i][j] << std::endl;
}
}
return 0;
}
output:
Size of array rows: 2
Size of array columns: 3
Enter entry of row 0 and column 0: 1
Enter entry of row 0 and column 1: 2
Enter entry of row 0 and column 2: 3
Enter entry of row 1 and column 0: 12
Enter entry of row 1 and column 1: 13
Enter entry of row 1 and column 2: 14
1
2
3
12
13
14
please don't use using namespace std; - read here why.
You initialized tom before actually getting the number of rows/columns.
#include <iostream>
int main()
{
int rows, columns;
std::cout << "Rows: ";
std::cin >> rows;
std::cout << "Columns: ";
std::cin >> columns;
int arr[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
std::cout << "Enter the value for [" << i << "][" << j << "] : ";
std::cin >> arr[i][j];
}
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
You cannot declare an array like this:
int tom[rows][columns];
since values of rows and columns are not known yet.
Instead you should initialize this array dynamically after asking for values.
Here is your code fixed:
#include <iostream>
using namespace std;
int main()
{
int rows, columns;
int **tom;
cout << "Size of array rows: ";
cin >> rows;
cout << "Size of array columns: ";
cin >> columns;
tom = new int*[rows];
for (int i = 0; i < rows; i++) {
tom[i] = new int[columns];
}
for(int count1 = 0; count1 < rows; count1++)
{
for(int count2 = 0; count2 < columns; count2++)
{
cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
cin >> tom[count1][count2];
}
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
cout << tom[i][j] << endl;
}
}
return 0;
}

Equivalence Relation

I am stuck on what to do next... The program is suppose to check to see if entered Zero-One Matrix is an Equivalence relation (transitive, symmetric, and reflexive) or not. I am still new to C++ (started this semester). I know how to create the matrix using vector but not on how to check if it is equivalence relation or not..
I assume I need to use boolean function but I'm stuck on what I need to put in as an argument or if this is correct. My original thought was... so for symmetric it will look like (which I know this goes after #include and beofre int main(). Any help would be awesome.
bool isSymmetric(vector<int> &vect, int Value)
{
for (int i = 0; i < Value; i++)
for (int j = 0; j < Value; j++)
if (vect[i][j] != vect[j][i])
return false;
return true;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > vec;
cout << "NxN matrix N: ";
int Value;
cin >> Value;
cout << Value << "x" << Value << " matrix\n";
for (int i = 0; i < Value; i++) {
vector<int> row;
for (int j = 0; j < Value; j++) {
cout << "Enter a number (0 or 1): ";
int User_num;
cin >> User_num;
while (User_num != 0 && User_num != 1) {
cout << "Invalid Entry! Enter 0 or 1!\n";
cout << "Enter a number (0 or 1): ";
cin >> User_num;
}
row.push_back(User_num);
}
vec.push_back(row);
}
cout << endl;
for (int i = 0; i < Value; i++) {
for (int j = 0; j < Value; j++) {
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}

Using for loops to enter data into arrays

So I have this C++ program that contains .h file and main.cpp. In .h I have this class:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
In main.cpp, I am trying to enter the data using for loop, and I manage to store data for int i = 0 state, but when i is increased, no data that has been entered is being stored into array. For the inside loop, I tried to put j < n, j < n-1 and j < n+1, but it's not working. How can I store all the data and print it out?
#include <iostream>
#include "Plaza.h"
using namespace std;
int main() {
int n;
Plaza *obj1;
cout << "Enter limit number (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
for (int i = 0; i < n; i++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " Length=" << obj1[i].length;
}
delete[] obj1;
system("pause");
return 0;
}
This is the print I get:
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Here's your culprit. Get rid of the inner for-loop (not the cin-statements, just the for... line and its closing bracket) and replace obj[j] with obj[i]. You are currently repeatedly writing to obj[0].
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Why there is a need of second for loop., if you check the j value, it is always 0 so only one value is inserted.,
try this
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
}

Passing 2D array to a Function in c++

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

How can I let users to input values into the sudoku board?

I'm having trouble generating and inserting numbers inside the Board. Here is what I have so far:
enter code here
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
bool Valid_Set(int line[])
{
bool found = true;
for (int t = 1; (t <= 9 && found); ++t)
{
found = false;
for (int i = 0; i < 9; ++i)
if (line[i] == t) found = true;
}
return found; // returns true if all value 1-9 are in array.
}
bool Valid_Matrix(int sud[9][9])
{
int i, j, check[9];
bool valid = true;
// check each row
for (j = 0; (j < 9) && valid; ++j)
{
for (i = 0; i < 9; ++i)
check[i] = sud[i][j];
valid = Valid_Set(check);
}
// check each column
for (j = 0; (j < 9) && valid; ++j)
{
for (i = 0; i < 9; ++i)
check[i] = sud[j][i];
valid = Valid_Set(check);
}
// check 3x3 area
for (i = 0; (i < 9) && valid; i += 3)
{
for (j = 0; (j < 9) && valid; j += 3)
{
int t = 0;
for (int x = 0; x < 3; ++x)
for (int y = 0; y < 3; ++y)
check[t++] = sud[x + i][y + j];
valid = Valid_Set(check);
}
}
return valid;
}
void numGenerator(int A[]){
for (int i=0; i<9; i++){
A[i]=(1+rand()%9);
}
}
bool check_for_validity(int A[]){
int counter=0;
while (counter!=9){
numGenerator(A);
counter++;
}
for (int i=0; i<9; i++)
for (int j=0; j<9; j++){
if(A[j]==A[i])
numGenerator(A);
}
return true;
}
void main (){
//Descriptions and genral ideas
cout << "WELCOME TO SUDOKU " << endl;
cout << endl;
cout << "RULES: "<< endl;
cout << endl;
cout << "->You'll be given a 9x9 board with some numbers depending on which level of difficulty you choose to play."<< endl;
cout << endl;
cout << "->You have to arrange numbers from 1 to 9 so that a number shows up once in one row, one column and in a 3x3 box." << endl;
cout << endl;
cout << "So, let's get started" << endl;
cout << endl;
cout <<endl;
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]='_';
}
}
char row[9];
char column[9];
int num[81];
int num2[9][9];
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified.
for (int i=0; i<length; i++) {
dash[row[i]][column[i]]=num[i]+'0';
}
//Builds the Sudoko board and outputs the full 9x9 array.
cout << " 0 1 2 3 4 5 6 7 8 " << endl;
cout << "-----------------------------------------" << endl;
int i=0;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "||_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "||" << i << endl;
i++;
}
cout << "-----------------------------------------" << endl;
int j=3;
for (int count=3; count<6; count++) {
for (int count2=0; count2<3; count2++) {
cout << "||_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "||" << j << endl;
j++;
}
cout <<"-----------------------------------------" << endl;
int z=6;
for (int count=6; count<9; count++) {
for (int count2=0; count2<3; count2++) {
cout << "||_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "||" << z << endl;
z++;
}
cout << "-----------------------------------------" << endl;
for (int row = 0; row < 9; row++) {
cout << "Enter values for row " << row + 1 << " : ";
for (int col = 0; col < 9; col++)
cin >> dash[row][col];
cout << endl << endl;
}
system("pause");
}
This whole section is wrong
char row[9];
char column[9];
int num[81];
int num2[9][9];
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified.
for (int i=0; i<length; i++) {
dash[row[i]][column[i]]=num[i]+'0';
}
You are using row and column even though they haven't got any values. Most likely this will crash your program.
Hard to know what you expected this to do. Perhaps you could explain?
Here's a suggestion for inputing values. Maybe you'll find it useful
// get the user's values
int row, column, value;
cout << "Enter a row number, column number, and value. All numbers should be between 1 and 9\n";
cin >> row >> column >> value;
// put the value in the board, add '0' to convert the integer to a digit
dash[row][column] = value + '0';