-1

I simply want a program that has the user input a value for a and b, and will ask the user to repeat this process if the value a is less than b. Here is my program:


#include <stdio.h>
#include <math.h>
int main(void)
{
        int a, b ,c;

while (a<=b)
{
        printf("Please enter a value for a:\n");
        scanf("%d", &a);
        printf("Please enter a value for b:\n");
        scanf("%d", &b);

        if (a<=b)
                printf("a must be greater than b:\n");
}
        c=a+b;
        printf("The answer of c is: %d\n", c);
return 0;
}

As soon as i run the program, it prints: "The answer of c is: 1829030" (Please note that the last number is always random)

Please help me run this program.

L.Kay
  • 61
  • 4

2 Answers2

0

The value of an uninitialized non static local variable is indeterminate. This means that the value can be anything at run time. In this case, the values of a, b, c are random and the loop may or may not be entered based on the random values of a, b, c.

try -

int a = 0, b = 0, c;
ytibrewala
  • 957
  • 1
  • 8
  • 12
0

You declare variables a, b, c but you do not give them an initial value. That means that they have an indeterminate value. Right after declaring a and b with no value given, you go on and compare them in your while (a <= b) condition. C does not know how to compare these value-less variables apparently, so it skips your loop altogether. You could avoid this problem by giving int a = 0, b = 1 values initially. This way you make sure that the loop will at least run once.

What happens with uninitialized variables is explained in this other SO answer

Community
  • 1
  • 1
Freeman Lambda
  • 3,567
  • 1
  • 25
  • 33
  • thank you! However i have used programs without declaring a and b with values and the program worked. Could you please explain when you are supposed to declare these with values? – L.Kay Apr 27 '17 at 10:21
  • Please read this other answer on SO: http://stackoverflow.com/questions/4532871/define-integer-int-whats-the-default-value – Freeman Lambda Apr 27 '17 at 10:25