C program (string - binary to decimal conversion)

AI Thread Summary
The C program for converting a binary string to decimal contains several issues, including incorrect loop conditions and missing braces. The loop is incorrectly set to iterate from 32 to 0, which should be reversed to properly process the string. Additionally, the program does not compile due to a missing closing brace for the main function. Suggestions include declaring variables on separate lines for clarity and using standard functions like getchar() instead of nonstandard ones like getch(). Overall, the code needs corrections in logic and syntax to function properly.
clook
Messages
32
Reaction score
0
here's what i have:

Code:
#include<stdio.h>
#include<string.h>
main() {
char string[32];
int sum = 0;
int a = 1;
int i;
printf("Please enter numbers:\n");
gets(string);
for (i=32;i<0;i--)
{
if(string[i] ==1)
{ sum = sum + a;
}
a = a * 2;
printf("The converted string is: %s \n", string[i]);
}

won't compile.. says "compound" statement is missing at the end.

what am i doing wrong?



Homework Equations





The Attempt at a Solution

 
Physics news on Phys.org
Count the number of left and right braces {}. You just spaced the one at the end of the main().
 
have you noticed one thing...that 1)in the program you have opened three braces and two closed braces{}, 2)why don't you declare as
int sum=o,a=1,i; 3)why don't you prefer to use getch( ); before the ending brace.
 
2)why don't you declare as
int sum=o,a=1,i;
It's a matter of style. Some prefer not to declare many things on one line, especially if there are initializers or modifiers involved.

3)why don't you prefer to use getch( ); before the ending brace.
(A) There's no reason to wait for a keypress
(B) getch is a nonstandard extension to the C language. You can only use it if you happen to be using a compiler or library that defines it. (Why not use getchar() instead?)
 
Did your teacher ever mention strtoul() ?
 

Similar threads

Replies
7
Views
2K
Replies
12
Views
2K
Replies
3
Views
1K
Replies
2
Views
2K
Replies
12
Views
2K
Replies
2
Views
2K
Back
Top