actually ive already started it but in the adding part when i print sum it displays wrong sum
2 x 4 array
i = 2
j = 4
~~~~
for(i=0;i%26lt;=1;i++)
{ for(j=0;j%26lt;=3;j++)
p("a[%d,%d]", i+1, j+1)
scans for elements~
}
for(i=0;i%26lt;=1;i++)
{ for(j=0;j%26lt;=3;j++)
x=j % 2
if(x==0)
sum = sum + a[i][j]
else
sum = sum + 0
}
p(%d, sum)
i cant find the problem
How to make C++ program that gets the sum of even columns in 2d arrays?
This looks like homework so I am just going to give a couple of hints.
First, it looks like you are missing a set of curly braces '{'.
for(i=0;i%26lt;=1;i++)
{ for(j=0;j%26lt;=3;j++)
Insert Opening Curly Brace Here
x=j % 2
...
Second, look into using j+=2 rather than just j++ in the inner for loop. This will allow you to work with only the even columns and never even see the odd ones simplifying your code.
Good luck
Reply:I have created some variables (numColumns and numRows) that you will have to fill with the correct value, but here is the general process:
Loop through every other column, starting at 0 (so 0, 2, 4...) and for each column you loop through, loop through each row (so 0, 1, 2, 3...) and add the value for that column/row combination to your sum.
sum = 0;
for (int i = 0; i %26lt; numColumns; i += 2)
{
for (int j = 0; j %26lt; numRows; j++)
{
sum += a[i][j];
}
}
p(%d, sum)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment