0
0
Cprogramming~10 mins

Why error handling is needed in C - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the file opened successfully.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "r");
    if (file == [1]) {
        printf("Failed to open file.\n");
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
ANULL
B0
C1
DEOF
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if file == 0 instead of NULL
Not checking the file pointer at all
2fill in blank
medium

Complete the code to handle division by zero error.

C
#include <stdio.h>

int main() {
    int a = 10, b = 0;
    if (b [1] 0) {
        printf("Error: Division by zero!\n");
    } else {
        printf("Result: %d\n", a / b);
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A==
B!=
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '=='
Not checking divisor before division
3fill in blank
hard

Fix the error in the code to properly handle file reading errors.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("input.txt", "r");
    char buffer[100];
    if (file == [1]) {
        perror("Error opening file");
        return 1;
    }
    if (fgets(buffer, sizeof(buffer), file) == [2]) {
        perror("Error reading file");
    }
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
A-1
BEOF
C0
DNULL
Attempts:
3 left
💡 Hint
Common Mistakes
Checking fgets result against EOF instead of NULL
Using 0 or -1 incorrectly
4fill in blank
hard

Fill both blanks to handle memory allocation errors.

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

int main() {
    int *ptr = (int *)malloc(sizeof(int) * 10);
    if (ptr == [1]) {
        printf("Memory allocation failed.\n");
        return [2];
    }
    free(ptr);
    return 0;
}
Drag options to blanks, or click blank then click option'
ANULL
B1
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking malloc result
Returning 0 on error
5fill in blank
hard

Fill all three blanks to handle user input errors safely.

C
#include <stdio.h>

int main() {
    int number;
    printf("Enter a number: ");
    if (scanf("%d", &number) != [1]) {
        printf("Invalid input!\n");
        return [2];
    }
    if (number [3] 0) {
        printf("You entered: %d\n", number);
        return 0;
    }
    printf("Number must be positive.\n");
    return 1;
}
Drag options to blanks, or click blank then click option'
A0
B1
C>
Attempts:
3 left
💡 Hint
Common Mistakes
Checking scanf result against 0
Not validating positive number
Returning 0 on error