Thread: Explanation for the Output

1. Explanation for the Output

Can someone please explain me how the output comes 20 if the n value is 5 or 56 if the n value is 8 for the following program?

Code:
```# include < stdio .h >
# include < stdlib.h >
int main (int argc , char * argv []) {
int a [64] , i;
int n = atoi ( argv [1]);
a [0] = 0;
for (i = 1; i < n; i ++) {
a[i] = a[i -1] + 2 * i;
}
printf(" %4d\n", a[n -1]);return 0;
}```
Thanks a lot.

2. > a[i] = a[i -1] + 2 * i;
A start would be to add after this line, a print statement like
printf("DEBUG: a[%d](=%d) = a[%d](=%d) + 2 * %d", i, a[i], i-1, a[i -1], i);

Or you could learn to use a debugger to watch how the code behaves, examine variables as they change, all without having to edit the code.

3. Do you want to print a[n-1] but the final result is in something else i suppose?

4. Does the casting print ascii?

The loop itself is nothing else than a result of x * (x - 1).

5. Originally Posted by Carnotter
Does the casting print ascii?
I do not see any explicit casts in any of the code posted thus far.

Popular pages Recent additions