Answer to Question #307892 in C for John

Question #307892

You are given a binary compass which shows the direction you are safe to go to.


The binary compass read n binary digits (bits) which interprets 1 to rotate 90o


to


the left and 0 rotate 90o


to the right. Initially you are facing North. Create a program


for this binary compass.



Sample Output 1:


Enter your name: Glenn G. Noynay


Hi! Glenn G. Noynay


Enter number of bits: 7


Enter 7 binaries: 0 0 0 0 0 0 0


Direction: Go West, Glenn G. Noynay!



Sample Output 2:


Enter your name: Rogelio P. Noynay


Hi! Rogelio P. Noynay


Enter number of bits: 5


Enter 5 binaries: 1 1 1 0 1


Direction: Go East, Rogelio P. Noynay!

1
Expert's answer
2022-03-08T13:06:55-0500
#include <stdio.h>
#include <string.h>
#include <stdio.h>

int main() {
    char name[1024];
    int len;
    int n, i;
    int direction = 0;
    int bit;
    char* dir_name[4] = {"North", "East", "South", "West"};

    printf("Enter your name: ");
    fgets(name, 1024, stdin);
    len = strlen(name);
    if (name[len-1] == '\n') {
        name[len-1] = '\0';
    }

    printf("Hi! %s\n", name);
    printf("Enter number of bits: ");
    scanf("%d", &n);

    printf("Enter %d binaries: ", n);
    for (i=0; i<n; i++) {
        scanf("%d", &bit);
        if (bit != 0 && bit != 1) {
            fprintf(stderr, "Incorrect input\n");
            exit(1);
        }
        direction += bit ? -1 : 1;
    }
    direction %= 4;
    if (direction < 0) {
        direction += 4;
    }
    
    printf("Direction: Go %s, %s!\n", dir_name[direction], name);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS