ok so I was able to initialize my array but not sure how to add the rows and display sum per row and display the total of all the rows could use help or explanation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main ()
{
// an array with 2 rows and 3 columns.
double a[2][3] = { 7.2,0.4,5.6,1.2,9.0,3.5};
// output each array element's value
for ( int i = 0; i < 2; i++ )
for ( int j = 0; j < 3; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
the way you initialized the array is not good practice, actually (I'm a beginner as well) i didn't know your initialization would even compile, but it does.
1 2 3 4 5 6 7 8 9
//initialize in the following two formats, to make code more readable
double a[2][3] = { { 7.2, 0.4, 5.6 },{ 1.2, 9.0, 3.5 } };
// or
double a[2][3] =
{
{ 7.2, 0.4, 5.6 },
{ 1.2, 9.0, 3.5 }
};
i tried the second way you have it but it didn't work for some reason but now im stuck on adding the rows and displaying the sum per row and displaying the total for all rows
// initialize in a readable format
double a[2][3] = { { 7.2, 0.4, 5.6 }, { 1.2, 9.0, 3.5 } };
//get a variable ready to store total
double total = 0;
//make a for loop for the outermost dimension
for (int i = 0; i < 2; i++) {
//here we'll get a variable ready to display total of the row
double row = 0;
// now make a for loop for the 2nd outer most
// dimension, your case: only 2D so this is the final loop
for (int j = 0; j < 3; j++){
// now output to console and add this to the row total
cout << "a [" << i << "][" << j << "] : ";
//here well use \n instead of endl which ive also heard is
//bad practice
cout << a[i][j] << "\n";
row += a[i][j];
}
// here we'll output the row total when the inner loop finishes
cout << "Row total is: " << row << "\n";
// also well add the row total to the grand total
total += row;
}
cout << "The Grand total is: " << total;