-1

Problem: I am doing an assignment that seems pretty straightforward, however, I am getting an error that says variable 'test1' is uninitialized. I declared it as an int, then initialized it in the scanf statement. any help here?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void main()
{
int hours, hours2, test1, test2, test3, avg, well;
avg = (test1 + test2 + test3) / 3;

printf("Enter your Cprogram Test grades here for Test 1, 2, and 3: \n");
scanf("%d%d%d", &test1, &test2, &test3);
printf("The average of these grades are: %d. \n", avg);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jcool1
  • 9
  • 3
  • See [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c/18721336#18721336) for a discussion of why there are only a few places where `void main()` is legitimate. – Jonathan Leffler Feb 18 '16 at 18:23

2 Answers2

4

You used the variable test1 in the line

avg = (test1 + test2 + test3) / 3;

which comes before the scanf. So test1 (and likewise test2 and test3) were uninitialized when used at that time.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
0

The calculation of avg = (test1 + test2 + test3) / 3; which references test1 needs to occur after you initialize it by reading from scanf. Move that line after scanf("%d%d%d", &test1, &test2, &test3); and it will work:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void main()
{
int hours, hours2, test1, test2, test3, avg, well;


printf("Enter your Cprogram Test grades here for Test 1, 2, and 3: \n");
scanf("%d%d%d", &test1, &test2, &test3);
avg = (test1 + test2 + test3) / 3;
printf("The average of these grades are: %d. \n", avg);

}

C,C++, like most procedural languages evaluates your code in the order in which it is written. That is, avg = (test1 + test2 + test3) / 3; assigns a value to avg based on the current values of test1,test2 and test3. These must be defined and initialized before the assignment is performed. That is what scanf("%d%d%d", &test1, &test2, &test3); does.

Vasim Shaikh
  • 4,485
  • 2
  • 23
  • 52
  • 1
    You're right. The code should also check that `scanf()` was able to read three integers successfully — you'll still use uninitialized variables if if fails to read all three. – Jonathan Leffler Feb 18 '16 at 18:24