Multi Dimension Arrays issue - c++

OK so basically i want this code to get the user to input a value each time into the array and they get to specify the amount of rows and columns. I think i that the problem is that each time the user enters the value it goes into the correct column but also into both rows so by the end it only prints out the last lot of numbers the user had entered in all of the rows.
Sorry if that was hard to understand as this is my first post to this site and as you can probably tell i am only learning c++. So if you could help it would be greatly appreciated.
#include <iostream>
using namespace std;
int main()
{
int row;
int column;
int value[row][column];
cout << "How Many Rows?\n";
cin >> row;
cout << "How Many Columns\n";
cin >> column;
for(int x = 0; x<row; x++) {
for(int y = 0; y<column; y++) {
cout << "Enter Value Now\n";
cin >> value[x][y];
}
cout << endl;
}
cout << endl;
for(int a = 0; a < row; a++) {
for(int b = 0; b < column; b++) {
cout << value[a][b] << " ";
}
cout << endl;
}
}

int value[row][column];
declares an array whose dimensions are based on 2 uninitialised values.
If you don't have to use a C-style array, you could use
std::vector<std::vector<int>> value;
and choose its dimensions based on user input.
Alternatively, you could continue to use a C-style array if you allocate it like
int** value;
// input row/column
value = new int*[row];
for (int i=0; i<row; i++) {
value[i] = new int[column];
}
If you use the latter approach, make sure to also delete all dynamically allocated memory later.

Related

Creating matrix using array

