Monday, July 2, 2007

Interesting C Program -1

The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.

#include"stdio.h"
#include"stdlib.h"
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
system("pause");
return 0;
}

The culprit is the initialization in the for loop. The initial value should be a positive integer.

Try this program. This program will do the intended task.

#include "stdio.h"
#include "stdlib.h"
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int array[] = {1,2,3,4,5};
int main()
{
unsigned int d;
for(d=0;d {
printf("%d",array[d]);
system("pause");

}
system("pause");
return 0;
}



A Contribution from Mr. SasiKumar:

The code can be replaced as follows:

#include"stdio.h"
#include"stdlib.h"
int array[] = {23,34,12,17,204,99,16};
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

int main()
{
int d;
for(d=-1;d < = (signed)(TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
system("pause");
return 0;
}

2 comments:

srsasi said...

When we compare the unsigned and signed numbers, the output is compiler depended. Usually the signed no will be treated as unsigned number.

Example:

unsigned int No1 = 10;
signed int No2 = -1;
printf("(No2 LessThan No1):%d\n",(No2LessThanNo1));

The output of this printf will be "ZERO" since the condition fails.

Balaji V said...

Thanx sasi, for your valuable input.
Balaji.V

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language