0% found this document useful (0 votes)
34 views

c language interview questions

The document provides an overview of various fundamental concepts in C programming, including storage classes, functions, structures, unions, arrays, pointers, operators, conditional branching, loops, and advanced topics like linked lists and dynamic memory allocation. It explains key differences between concepts, provides examples of syntax, and illustrates how to implement various data structures and algorithms. Additionally, it includes problem-solving examples to demonstrate practical applications of these concepts.

Uploaded by

siroh98121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

c language interview questions

The document provides an overview of various fundamental concepts in C programming, including storage classes, functions, structures, unions, arrays, pointers, operators, conditional branching, loops, and advanced topics like linked lists and dynamic memory allocation. It explains key differences between concepts, provides examples of syntax, and illustrates how to implement various data structures and algorithms. Additionally, it includes problem-solving examples to demonstrate practical applications of these concepts.

Uploaded by

siroh98121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Storage Classes

1. What are the different storage classes in C?


o The different storage classes in C are auto, register, static, and extern.
2. Explain the difference between auto and register storage classes.
o auto: The default storage class for local variables. These variables are stored
in memory.
o register: Requests that the variable be stored in a CPU register instead of
RAM for faster access.
3. What is the static storage class and how is it used?
o static variables retain their value between function calls. They are initialized
only once.
4. Describe the extern storage class and its purpose.
o extern declares a variable that is defined in another file or scope, allowing
shared access.
5. How does the storage class affect the scope and lifetime of a variable?
o Storage classes determine the visibility (scope) and the duration (lifetime) of a
variable's existence.

Functions

6. What are the different types of functions in C?


o Standard library functions, user-defined functions, and inline functions.
7. Explain the difference between call by value and call by reference.
o Call by value passes a copy of the variable's value, while call by
reference passes the variable's address, allowing direct modification.
8. How do you declare and define a function in C?
o Declaration: int functionName(int param1, float param2);
o Definition: int functionName(int param1, float param2) { /*
function body */ }
9. What is a recursive function and provide an example?
o A function that calls itself. Example: Finding factorial of a number.

int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}

10. How do function pointers work in C?


o Function pointers store the address of a function and can be used to call the
function.

void (*funcPtr)(int, float);


funcPtr = &someFunction;
funcPtr(10, 5.5);
Structures and Unions

11. What is a structure in C and how is it declared?


o A structure groups different data types under a single name.

struct Student {
char name[50];
int age;
float gpa;
};

12. Explain the concept of nested structures.


o Structures within structures.

struct Address {
char city[50];
int zipCode;
};
struct Student {
char name[50];
int age;
struct Address address;
};

13. How do you access members of a structure?


o Using the dot operator (.) for direct access or arrow operator (->) for pointers.

student1.age; // Direct access


ptr->name; // Pointer access

14. What is a union and how is it different from a structure?


o A union allows storing different data types in the same memory location,
while a structure allocates separate memory for each member.

union Data {
int intVal;
float floatVal;
char charVal;
};

15. Provide an example of how to use a union in C.

union Data data;


data.intVal = 10;
printf("Int: %d\n", data.intVal);
data.floatVal = 5.5;
printf("Float: %f\n", data.floatVal);

Arrays and Pointers

16. How do you declare and initialize an array in C?


o Declaration: int arr[10];
o Initialization: int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
17. What is the difference between one-dimensional and multi-dimensional arrays?
o One-dimensional arrays hold a single line of elements, while multi-
dimensional arrays have multiple lines, like a table.

int oneD[5]; // One-dimensional


int twoD[3][4]; // Two-dimensional

18. How do you pass an array to a function?


o By passing the array's name, which is a pointer to the first element.

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
}

18. How do you pass an array to a function? In C, when you pass an array to a function,
you actually pass a pointer to its first element. Here's an example:

c
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
return 0;
}

19. Explain the concept of pointers in C. Pointers are variables that store memory addresses
of other variables. They are powerful tools that enable dynamic memory allocation, array
manipulation, and efficient function arguments passing. Here’s a basic pointer example:

c
int x = 10;
int *ptr = &x; // ptr stores the address of x
printf("%d", *ptr); // Output: 10
20. What are pointer arithmetic and its uses? Pointer arithmetic allows the manipulation of
the addresses stored in pointers. It supports operations like increment (++), decrement (--),
addition (+), and subtraction (-). This is useful for iterating through arrays.

c
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Outputs the array elements
}

Operators

21. What are the different types of operators in C? C has several operators:

• Arithmetic: +, -, *, /, %
• Relational: ==, !=, >, <, >=, <=
• Logical: &&, ||, !
• Bitwise: &, |, ^, ~, <<, >>
• Assignment: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
• Miscellaneous: sizeof, ? : (ternary), & (address of), * (pointer dereference)

22. Explain the difference between the && and || operators. The && (logical AND)
operator returns true if both operands are true. The || (logical OR) operator returns true if at
least one operand is true. They are used to combine multiple conditions in logical
expressions.

23. What is the sizeof operator and how is it used? The sizeof operator returns the size,
in bytes, of its operand. It is used to determine the memory size required for a data type or
variable.

c
int a = 10;
printf("Size of a: %zu bytes\n", sizeof(a)); // Outputs the size of int

24. How does the ternary (conditional) operator work in C? The ternary operator (? :) is
a shorthand for the if-else statement. It evaluates a condition and returns one value if true,
and another if false.

c
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Maximum: %d\n", max); // Outputs: Maximum: 20

25. What is the difference between ++a and a++? ++a is the prefix increment operator,
which increments a before using its value. a++ is the postfix increment operator, which
increments a after using its value.

c
int a = 5;
printf("%d\n", ++a); // Outputs: 6
printf("%d\n", a++); // Outputs: 6
printf("%d\n", a); // Outputs: 7

Conditional Branching

26. Explain the if-else statement in C. The if-else statement allows conditional
execution of code blocks based on whether a condition is true or false.

c
int a = 10;
if (a > 5) {
printf("a is greater than 5");
} else {
printf("a is not greater than 5");
}

27. How does the switch statement work and provide an example? The switch statement
allows multi-way branching based on the value of an expression. It executes the
corresponding case block and can use break to exit the block.

c
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day"); break;
}

28. What is a nested if-else statement? A nested if-else statement is an if-else


statement inside another if-else statement, allowing multiple levels of conditional logic.

c
int a = 10, b = 20;
if (a > b) {
printf("a is greater");
} else {
if (a == b) {
printf("a and b are equal");

28. How does the switch statement work and provide an example?

The switch statement allows a variable to be tested against a list of values, each with a
corresponding action. It provides a way to execute different parts of code based on the value
of a variable.

c
#include <stdio.h>

int main() {
int number = 2;
switch (number) {
case 1:
printf("Number is 1\n");
break;
case 2:
printf("Number is 2\n");
break;
case 3:
printf("Number is 3\n");
break;
default:
printf("Number is not 1, 2, or 3\n");
break;
}
return 0;
}

29. What is a nested if-else statement?

A nested if-else statement is an if-else statement within another if-else statement. It


allows more complex decision-making by having multiple layers of conditions.

c
#include <stdio.h>

int main() {
int number = 20;
if (number > 0) {
if (number % 2 == 0) {
printf("Number is positive and even\n");
} else {
printf("Number is positive and odd\n");
}
} else {
printf("Number is not positive\n");
}
return 0;
}

30. Describe the use of the break statement in conditional branching.

The break statement is used to exit a loop or switch statement prematurely. It stops the
execution of the loop or switch and transfers control to the statement immediately following
the loop or switch.

31. What is the purpose of the default case in a switch statement?

The default case in a switch statement is executed if none of the case labels match the
value of the switch expression. It acts as a catch-all for values not explicitly handled.

Looping

32. What are the different types of loops in C?

The different types of loops in C are:


• for loop
• while loop
• do-while loop

33. Explain the for loop with an example.

The for loop is used to repeat a block of code a certain number of times. It includes an
initialization, a condition, and an increment/decrement.

c
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}

34. Describe the do-while loop and how it differs from the while loop.

• Answer: The do-while loop is similar to the while loop, but with a key difference:
the do-while loop executes the code block at least once before checking the
condition. The syntax is:

c
do {
// code block to be executed
} while (condition);

The condition is evaluated after executing the code block. If the condition is true, the code
block is executed again. This continues until the condition becomes false.

35. How do you use the break and continue statements in loops?

• Answer: The break statement is used to terminate the loop or switch statement
prematurely. When encountered, the control immediately exits the loop. The
continue statement, on the other hand, skips the remaining code inside the current
iteration of the loop and proceeds with the next iteration. Example:

c
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // skip the current iteration if i is even
}
printf("%d ", i);
}
Advanced Topics