I made an array matrix and used for loops, the problem is that it only displays my last input. Please refer to the sample result below.
#include<iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
int a[x][y], i, j;
cout<<"Enter number of Columns: ";
cin>>y;
cout<<"Enter number of Rows: ";
cin>>x;
cout<<endl;
for(i=0; i<x; i++)
{
cout<<endl;
cout<<"Enter values or row/s: ";
cout<<endl;
for(j=0; j<y; j++)
{
cout<<endl;
cout<<"Row "<< i+1 << ": ";
cin >> a[i][j];
}
}
cout<<endl;
cout<<"Entered Matrix is: ";
cout<<endl;
for(i=0; i<x; i++)
{
for(j=0; j<y; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
SAMPLE RESULT:
Enter number of Columns: 3
Enter number of Rows: 2
Enter values or row/s:
Row 1: -1
Row 1: -2
Row 1: -3
Enter values or row/s:
Row 2: 4
Row 2: 5
Row 2: -6
Entered Matrix is:
4 5 -6
4 5 -6
Just change declaration of array like this:
int[x][y] to int[10][10]
The problem here is that you want to use arrays with a variable size. So, input "x" and "y" and then use this as the array size. (array[x][y])
This does not work in C++. There are no dynamic, so called VLAs (Variable Length Arrays) in C++.
There are some dialects or compiler extensions, which can handle VLA, but C++ does not allow VLAs.
This means, you cannot write somthing like:
int arraySize{};
std::cin >> arraySize;
int array[arraySize];
This is invalid C++ code.
C-Style arrays must have a compile time constant value. You can define it with const or constexpr or even a number literal like 42. Magic constants liek 42 or the worst solution. Anyway, you could write
constepxr int arraySize = 42;
int array[arraySize];
This is syntactically correct.
But, it will not help you. Because you need something "dynamic". The idiomatic correct approach in C++ is to use a std::vector. Please read here about that. And using a 2d std::vector the C++ solution would look like that:
#include <iostream>
#include <vector>
int main() {
// Get user input. Size of matrix. Number of rows and columns
std::cout << "\nEnter number of Rows: ";
if (size_t numberOfRows{}; (std::cin >> numberOfRows) and (numberOfRows > 0)) {
std::cout << "\nEnter number of columns: ";
if (size_t numberOfColumns{}; (std::cin >> numberOfColumns) and (numberOfColumns > 0)) {
// Define 2d matrix and initialze all values to 0
std::vector<std::vector<int>> matrix(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Read all values of matrix
std::cout << "\n\Please enter matrix values in row-column order:\n";
for (std::vector<int>& row : matrix)
for (int& column : row)
std::cin >> column;
// Now show matrix
std::cout << "\n\nThe entered Matrix is:\n\n";
for (std::vector<int>& row : matrix) {
for (int& column : row) std::cout << column << ' ';
std::cout << '\n';
}
}
}
}
But, next, we often hear the statement that you did not learn about std::vector yet. And then, you need to use the approach to use old style memory allocation using new and delete. This is a non-recommend approach, but for teaching purposes, it is still often used.
So, you first allocate memory that will hold pointers to array (for the rows) and then allocate memory for the columns in the rows.
This would then look like the below:
#include <iostream>
int main() {
// Get user input. Size of matrix. Number of rows and columns
std::cout << "\nEnter number of Rows: ";
if (size_t numberOfRows{}; (std::cin >> numberOfRows) and (numberOfRows > 0)) {
std::cout << "\nEnter number of columns: ";
if (size_t numberOfColumns{}; (std::cin >> numberOfColumns) and (numberOfColumns > 0)) {
// Define 2d matrix
int** matrix;
matrix = new int* [numberOfRows];
for (int row = 0; row < numberOfRows; ++row)
matrix[row] = new int[numberOfColumns];
// Read all values of matrix
std::cout << "\n\Please enter matrix values in row-column order:\n";
for (int row = 0; row < numberOfRows; ++row)
for (int column=0; column < numberOfColumns; ++column)
std::cin >> matrix[row][column];
// Now show matrix
std::cout << "\n\nThe entered Matrix is:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int column = 0; column < numberOfColumns; ++column) std::cout << matrix[row][column] << ' ';
std::cout << '\n';
}
// Release memory
for (int row = 0; row < numberOfRows; ++row)
delete [] matrix[row];
delete matrix;
}
}
}
As said, often teached, but strongly discouraged.

2D integer array in c++ with uneven number of elements in each row

The number of rows and columns of this array are given by the user however the number of rows are not the same (the array is uneven) and also the user will fill the array by entering the elements.
This is the code that I wrote but when I try to take input from user, the code crashes after taking some inputs. Please could you help me out and correct my code and point my flaws. Thank you.
#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int **a = new int *[row];
for (int r = 0; r < row; r++)
{
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cin >> a[i][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
delete[] a;
a = NULL;
return 0;
}
There was an extra for loop. Also, you have to store the size of each row.
And make the proper deallocation of the 2D array.
#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
cout<<"Enter the row number:"<<endl;
cin>>row;
int **a=new int *[row];
int *col_x = new int [row];
for(int r=0;r<row;r++){
cout<<"Enter the column no.of array "<<r<<endl;
cin>>col_x[r];
a[r]=new int[col_x[r]];
cout<<"Enter the elements in the array:"<<endl;
for(int j=0;j<col_x[r];j++){
cin>>a[r][j];
}
}
cout<<"The elements in the array:"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col_x[i];j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for (int i=0; i<row; ++i)
delete[] a[i];
delete []a;
delete []col_x;
return 0;
}
The way you are getting the input from the user is very vague, and is prone to accessing invalid memory. You are getting the same row many times in the inner loop.
Try something like this:
#include <iostream>
//2d array
using namespace std;
int main() {
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int ** a = new int * [row];
for (int r = 0; r < row; r++) {
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int j = 0; j < col_x; j++) {
cin >> a[r][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col_x; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
delete[] a;
a = NULL;
return 0;
}
Also, note that col_x will hold only the size of the last row. So, it's not working for the printing at the end of the code.
Not sure what you are trying to achieve, but the main issue with above code is, that you are accessing non-existing elements of your array. Maybe your loop over r should end in line 18? Even then, you would have to store the number of columns per row in some external variable. I would suggest to use a std::vector as the container instead of fixed arrays, in your case a std::vector< std::vector<int> >. The vector class has a method size() which stores its actual size.
Since you are using C++, you should take advantage of the containers it provides for you to store your data, in this case a vector of vectors would be appropriate:
Live Sample
#include <iostream>
#include <vector>
using namespace std; //<-- for test, souldn't be used
int main() {
int rows, cols, temp;
vector<vector<int>> matrix;
cout << "Enter the row number:" << endl;
cin >> rows;
for (int i = 0; i < rows; i++){
vector<int> v;
cout << "Enter the column no.of array " << i << endl;
cin >> cols;
cout << "The elements in the array:" << endl;
for (int j = 0; j < cols; j++){
cin >> temp;
v.push_back(temp);
}
matrix.push_back(v);
}
cout << endl;
for( auto i: matrix){ //print results
for(int j: i)
cout << j << " ";
cout << endl;
}
}

Dynamic arrays using float

I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}

Adding integers with c++

I am trying to write a program in c++ that allows you to enter 10 numbers and receive the sum of those numbers using a for loop. However, I am encountering a problem where I am not getting the added integers and instead getting the sum of the last 2 numbers.
#include <iostream>
using namespace std;
int main ()
{
int i;
int number;
for(i; i < 10; i++)
{
cout << "enter a number" << endl;
cin >> number;
if( i < 10)
number+= number;
}
cout << number;
return 0;
}
1) You never initialize i, you should do so in the for loop.
for(int i=0; i < 10; ++i)
You also don't need:
if( i < 10 )
because based on your for loop conditions, this can never be false.
2) You also need to initialize number.
int number = 0;
3) You shouldn't cin directly to number or you will replace the total every single time. You could do this in your for loop for example.
int temp = 0;
cin >> temp;
number += temp;
Summary
If you correct the above three issues, the modified code would look like this:
int main ()
{
int number = 0;
for(int i=0; i < 10; ++i)
{
cout << "enter a number" << endl;
int temp = 0;
cin >> temp;
number += temp;
}
cout << number;
return 0;
}
When you write cin >> number; you are replacing your sum so far. You need to take user input into a separate variable and then add it. Something like:
for(i = 0; i < 10; i++)
{
cout << "enter a number" << endl;
int input;
cin >> input;
number += input;
}
A couple of things. You need to initialize i before you use it in a for loop
for(int i=0; i<10; i++)
Also, you are using the same variable to get the number from cin as you are using to store the sum. You should use two separate variables.
Here's a list of things to change and a working program with a few modifications below
1.You must initialize variables before you can use them in any meaningful way.
Initialize means assigning an initial value but it also requires you declare variables and that they are properly defined (e.g. loop variable is i NOT defined to be an int)
Therefore, you have to initialize the for loop variable i. You also have to initialize number by changing it to 0
2. Use a different number for your input and for your sum because you will just overwrite any old values as you read them. Note that you do not need to assign a value to this number because you are reading from the input stream into it
int sum=0,n;//n is input
for(int i=0; i < 10; i++)
{
cout << "enter a number" << endl;
cin >> n;
sum+= n;
}
cout << sum;

