function that reads a 2d array in c++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to write a function that reads a 2D array of integers where the user is the one who enters the size of the array (it shouldn't be defined before ) . I tried this but it's not working.
I appreciate your help!
line 6 is the declaration of the function
this is my code:
#include <iostream>
using namespace std;
void Fill_table(int mat[][], int s) {
for (int i = 0; i<s; i++) {
for (int j = 0; j<s; j++) {
cout << "mat[" << i << "][" << j << "]:" << endl;
cin >> mat[i][j];
}
}
}
int main()
{
int n;
cout << "Enter the size: ";
cin >> n;
int a[n][n];
Fill_table(a, n);
return 0;
}

Just to give you a simple alternative. Instead of declaring a 2D array with [][], you could use [n*n] and then subscript with i*s + j. The code would be
#include <iostream>
using namespace std;
void Fill_table(int* mat, int s) {
for (int i = 0; i<s; i++) {
for (int j = 0; j<s; j++) {
cout << "mat[" << i << "][" << j << "]:" << endl;
cin >> mat[i*s+j];
}
}
}
int main()
{
int n;
cout << "Enter the size: ";
cin >> n;
int a[n * n];
Fill_table(a, n);
return 0;
}
1D arrays can be passed as a pointer to a function. You also need to pass the size (as you did). For 2D arrays, you need to know the size at compile time.

You cannot set the size of a multidimensional array at runtime.
The error
error: declaration of ‘mat’ as multidimensional array must have bounds for all dimensions except the first
void Fill_table(int mat[][], int s)
tells you exactly that.
Consider using C++ data structure instead, in this case vector<vector<int>>, you have a somewhat simple how-to guide in Creating a Matrix using 2D vector in C++ – Vector of Vectors.

Related

Reversing a vector using functions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to reverse a vector using functions but whenever I run the program it terminates and outputs nothing. Can anyone please tell me what I am doing wrong?
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i) {
vect.push_back(input);
}
reverseavector(vect);
return 0;
}
In your code, you declared the following statement:
vector<int> vect;
This statement means that a vector of integers named vect get created, but you didn't specify a size for it, therefore when the following loop is reached:
for (int i = 0; i < vect.size(); ++i){
vect.push_back(input);
}
vect.size() return 0 because you didn't specify a size for vect, therefore the loop never gets executed. Because the condition is false.
I made some changes to the code you have. Take a look:
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
bool stop = false; // This bool will keep allow the while loop to keep prompting the user to enter a number until the input is -1
while (stop == false)
{
cout << "Enter a value to the vector to be reversed, or -1 to stop entering values" << endl;
cin >> input;
vect.push_back(input);
if (input == -1)
{
stop = true;
}
}
reverseavector(vect);
return 0;
}
The main thing about your code is that you needed a way to loop taking values into input. There are other ways to do this, but this was the first one I came up with.
When you run
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i)
vect.size() remains at 0, because the vector is empty. So, i < vect.size() remains false, and the loop doesn't enter.
So, reverseavector gets an empty vector and outputs nothing.

C++ assignment to copy parts of One-dimensional array to multidimensional array

this is my first time posting on here, and I may not be doing this the right way, sorry in advance.
I am having trouble understanding how to copy two separate one dimensional arrays into one multidimensional array. It is part of my assignment, but I already turned it in and am probably going to lose points in it, but it's ok. As long as I get to understand how it's done, I'd still be happy.
The specific part I am having trouble with is section 5, I got everything else down, maybe it's because its been a long day, but I just can't seem to get it. I will post the whole assignment as well as my code. Thank you for taking the time to read all this if you did.
Write a C++ program that tests the function main and the functions discussed in parts 1 through 7. (Add additional functions, such as printing a two-dimensional array, as needed.).
Consider the following function main:
<code>int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4] = {11, 13, 15, 17};
int delta[10] = {3, 5, 2, 6, 10, 9, 7, 11, 1, 8};
.
.
.
}</code>
Write the definition of the function setZero that initializes any one-dimensional array of type int to 0 (alpha and beta).
Write the definition of the function inputArray that prompts the user to input 20 numbers and stores the numbers into alpha.
Write the definition of the function doubleArray that initializes the elements of beta to two times the corresponding elements in alpha. Make sure that you prevent the function from modifying the elements of alpha.
Write the definition of the function copyGamma that sets the elements of the first row of inStock from gamma and the remaining rows of inStock to three times the previous row of inStock. Make sure that
you prevent the function from modifying the elements of gamma.
5. Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
Write the definition of the function printArray that prints any one-dimensional array of type int.
Write the definition of the function setInStock that prompts the user to input the elements for the first column of inStock. The function should then set the elements in the remaining columns to two times the
corresponding element in the previous column, minus the corresponding element in delta.
Here is my code:
<code>
#include <iostream>
using namespace std;
int setZero(int alpha[], int beta[]);
int inputArray(int alpha[]);
int doubleArray(const int alpha[], int beta[]);
int copyGamma(const int gamma[], int inStock[][4]);
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize);
void printArray(int print[], int n);
int setInStock(int inStock[][4],const int delta[]);
int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4]={11,13,15,17};
int delta[10]={3,5,2,6,10,9,7,11,1,8};
setZero(alpha, beta);
cout << "Alpha after initialization" << endl;
printArray(alpha, 20);
inputArray(alpha);
cout << "Alpha after reading 20 numbers" << endl;
printArray(alpha, 20);
doubleArray(alpha, beta);
cout << "Beta after a call to doubleArray" << endl;
printArray(beta, 20);
copyGamma(gamma, inStock);
copyAlphaBeta(inStock, 10, alpha, beta, 20);
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << '\t';
}
cout << endl;
setInStock(inStock, delta);
return 0;
}
int setZero(int alpha[], int beta[])
{
for (int i=0; i<20; i++)
{
alpha[i]=0;
beta[i]=0;
}
cout << endl;
}
int inputArray(int alpha[])
{
cout << endl;
cout << "Enter 20 integers" << endl;
for (int i=0; i<20; i++)
{
cin >> alpha[i];
}
cout << endl;
return 0;
}
int doubleArray(const int alpha[], int beta[])
{
cout << endl;
for (int i=0; i<20; i++)
{
beta[i]=alpha[i]*2;
}
cout << endl;
return 0;
}
int copyGamma(const int gamma[], int inStock[][4])
{
cout << endl;
cout << "inStock after a call to copyGamma" << endl;
for (int row=0;row<10;row++)
for (int column=0;column<4;column++)
{
if (row==0)
inStock[row][column]=gamma[column];
else
inStock[row][column]=3*inStock[row-1][column];
}
cout << endl;
for (int r=0;r<10;r++)
for (int c=0; c<4;c++)
{
if (c==0)
cout << endl;
cout << inStock[r][c] << '\t';
}
cout << endl;
return 0;
}
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}
void printArray(int print[], int n)
{
cout << endl;
for (int i=0;i<n;i++)
cout << print[i] << " ";
cout << endl;
}
int setInStock(int inStock[10][4],const int delta[])
{
int input;
cout << endl;
cout << "Enter 10 integers" << endl;
for (int r=0;r<10;r++)
for (int c=0;c<4;c++)
{
if(c==0)
{
cin >> inStock[r][c];
}
else
inStock[r][c] = 2 * inStock[r][c-1] - delta[r];
}
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << " ";
}
}
TL;DR - Need help understanding past homework, I just want to know the proper way to do it. Also please critique, looking for ways to improve. Thank you!
Edit:
The problem I have is with this part:
Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
and my code relating to this portion of the question is:
<code>
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}</code>
Thank you for the links, I am not allowed to use vectors at the moment, but I am definitely going to study up on them.
First of all, if you're allowed to use std::vector you should use it. Read up on std::vector here for more details.
Vector provides a dynamically allocated (in the back) chunk of memory that can "expand" and change at runtime depending on adding/deleting elements. You might want to learn to use a vector as they are very useful.
However, you don't really need a vector to do your copying. You can use std::copy to do this for you. More info for it here: std::copy
You can use it to take 3 inputs for your case. First two are the beginning and end pointers, the last input is the starting pointer for the destination. You should be able to figure out what they are for your project.
In your nested for-loops, the last loop is wrong and it will repeatedly put different values of alpha[count] and beta[count] into a same inStock[r][c] element.
You can remove this loop and change the code like
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
if(r<5)
{
inStock[r][c]=alpha[c]; // assuming size of alpha is 4
}
else if (r>=5)
{
inStock[r][c]=beta[c]; //assuming size of beta is 4
}
}
}
In this code, you have assumed inStock has 4 columns, these 4 columns of each row, are going to be filled with 4 elements of alpha and beta arrays.