36. What is a linked list and how is it implemented in C?

• Answer: A linked list is a linear data structure where elements are stored in nodes,
and each node points to the next node in the sequence. It is implemented using
structures in C:

c
struct Node {
int data;
struct Node* next;
};

Each node contains data and a pointer to the next node.

37. How do you implement a stack using arrays in C?

• Answer: A stack can be implemented using arrays by defining an array and a top
pointer:

c
#define MAX 100
int stack[MAX];
int top = -1;

void push(int x) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = x;
}
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}

38. Explain the concept of dynamic memory allocation.

• Answer: Dynamic memory allocation allows the allocation of memory during


runtime using functions like malloc, calloc, realloc, and free. This provides
flexibility in managing memory for variables whose size may not be known at
compile-time.

39. What is a binary tree and how is it traversed?

• Answer: A binary tree is a hierarchical data structure where each node has at most
two children, referred to as the left and right child. Traversal methods include:
o In-order (Left, Root, Right)
o Pre-order (Root, Left, Right)
o Post-order (Left, Right, Root) Example of in-order traversal:

c
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

40. Describe the use of malloc and free functions.

• Answer: The malloc function allocates memory of a specified size and returns a
pointer to the allocated memory. The free function deallocates the memory
previously allocated by malloc, calloc, or realloc.

c
int* ptr = (int*)malloc(10 * sizeof(int)); // Allocate memory for 10
integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
} else {
// Use the allocated memory
free(ptr); // Deallocate memory
}

Problem-Solving

41. Write a C program to find the largest element in an array.

• Answer:

c
#include <stdio.h>

int findLargest(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
printf("The largest element is %d\n", findLargest(arr, n));
return 0;
}
41. Write a C program to find the largest element in an array.

c
#include <stdio.h>

int main() {
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int max = arr[0];


for (i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

printf("The largest element in the array is: %d\n", max);


return 0;
}

42. Write a C program to reverse a linked list.

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

struct Node {
int data;
struct Node* next;
};

void reverse(struct Node** head_ref) {


struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}

void push(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}

int main() {
struct Node* head = NULL;

push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);

printf("Given linked list\n");


printList(head);
reverse(&head);
printf("\nReversed linked list\n");
printList(head);

return 0;
}

43. Write a C program to check if a string is a palindrome.

c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPalindrome(char str[]) {


int l = 0;
int h = strlen(str) - 1;

while (h > l) {
if (str[l++] != str[h--]) {
return false;
}
}
return true;
}

int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);

if (isPalindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}

44. What is a typedef in C and how is it used?


typedef is a keyword used in C to create an alias or a new name for an existing data type. It
is commonly used to simplify complex declarations and make the code more readable.

Example:

c
#include <stdio.h>

typedef unsigned long ulong;

int main() {
ulong num = 123456789;
printf("num: %lu\n", num);
return 0;
}

45. Explain the concept of logical operators in C.

Logical operators are used to perform logical operations on expressions. They return either
true (non-zero) or false (zero) based on the result of the logical operation.

• && (logical AND): Returns true if both operands are true.


• || (logical OR): Returns true if at least one operand is true.
• ! (logical NOT): Returns true if the operand is false.

Example:

c
#include <stdio.h>

int main() {
int a = 5, b = 10, c = 0;

if (a && b) {
printf("Both a and b are non-zero.\n");
}
if (a || c) {
printf("Either a or c is non-zero.\n");
}
if (!c) {
printf("c is zero.\n");
}
return 0;
}

46. Explain the concept of bitwise operators in C.

Bitwise operators are used to perform operations on individual bits of integers. They are
mainly used in low-level programming, such as system programming and embedded systems.

• & (bitwise AND): Performs AND operation on corresponding bits.


• | (bitwise OR): Performs OR operation on corresponding bits.
• ^ (bitwise XOR): Performs XOR operation on corresponding bits.
• ~ (bitwise NOT): Inverts all the bits.
• << (left shift): Shifts bits to the left by a specified number of positions.
• >> (right shift): Shifts bits to the right by a specified number of positions.

Example:

c
#include <stdio.h>

int main() {
int a = 5, b = 3;

printf("a & b = %d\n", a & b); // 1 (0001)


printf("a | b = %d\n", a | b); // 7 (0111)
printf("a ^ b = %d\n", a ^ b); // 6 (0110)
printf("~a = %d\n", ~a); // -6 (1111...1010)
printf("a << 1 = %d\n", a << 1); // 10 (1010)
printf("a >> 1 = %d\n", a >> 1); // 2 (0010)

return 0;
}

