Creates an array that stores character by character in c

Viewed 65

I'm trying to create an array that allows me to enter the characters depending on the number that the user has previously entered, if I enter 10 I only want the user to enter 10 characters, A or F. The problem is that it does not work as expected, when entering the number it sends me to the while loop and does not let me exit.

#include <stdio.h>

int main() {
    int i, students;
    char grade[100];

    printf("Welcome, enter the number of students to assign school grade: \n");
    scanf("%d", &students);

    printf("Enter A (Approved) or F (Failure)\n");
    for (i = 0; i < students; i++) {
        printf("School grade for student %d: \n", i + 1);
        scanf("%c", &grade[i]);
        while (grade[i] != 'A' || grade[i] != 'F') {
            printf("Please enter a valid school grade: ");
            scanf("%c", &grade[i]);
        }
    }
    return 0;
}

After I enter the number 10, the program skips the second scanf and sends me into the while loop.

Console error

By changing scanf("%c", &grade[i]) into scanf (" %c", &grade[i]), the problem is that now the while loop is held even when I enter A or F.

Console after put space in scanf

1 Answers

Logic error. Your loop condition is always true.

while (grade[i] != 'A' || grade[i] != 'F')

If the value is A then it is not F. And vice versa.

It looks like you want:

while (grade[i] != 'A' && grade[i] != 'F')

This would loop while any value that is not A or F is entered. It's logically equivalent to:

while (!(grade[i] == 'A' || grade[i] == 'F'))

Please read De Morgan's laws for more information.

Related