You are here:

C/logical error neglected

Advertisement


Question
hi,
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  

Answer
It 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.