47. How do you handle file operations in C?

File operations in C involve opening, reading, writing, and closing files using the standard
I/O functions.

Example:

c
#include <stdio.h>

int main() {
FILE *file;
char str[100];

// Open a file in write mode


file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);

// Open a file in read mode


file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
while (fgets(str, 100, file) != NULL) {
printf("%s", str);
}
fclose(file);

return 0;
}
48. What is a preprocessor directive and provide an example?

A preprocessor directive is a command that instructs the compiler to perform specific


operations before the actual compilation begins. They typically start with a # symbol.

Example:

c
#include <stdio.h>
#define PI 3.14159

int main() {
printf("Value of PI: %f\n", PI);
return 0;
}

49. How do you create and use macros in C?

Macros are defined using the #define preprocessor directive and are used to create constants
or inline functions.

Example:

c
#include <stdio.h>
#define SQUARE(x) ((x) * (x))

int main() {
int num = 5;
printf("Square of %d: %d\n", num, SQUARE(num));
return 0;
}
Basic C Programming Questions

1. Difference between printf and scanf:


o printf is used to display output on the screen.
o scanf is used to take input from the user.
2. Purpose of #include:
o It is used to include header files in the program, which contain
predefined functions.
3. main() function:
oIt is the entry point of a C program. Execution starts from here.
4. Keywords in C:
o Reserved words with special meaning (e.g., int, float, if, else, return).
5. Difference between int and float:
o int stores whole numbers, while float stores decimal numbers.
6. Use of sizeof():
o It returns the size (in bytes) of a variable or data type.
7. Variable declaration:
o Example: int x; declares an integer variable x.
8. Difference between ++i and i++:
o ++i increments i before using its value.
o i++ increments i after using its value.
9. Output of the code:
c

Copy

int a = 5;
printf("%d", a++);
Answer: 5
10. Output of the code:
c

Copy

int a = 5;
printf("%d", ++a);
Answer: 6
Control Flow Questions

11. Difference between if and switch:


o if is used for conditional branching, while switch is used for multi-way
branching.
12. Program to check even or odd:
c

Copy

if (num % 2 == 0) printf("Even");
else printf("Odd");
13. Output of the code:
c

Copy

int x = 10;
if (x = 20) printf("True");
else printf("False");
Answer: True (assignment operator = is used instead of ==).
14. Program to find the largest of three numbers:
c

Copy

if (a > b && a > c) printf("%d", a);


else if (b > c) printf("%d", b);
else printf("%d", c);
15. Output of the code:
c

Copy

int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
Answer: 0 1 2 3 4
16. Difference between while and do-while:
o while checks the condition before execution.
o do-while checks the condition after execution.
17. Program to print first 10 natural numbers:
c
Copy

for (int i = 1; i <= 10; i++) printf("%d ", i);


18. Output of the code:
c

Copy

for (int i = 0; i < 5; i++) {


if (i == 3) break;
printf("%d ", i);
}
Answer: 0 1 2
19. Purpose of continue:
o It skips the current iteration of a loop and moves to the next iteration.
20. Program to print Fibonacci series:
c

Copy

int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
printf("%d ", a);
c = a + b;
a = b;
b = c;
}

Functions Questions

21. Function in C:
o A block of code that performs a specific task.
22. Difference between declaration and definition:
o Declaration: int func();
o Definition: int func() { return 0; }
23. Default return type of a function:
o int (if not specified).
24. Output of the code:
c

Copy

void print() {
printf("Hello, World!");
}
int main() {
print();
return 0;
}
Answer: Hello, World!
25. Recursion example (factorial):
c

Copy

int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
26. Difference between call by value and call by reference:
Call by value: Passes a copy of the variable.
o
o Call by reference: Passes the address of the variable.
27. Output of the code:
c

Copy

void change(int x) {
x = 10;
}
int main() {
int x = 5;
change(x);
printf("%d", x);
return 0;
}
Answer: 5 (call by value).
28. Program to swap two numbers using pointers:
c

Copy

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}
29. Static function:
A function with static keyword has file scope (cannot be accessed
o
outside the file).
30. Output of the code:
c

Copy
int func() {
static int x = 0;
x++;
return x;
}
int main() {
printf("%d ", func());
printf("%d ", func());
return 0;
}
Answer: 1 2 (static variable retains its value).

Arrays and Strings Questions

31. Array declaration:


o Example: int arr[5];
32. Difference between array and pointer:
o Array is a collection of elements, while a pointer stores the address of a
variable.
33. Program to find the sum of array elements:
c

Copy

int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
34. Output of the code:
c

Copy

int arr[5] = {1, 2, 3, 4, 5};


printf("%d", arr[2]);
Answer: 3
35. Multidimensional array declaration:
o Example: int arr[3][3];
36. Program to multiply two matrices:
c

Copy

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
result[i][j] = 0;
for (int k = 0; k < 3; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
37. String in C:
A sequence of characters terminated by \0.
o
38. Output of the code:
c

Copy

char str[] = "Hello";


printf("%d", sizeof(str));
Answer: 6 (includes \0).
39. Program to reverse a string:
c

Copy

int len = strlen(str);


for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
40. Difference between strlen() and sizeof():
o strlen() returns the length of the string (excluding \0).
o sizeof() returns the total memory allocated (including \0).

Pointers Questions

41. Pointer declaration:


Example: int *p;
o
42. Output of the code:
c

Copy

int x = 10;
int *p = &x;
printf("%d", *p);
Answer: 10
43. Difference between *p and p:
o *p is the value at the address stored in p.
o p is the address stored in the pointer.
44. Program to swap two numbers using pointers:
c
Copy

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}
45. Null pointer:
o A pointer that does not point to any memory location (NULL).
46. Output of the code:
c

Copy

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


int *p = arr;
printf("%d", *(p + 1));
Answer: 2
47. Pointer to a pointer:
o Example: int **p;
48. Program to find string length using pointers:
c

Copy

int len = 0;
while (*str != '\0') {
len++;
str++;
}
49. Difference between int *p and int **p:
o int *p is a pointer to an integer.
o int **p is a pointer to a pointer to an integer.
50. Output of the code:
c

Copy

int x = 10;
int *p = &x;
int **q = &p;
printf("%d", **q);
Answer: 10

Structures and Unions Questions


51. Structure declaration:

Copy

struct Point {
int x;
int y;
};
52. Difference between structure and union:
o Structure allocates memory for all members.
o Union allocates memory for the largest member only.
53. Program to store and display student details:
c

Copy

struct Student {
char name[50];
int roll;
};
struct Student s = {"John", 1};
printf("%s %d", s.name, s.roll);
54. Output of the code:
c

Copy

struct Point p = {1, 2};


printf("%d %d", p.x, p.y);
Answer: 1 2
55. Size of an empty structure:
o Typically 1 byte (compiler-dependent).
56. Program to demonstrate union:
c

Copy

union Data {
int x;
float y;
};
union Data d;
d.x = 10;
printf("%d", d.x);
57. Output of the code:
c
Copy

union Data d;
d.x = 10;
printf("%d", d.x);
Answer: 10
58. Difference between struct and typedef:
o struct defines a new data type.
o typedef creates an alias for an existing data type.
59. Program to demonstrate nested structures:
c

Copy

struct Address {
char city[50];
};
struct Person {
char name[50];
struct Address addr;
};
60. Output of the code:
c

Copy

struct Point p = {1, 2};


struct Point *ptr = &p;
printf("%d", ptr->x);
Answer: 1

File Handling Questions

61. File handling functions:


o fopen(), fclose(), fprintf(), fscanf(), fgets(), fputs(), etc.
62. Program to read and display file contents:
c

Copy

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


char ch;
while ((ch = fgetc(fp)) != EOF) printf("%c", ch);
fclose(fp);
63. Difference between fprintf() and fscanf():
o fprintf() writes formatted data to a file.
o fscanf() reads formatted data from a file.
64. Program to write data to a file:
c

Copy

FILE *fp = fopen("file.txt", "w");


fprintf(fp, "Hello, World!");
fclose(fp);
65. Output of the code:
c

Copy

FILE *fp = fopen("test.txt", "w");


fprintf(fp, "Hello, World!");
fclose(fp);
Answer: Creates a file test.txt with content Hello, World!.
66. Purpose of fseek() and ftell():
o fseek() moves the file pointer to a specific location.
o ftell() returns the current position of the file pointer.
67. Program to append data to a file:
c

Copy

FILE *fp = fopen("file.txt", "a");


