main()
{
int i;
int a[5];
for (i = 1; i <= 5; i++)
a[i] = 0;
printf("Hello, how are you? ");
}
why is the program not coming out of the loop?
main()
{
int i;
int a[5];
for (i = 1; i <= 5; i++)
a[i] = 0;
printf("Hello, how are you? ");
}
why is the program not coming out of the loop?
C arrays are zero-based so you should use indexes [0..4] rather than [1..5].
Writing to a[5]
writes beyond the bounds of your array. This has undefined results; in your case, this happens to be the address of your loop counter i
which is reset to 0.
You can fix this by using
for (i = 0; i < 5; i++)
or, better,
for (i = 0; i < sizeof(a)/sizeof(a[0]); i++)
as your loop.
You're accessing the array out of bounds (the legal indices for an array of size 5 are indices 0 to 4, not 1 to 5). As far as the standard is concerned, this means your program invokes undefined behavior and can behave any way it pleases.
In terms of the actual implementation, what's actually happening is probably that your last array access (i.e. a[5] = 0;
) write over variable that comes after a
in memory, which happens to be i
on your system. So i
is reset to 0 and the loop continues forever.
#include <stdio.h>
main()
{
int a[5];
int i;
printf("Memory location of i = %p\n",&i);
printf("Memory location of a[5] = %p\n",&a[5]);
for (i = 1; i <=5; i++)
{
a[i] = 0;
sleep (2);
printf("Value of i=%d\n",i);
}
printf("Hello, how are you? \n");
}
See the o/p it is interesting .. [ will understood why value of i became 0(Zero)]
mnds@mind-AcerPower-Series:/tmp$ ./a.out
Memory location of i = 3218951772
Memory location of a[5] = 3218951772
Value of i=1
Value of i=2
Value of i=3
Value of i=4
Value of i=0
If you are writing a[5]
, that's outside the boundary.
Your loop should be:
for(i=0; i<5; i++)
You pass the size of the integer array, array size is 5 so maximum a[4]
is accessible.
Try this:
main()
{
int i;
int a[5];
for (i = 0; i < 5; i++)
a[i] = 0;
printf("Hello, how are you? ");
}
Because it invokes undefined behavior, so anything can happen (infinite loops included).
When your array has 5 elements, the indices of these elements range from 0 to 4. Accessing a[5]
is an invalid operation.
Arrays in C are zero-indexed, so in order your program to work correctly, you should have written
for (i = 0; i < 5; i++)