operating arrays

We are asked to read the top right triangle of a 2d array-I dont know if I can illustrate it but imagine the 1s and 0s to constitude the cells in the 2d array. The question asks to sum the contents of the cells that are located in 1s.
01111
00111
00011
00001
00000

I came up with the following code but it seems inconvinent to use several if statments when I could use a short cut but the thing is I dont know the short cut!
1
2
3
4
5
6
7
8
9
10
11
12
13
int sumtriangle(int final2d[5][5],int sum, int noofrows )
{
sum=0;
for(int i=0; i<noofrows; i++)
for(int j=0; j<5; j++)
{if ((i=0)&&(j>0))
   if((i=1)&&(j>1))
	   if((i=2)&&(j>2))
		   if((i=3)&&(j=4))
             sum=sum+final2d[i][j];
		   break;

}

Then I'm supposed to swap column 1 and 3 of the array and tried the following code but it isnt working-any ideas on what I should be changing?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void swap(int final2d[5][], int noofrows)
{
 int temp[5], temp2[5];
for(int i=0; i<5; i++)
{
	for(int j=0; j<5; j++)
{ 
		while(j=1)
{
		temp[i]=final2d[i][j];
	    while (j=3)
	{
		final2d[i][j]=temp2[i];
	    final2d[i][j]=temp[i];}
        final2d[i][j]=temp2[i]
	}
}
}cout<<final2d[i][j];
}

Thanx in advance
Hi again

Some questions:
(1) Do you have two assignments: Sum top right hand entries and swap columns?

(2) Do you know that your 2D array is always 5x5 or do the size vary?
no its one past exam question(different parts of the same question which asks to write a program with various functions)-I didnt want to post the whole code (for the one question) but rather solve it bit by bit sorry if it was confusing. the 2d aray is 5*5- how can it vary? Im using the same array and since array size is a constant I didnt think that would be subject to change or am I mistaken? What we are asked to do is all based on the same array. The user enters the numbers into the array (all cells-that's what I presumed anyway)
Last edited on
Right. Here are some hints given under the assumption that final2D is a 5x5 array and noofrows defines the number of entries to sum (i.e., noofrows is 4 in your first example):

(1) Notice how, in row 0, you sum the last noofrows entries.
(2) Notice how, for each row you advance, you decrement the number of entries in the row to add to the sum. This means that row number + number of entries to add for that row is constant and = noofrows.
(3) Notice how you stop adding when current row number is = noofrows

Try to use this and two for-loops to write the code...
Topic archived. No new replies allowed.