Link to home
Start Free TrialLog in
Avatar of goofy26
goofy26

asked on

can someone help me with this logic

im still quite new in writting C so this might be a silly question

what im trying to do is:

have 2 arrays for example

a[]={0,1,2,3}

and

b[][]={{0,2,1,3},
{2,0,5,8},
{1,5,0,7},
{3,8,7,0}}

and based on the numbers from array a[] use them as the locations for numbers in array b
by taking pairs from the first array

so here we have a[]'s first 2 numbers 0 and 1

then the number from b[][] = 2

the second pair from a[] is 1 and 2

then b[][]=5 and so on

any ideas how should i do that?

ultimately i want to find the sum based on the sequence i gave it in a[]
but i think i know how to do that bit

thanks :)
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Goofy,

You'll probably want a little different structure for b[][] as to C, it's nothing more than a memory region.  You're probably thinking that b[][] is a two-dimensional array like b[4][4].  But since the size isn't declared, C can't index into your array.

There are a couple of ways around this.  One is to define b[][] as a fixed size array, such as b[4][4].  The other is to define *b* as an array of pointers such as **b or *b[].  You'd then use malloc() to assign memory to each row of data.  C will figure that out and let you index into it, but setting it up as constant/static memory (initialized by the compiler) is challenging.


Kent
Avatar of goofy26
goofy26

ASKER

oh yes, b's size would be fixed sorry i forgot to mention that...

i will try ur suggestion ozo thanks :)
Avatar of goofy26

ASKER

thanks this is what i couldnt think of :)

i made it do the sum as well :)

thanks a lot to both
#include "stdafx.h"
#include <stdio.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
 
	int a[4]={0,1,2,3};
	int sum=0;
 
	int i;
 
	int k[4][4]={{ 0,12,10,11},
				{12, 0, 5, 8},
				{10, 5, 0, 7},
				{11, 8, 7, 0}};
 
	for(i=0;i<3;i++){
		
		
		printf("Numbers are: %d\n",k[a[i]][a[i+1]]);
		sum+=k[a[i]][a[i+1]];
		}
	printf("sum is: %d\n",sum);
 
	return 0;
}

Open in new window