FIREHIVE - 10 days ago 4x
C Question

# From-keyboard array of 1 and 0

I want to make a program that applies AND OR and XOR from logic class to 2 arrays of 1 and 0 (bits) . The problem is I don't know how to make the arrays to store only 1 and 0 , for exemple if I give from keyboard an element 5 for array I want the program to tell me it's not 0 and 1 and start again to let me give elements , I tried something but it's not working..

``````int v1[50],v2[50],i,j,n;
printf("Number of elements in arrays : ");
scanf("%d",&n);

printf("Introduce elements of first array :\n");

for(i=0;i<n;i++)
if(v1[i] == 0 || v1[i]==1)
scanf("%d",&v1[i]);
else (i'll make it a function and I want it to repeat if the elements given are not 1 and 0)

for(i=0;i<n;i++)
printf("%d",v1[i]);
``````

Answer

In your first for loop, where you are reading the input, you should read the input first, and then decide whether you want to have the user try the input again. So, the first few lines of your for loop should look like this:

``````for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
//Ask for another input, but do not advance i
}
}
``````

This code will tell the user if they inputted a bad character, but it will not update the array correctly. To do this, all you need to do is decrement i once. This will make the previous "bad" value in `v1` get overwritten.

``````for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
``````

We are not done, however. In your original code, you defined v1 to be an array of 50 elements. What if someone wants to input 51 elements? You would eventually end up with accessing an array index that is out of bounds, which could lead to some very big issues. So, you need to do some dynamic memory allocation using `malloc`

``````int *v1, i, n;

printf("How many elements will be in the bit array? ");
scanf("%d", &n);

//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));
``````

You can read more about malloc here. So, the whole code would look like this:

``````#include <stdlib.h>
#include <stdio.h>

int main() {
int *v1, i, n;

printf("How many elements will be in the bit array? ");
scanf("%d", &n);

//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));

printf("Input the elements of the first array (separated by newlines):\n");

for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
``````
Source (Stackoverflow)
Comments