dec is not initialized.
- '0' is inappropriate because a[j] is a bit (0 or 1), not a character code ('0' or '1').
Either j is not needed (you can use 31-i) or it is not calculated correctly (should start at 31 and work down to 0 while i starts at 0 and works up to 31, or j can be calculated from i in each iteration).
With those errors corrected, the program produces the desired output. However, there are a number of other issues regarding the correct declaration of main and certain aspects of style, so here is a new version addressing some of them:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
// Declare main as "int main(void)" or "int main(int argc, char *argv[])".
int main(void)
{
uint32_t f;
int a[32] = { 0 };
/* Do not declare identifiers where you do not need them. This avoids
various errors that can occur where things are mistakenly used where
they were not intended.
i is used only in loops, so it is declared only inside those loops.
dec is only needed after some other work, so it is declared later.
j is not needed at all.
*/
printf("Enter a value:");
/* Do not put a space between a function and the parentheses for its
arguments.
*/
scanf("%" SCNu32, &f);
// Use more spaces; do not crowd symbols together.
for (int i=0; f>0; i++) // Or "for (int i = 0; i > 0; i++)".
/* Indent a loop body more than the code it is in; do not put { and }
further to the left and keep the loop body at the same indentation as
the code it is in.
*/
{
a[i] = f%2;
f = f/2;
}
printf("\nBinary number (LSB) is = ");
for (int i=0; i<=31; i++)
printf("%d", a[i]);
printf("\n");
/* Put blank lines in transitions between code that finishes one task,
like printing output, and code that starts another task, like
converting to binary.
*/
int dec = 0; // Declare dec here, just before it is needed.
for (int i=31; i>=0; i--)
{
/* Remove "- '0'" here. a[j] is a bit (0 or 1), not a character code
('0' or '1').
Do not use j. This loop has a counter, i. Using two counters for
different things may have confused you. While you want i to run
from 0 to 31, you want j to run from 31 to 0. You could use a
separate j for this, but it is easily replaced by 31-i.
*/
dec = dec + (1u << i) * a[31-i];
}
// Include spaces in output, like after the colon, to avoid crowding.
/* Print a "\n" at the end of each line of output. C is designed to use
"\n" to end lines, not to start them, because "\n" causes output to be
sent to interactive devices immediately instead of buffered.
*/
printf("The decimal representation: %u\n", dec);
return 0;
}
decvariable. Changeint dec, j = 0;toint dec = 0, j = 0;49mentioned is, curiously, the ASCII value for'1'.- '0'indec = dec + (1u << i) * (a[j] - '0');looks a bit spurious.int dec, j = 0;toint dec = 0, j = 0;the difference is now48instead of49and I guess that is the ASCII value of0?a[j]value? You never add an ASCII value to that when you form theaarray.