fprintf(fp, "New Data");
fclose(fp);
68. Difference between r and w modes:
o r opens a file for reading.
o w opens a file for writing (overwrites existing content).
69. Program to count lines in a file:
c

Copy

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


int count = 0;
char ch;
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n') count++;
}
fclose(fp);
70. Output of the code:
c
Copy

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


if (fp == NULL) printf("File not found");
else printf("File opened successfully");
fclose(fp);
Answer: File not found (if test.txt does not exist).

Dynamic Memory Allocation Questions

71. Dynamic memory allocation functions:


o malloc(), calloc(), realloc(), free().
72. Difference between malloc() and calloc():
o malloc() allocates memory without initialization.
o calloc() allocates memory and initializes it to zero.
73. Program to allocate memory for an array:
c

Copy

int *arr = (int *)malloc(n * sizeof(int));


74. Output of the code:
c

Copy

int *p = (int *)malloc(sizeof(int));


*p = 10;
printf("%d", *p);
free(p);
Answer: 10
75. Purpose of free():
o Deallocates memory allocated by malloc(), calloc(), or realloc().
76. Program to allocate memory for a 2D array:
c

Copy

int **arr = (int **)malloc(rows * sizeof(int *));


for (int i = 0; i < rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
}
77. Difference between malloc() and realloc():
o malloc() allocates new memory.
o realloc() resizes previously allocated memory.
78. Program to demonstrate calloc():
c

Copy

int *arr = (int *)calloc(n, sizeof(int));


79. Memory leak:
o Occurs when dynamically allocated memory is not deallocated.
80. Output of the code:
c

Copy

int *p = (int *)calloc(5, sizeof(int));


for (int i = 0; i < 5; i++) printf("%d ", p[i]);
free(p);
Answer: 0 0 0 0 0 (initialized to zero by calloc()).

Advanced C Programming Questions

81. Function pointer declaration:

Copy

int (*ptr)(int, int);


82. Program to demonstrate function pointer:
c

Copy

int add(int a, int b) { return a + b; }


int (*ptr)(int, int) = add;
printf("%d", ptr(2, 3));
83. Output of the code:
c

Copy

void func(int x) { printf("%d ", x); }


int main() {
void (*ptr)(int) = &func;
(*ptr)(10);
return 0;
}
Answer: 10
84. typedef example:
c

Copy

typedef int Integer;


Integer x = 10;
85. Program to demonstrate typedef:
c

Copy

typedef struct {
int x;
int y;
} Point;
Point p = {1, 2};
86. Difference between const and volatile:
o const makes a variable read-only.
o volatile indicates that a variable's value may change unexpectedly.
87. Output of the code:
c

Copy

#define SQUARE(x) (x * x)
printf("%d", SQUARE(2 + 3));
Answer: 11 (due to operator precedence).
88. Purpose of #define:
o Used to define macros.
89. Program to demonstrate #ifdef:
c

Copy

#define DEBUG
#ifdef DEBUG
printf("Debug mode");
#else
printf("Release mode");
#endif
90. Output of the code:
c

Copy
#ifdef DEBUG
printf("Debug mode");
#else
printf("Release mode");
#endif
Answer: Release mode (if DEBUG is not defined).

Miscellaneous Questions

91. Difference between ++i and i += 1:


o Both increment i by 1, but ++i is more concise.
92. Program to check if a number is a palindrome:
c

Copy

int reversed = 0, original = num;


while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
if (original == reversed) printf("Palindrome");
93. Output of the code:
c

Copy

int x = 5, y = 10;
printf("%d", x > y ? x : y);
Answer: 10
94. Difference between strcpy() and strncpy():
o strcpy() copies the entire string.
o strncpy() copies up to n characters.
95. Program to sort an array using bubble sort:
c

Copy

for (int i = 0; i < n - 1; i++) {


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
96. Output of the code:
c

Copy

int x = 5;
int *p = &x;
int **q = &p;
printf("%d", **q);
Answer: 5
97. Difference between exit() and return:
o exit() terminates the entire program.
o return exits the current function.
98. Program to find GCD of two numbers:
c

Copy

while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
printf("%d", a);
99. Output of the code:
c

Copy

int x = 5;
printf("%d", x << 1);
Answer: 10 (left shift by 1 multiplies by 2).
100. Difference between memcpy() and memmove():
o memcpy() does not handle overlapping memory regions.
o memmove() handles overlapping memory regions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy