50 Best Multiple Choice Questions for C Programming

C Programming Language Overview

C is a popular procedural programming language that is commonly used in the development of operating systems. It is also the precursor to C++, which is widely utilized today. Some of the language's noteworthy features include its simplicity, efficient memory usage, utilization of pointers, fast execution speed, structured programming language, mid-level programming language, portability across machines, and rich user library.

Components of a C Program

The main components constituting a C program are:

  • Header Files: A header file is a file with an extension .H that contains C function declarations and macros. These are intended to be shared between numerous source files, which allows for reusability and greater efficiency in programming logic development.
  • Main Method: The main method is a function that marks the starting point for program execution in C.
  • Program Body: The program body is the primary part of the program in which all programming logic is composed. It encompasses all variable declarations, program logic (loops, conditional statements, function calls, etc.), and the return statement that terminates the program.
//example of C code

Range of int datatype in C

In C programming language, the int datatype can represent whole numbers within the range from -(2^31) to (2^31) - 1. This range can also be represented as -2147483648 to 2147483647. Integers outside of this range may result in overflow or undefined behavior.


int minValue = -2147483648;
int maxValue = 2147483647;

H3. Code Output

The output of the code snippet will be:

5 3

Initializing an Array in C Language

In C language, an array can be initialized at the time of declaration by using braces ({}) and assigning the values inside separated by commas. The correct syntax for initializing an array in C language would be:

int a[3] = {1, 2, 3};

This creates an integer array named 'a' with size 3 and initializes the first element with the value 1, the second element with the value 2, and the third element with the value 3. Option A is the correct way of initializing an array in C language.Unfortunately, the code snippet provided in the question is incomplete. It appears that the code has been cut off mid-statement. Without the full statement, it is impossible to accurately determine the output of the code. Could you please provide the full code snippet so that I can assist you better? Thank you!

Code Output Determination

C
#include <stdio.h>
int main() {
    int sum = 2 + 4 / 2 + 6 * 2;
    printf("%d", sum);
    return 0; 
}

The output of the above C program is 16.

Explanation: The expression in the given code (`sum = 2 + 4 / 2 + 6 * 2`) involves addition, multiplication, and division. According to the order of operations, multiplication and division should be performed first, followed by addition and subtraction. Therefore, "4/2" is simplified to 2, and "6*2" is simplified to 12. Then, the expression becomes `2 + 2 + 12 = 16`. Finally, the value 16 is printed to the console output using `printf` statement.

Accessing the 3rd Element in an Array with Pointer Notation

In order to access the 3rd element in an array using pointer notation, you would use the expression *(a + 3).

This is because *(a + 3) is equivalent to a[3] in C. Basically, you're adding 3 to the address of the first element in the array and then dereferencing the resulting pointer to obtain the value stored at that memory location.

So if you have an array declared as int a[] = {1, 2, 3, 4, 5};, *(a + 3) would give you the value 4.

It's important to note that the parentheses around (a + 3) are necessary to ensure that the addition is performed before the dereferencing.

Representation of Strings in Memory in C

In C programming language, a string is internally represented as an array of characters. The array may contain null character '\0' at the end to mark the termination of the string.

This representation allows us to manipulate strings in a way similar to other arrays. We can traverse through each character, access or modify a specific character, etc.

Example code to define and initialize a string in C:


    char str[50] = "Hello World!";

Here, we have defined a character array 'str' with size 50 and initialized it with the string "Hello World!".

It's worth noting that C does not have a dedicated 'string' data type like many other programming languages. Instead, programmers use character arrays to represent strings and manipulate them using built-in string functions or user-defined functions.As the given code is incomplete, it is not possible to predict the output of this code. The code has opened a for loop but did not close it. Additionally, It is missing the curly brace and semicolon outside the for loop. The code is also missing the standard header files.

A possible completed version of this code could be:


#include <iostream>
using namespace std;

void solve() {
    int a[] = {1, 2, 3, 4, 5};
    int sum = 0;
    for(int i = 0; i < 5; i++) {
        sum += a[i];
    }

    cout << "The sum is: " << sum << endl;
}

int main() {
    solve();
    return 0;
}

This code initializes an integer array `a` with values {1, 2, 3, 4, 5} and calculates the sum of all the elements using a for loop. It then prints out the sum as output.

The output of the above code snippet will be:


The sum is: 15

Solution:

The output of the code snippet will be "10 30".

Explanation:

