Hector Sanabria Hector Sanabria - 1 year ago 59
C Question

Error when using array elements in conditional statements in C

I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.

From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.

Here is the code:

#include <stdio.h>

int power (int x, int y); //prototype

int main(void)
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);

//initialize array
temp %= power(10,n);

//update to question:
if ((bin[test]!=0)&&(bin[test]!=1)){
printf("Error, number entered was not binary.\n");
return 0; }

n--; }

//convert to decimal
n++; }

printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;

//function definition
int power(int x, int y)
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;

Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.

Update: I moved the if statement back to the while loop before. This should still work right? But I get an error message

sps sps
Answer Source

One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.

for (test=4; test>=0; test--){
    if ((bin[test]!=0)&&(bin[test]!=1))
        printf("Error, numbered entered was not binary.\n");
        // Issue here, you are returning outside if
        return 0; }  //exit program 

You can change that to:

for (test=4; test>=0; test--){
    if ((bin[test]!=0)&&(bin[test]!=1)) {
         printf("Error, numbered entered was not binary.\n");
         // Return inside the if
         return 0; // exit program
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download