# For loop with a two-dimensional array

• 01-24-2013
slimd
For loop with a two-dimensional array
Hey!

I'm working on a program that will calculate prices for coins. I'm using a two-dimensional array to save the year, and the condition of the coin.

Here are the basics.

Code:

j = 0;
k = 0;

coinCount = 2; // previously prompted

for (i = 0; i < coinCount; i++)

{
printf("\nYear: ");
coin[j][k] = check(a); //A function that validates the input
k++;

printf("\nCondition: ");
coin[j][k] = check(a);
j++;
}

j = 0;
k = 0;

// For every coin, check if condition is 1.

for (i = 0; i < coinCount; i++)
{
if (coin[j][1] == 1)
{
mint = mint + (3 * coin[j][0]); // THIS doesn't work.
j++;
}
}

I'm trying to make it print the variable 'mint', but it only stores the values from one loop. Am I doing something terribly wrong?

Is a two-dimensional array the way you would approach this?
Is there a way to make "object-like" things in C?
Like Coin1.year and Coin1.condition?

Thank you and sorry for my bad language :)

• 01-25-2013
Salem
First, use "paste as text" when you paste code, then it looks like this
Code:

j = 0;
k = 0;

coinCount = 2;                // previously prompted

for (i = 0; i < coinCount; i++) {
printf("\nYear: ");
coin[j][k] = check(a);      //A function that validates the input
k++;

printf("\nCondition: ");
coin[j][k] = check(a);
j++;
}

j = 0;
k = 0;

// For every coin, check if condition is 1.

for (i = 0; i < coinCount; i++) {
if (coin[j][1] == 1) {
mint = mint + (3 * coin[j][0]); // THIS doesn't work.
j++;
}
}

Next, look at your loop variables.
Code:

for (i = 0; i < coinCount; i++) {
if (coin[j][1] == 1) {
mint = mint + (3 * coin[j][0]); // THIS doesn't work.
j++;
}
}

You don't need j at all.

In fact, in all the code, you may as well stick with coin[i][0] and coin[i][1]
• 01-25-2013
c99tutorial
Quote:

Originally Posted by slimd
Is there a way to make "object-like" things in C?
Like Coin1.year and Coin1.condition?

That is a struct in C. Example

Code:

typedef struct {
int year;
char condition[100];
} COIN;

Code:

COIN Coin1;
Coin1.year = 1920;