C CODE PLZ! Need all TO DO sections finished thanks #include <stdio.h> int main(int argc, char **argv) { const int BUF_LEN = 128; char str[BUF_LEN]; int i; char c; int is_binary; int d, n; /* Get the user to enter a string */ printf("Please enter a string made of 0s and 1s, finishing the entry by pressing Enter.\n"); for (i=0; i<BUF_LEN-1; i++) { scanf("%c", &c); if (c == '\n') { break; } str[i] = c; } str[i] = '\0'; /* Check if the user string contains nothing but 0s and 1s */ is_binary = 1; /* TODO */ /* Proceed only of the string contains only 0s and 1s */ if (is_binary) { /* Convert the string of 0s and 1s to an integer number n */ n = 0; /* TODO */ printf("The binary number %s is %d in decimal.\n", str, n); } else { printf("The string you entered, \"%s\", contains characters other than 0 and 1.\n", str); } return 0; }
//header files
#include <stdio.h>
//included this header file as pow function is in this header files
#import <math.h>
//main function
int main(int argc, char **argv) {
//string length
const int BUF_LEN = 128;
//array of characters str having capacity of BUF_LEN
char str[BUF_LEN];
//declaring variables
int i;
char c;
int is_binary;
int d, n;
/* Get the user to enter a string */
printf("Please enter a string made of 0s and 1s, finishing the entry by pressing Enter.\n");
for (i=0; i<BUF_LEN-1; i++) {
scanf("%c", &c);
if (c == '\n') {
break;
}
str[i] = c;
}
str[i] = '\0';
/* Check if the user string contains nothing but 0s and 1s */
is_binary = 1;
/* TODO */
//i is the number of characters in character array
//j going 0 to i-1
for(int j=0;j<i;j++)
{
//if the character at index j is neither 0 nor 1
if(str[j]!='0' && str[j]!='1')
{ //set is_binary to 0 which indicates that the string does not represent binary number
is_binary=0;
//go out of the loop
break;
}
}//loop ends
/* Proceed only of the string contains only 0s and 1s */
//if is_binary is 1
if (is_binary) {
/* Convert the string of 0s and 1s to an integer number n */
n = 0;
/* TODO */
//set d to 0 which points to the position of the first bits from the right side
d=0;
//j going from i-1 to 0 that means converting bits(from right side) to decimal and adding the results
for(int j=i-1;j>=0;j--)
{
//use this formula
//pow(2,d) which is 2 to the power d
//(int) will convert the character(either 0 or 1) to its ASCII value(integer)
//ASCII value of 1 is 49 and for 0 is 48 so here i am subtracting 48 from the ASCII value to get the real bit value
//1-0=1 that is 49-48=1
//0-0=0 that is 48-48 =0
//((int)str[j]-48) means the bit value at index j
n=n+pow(2,d)*((int)str[j]-48);
//incrementing position
d++;
}
//printing the decimal value
printf("The binary number %s is %d in decimal.\n", str, n);
}
//if is_binary is 0
else {
//print this message
printf("The string you entered, \"%s\", contains characters other than 0 and 1.\n", str);
}
return 0;
}
//main ends
Get Answers For Free
Most questions answered within 1 hours.