I am very new to C, and I was just playing around and seeing if I could recreate a simple subarray adding program (finds the largest continuous subarray in an array). I ran in to an odd issue where if I defined n as an integer and used it as a condition in my for loop I would get absolute junk back.
Forgive this weird code, I pretty much just copied and pasted a file I was monkeying around with (lots of extra printfs etc). If I run this, I get an output of "4196053", or something similar to that, for each printf call in the for loop. Even in the first printf call (before entering the loop) it seems to be messed up.
#include <stdio.h>
int maxI (int a, int b)
{
int max = (a >= b) ? a : b;
return max;
}
int main (void)
{
int array[] = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
int n = 11;
int maxSoFar, i = 0;
int maxHere = 0;
printf ("%i\n", maxSoFar); //why is it screwing up here?
for (i = 0; i < n; i++) {
printf ("%i\n", maxSoFar);
maxHere = maxI(maxHere + array[i], 0);
maxSoFar = maxI(maxSoFar, maxHere);
}
printf ("The max is %i.\n", maxSoFar);
return 0;
}
If I just use 11 in the conditional instead of a variable it works fine. Anyone know what is going on here?