PointerArray PointerArray - 3 months ago 9
C Question

I can't find the bug in this c program

I found this in a tutorial. It is a program to print the given array backward. But it doesn't print the array backward, cause it has a bug. It says I should find the bug, which I can't.

#include <stdio.h>

int main()
{
int ara[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

int i, j, temp;

for(i = 0, j = 9; i < 10; i++, j--)
{
temp = ara[j];
ara[j] = ara[i];
ara[i] = temp;
}

for(i = 0; i < 10; i++)
{
printf("%d\n", ara[i]);
}
return 0;
}

Answer

Swap twice be same as do nothing. Make it swap once only.

for(i = 0, j = 9; i < 5; i++, j--)
{
    temp = ara[j];
    ara[j] = ara[i];
    ara[i] = temp;
}