Read the grade of students by Array C++ [duplicate]

This question already has answers here:
Why no variable size array in stack?
(7 answers)
Closed 8 years ago.
This simple program to read the grade of students. I want to take how many students the user want to enter, but when I'm writing int g[size];it will be compilation error! I wonder how can I write it correct?
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter how many student ..? ";
cin >> x;
const int size = x;
int g[size];
cout << "enter " << size << "your ";
for (int i = 0; i < size; i++){
cin >> g[i];
}
for (int i = 0; i < size; i++){
cout << "student" << i + 1 << "grade is : " << g[i] << endl;
}
system("pause");
return 0 ;
}
The line int g[size]; causes a compile error because size is not known at compile time (but obviously at runtime).
So you need to allocate memory for the array at runtime.
int *g = new int[size]; // instead of int g[size];
This stores a pointer to the first element of the array in g. Now the compiler can no longer track the lifetime of the array and delete it for you when it isn't needed anymore so you need to do this yourself as well.
delete[] g; // this frees the memory again
system("pause");
As a side note: Your program is valid C++14 which is not yet (fully) supported by Microsoft's Visual C++ compiler but other compilers like clang and g++ already support it.

How can I limit my Array to only a size of however many values are entered, when the maximum number possible to enter is 1000?

#include <iostream>
using namespace std;
void displayListValues(int Array[], int Max)
{
int counter = 0;
for (int i = 0; i < Max; i++)
{
cout << counter << " = " << Array[i] << endl;
counter++;
}
}
void main()
{
const int Max = 1000;
int Array[Max]; // this is where I couldn't figure out what to change so the array isn't so huge
int counter = 0;
cout << "Enter Numbers. If finished, enter a negative number to continue" << endl;
do
{
cin >> Array[counter];
if (Array[counter] < 0)
break;
} while (counter < Max);
displayListValues(Array, Max);
}
details details details, any assistance would be fantastic!!! Thanks guys!!!! :D :D :D
I don't know what else to include in here because it keeps saying my post is mostly code. I apologize for this nonsensical gibberish at the bottom of the post.
Short answer is you can't. C/C++ arrays are a fixed size once defined.
The long answer is you need to use something other than an array. You should use a std::vector, this behaves similar to an array but can be resized.

I am getting C++ syntax error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This script is supposed to read chars from keyboard, store them into arrays, and then output them:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void storeArraysintoStruct(char[], int);
int main()
{
char test[] ="";
int a = 0;
storeArraysintoStruct(test, a);
system("pause");
return 0;
}
void storeArraysintoStruct(char test[], int a)
{
int n;
cout << "Enter number of entries: " << endl;
cin >> n;
int i = 0;
for (i=0, i<n, i++)
{
cout << "Enter your character: " << endl;
cin.getline(test, n);
}
while (i < n)
{
cout << test[i] << endl;
i++;
}
}
Edit: fixed it:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void storeArraysintoStruct(char[], int);
int main()
{
char test[40] = "";
int a = 0;
storeArraysintoStruct(test, a);
system("pause");
return 0;
}
void storeArraysintoStruct(char test[], int a)
{
int n;
cout << "Enter number of entries: " << endl;
cin >> n;
int i;
for (i=0; i < n; i++)
{
cout << "Enter your character: " << endl;
cin >> test[i];
if (test[n-1])
{
cout << endl;
}
}
i =0;
while (i < n)
{
cout << test[i] << endl;
i++;
if(test[n-1])
{
cout << endl;
}
}
}
However, I am getting the errors Expected: primary expression before ")" and ";" before while. Any help will be greatly appreciated.
Edit: The script doesn't work as expected, for it doesn't output the stored characters. Any advice would be greatly appreciated.
The syntax error has already been pointed out in the comments. Also, as it has been mentioned, you never reset i after for loop, which prevents your while loop from running.
However, you have to also take in mind that this
char test[] = "";
allocates array test of only 1 character long. You cannot put more than one character of data into that array. In other words, your storeArraysintoStruct is sure to overrun the array and fall into undefined behavior territory.
In you want to preallocate a larger buffer for future use in storeArraysintoStruct, you have to specify the size explicitly. For example
char test[1000] = "";
will make test an array of 1000 characters. Of course, regardless of how large the array is, it is your responsibility to observe the size limit.
P.S. What is the point of that parameter a, if you never use it inside storeArraysintoStruct?