In the given code snippet, a function named "solve" is defined which has two variables "first" and "second" initialized with values 10 and 20 respectively. A third variable named "third" is initialized as the sum of the first two variables.

Inside the curly braces "{}", a new variable "third" is declared and initialized as the difference between the second and the first variable i.e. 20-10, hence the value of "third" becomes 10. Then, this local variable "third" is printed using the printf function which prints the value of the variable followed by a space. So, "10" is printed to the console.

After the curly braces, the global "third" variable is printed using the printf function which again prints "30" to the console, followed by a new line because there is no space given in printf function before the second parameter.

Therefore, the final output of this code will be "10 30".

Disadvantage of Arrays in C

One disadvantage of arrays in C is that the amount of memory to be allocated must be known beforehand. This can be problematic in cases where the size of the array needs to be adjusted dynamically at runtime.

However, arrays have several advantages such as constant time access to elements and the ability to store elements in contiguous memory blocks. Additionally, arrays can be used to implement multiple other data structures.

//example code of array declaration and initialization
int arr[5] = {1, 2, 3, 4, 5};

Understanding post and pre increment operators in C++

The output of the code will be 20.

Explanation:

In the solve() function, we have initialized the integer variable 'a' to 3.

Next, we have used post-increment operator 'a++' and pre-increment operator '++a' in an expression along with the 'a' variable.

Here is how the operators in the expression will be resolved:

- a++ is evaluated first which returns 3 and then increments the value of a to 4.

- ++a increments the value of a from 4 to 5 and returns 5.

- a++ is evaluated again which returns 5 and then increments the value of a to 6.

- ++a increments the value of a from 6 to 7 and returns 7.

Now, the final expression will be resolved as follows:

3 + 5 + 5 + 7 = 20

Therefore, the output of the code will be 20.H3 tag: Code Output

Hello 5

H3 tag: Solution

The value of x in the given code snippet will be 5. At the line `int x = printf("Hello");`, the `printf` function returns the number of characters printed which is `5` for the string "Hello". This value is then assigned to the `x` variable. So, when we print the value of `x` using the `printf` function at the line `printf(" %d", x);`, it will print `5` as the output.

Understanding the Declaration int x: 8;

The declaration "int x: 8;" indicates that the variable "x" is an integer that can store a maximum value of 8. In C programming language, this is a way to declare a bit-field variable, which is a part of a larger data structure and requires a certain number of bits to store the data.

Therefore, the correct answer is B, which means that "x" is an 8-bit integer.

Proper Syntax for Declaring Macros in C

In C, the proper syntax for declaring macros is using the #define preprocessor directive. The general syntax for declaring macros is as follows:


#define MACRO_NAME replacement_text

To declare a macro that represents `long long`, the correct syntax would be:


#define ll long long

Therefore, option B is the correct answer.

Identification of an Exit-Controlled Loop

In programming, a loop is a set of instructions that are repeatedly executed until a certain condition is met. Looping constructs can be either exit-controlled or entry-controlled.

An exit-controlled loop runs until the condition is true. In this type of loop, the condition is evaluated at the end of each iteration.

The do-while loop is an example of an exit-controlled loop. By contrast, a for loop and a while loop are entry-controlled loops.

Therefore, the answer is C. The do-while loop is an exit controlled loop.

Size of int data type in C

The int data type in C has a size of 4 bytes.

int size = sizeof(int); // size will be 4

# Code Explanation #

The given C code defines a `swap` function that takes two integer pointers as input arguments and swaps their values. The `solve` function initializes two integer values `a` and `b`. It calls the `swap` function by passing the memory addresses of `a` and `b` as arguments. Finally, the `printf` statement prints the values of swapped integers.

The output of the program will be `5 3`, which corresponds to the swapped values of `a` and `b`.

How to Declare a Double-Pointer in C?

In C, to declare a double-pointer, we use the syntax "int **val". This indicates that the variable "val" is a pointer to a pointer of an integer. For example:

Code:


int num = 10;
int *ptr1 = &num; // pointer to an integer
int **ptr2 = &ptr1; // pointer to a pointer to an integer

Here, "ptr1" is a pointer to an integer variable "num". And "ptr2" is a pointer to a pointer to an integer, which points to "ptr1". We can access the value of "num" using both "ptr1" and "ptr2" as shown below:

Code:


printf("%d\n", *ptr1); // Output: 10
printf("%d\n", **ptr2); // Output: 10

Note that the double-pointer is helpful when we want to access a pointer that points to an integer or an array of integers.

Pointer Arithmetic in C

Pointer arithmetic is the arithmetic performed on a pointer variable that holds the memory address of another variable. If p is an integer pointer with a value 1000, then adding 5 to p will increment its address location by 5 times the size of an integer, i.e., 4 bytes on most systems, resulting in the incremented address location of 1020. Therefore, the answer is:

1020


Output of code snippet with macro in C

The output of the provided code snippet is 34. This is because of the macro definition of `VAL` with the expression `3 * (2 + 6)` which is then used in the main function while computing the value of `a` by adding VAL with 10, i.e., `int a = 10 + VAL` leads to `int a = 10 + 3 * (2 + 6)` which results in `a` having the value of 34 after the computation. Finally, `printf("%d", a)` statement is used to print the value of `a` which is 34.

Identifying Standard Header Files in C

Code:

c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main() {
   printf("All header files mentioned are valid header files in C.\n");
   
   return 0;
}

The given code confirms that all the header files mentioned in the options are standard header files in C. Therefore, the correct answer is option D, "None of the above."

The output of the code snippet will be:

19 23

Explanation: The number 023 is interpreted as an octal number in C programming language. Its decimal equivalent is 19. Therefore, 19 and 23 will be printed on the console.

Understanding different number bases in C programming

The code snippet will output: 62 28 135.

Explanation: The values in the printf statement are being printed using different number bases.

- The first value (076) is written in octal base, and its decimal equivalent is (7 * 8^1) + (6 * 8^0) = 62. - The second value (28) is written in decimal base, so its value remains 28. - The third value (0x87) is written in hexadecimal base, and its decimal equivalent is (8 * 16^1) + (7 * 16^0) = 135.

Therefore, the output will be "62 28 135".Unfortunately, the code snippet provided in the prompt is incomplete and ends abruptly. It is not possible to determine what the result of the code would be without having access to the full code. Can you please provide the complete code so that I may assist you better? Thank you.# Missing Title ## Code:

c
#include <stdio.h>
#include <stdbool.h> // include standard bool header

void solve() {
    bool ok = false;
    printf(ok ? "YES" : "NO"); // using ternary operator to print YES if ok is true else NO.
}

int main() {
    solve();
    return 0;
}

The output of the above code will be "NO".

The code includes the header file `stdbool.h` which defines the boolean data type in C.

The `solve()` function initializes the boolean variable `ok` to false and then uses the ternary operator to print "YES" if `ok` is true and "NO" if `ok` is false. Since `ok` is initialized to false, the program will print "NO" when executed.

There are no compilation errors in this code snippet.

Function Overloading in Programming Languages

Function Overloading is a feature in Object-Oriented languages that allows you to use the same function name with different input parameters. This can help to reduce similar code and improve the readability of the code. However, function overloading is not possible in all programming languages.


// Example of Function Overloading in C++
#include <iostream>
using namespace std;

void print(int a){
   cout << "Printing integer: " << a << endl;
}

void print(double  b){
   cout << "Printing float: " << b << endl;
}

int main( ){
   print(42);
   print(3.14159);
   return 0;
}

Out of the given languages, C does not support function overloading as it is not an object-oriented language. Therefore, in C, you must use unique function names for each function that performs a different task.

C++ Function to Open a File

In C++, the

fopen

function is used to open a file. It takes two parameters: the name of the file and the mode in which the file is to be opened. For example, to open a file named "example.txt" in read mode, the code would be:

FILE *fp;
fp = fopen("example.txt", "r");

This will create a file pointer

fp

that points to the beginning of the file.

Remember to always close the file when you're finished using it with the

fclose

function:

fclose(fp);

Other file-related functions like

fseek

,

fgets

and many others are used to manipulate and read data from the file.

Valid File Opening Modes in C

In C, the following are valid modes to open a file:

r

Open for reading. The file must already exist.

rb

Open a binary file for reading. The file must already exist.

w

Open for writing. If the file already exists, it will be truncated to zero length. If the file doesn't exist, a new file will be created.

Therefore, option D - "All of the above" - is the correct answer.

Explanation:

In C programming language, the return type of the fopen() function is a pointer to a FILE object. This FILE object is used to handle and control input and output operations on a file that is pointed by the file pointer. The FILE object contains information about the opened file, including its name, location, permissions, and other details.

Therefore, to use the contents of a file in a C program, we need to use the fopen() function to open the file in read or write mode. The returned file pointer is then used in various other functions to read from or write to the file.

Example:


FILE *fp; // declaring the file pointer 
fp = fopen("file.txt", "r"); // opening a file for reading 

# Understanding switch fall-through

The given code defines a function `solve()` that initializes an integer variable `ch` to 2 and uses it in a switch statement. The switch statement contains several cases and a default case. However, there are no break statements in cases 1, 2, and 3, which means that control will fall through to subsequent cases until a break statement is encountered.

The `main()` function just calls the `solve()` function and returns 0.

Therefore, the output of the code will be:

2 3 None

This is because the value of `ch` is 2, which matches case 2, and so "2 " is printed. However, since case 2 does not have a break statement, control falls through to case 3, which also prints "3 ". However, case 3 also does not have a break statement, so control falls to the default case, which prints "None".

If we had included breaks in each case, the output would have been "2".Code:

c
#include <stdio.h>
void compareNumbers() {
    int x = 1, y = 2;
    if(x > y) {
        printf("Greater");
    } else if (x == y) {
        printf("Equal");
    } else {
        printf("Lesser");
    }
}
int main() {
    compareNumbers();
    return 0;
}

Output:


Lesser

**Explanation:**

The given code uses a ternary operator to compare two variables x and y. It prints "Greater" if x is greater than y, "Equal" if x equals y, and "Lesser" if x is less than y.

However, the correct output should be "Lesser" since x is less than y. Instead of using the ternary operator, we can use an if-else statement to compare x and y and print the correct output.

We have renamed the function to `compareNumbers()` to make it more understandable.As the code is incomplete, it is difficult to predict the output of it. The code is missing the closing bracket of the while loop. Please provide the complete code snippet for accurate output.The output of the code snippet will be "4 4.500000".

In the function solve(), the first printf() statement will print the result of 9 divided by 2, which is equal to 4. The second printf() statement will print the result of 9.0 divided by 2, which is equal to 4.500000 because it is a floating point division and the result is not rounded off.

In the main() function, solve() is called and the output is printed to the console before the program exits with a status code of 0.

Explanation

The given code uses bitwise shift operators. `(x > 1)` is equivalent to `x / 2`. So, the result will be `2 * 2 + 2 / 2 = 5`.

Therefore, the output of the code snippet will be 5.

Code:


#include <stdio.h>

 //function to solve the problem
void solve() {
    int x = 2;
    printf("%d", (x << 1) + (x >> 1));
}

//main function
int main() {
    solve();
    return 0;
}

The code snippet will output: 5.

EXPLANATION: The code defines a macro VAL with a value of 5. Then, there is a function called getInput() which simply returns the value of VAL. In the function solve(), the constant integer x is assigned the value returned by getInput(). Finally, the value of x is printed using printf() and since x was assigned the value of VAL which is 5, the output will be 5.

Finding the Length of an Array in C

To find the length of an array in C, you can use the formula:

sizeof(array)/sizeof(array[0])

This formula works because the

sizeof()

operator returns the size of an object in bytes. So, if you divide the size of the entire array by the size of a single element in it, you will get the number of elements in the array.

Here's an example code snippet:


int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr)/sizeof(arr[0]);
printf("The size of the array is %d", size);

This code will output:

The size of the array is 5

Not a Storage Class Specifier in C

In the C programming language, there are four storage class specifiers: extern, typedef, static, and auto. The keyword volatile is not a storage class specifier in C.


// Example:
int main() {

    static int var1 = 5; // static storage class
    extern int var2; // extern storage class
    typedef int myInt; // typedef storage class
    auto int var3; // auto storage class

    volatile int var4; // volatile variable
    return 0;
}

When declared, variables and functions can be assigned a storage class specifier. The storage class specifier determines the storage duration, linkage, and scope of the variable or function.

The output of the code snippet would be: "3 2 1 0 1 2 3".

The function "solve" takes an integer parameter "x". If "x" equals 0, it prints "0" and returns. Otherwise, it first prints the value of "x", recursively calls "solve" with the parameter "x-1", and then prints the value of "x" again.

In the "main" function, the "solve" function is called with the value "3". So, first "3" gets printed, then "solve" is called with the value "2". Similarly, "2" gets printed, "solve" is called with "1", "1" gets printed, "solve" is called with "0", "0" gets printed, and the function returns to the previous level of recursion. At this point, "1" gets printed again, then "2", "3" and the function returns to "main".I'm sorry, but the code snippet you provided is incomplete and ends with an "else if" clause. Please provide the complete code snippet or provide the rest of the "else if" clause and the corresponding "else" clause for me to be able to help you with the output.There is no code snippet provided to answer this question. Please provide the code snippet for me to be able to answer this question.The output of the given code snippet cannot be determined as it may lead to a program crash. The reason is that the set function makes a copy of the original pointer, which means the changes are not reflected back to the original pointer *PTR. Therefore, if the pointer *PTR points to a random memory location before and after the set function, the program may crash when we try to dereference it.

