Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to sum up columns of a predefined 2 D array, but my code seems not to work. E. g. for a 2D array with rows 2 3 and 4 5
I am getting following column sums:
-117393687 and -113194156
Here is the part of my code where I sum up the columns:
//sum columns
for(i=0; i<m; i++)
{
for(ii=0; ii<m; ii++)
{
sum += myarray[i][ii];
}
cout <<"column sum: "<<sum<<endl;
{
Rest of my code:
#include <iostream>
using namespace std;
int main()
{
int i, ii, n, m, sum;
int array[n][m];
sum=0;
cout <"no. of rows"<<endl;
cin>>n;
cout <"no. of columns"<<endl;
cin>>m;
for(i=0; i<n; i++)
{
for(ii=0; ii<n; ii++)
{
cout<<"row "<<i+1<<" column "<<ii+1<<endl;
cin>>array[n][m];
}
}
}
//sum columns
for(i=0; i<m; i++)
{
for(ii=0; ii<m; ii++)
{
sum += myarray[i][ii];
}
cout <<"column sum: "<<sum<<endl;
{
There are quite a few errors on your code, and it has quite a weird structure, but trying not to change it too much (so it's still easy for you to follow the fixes), let's see it fixed then I'll explain it (please note that this version will compile and run in practice):
#include <iostream>
using namespace std;
int main()
{
int i, ii, n, m, sum;
cout << "no. of rows" << endl;
cin >> n;
cout << "no. of columns" << endl;
cin >> m;
int array[n][m];
for (i=0; i<n; i++)
{
for (ii=0; ii<m; ii++)
{
cout << "row " << i+1 << " column " << ii+1 << endl;
cin >> array[i][ii];
}
}
sum=0;
for (i=0; i<n; i++)
{
for (ii=0; ii<m; ii++)
{
sum += array[i][ii];
}
}
cout << "Sum: " << sum << endl;
}
Ok, so, first, you should only declare the array after you know what "n" and "m" variables are. Edit: also, not all compilers will accept declaring the dynamic array that way, but again, I tried to keep your original structure as much as possible.
Second, in your input loop, you should index the array by "i" and "ii", but you were always indexing by "n" and "m", that is, only writing to the latest index, which would even cause an exception.
Last, while summing, again you should use "i" and "ii" as array indices, so you correctly scan the array.
And that is it.
You're not declaring your array size properly. When you create the array n and m aren't set yet. You need to determine their size first. And even then you have to pass in constants to an array because arrays in C++ cannot be dynamically sized. If you want the user to determine container size like this then use a vector of vectors. Arrays are to be used when you know the size from the beginning of the program.
According to the code shown above:
You are mistaking while taking the iputs. Try this:
for(i=0; i<n; i++)
{
for(ii=0; ii<n; ii++)
{
cout<<"row "<<i+1<<" column "<<ii+1<<endl;
cin>>array[i][ii];
}
}
You are initializing the 2D array in a wrong way, you need to define the size first, m and n are not initalized when declaring the array.
On C++ using containers like vector is better.
You also had a error in the input code (2 n instead of n and m in the for loop).
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rows, cols, sum = 0;
std::vector<std::vector<int>> array;
cout << "No. of rows: ";
cin >> rows;
cout << "No. of columns: ";
cin >> cols;
for(int i = 0; i< rows; i++)
{
std::vector<int> v;
for(int j = 0; j < cols; j++)
{
cout << "Value for row " << i + 1 << " and column "<< j + 1 << ": ";
int val;
cin >> val;
v.push_back(val);
}
array.push_back(v);
}
for (auto i: array)
{
for(auto j: i)
{
sum += j;
}
}
cout << "The sum is: " << sum << endl;
}
Related
This question already has answers here:
Printing an array in C++?
(14 answers)
Closed 3 months ago.
#include <iostream>
using namespace std;
int main() {
int marks[1000], i, j;
cout << "Enter the size of an array: ";
cin >> i;
for (j = 0; j <= i; j++) {
cout << "Enter " << i << " element of array: ";
cin >> marks[i];
i++;
}
for (j = 0; j <= i; j++) {
cout << "The " << i << " element of array is: " << endl;
i++;
}
return 0;
}
I declared an integer array initially along with i and j variables. Then I asked the user for the size of an array and then assigned it to i variable. Then i initialized a for loop and asked the user to input the element of an array and stored them in i of array. I think I made some mistake in for loop so can you guys help me with that?
You're missing the actual printing of the element. Also, in the loops, you don't need to increment the size of the arrays:
for ( j = 0; j < i; j++)
{
cout<<"Enter "<<j<<" element of array: ";
cin>>marks[j];
}
for ( j = 0; j < i; j++)
{
cout<<"The "<<j<<" element of array is: "<<marks[j]<<endl;
}
It's advised to use more descriptive name for variables (e.g. elemCount) so that you can avoid these kind of mistakes.
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 2 years ago.
Improve this question
In my code below, I try to find an 'x' in a 2D array and display its row and column. But it always shows the a[0][1] in the result. Can someone tell me where did I wrong and why is that? I tried other code but there is no difference. Thanks
My code:
#include <iostream>
using namespace std;
int main(){
int m, n, i, j, a[m][n], sum, x, sl=0;
cout<<"insert array number of rows: "; cin>>m;
cout<<"insert array number of columns: "; cin>>n;
for(i=0;i<m;i++){
sum=0;
for(j=0;j<n;j++){
cout<<"insert board["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
sum+=a[i][j];
}
cout<<"the summary of rows "<<i<<" is: "<<sum<<endl;
}
cout<<"search x= "; cin>>x;
for (i=0; i<=m-1; i++){
for (j=0; j<=n-1; j++){
if (a[i][j]==x){
sl++;
cout<<"x is at "<<"a["<<i<<"]["<<j<<"]"<< endl;
}
}
}
if(sl==0){
cout<<"there is no x in the array";
}
cout<<sl;
return 0;
}
My results:
Sources of error in your code:
You were using a variable length array (which is not a part of C++ standard). Moreover you were setting its rows and columns before even initializing/inputting n and m.
Fixed Code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n, x, sl = 0;
cout << "Insert number of rows in the array: ";
cin >> m;
cout << "\nInsert number of columns in the array: ";
cin >> n;
// put the below line after cin >> m; cin >> n;
vector<vector<int>> a(m, vector<int>(n, 0)); // <-- Use this instead of int a[m][n];
cout << endl;
for (int i = 0; i < m; ++i) {
int sum = 0;
for (int j = 0; j < n; ++j) {
cout << "\nInsert board[" << i << "][" << j << "]: ";
cin >> a[i][j];
sum += a[i][j];
}
cout << "\nThe sum of the row " << i << " is: " << sum << endl;
}
cout << "\nSearch x = ";
cin >> x;
cout << '\n' << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (a[i][j] == x) {
sl++;
cout << "x is at a[" << i << "][" << j << "]\n";
}
}
}
if (sl == 0) { cout << "\nThere is no x in the array!"; }
else cout << '\n' << sl;
return 0;
}
Sample Input :
2
2
3
4
7
3
3
Sample Output :
Insert number of rows in the array:
Insert number of columns in the array:
Insert board[0][0]:
Insert board[0][1]:
The sum of the row 0 is: 7
Insert board[1][0]:
Insert board[1][1]:
The sum of the row 1 is: 10
Search x =
x is at a[0][0]
x is at a[1][1]
2
For interactive run, you can remove the newline characters at your wish.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int main ()
{
int A[6][6], i, j, k, max, min;
for (int i=0; i<6; i++)
{
cout << "Enter a number: "<<endl;
for (int j=0; j<6; j++)
{
cin >> A[i][j];
}
}
for (int i=0; i<6; i++)
{
for (int j=0; j<6; j++)
{
cout << " " << A[i][j];
}
}
if (j > 0)
{
cout << "A: "<<endl;
}
else if (j < 0)
{
cout << "B: "<<endl;
}
cin.get();
char ch1;
cin>>ch1;
return 0;
}
I've been looking through the codes here but they all include things I haven't yet learned in C++, I need to make it so the positive numbers are are put in section A and the negative ones in B, and to show them again in that order. How do I do that?
First of all you do understand that your loop runs for 6 times and keep asking to enter numbers until you enter 36 inputs.
I would recommend using a 1D array instead of a 2D array. And reduce the number if you can or add a functionality to stop taking inputs when the user think it's enough. You could do this easily with a if condition.
Anyway just to make your code do what it suppose to do(If i get it correctly),
#include <iostream>
using namespace std;
int main ()
{
int A[2][2], i, j, k, max, min;
for (int i=0; i<2; i++)
{
cout << "Enter a number: "<<endl;
for (int j=0; j<2; j++)
{
cin >> A[i][j];
}
}
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
if (A[i][j] > 0)
{
cout << "A: " << A[i][j] <<endl;
}
else if (A[i][j] < 0)
{
cout << "B: "<< A[i][j] <<endl;
}
}
}
cin.get();
char ch1;
cin>>ch1;
return 0;
}
You can change the last for loop like this.I have changed the array size to 2 since I can't enter 36 inputs.What's wrong with your code is that the second set of for loops finish running and print all the numbers and after that it runs the if statement which is again not correct because you are checking the value of j instead of checking the numbers you entered.Hope this will be helpful.
you can include then use sort function. In sort function you can write a sort method or you can use greater () as a sort method
The j variable is not initialized in
if (j > 0)
{
cout << "A: "<<endl;
}
else if (j < 0)
{
cout << "B: "<<endl;
}
It is not the same j as those which are used for the for loops since these ones are declared in the loop (with int).
Be careful to use only initialized variables.
Also I think you just need to make another for loop with i and j to check whether every element of the array is positive or negative (how about zero elements?).
I've just completed a program which does as follows:
You have t[10][5] and p[10] arrays.
You read dimT and dimP.
You write dimT values in t[][] and dimP values in p[].
For writing values in t[][], you have to fill lines before. The output must be the column which has highest number of matches for the p[] array.
Example:
INPUT -> 14 (dimT) 2 (dimP) 0 1 2 3 4 0 2 7 9 1 0 11 12 0 (t[][]) 0 0 (p[])
So the final matrix display is:
0 1 2 3 4
0 2 7 9 1
0 11 12 0
OUTPUT -> The best matching column is 0 with 2 matches (overlap counted).
I created this program using arrays but it's really horrible, so I'm looking for a better and cleaner solution from some experts possibly, using vectors instead of simple arrays.
Here is my current code. It would be better if I had split it into a function or two more, but it is shorter this way:
#include <iostream>
#include <vector>
using namespace std;
bool IsMatch(vector<double>& col, vector<double>& p, int n)
{
for (size_t i=0; i<p.size() ;i++)
if (col[i+n]!=p[i])
return false;
return true;
}
int main()
{
int dimT;
int dimP;
cin >> dimT;
cin >> dimP;
int lineN = (dimT+5-1)/5;
vector<vector<double> > t(lineN,vector<double>(5));
vector<vector<double> > tTran(5,vector<double>());
vector<double> p(dimP);
t[lineN-1].resize(dimT%5);
//input matrices
for (int i=0; i<dimT;i++) {
double inputVal;
cin >> inputVal;
tTran[i%5].push_back(inputVal);
t[i/5][i%5]=inputVal;
}
for (int i=0; i<dimP;i++)
cin >> p[i];
//print it out
for (int line=0; line<lineN; line++){
for (size_t j=0; j<t[line].size(); j++)
cout << t[line][j] << " ";
cout << endl;
}
//transpose t
/*vector<vector<double> > tTran(5,vector<double>());
for (int line=0; line<lineN; line++)
for (size_t j=0; j<t[line].size(); j++)
tTran[j].push_back(t[line][j]);
//output tTran
for (int line=0; line<5; line++){
for (size_t j=0; j<tTran[line].size(); j++)
cout << tTran[line][j] << " ";
cout << endl;
}
*/
int maxCol=0;
int maxMatchN=0;
for (int col=0; col<5; col++){
int matchN=0;
for (size_t j=0; j<tTran[col].size()-p.size()+1; j++)
if (IsMatch(tTran[col],p,j) )
matchN++;
if (matchN>maxMatchN){
maxMatchN = matchN;
maxCol = col;
}
}
cout << "The best matching column is " << maxCol
<< " with " << maxMatchN << " matches (overlap counted)." << endl;
}
Here is the simpler (all transposed) version I was suggesting in the comments: The point I'm trying to show is that the non transposed copy has no value. You understood it is easier to transpose during input than later. But you kept the non transposed copy as well, and did the output from the non transposed copy and processing from transposed copy.
Take a look at all the extra nonsense that can be skipped if you don't have a non transposed copy. Then compare the output loop directly from the transposed copy to the original output loop. The change to the output loop was trivial and the benefit significant.
int main()
{
int dimT;
int dimP;
cin >> dimT;
cin >> dimP;
vector<double> t[5+1]; // +1 because empty guard vector makes output loop simpler
vector<double> p(dimP);
//input matrices
for (int i=0; i<dimT;i++) {
double inputVal;
cin >> inputVal;
t[i%5].push_back(inputVal);
}
for (int i=0; i<dimP;i++)
cin >> p[i];
//print it out
for (size_t line=0; line<t[0].size(); line++){
for (size_t j=0; line<t[j].size(); j++)
cout << t[j][line] << " ";
cout << endl;
}
int maxCol=0;
int maxMatchN=0;
for (int col=0; col<5; col++){
int matchN=0;
for (size_t j=0; j<t[col].size()-p.size()+1; j++)
if (IsMatch(t[col],p,j) )
matchN++;
if (matchN>maxMatchN){
maxMatchN = matchN;
maxCol = col;
}
}
cout << "The best matching column is " << maxCol
<< " with " << maxMatchN << " matches (overlap counted)." << endl;
}
That empty "guard" vector is a useful trick to know and in more complicated problems avoids a lot of detail and likely mistakes. In this code it just saved needing j<5 && in one spot.
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;
}