Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if file == 0 instead of NULL
Not checking the file pointer at all
✗ Incorrect
In C, fopen returns NULL if the file cannot be opened. Checking if file == NULL helps detect errors.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '=='
Not checking divisor before division
✗ Incorrect
To avoid division by zero, check if the divisor b is equal to zero before dividing.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking fgets result against EOF instead of NULL
Using 0 or -1 incorrectly
✗ Incorrect
fopen returns NULL on failure; fgets returns NULL on failure or end of file. Checking against NULL detects errors.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking malloc result
Returning 0 on error
✗ Incorrect
malloc returns NULL if memory allocation fails. Returning 1 indicates an error exit status.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking scanf result against 0
Not validating positive number
Returning 0 on error
✗ Incorrect
scanf returns the number of successfully read items, so it should be 1. Return 1 for error. Check if the number is greater than zero for positivity.