Minor editing on C code

0 comments

#include<stdio.h>
#include<stdbool.h>
#define KEY_ARRAY_LENGTH 15
 
 
//takes size of an array and input to the array from user, takes a code from the user and then encodes the input array with a simple function, displaying the result.
 
void encode(int a[], int b[], int key[], int n){ //the encoding function. Populates the encoded array with the indices of the numbers in the key array that correspond to a number in the input array.
for(int i = 0; i < n; i++){
for(int j = 0; j < KEY_ARRAY_LENGTH; j++){
if(a[i] == key[j]){
b[i] = j;
}
}
}
}
 
int main(){
int input_size;
char key_input_array[KEY_ARRAY_LENGTH];
printf("please enter the size of your input array:");
scanf("%d", &input_size);
char input_array[input_size + 2];
printf("please enter your input array:");
while(fgets(input_array,(input_size+2), stdin) != NULL){
if(input_array[input_size] == 'n'){
input_array[input_size] = '';
break;
}
}
printf("please enter key array:");
if(fgets(key_input_array, KEY_ARRAY_LENGTH + 2, stdin) != NULL){
if(key_input_array[KEY_ARRAY_LENGTH] == 'n'){
key_input_array[KEY_ARRAY_LENGTH] = '';
}
}
int integer_input_array[input_size];
int key_array[KEY_ARRAY_LENGTH];
int encoded_array[input_size];
for(int i = 0; i < input_size; i++){
integer_input_array[i] = (input_array[i] - 48);
}
for(int i = 0; i < KEY_ARRAY_LENGTH; i++){
key_array[i] = (key_input_array[i] - 48);
}
encode(integer_input_array, encoded_array, key_array, input_size);
printf("your encoded array is:");
for(int i = 0; i < input_size; i++){
printf("%d", encoded_array[i]);
}
return 0;
}

Edit the code by replacing fgets with scanf 

About the Author

Follow me


{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}