Explanation:

Calling the free() function on a NULL pointer is not an error and will not cause any issues. In fact, it is a common practice to check if a pointer is NULL before freeing it. If the pointer is already NULL, the free() function will simply do nothing and return.

Correctly Freeing Memory from Pointers in C++

In C++, memory can be dynamically allocated using the `new` operator. However, it is important to free up this memory when it is no longer needed to avoid memory leaks. The correct way to free up memory from a pointer that was allocated using the `new` keyword is by using the `delete` keyword.

Option B (`delete`) is the correct answer.

Option A (`free()`) is not the appropriate way to free memory that was allocated using `new`. `free()` should only be used to free memory that was allocated using the `malloc()` or `calloc()` functions.

Option C (`realloc()`) is used to change the size of dynamically allocated memory blocks, but it should not be used to free up memory.

Option D (`None of the above`) is incorrect because option B (`delete`) is the correct way to free up memory from a pointer allocated using the `new` keyword.

Therefore, the correct answer is option B (`delete`).

Recursion Handling Data Structure in C

In C, the data structure that is typically used to handle recursion is a stack. When a function calls itself recursively, each invocation of the function creates a new stack frame, which contains information such as the function arguments, local variables, and return address. This stack of frames is known as the call stack.

Each time a function is called recursively, a new stack frame is pushed onto the call stack. When the function returns, the frame is popped off the stack. This allows the program to keep track of where it is in the recursive process and to return to the correct point in the function when the recursion is complete.

Other data structures such as queues, deques, and trees can also be used for recursion in certain cases, but stacks are the most commonly used and efficient data structure for handling recursion in C.

Macro Calculation

The correct answer is B) 648.

The code uses a macro CUBE(x) which multiplies the value of x by itself three times. In the solve function, the macro is used with a value of 3, so it is expanded to 3 * 3 * 3, which is equal to 27.

Then, the solve function calculates the value of 216 divided by 27, which is equal to 8.

Finally, the main function calls the solve function and prints the result, which is 8.

Therefore, the output of the code snippet is 648, making B) the correct answer.The output of the code will be: 19 82

Clarifying C Structs

In C, structs do not support data hiding. It means that the members of a struct are accessible from outside the struct. Functions are also not allowed inside structs in C. C structs do not have constructors as well. However, you can define functions outside the struct to create and initialize structs. A struct in C can have static members in the struct body.The code snippet is using the C programming language to declare a structure named "School" that has two variables, namely "age" and "rollNo". The function "solve()" initializes the values of these two variables and then prints the size of the entire structure using the "sizeof()" operator. Finally, the main function calls the "solve()" function and returns 0.

The output of this code snippet will be "8" because the two integer variables in the "School" structure have a combined size of 8 bytes (4 bytes each). Due to this, the "sizeof()" operator will return 8, which will be printed by the "printf()" statement inside the "solve()" function.The given code creates a union that contains three variables - age (int), rollNo (int), and marks (double). In the solve function, an object of the School union is created and all three variables are assigned values. Finally, the size of the union is printed using the sizeof operator.

Since the largest variable in the union is double (which has a size of 8 bytes), the size of the entire union will be 8 bytes. Therefore, the output of the code will be 8.

Optimized code with comments:


#include <stdio.h>

// Define a union called School with three variables - age, rollNo, and marks
union School {
    int age;
    int rollNo;
    double marks;
};

// Function to solve the problem
void solve() {
    // Create an object of the School union
    union School sc;
    
    // Assign values to all three variables
    sc.age = 19;
    sc.rollNo = 82;
    sc.marks = 19.04;
    
    // Print the size of the union using sizeof operator
    printf("%d", (int)sizeof(sc));
}

// Main function to call the solve function
int main() {
    solve();
    return 0;
}

The given code will output "Hello Hello". The solve() function initializes a character array 's' with the string "Hello" and prints it. Then, it declares another character array 't' and uses the strcpy() function to copy the contents of 's' into 't'. Finally, it prints 't', which contains the string "Hello". Thus, the output will be "Hello Hello".

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.