Need little help with a function please.

Hi i'm quite the beginner and I'm just trying to make this work:

for(i=1;i<=parties;i++){
if(tabC[i]-tabA[i]>diff)
diff=tabC[i]-tabA[i];
tabC[i]=X;
tabA[i]=Y;
}


all variables have been defined as Int, the tab works well with my other functions (it contains numbers from 0 to 9 and the tab is only 9 in length at max. parties also never exceeds 9.

but for some reason X, Y and diff turn out as 2686760, 2686756 and 2686324. I can't see why­ since as i said before, the tab works well in my other function and I only type in the values manually once.

Lmk if anyone can help out, or if I didnt give enough information. Thanks in advance !
If I got this right, your code should look like this:

1
2
3
4
5
6
7
for(i=1;i<=parties;i++)
{
     if(tabC[i]-tabA[i]>diff)
         diff=tabC[i]-tabA[i];
     tabC[i]=X;
     tabA[i]=Y;
}


Thus the tabC and tabA are not part of the if block, but are still part of the for loop.

But what I'm not getting is what happens to X and Y outside of this loop, considering that nothing is happening to them in this code snippet.

If you respond to this, it'll help a lot in letting us solve this.
Yes that is exactly how my code looks in Dev C++,

I want the TabC and tabA to be part of the if, as in : i only want them to be = to X and Y if the if condition is met.

To my untrained eye I would say they ARE part of the if block, can you let me know why they are not ?
Ty for the fast answer btw!


edit; diff=0 at first, before being manipulated by the function
Last edited on
I want X to take the value of Tabc[i] and Y too, should it be the other way around ?

IE: X=tabC[i]; instead of tabC[i];=X ?

Since X and Y have no value in them prior to this function
So your issue is that an if statement will only take up until the next semicolon as what happens if the condition is true. To fix this, you'll need to add braces so that your code looks like this:

1
2
3
4
5
6
7
8
9
for(i=1;i<=parties;i++)
{
     if(tabC[i]-tabA[i]>diff)
     {
         diff=tabC[i]-tabA[i];
         tabC[i]=X;
         tabA[i]=Y;
     }
}


This way, all of these statements will run only if (tabC[i]-tabA[i])>diff. (Parentheses for clarification purposes).

And if you want X and Y to take those values, than they go on the left side of the equals sign.
Topic archived. No new replies allowed.