Filipe, you have got to put the horse before the cart. Variables must be initialized with a value before you multiply them together. (in fact, attempting to access a value in an uninitialized variable invokes Undefined Behavior (that's bad....)
Just what do you expect to happen in the following code?
int num1, num2;
int num3 = num1 * num2;
What values are contained in num1
, num2
? What do you think will get put in num3
? In instances like this it is really a good idea to see How to debug small programs and talk to the duck... Really, it helps :)
Next there is unvalidated user input, e.g.
scanf ("%d", &num1);
What happens if the user enters "one"
(or a cat steps on the keyboard)? Always, always validate user input. scanf
returns the number of successful conversions that take place. In the case of "%d"
-- that's 1
if the command successfully places an integer value in num1
. A simple test can save a lot of grief, e.g.
printf ("Enter a number: ");
if (scanf ("%d", &num1) != 1) { /* validate ALL user input */
fprintf (stderr, "error: invalid input or user canceled.\n");
return 1;
}
By checking that the returns of scanf
is 1
, you protect against both matching and input failures (see: man scanf
).
Only after you have successfully placed values in num1
and num2
can you validly multiply num1
and num2
together, e.g.
num3 = num1 * num2; /* num1 & num2 must have values first */
Putting all the pieces together, the horse before the cart, and noting that main()
is type int
and therefore should return
a value [1], you could do something similar to the following:
#include <stdio.h>
int main (void) {
int num1, num2, num3;
printf ("Enter a number: ");
if (scanf ("%d", &num1) != 1) { /* validate ALL user input */
fprintf (stderr, "error: invalid input or user canceled.\n");
return 1;
}
printf ("Enter one more number: ");
if (scanf ("%d", &num2) != 1) { /* Ditto */
fprintf (stderr, "error: invalid input or user canceled.\n");
return 1;
}
num3 = num1 * num2; /* num1 & num2 must have values first */
printf ("The result of %d * %d is %d\n", num1, num2, num3);
return 0; /* main() is type int and returns a value. */
}
Example Use/Output
$ ./bin/multiply
Enter a number: 8
Enter one more number: 7
The result of 8 * 7 is 56
Look things over and let me know if you have further questions.
footnote[1] See: C11 Standard §5.1.2.2.1 Program startup (draft n1570). See also: See What should main() return in C and C++?