I want to write a C program that evaluates the factorials of the integers from 1 to 5 and print them in a tabular format. However, I keep getting a strange number over everythin
Unlike scanf
, printf()
with format %d
requires integer values, not addresses (&x
is the address containing an integer, so a pointer to integer which type is int *
). The correct expression is
printf("%d\t %d\n", x, factorial);
With printf("%d\t %d\n", &x, &factorial);
you are asking to printf to print the decimal representations of the addresses of x
and factorial
respectively.
For this reason it is not surprising that the values that used to be printed, 6356768
and 6356772
:
You can find printf
documentation here.
Remove &
which stands for address of. You are printing address of the variable, not its value.
printf("%d\t %d\n", x, factorial);
When using printf
(and related output functions), the %d
format specifier expects an int
as the corresponding argument. In your printf("%d\t %d\n", &x, &factorial);
you are passing the addresses of the x
and factorial
variables.
So, just remove the two &
(address of) operators: printf("%d\t %d\n", x, factorial);
!
You are possibly being confused by the fact that, for scanf
(and other input functions), the %d
specifier requires a pointer to its target variable.
In the statement printf("%d\t %d\n", &x, &factorial); you have used '&' which prints the address of that element.
printf("%d\t %d\n", &x, &factorial); &x and &factorial are addresses of those variables, not the variables themself. Omit the &.