A character array of type char is entered manually. It is necessary then to make the check of each element equal to 1 or 0, if at least one of the array elements is not 0 or 1, then output Number is wrong.

My code looks like this, I can not understand what the error is:

#include <stdio.h> int main() { char str[10] = {0}; scanf("%s", str); for(int i = 0; i < 6; i++) { if(str[i] != 0 && str[i] != 1) printf("Number is wrong"); } system("pause"); return(0); } 
  • What is meant by 1 and 0? 1 and 0 ? Or '1' and '0' ? These are completely different things. - AnT 4:44 pm

1 answer 1

You are comparing a character with a number. It is necessary to compare the symbol with the symbol:

 if (str[i] != '0' && str[i] != '1') 

In addition, it is not clear why you chose line 6 as the size. Use the strlen() function:

 for (int i = 0; i < strlen(str); ++i) 
  • Yes indeed. Stupid mistake on my part, I corrected and everything turned out. Thank you very much! And can you tell me how you can make the conclusion of each element separately? - David
  • @David using a loop. In the example, the passage and verification of each character, and you need to display it on the screen. for (int i = 0; i < strlen(str); ++i) printf("%c", str[i]); - acade