C/logical error neglected
Expert: Narendra - 10/21/2005
Questionhi,
please read the following code
//outputs the average of previous positive numbers
#include<stdio.h>
main()
{ /*Beginning of main()*/
int n,count=0; /*Local declarations */
float sum; //not initialized
/*Local statements*/
printf("Enter the numbers :");
while(n)
{
scanf("%d",&n);
if(n<0)
{
printf("The average of the previous positive numbers is %f\n",sum/count);
break;
}
sum=sum+n;
count++;
}
return(0);
} /*End of main() */
as shown above the variable sum is not initialized.
inspite of this logica error the output of the proram is correct.according to the concept that i know if a variable is not initialized it has a random value.but if the program is executed in turbo c or gcc(in linux) it works.
can this be explained.
Please help
eaerly waiting for ur reply.
thankin u
AnswerIt is working by chance.
If you try on different systems, (even with the same compiler) you will see that it is giving different o/ps.
Actually this is not a logical error.
This is a requirement of C language.
If you had declared the variable sum outside main(), then you wouldn't have needed this initialization.
If a local variable is getting initialized to 0 (where you haven't done any initialization), it is only BY CHANCE.
You can just try to interchange the two lines of declaration and see how it affects the UNINITIALIZED variables.
Here is your modified code, which you can try:
#include <stdio.h>
main()
{ /*Beginning of main()*/
float sum; //not initialized
int n, count=0; /*Local declarations */
/*Local statements*/
printf("n = %d\n", n);
printf("sum = %f\n", sum);
printf("Enter the numbers : ");
while (n < 0)
{
scanf("%d", &n);
if (n < 0)
{
printf("The average of the previous positive numbers is %f\n", sum/count);
break;
}
sum = sum + n;
count++;
}
return(0);
}
Tell me what happened after executing this?
-Narendra