FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
} else {
printf("File opened successfully!\n");
fclose(fp);
}
Correct Answer: Opens a file “data.txt” for reading and prints success message if opened successfully
Explanation: The code snippet tries to open a file named “data.txt” for reading (`”r”` mode). If successful, it prints “File opened successfully!” and then closes the file stream using `fclose()`.
FILE *fp;
fp = fopen("output.txt", "w");
fprintf(fp, "Hello, World!");
fclose(fp);
Correct Answer: Closes the file “output.txt” after writing “Hello, World!” to it
Explanation: The code snippet opens a file “output.txt” for writing (`”w”` mode), writes “Hello, World!” to it using `fprintf()`, and then closes the file using `fclose()`.
char buffer[100];
FILE *fp;
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
} else {
fgets(buffer, sizeof(buffer), fp);
printf("Read from file: %s\n", buffer);
fclose(fp);
}
Correct Answer: Reads a line of text from a file “input.txt” and prints it to the console
Explanation: The code snippet opens a file “input.txt” for reading (`”r”` mode), reads a line of text using `fgets()` into the `buffer` array, and then prints the read content to the console.
int number = 42;
FILE *fp;
fp = fopen("output.txt", "w");
fprintf(fp, "The answer is %d\n", number);
fclose(fp);
Correct Answer: Prints “The answer is 42” to a file “output.txt”
Explanation: The code snippet opens a file “output.txt” for writing (`”w”` mode), formats a string “The answer is 42” with the value of `number` (42) using `fprintf()`, and writes it to the file. Then it closes the file using `fclose()`.
int num;
FILE *fp;
fp = fopen("data.txt", "r");
fscanf(fp, "%d", &num);
printf("Read number: %d\n", num);
fclose(fp);
Correct Answer: Reads an integer from a file “data.txt” and prints it to the console
Explanation: The code snippet opens a file “data.txt” for reading (`”r”` mode), reads an integer using `fscanf()` from the file into the variable `num`, and then prints the read number to the console.
FILE *fp;
fp = fopen("output.txt", "w");
putc('A', fp);
putc('B', fp);
putc('C', fp);
fclose(fp);
Correct Answer: Writes ‘A’, ‘B’, and ‘C’ to a file “output.txt”
Explanation: The code snippet opens a file “output.txt” for writing (`”w”` mode) and uses `putc()` to write characters ‘A’, ‘B’, and ‘C’ sequentially to the file. Then it closes the file using `fclose()`.
char ch;
FILE *fp;
fp = fopen("data.txt", "r");
while (!feof(fp)) {
ch = fgetc(fp);
if (!feof(fp)) {
printf("%c", ch);
}
}
fclose(fp);
Correct Answer: Tests the end-of-file indicator for a file
Explanation: The code snippet opens a file “data.txt” for reading (`”r”` mode), uses `feof()` inside a loop to test the end-of-file indicator for the file stream `fp`, and reads characters using `fgetc()` until the end of file is reached.
int status;
status = remove("output.txt");
if (status == 0) {
printf("File deleted successfully!\n");
} else {
printf("Error deleting file!\n");
}
Correct Answer: Deletes a file named “output.txt” from the file system
Explanation: The `remove()` function in `<stdio.h>` deletes a file named “output.txt” from the file system. The return value (`status`) will be 0 if the file is deleted successfully.
FILE *fp;
fp = fopen("data.txt", "r");
rewind(fp);
fclose(fp);
Correct Answer: Positions the file pointer at the beginning of the file “data.txt”
Explanation: The `rewind()` function in `<stdio.h>` positions the file pointer associated with `fp` at the beginning of the file “data.txt”, allowing subsequent operations to read from the start of the file.
FILE *fp;
fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
perror("Error opening file");
}
Correct Answer: Prints an error message to the standard output
Explanation: The `perror()` function in `<stdio.h>` prints an error message to the standard output (`stderr`) followed by the error message corresponding to the current value of `errno`. In this case, it will print “Error opening file: No such file or directory”.
Correct Answer: `strlen()`
Explanation: The `strlen()` function in `<string.h>` is used to calculate the length of a string in C, excluding the null-terminator.
Correct Answer: Copies a string from source to destination including null-terminator
Explanation: The `strcpy()` function in `<string.h>` copies a string from source to destination including the null-terminator.
Correct Answer: Compares two strings lexicographically up to a specified maximum length
Explanation: The `strncpy()` function in `<string.h>` copies up to a specified maximum number of characters from source to destination, ensuring null-termination if the maximum length allows.
Correct Answer: `strcat()`
Explanation: The `strcat()` function in `<string.h>` concatenates (appends) the string pointed to by the source to the end of the string pointed to by the destination. The destination string must have enough space to hold the concatenated result.
Correct Answer: Compares two strings lexicographically
Explanation: The `strcmp()` function in `<string.h>` compares two strings lexicographically (based on ASCII values of characters) and returns an integer less than, equal to, or greater than zero if the first string is lexicographically less than, equal to, or greater than the second string, respectively.
Correct Answer: Finds the first occurrence of a character in a string
Explanation: The `strchr()` function in `<string.h>` searches for the first occurrence of a specified character in a string and returns a pointer to the first occurrence of the character in the string, or NULL if the character is not found.
Correct Answer: `strstr()`
Explanation: The `strstr()` function in `<string.h>` searches for the first occurrence of the substring `needle` in the string `haystack` and returns a pointer to the beginning of the substring within the string, or NULL if the substring is not found.
Correct Answer: Splits a string into tokens based on delimiters
Explanation: The `strtok()` function in `<string.h>` splits the string into tokens based on delimiters specified in a separate string. It returns a pointer to the next token in the string, or NULL if no more tokens are found.
Correct Answer: Compares two strings lexicographically up to a specified maximum length
Explanation: The `strncpy()` function in `<string.h>` copies up to a specified maximum number of characters from source to destination, ensuring null-termination if the maximum length allows.
Correct Answer: `strcspn()`
Explanation: The `strcspn()` function in `<string.h>` returns the length of the initial segment of the string `str1` that consists of only the characters not found in the string `str2`.
char str1[] = "Hello";
char str2[] = "World";
strcat(str1, str2);
printf("%s\n", str1);
Correct Answer: Prints “HelloWorld”
Explanation: The code snippet concatenates (`strcat()`) the string `str2` to the end of `str1`, modifying `str1` to hold “HelloWorld”. It then prints `str1`.
char str[] = "Hello, World!";
int len = strlen(str);
printf("Length of the string: %d\n", len);
Correct Answer: Prints the length of the string “Hello, World!”
Explanation: The code snippet calculates the length of the string `str` using `strlen()` and prints the length, which is 13 characters including the null-terminator.
char str[] = "Hello, World!";
char *ptr = strchr(str, ',');
if (ptr != NULL) {
printf("Found comma at position: %ld\n", ptr - str);
} else {
printf("Comma not found in the string.\n");
}
Correct Answer: Finds the first occurrence of character ‘,’ in the string and prints its position
Explanation: The code snippet uses `strchr()` to find the first occurrence of ‘,’ in the string `str`. It prints the position of ‘,’ relative to the start of the string `str`.
char str[] = "Hello,World,,from,C Programming";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
Correct Answer: Splits the string into tokens based on comma delimiters and prints each token
Explanation: The code snippet uses `strtok()` to split the string `str` into tokens based on ‘,’ delimiters. It prints each token until no more tokens are found (`token` becomes NULL).
char str1[] = "Programming";
char str2[] = "ming";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("String str1 is less than str2.\n");
} else {
printf("String str1 is greater than str2.\n");
}
Correct Answer: Compares two strings lexicographically and prints if they are equal
Explanation: The code snippet uses `strcmp()` to compare `str1` ("Programming") with `str2` ("ming"). It prints whether `str1` is equal to, less than, or greater than `str2` based on ASCII values of characters.
char str[] = "Hello, World!";
char *ptr = strstr(str, "World");
if (ptr != NULL) {
printf("Substring 'World' found in '%s'\n", str);
} else {
printf("Substring 'World' not found in '%s'\n", str);
}
Correct Answer: Searches for the substring "World" in the string and prints if found
Explanation: The code snippet uses `strstr()` to search for the substring "World" in the string `str`. It prints whether the substring is found or not.
char str[] = "This is a test";
size_t len = strcspn(str, "aeiou");
printf("Length of initial segment without vowels: %zu\n", len);
Correct Answer: Calculates the length of the initial segment without vowels and prints it
Explanation: The code snippet uses `strcspn()` to calculate the length of the initial segment of `str` that consists of characters not in the string "aeiou". It then prints the length.
char str[] = "Hello, World!";
strncpy(str, "Goodbye", 7);
printf("%s\n", str);
Correct Answer: Copies "Goodbye" to `str` up to 7 characters
Explanation: The code snippet uses `strncpy()` to copy the string "Goodbye" to `str` up to 7 characters or until a null-terminator is encountered. It then prints `str`.
char str[] = "Hello, World!";
size_t len = strspn(str, "Hello");
printf("Length of initial segment with 'Hello': %zu\n", len);
Correct Answer: Calculates the length of the initial segment of `str` that consists of characters in "Hello"
Explanation: The code snippet uses `strspn()` to calculate the length of the initial segment of `str` that consists of characters in the string "Hello". It then prints the length.
char str[] = "Hello, World!";
char *ptr = strrchr(str, 'o');
if (ptr != NULL) {
printf("Last occurrence of 'o' is at position: %ld\n", ptr - str);
} else {
printf("Character 'o' not found in '%s'\n", str);
}
Correct Answer: Finds the last occurrence of character 'o' in the string and prints its position
Explanation: The code snippet uses `strrchr()` to find the last occurrence of 'o' in the string `str` and prints its position relative to the start of `str`.
Correct Answer: All of the above
Explanation: In C, `malloc()`, `calloc()`, and `realloc()` are used for dynamic memory allocation depending on the specific requirements of the program.
Correct Answer: Allocates memory for an array of elements, leaving the allocated memory uninitialized
Explanation: The `malloc()` function allocates a specified number of bytes of memory and returns a pointer to the allocated memory block. The allocated memory is uninitialized and should be initialized before use.
Correct Answer: Allocates memory for an array of elements, initializing all bytes to zero
Explanation: The `calloc()` function allocates memory for a specified number of elements of a specified size, initializing all bytes to zero, and returns a pointer to the allocated memory block.
Correct Answer: Resizes a previously allocated block of memory
Explanation: The `realloc()` function in C reallocates (resizes) a previously allocated block of memory, possibly moving it to a new location, and returns a pointer to the reallocated memory block.
Correct Answer: Returns a NULL pointer
Explanation: If `malloc()` or `calloc()` fails to allocate memory, they return a NULL pointer, indicating that the allocation request could not be fulfilled.
Correct Answer: To resize an existing dynamically allocated memory block
Explanation: `realloc()` in C is used to resize (expand or shrink) an existing dynamically allocated memory block to accommodate more or fewer elements as needed.
Correct Answer: `malloc()` allocates memory for a single element; `calloc()` for multiple elements
Explanation: `malloc()` allocates memory for a single element, whereas `calloc()` allocates memory for a specified number of elements, initializing all bytes to zero.
Correct Answer: To deallocate a block of memory previously allocated with `malloc()`, `calloc()`, or `realloc()`
Explanation: The `free()` function in C deallocates (frees) a block of memory that was previously allocated dynamically using `malloc()`, `calloc()`, or `realloc()`.
Correct Answer: `memset()`
Explanation: The `memset()` function in C is used to initialize a block of memory to a specific value, typically zero or some other specified byte pattern.
int *ptr;
ptr = (int *)malloc(5 * sizeof(int));
if (ptr != NULL) {
for (int i = 0; i < 5; ++i) {
ptr[i] = i + 1;
}
printf("Array elements: ");
for (int i = 0; i < 5; ++i) {
printf("%d ", ptr[i]);
}
printf("\n");
free(ptr);
} else {
printf("Memory allocation failed.\n");
}
Correct Answer: Allocates memory for an array of 5 integers, initializes them, prints them, and deallocates the memory
Explanation: The code snippet allocates memory for an array of 5 integers using `malloc()`, initializes the array elements, prints them, and then deallocates the allocated memory using `free()`.
#include <stdio.h>
#include <math.h>
int main() {
double x = 2.0, result;
result = sqrt(x);
printf("Square root of %.1f is %.4f\n", x, result);
return 0;
}
Correct Answer: Computes the square root of 2.0 and prints the result
Explanation: The code snippet includes `<math.h>` to use the `sqrt()` function, which computes the square root of `x` (2.0 in this case) and prints the result.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n = 5;
arr = (int *)malloc(n * sizeof(int));
if (arr != NULL) {
for (int i = 0; i < n; ++i) {
arr[i] = i + 1;
}
printf("Array elements: ");
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
} else {
printf("Memory allocation failed.\n");
}
return 0;
}
Correct Answer: Allocates memory for an array of 5 integers, initializes them, prints them, and deallocates the memory
Explanation: This code snippet dynamically allocates memory for an array of 5 integers using `malloc()`, initializes the array elements, prints them, and then deallocates the allocated memory using `free()`.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
Correct Answer: Splits the string into tokens based on comma delimiters and prints each token
Explanation: The code snippet uses `strtok()` from `<string.h>` to split the string `str` into tokens based on ',' delimiters and prints each token until no more tokens are found (`token` becomes NULL).
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("Sorted array: ");
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Correct Answer: Sorts the array using quicksort algorithm
Explanation: The code snippet uses `qsort()` from `<stdlib.h>` with a comparison function `compare()` to sort the array `arr` in ascending order using the quicksort algorithm and prints the sorted array.
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
if (isalpha(ch)) {
if (isupper(ch)) {
printf("%c is an uppercase alphabet.\n", ch);
} else {
printf("%c is a lowercase alphabet.\n", ch);
}
} else {
printf("%c is not an alphabet character.\n", ch);
}
return 0;
}
Correct Answer: Checks if `ch` is an uppercase alphabet and prints the message accordingly
Explanation: The code snippet uses `isalpha()` and `isupper()` from `<ctype.h>` to check if `ch` is an alphabet character and if it is uppercase, then prints a message accordingly.
#include <stdio.h>
#include <math.h>
int main() {
double x = 3.14, y = 2.71, result;
result = pow(x, y);
printf("%.2f raised to the power %.2f is %.4f\n", x, y, result);
return 0;
}
Correct Answer: Computes 3.14 raised to the power 2.71 and prints the result
Explanation: The code snippet includes `<math.h>` to use the `pow()` function, which computes `x` raised to the power `y` (3.14 raised to the power 2.71 in this case) and prints the result.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Correct Answer: Concatenates the strings "Hello" and "World" and prints the result
Explanation: The code snippet uses `strcat()` from `<string.h>` to concatenate `str2` ("World") to the end of `str1` ("Hello"), modifying `str1` to hold "HelloWorld", which is then printed.
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int arr[] = {9, 5, 2, 7, 1, 3, 8, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("Sorted array: ");
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Correct Answer: Sorts the array using quicksort algorithm
Explanation: The code snippet uses `qsort()` from `<stdlib.h>` with a comparison function `compare()` to sort the array `arr` in ascending order using the quicksort algorithm and prints the sorted array.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello123";
int i = 0;
while (str[i]) {
if (isdigit(str[i])) {
printf("%c is a digit.\n", str[i]);
}
i++;
}
return 0;
}
Correct Answer: Checks if each character in `str` is a digit and prints it if true
Explanation: The code snippet uses `isdigit()` from `<ctype.h>` to iterate through each character in `str` ("Hello123") and prints the character if it is a digit.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C Programming Language";
char *ptr = strchr(str, 'm');
if (ptr != NULL) {
printf("Character 'm' found at position: %ld\n", ptr - str);
} else {
printf("Character 'm' not found in '%s'\n", str);
}
return 0;
}
Correct Answer: Finds the first occurrence of character 'm' in the string and prints its position
Explanation: The code snippet uses `strchr()` from `<string.h>` to find the first occurrence of 'm' in the string `str` ("C Programming Language") and prints its position relative to the start of `str`.