C++ Program Debugging

I seem to be having some problems with my program. It compiles fine, but when I get to my first loop it asks me for a positive integer than it asks me again like its suppose too. Than it hops down a blank space and wont run any further until you enter another number which its not suppose to do. But than when you enter a number it goes back and asks me to enter an integer also like its suppose to the problem is, IT will do this infinite amount of times until I quit the program. Any suggestions as to why this is happening?
/* Search the entries of the n X n matrix mat in rowwise order for an entry to item */
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row=3, col=3, mat[row][col];
bool found;
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
{
cout << "Enter Positive Integer : ";
cin >> row;
cout << " Enter Positive Integer : ";
cin >> mat[row][col];
}
cout << "Enter a positive integer you want to be searched: ";
cin >> item;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
if(found==true)
cout << "item found" ;
else
cout << "item found ";
return 0;
}
The line for (int cols = 0; cols < 5; col++) increments the variable col, not cols. Since cols is always 0, the loop will never terminate.
You've done the same in for (int rows = 0; rows < 5; row++). Infinite loops often occur due to typos in loop conditions ;)
I would also like to point out some logic errors during your search:
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
When that loop ends, found will only be true if mat[row-1][col-1] == item (the very last element). Heck, row and col never change in the loop so you are repeatedly checking the exact same element every time! You should also expect even more funky program behavior if you don't get a grasp on your variable names. I strongly recommend adding debug statements to see how your variables are being modified throughout the program (aka: cout << "rows = " << rows << endl;, and cout << "i = " << i << endl;, etc). You're preparing a recipe for disaster when you reuse your variables.
Disclaimer: Reusing variables is not always a bad thing. However, it's best to avoid it until you have a stronger understanding of variables.
In your loop you are incrementing row and col not rows and cols.
It looks to me like you are using the same variable for the loop counter and the user input storage. That is doomed to not do what you want.
Do something like:
for (rowCounter = 0; rowCounter < 3; rowCounter++) {
for (colCounter = 0; colCounter < 3; colCounter++) {
cout << “Give me value for (“ << rowCounter << “,” << colCounter << “) :”;
cin >> mat[rowCounter][colCounter];
}
}
and then the rest of your code
It seems you had a couple of issues.
In the first for loop, you were incrementing the wrong variable (col instead of cols), you also went from 0 to 4 in a 3x3 matrix
you asked the user for 2 numbers then you asked the user to put in a number in the matrix, but its only a 3x3 matrix, the user could easy go out of bounds. I think what you were trying to do was populate the matrix with users number. So i made that change.
In the second for loop, you set found =true, but the loop will keep going, meaning the last number it searched, if it was false, then found = false, also changed it to mat[i][j] instead of mat[row][col], so it doesn't check the same one every time.
both found = true and found = false would return "item found", i think you left off the "not" in the second hard coded string.
I added a pause so you can read the output at the end.
I fixed them and I think this code should do what you want it to now.
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row = 3, col = 3;
int mat[3][3];
bool found = false;
int j,k;
for (int rows = 0; rows < 3; rows++)
for (int cols = 0; cols < 3; cols++)
{
cout << "Enter row Integer: ";
cin >>j;
cout << "Enter col Integer: ";
cin >> k;
cout << "Enter Positive Integer : ";
cin >> mat[j][k];
}
cout << "Enter a poistive integer you want to be searched: ";
cin >> item;
int flag = 0;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[i][j] == item)
{
flag = flag + 1;
}
}
}
if(flag > 0)
found = true;
if(found==true)
cout << "item found" ;
else
{
cout << "item not found ";
}
system("PAUSE");
return 0;
}