*** 1. Why is C called a mid-level programming language?
C is called a mid-level programming language because it combines the features of both:
- Low-level languages (like Assembly)
- High-level languages (like Java or Python)
Why?
High-Level Features
- Easy to read and write
- Supports functions and structured programming
- Portable across multiple systems
Low-Level Features
- Direct memory access using pointers
- Fast execution
- Can interact with hardware and system resources
Example
int x = 10;
int *p = &x;
Here, pointers allow direct memory manipulation, which is a low-level feature.
Interview Insight
Interviewers ask this question to check whether you understand:
- System programming concepts
- Memory-level operations
- Why C is powerful for OS and embedded systems
*** 2. What are the features of C language?
C provides many powerful features that make it one of the most widely used programming languages.
Main Features of C
1. Simple and Efficient
- Easy syntax
- Fast execution speed
2. Portable
- Programs can run on different machines with little modification.
3. Structured Programming
- Large programs can be divided into functions.
4. Rich Library Support
- Provides many built-in functions.
5. Pointer Support
- Allows direct memory access.
6. Dynamic Memory Allocation
- Memory can be allocated at runtime using:
malloc(), calloc(), free()
7. Fast Execution
- C programs are compiled directly into machine code.
8. Extensible
- Users can create their own functions.
9. Supports Recursion
- Functions can call themselves.
10. Middle-Level Language
- Supports both system-level and application-level programming.
Real-World Uses
- Operating Systems
- Compilers
- Embedded Systems
- Device Drivers
- Databases
Interview Insight
Common follow-up:
“Why is C still used today?”
Answer:
Because of its speed, low-level memory control, and efficiency.
** 3. What are tokens in C?
Tokens are the smallest individual units in a C program.
Types of Tokens in C
| Token Type | Example |
|---|---|
| Keywords | int, return, if |
| Identifiers | num, main |
| Constants | 10, 'A' |
| Strings | "Hello" |
| Operators | +, -, == |
| Special Symbols | {}, (); |
Example
int sum = a + b;
Tokens are:
int
sum
=
a
+
b
;
Interview Insight
A common question:
“Is whitespace a token?”
Answer:
No. Whitespace only separates tokens.
*** 4. Difference between declaration and definition?
| Feature | Declaration | Definition |
|---|---|---|
| Purpose | Tells compiler about variable/function | Allocates memory |
| Memory Allocation | No | Yes |
| Multiple Allowed | Yes | No |
| Example | extern int x; | int x = 10; |
Variable Example
extern int x; // Declaration
int x = 10; // Definition
Function Example
void display(); // Declaration
void display() { // Definition
printf("Hello");
}
Interview Insight
Important concept:
Every definition is a declaration, but every declaration is not a definition.
*** 5. What is scope of a variable?
Scope defines the region of the program where a variable can be accessed.
Types of Scope in C
1. Local Scope
Declared inside a function or block.
void test() {
int x = 10;
}
x can only be used inside test().
2. Global Scope
Declared outside all functions.
int x = 100;
Accessible throughout the program.
3. Block Scope
Variables declared inside {} are accessible only inside that block.
if (1) {
int a = 5;
}
Interview Insight
Scope controls:
- Visibility
- Accessibility
- Memory lifetime behavior
*** 6. Difference between local and global variables?
| Feature | Local Variable | Global Variable |
|---|---|---|
| Declared | Inside function/block | Outside all functions |
| Scope | Limited | Entire program |
| Lifetime | Until function ends | Entire program execution |
| Default Value | Garbage value | 0 |
| Accessibility | Only inside block | Accessible everywhere |
Example
int g = 100; // Global
void test() {
int x = 10; // Local
}
Interview Insight
Interviewers may ask:
“Which variable is stored longer?”
Answer:
Global variables exist throughout the program execution.
** 7. What are storage classes in C?
Storage classes define:
- Scope
- Lifetime
- Memory location
- Visibility of variables/functions
Types of Storage Classes in C
| Storage Class | Keyword |
|---|---|
| Automatic | auto |
| External | extern |
| Static | static |
| Register | register |
Interview Insight
This is one of the most frequently asked theory topics in C interviews.
*** 8. Explain auto, static, extern, and register.
1. auto Storage Class
- Default storage class for local variables
- Stored in memory (RAM)
auto int x = 10;
Features
- Local scope
- Garbage initial value
- Lifetime until function ends
2. static Storage Class
- Retains value between function calls
static int count = 0;
Features
- Value persists
- Initialized only once
- Default value = 0
Example
void test() {
static int x = 0;
x++;
printf("%d", x);
}
Output after multiple calls:
1 2 3
3. extern Storage Class
Used to access global variables from another file.
extern int x;
Features
- No memory allocation
- References existing variable
4. register Storage Class
Requests compiler to store variable in CPU register for faster access.
register int i;
Features
- Faster access
- Address cannot be obtained using
&
Interview Insight
Very common question:
“Which storage class preserves value between function calls?”
Answer:
static
** 9. What is the volatile keyword?
volatile tells the compiler that a variable’s value may change unexpectedly at any time.
So, the compiler should not optimize that variable.
Syntax
volatile int x;
Used In
- Embedded systems
- Hardware registers
- Interrupt handling
- Multithreading
Example
volatile int flag = 0;
Why Important?
Without volatile, compiler optimization may use cached values instead of updated values.
Interview Insight
Common follow-up:
“Where is volatile used in real projects?”
Answer:
- Device drivers
- Embedded systems
- Shared memory programming
*** 10. Difference between = and == ?
| Operator | Meaning | Purpose |
|---|---|---|
= | Assignment Operator | Assigns value |
== | Equality Operator | Compares values |
Example of =
int x = 10;
Assigns 10 to x.
Example of ==
if (x == 10)
Checks whether x is equal to 10.
Common Beginner Mistake
if (x = 10)
This assigns 10 to x instead of comparing.
Condition becomes true.
Interview Insight
Very frequently asked trick question:
“Why is
if(a = b)dangerous?”
Because assignment happens instead of comparison, leading to logical bugs.
*** 11. Difference between i++ and ++i?
Both operators are used to increment a variable by 1, but they work differently.
| Operator | Name | Operation |
|---|---|---|
i++ | Post-increment | Use value first, then increment |
++i | Pre-increment | Increment first, then use value |
Example of i++
int i = 5;
int a = i++;
Execution
-
a = 5 -
i = 6
Example of ++i
int i = 5;
int a = ++i;
Execution
-
i = 6 -
a = 6
Key Difference
Post Increment -> Use then Increment
Pre Increment -> Increment then Use
Interview Insight
Common interview question:
“Which is faster: i++ or ++i?”
For primitive types in C, both are almost same after compiler optimization.
** 12. What is typecasting?
Typecasting is the process of converting one data type into another.
Types of Typecasting in C
1. Implicit Typecasting
Done automatically by compiler.
int x = 10;
float y = x;
x automatically converts to float.
2. Explicit Typecasting
Done manually by programmer.
float x = 5.7;
int y = (int)x;
Output:
5
Fractional part is removed.
Why Typecasting is Used
- Data conversion
- Memory optimization
- Prevent data loss
- Mathematical operations
Interview Insight
Common follow-up:
“What is data loss in typecasting?”
Example:
float x = 9.8;
int y = (int)x;
Decimal part is lost.
** 13. What is an l-value and r-value?
l-value
An l-value refers to a memory location.
It can appear on the left side of assignment.
Example
int x = 10;
x is an l-value.
r-value
An r-value refers to a data value.
It usually appears on the right side of assignment.
Example
int x = 20;
20 is an r-value.
Important Rule
10 = x; // Invalid
Because constant values are not l-values.
Interview Insight
Simple definition interviewers like:
l-value -> Has memory address
r-value -> Temporary value/data
*** 14. What are entry-controlled and exit-controlled loops?
Loops are categorized based on when the condition is checked.
1. Entry-Controlled Loop
Condition is checked before loop execution.
Examples
-
for -
while
while(i < 5) {
printf("%d", i);
}
If condition is false initially, loop will not run.
2. Exit-Controlled Loop
Condition is checked after loop execution.
Example
-
do-while
do {
printf("Hello");
} while(i < 5);
Runs at least once.
Key Difference
| Feature | Entry-Controlled | Exit-Controlled |
|---|---|---|
| Condition Check | Before execution | After execution |
| Minimum Executions | 0 | 1 |
Interview Insight
Very common question:
“Which loop executes at least once?”
Answer:
do-while loop.
*** 15. Difference between break, continue, and goto?
| Statement | Purpose |
|---|---|
break | Terminates loop/switch |
continue | Skips current iteration |
goto | Jumps to labeled statement |
break Example
for(int i=0; i<5; i++) {
if(i==3)
break;
}
Loop stops when i == 3.
continue Example
for(int i=0; i<5; i++) {
if(i==2)
continue;
}
Skips iteration when i == 2.
goto Example
goto label;
label:
printf("Hello");
Key Difference
| Statement | Loop Ends? | Skips Iteration? |
|---|---|---|
| break | Yes | No |
| continue | No | Yes |
| goto | Jumps anywhere | Depends |
Interview Insight
Interviewers often ask:
“Why is goto discouraged?”
Because it makes code difficult to read and maintain.
*** 16. Difference between if-else and switch?
| Feature | if-else | switch |
|---|---|---|
| Condition Type | Any expression | Constant values only |
| Multiple Conditions | Easy | Limited |
| Performance | Slower for many cases | Faster |
| Readability | Complex for many cases | Cleaner |
if-else Example
if(marks > 90)
printf("A");
else
printf("B");
switch Example
switch(day) {
case 1:
printf("Monday");
break;
}
When to Use
- Use
if-elsefor ranges and complex conditions. - Use
switchfor fixed values/menu programs.
Interview Insight
Important point:
switch only works with:
-
int -
char - enum values
(Not with float/string in C)
*** 17. What happens if break is omitted in switch?
If break is omitted, execution continues into the next case.
This is called fall-through behavior.
Example
switch(x) {
case 1:
printf("One");
case 2:
printf("Two");
}
If x = 1
Output:
OneTwo
Because control falls into next case.
Why Sometimes Useful?
Used intentionally in:
- Grouped cases
- Menu systems
Interview Insight
Very common interview concept:
Missing break causes fall-through.
** 18. What is while(1)?
while(1)
creates an infinite loop because condition 1 is always true.
Example
while(1) {
printf("Running...");
}
Loop never stops unless:
-
breakis used - program terminates
Common Uses
- Servers
- Operating systems
- Embedded systems
- Event listeners
Interview Insight
Follow-up question:
“Difference between while(1) and while(true)?”
-
while(1)is common in C -
truerequires<stdbool.h>
*** 19. How to create an infinite loop?
An infinite loop runs forever until externally stopped.
Methods to Create Infinite Loop
1. Using while
while(1) {
}
2. Using for
for(;;) {
}
3. Using do-while
do {
} while(1);
Most Common Method
for(;;)
because it avoids condition checking overhead.
Interview Insight
Common question:
“Where are infinite loops used?”
Answer:
- Web servers
- Game loops
- Operating systems
- Real-time systems
* 20. Why can't reserved keywords be used as variable names?
Reserved keywords have predefined meanings in C.
The compiler uses them for syntax and program structure.
Examples of Keywords
int
float
return
if
while
Invalid Example
int return = 10;
This causes compilation error.
Why Restriction Exists
To avoid:
- Syntax confusion
- Parsing ambiguity
- Compiler errors
Valid Alternative
int returnValue = 10;
Interview Insight
Common follow-up:
“Can keywords be used in other programming languages?”
Some modern languages allow escaped identifiers, but C does not.
** 21. What are header files?
Header files are files that contain:
- Function declarations
- Macros
- Constants
- Data type definitions
They help reuse code across multiple C programs.
Common Header Files
| Header File | Purpose |
|---|---|
stdio.h | Input/Output functions |
math.h | Mathematical functions |
string.h | String handling |
stdlib.h | Memory allocation and utilities |
Example
#include <stdio.h>
int main() {
printf("Hello");
return 0;
}
Here:
stdio.h
contains declaration of printf().
Advantages
- Code reusability
- Easier maintenance
- Modular programming
Interview Insight
Common question:
“What happens if we do not include stdio.h?”
Compiler may show warning/error because printf() declaration is missing.
*** 22. What are preprocessor directives?
Preprocessor directives are commands processed before compilation.
They begin with:
#
Common Preprocessor Directives
| Directive | Purpose |
|---|---|
#include | Includes header files |
#define | Defines macros |
#if | Conditional compilation |
#ifdef | Checks macro definition |
#undef | Removes macro |
Example
#define PI 3.14
Important Point
Preprocessor directives do not end with semicolon (;).
Interview Insight
Very common question:
“When does preprocessing happen?”
Answer:
Before actual compilation starts.
*** 23. Difference between #include <> and #include ""?
| Syntax | Searches In |
|---|---|
#include <file> | System directories |
#include "file" | Current directory first |
Example
System Header
#include <stdio.h>
User-Defined Header
#include "myheader.h"
Usage
-
< >→ Standard library headers -
" "→ Custom/user-defined headers
Interview Insight
Common follow-up:
“Can #include "" also search system directories?”
Yes. If file is not found locally, compiler searches system paths.
*** 24. What is a macro?
A macro is a name or symbol that represents a value or code fragment.
Macros are created using:
#define
Example
#define PI 3.14
Now PI is replaced by 3.14 during preprocessing.
Function-like Macro
#define SQUARE(x) ((x) * (x))
Usage:
SQUARE(5)
Advantages
- Faster execution
- Code reusability
- Easy constant management
Interview Insight
Important concept:
Macros are expanded before compilation.
*** 25. Difference between macros and functions?
| Feature | Macro | Function |
|---|---|---|
| Processed By | Preprocessor | Compiler |
| Speed | Faster | Slightly slower |
| Memory | No function call overhead | Uses stack memory |
| Type Checking | No | Yes |
| Debugging | Difficult | Easier |
Macro Example
#define SQUARE(x) ((x)*(x))
Function Example
int square(int x) {
return x * x;
}
Key Difference
Macros perform text replacement, while functions execute compiled code.
Interview Insight
Very common question:
“Why are macros faster?”
Because no function call happens.
** 26. What is typedef?
typedef is used to create a new name (alias) for an existing data type.
Syntax
typedef existing_type new_name;
Example
typedef int INTEGER;
INTEGER x = 10;
Structure Example
typedef struct {
int id;
char name[20];
} Student;
Usage:
Student s1;
Advantages
- Improves readability
- Simplifies complex declarations
- Better code maintenance
Interview Insight
Common use:
typedef is heavily used with structures and pointers.
** 27. What are enumerations (enum)?
enum is a user-defined data type used to assign names to integer constants.
Syntax
enum Day {
MON,
TUE,
WED
};
Default Values
| Enumerator | Value |
|---|---|
| MON | 0 |
| TUE | 1 |
| WED | 2 |
Example
enum Day today = MON;
Advantages
- Improves readability
- Makes code meaningful
- Easy constant management
Interview Insight
Common question:
“Can enum values be customized?”
Yes.
enum Day {
MON = 1,
TUE = 5
};
*** 28. What is the sizeof() operator?
sizeof() returns the size of a variable or data type in bytes.
Syntax
sizeof(data_type)
or
sizeof(variable)
Example
int x;
printf("%lu", sizeof(x));
Output
Depends on system architecture.
Example:
4
for int on many systems.
Important Uses
- Dynamic memory allocation
- Array size calculation
- System-level programming
Interview Insight
Common question:
“Is sizeof() a function?”
Answer:
No. It is an operator.
*** 29. What is recursion?
Recursion is a technique where a function calls itself.
Basic Structure
function() {
function();
}
Important Components
1. Base Condition
Stops recursion.
2. Recursive Call
Function calls itself.
Example
void test(int n) {
if(n == 0)
return;
printf("%d ", n);
test(n - 1);
}
Advantages
- Simplifies complex problems
- Useful for tree and graph problems
Disadvantages
- More memory usage
- Stack overflow risk
Interview Insight
Very common question:
“What happens without base condition?”
Answer:
Infinite recursion causing stack overflow.
*** 30. Recursive factorial program
Factorial of n:
n! = n × (n-1)!
Recursive Factorial Program
#include <stdio.h>
int factorial(int n) {
// Base condition
if(n == 0 || n == 1)
return 1;
// Recursive call
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial = %d", factorial(num));
return 0;
}
Output
Factorial = 120
How It Works
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
...
= 120
Interview Insight
Common follow-up:
“What is time complexity of recursive factorial?”
Answer:
O(n)
because function is called n times.
*** 31. Fibonacci using recursion
In recursion, a function calls itself to generate Fibonacci numbers.
Fibonacci Series
0 1 1 2 3 5 8 13 ...
Each number is the sum of previous two numbers.
Recursive Fibonacci Program
#include <stdio.h>
int fibonacci(int n) {
// Base conditions
if(n == 0)
return 0;
if(n == 1)
return 1;
// Recursive call
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 7;
for(int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Output
0 1 1 2 3 5 8
Drawback
Recursive Fibonacci is slower because same values are calculated multiple times.
Interview Insight
Common question:
“What is time complexity of recursive Fibonacci?”
Answer:
O(2^n)
*** 32. Fibonacci without recursion
This approach uses loops instead of recursive function calls.
Iterative Fibonacci Program
#include <stdio.h>
int main() {
int n = 7;
int a = 0, b = 1, c;
printf("%d %d ", a, b);
for(int i = 2; i < n; i++) {
c = a + b;
printf("%d ", c);
a = b;
b = c;
}
return 0;
}
Output
0 1 1 2 3 5 8
Advantages over Recursion
- Faster
- Less memory usage
- No stack overhead
Interview Insight
Very common comparison question:
“Which Fibonacci approach is better?”
Iterative approach is more efficient.
*** 33. Prime number program
A prime number is divisible only by:
- 1
- itself
Examples:
2, 3, 5, 7, 11
Prime Number Program
#include <stdio.h>
int main() {
int num = 13;
int isPrime = 1;
if(num <= 1) {
isPrime = 0;
}
for(int i = 2; i <= num / 2; i++) {
if(num % i == 0) {
isPrime = 0;
break;
}
}
if(isPrime)
printf("Prime Number");
else
printf("Not Prime Number");
return 0;
}
Output
Prime Number
Interview Insight
Optimization question:
“Why not loop till num-1?”
Because checking till num/2 or sqrt(num) is enough.
** 34. Armstrong number program
An Armstrong number is a number equal to the sum of cubes of its digits.
Example:
153 = 1³ + 5³ + 3³
Armstrong Number Program
#include <stdio.h>
int main() {
int num = 153;
int original = num;
int rem, sum = 0;
while(num > 0) {
rem = num % 10;
sum += rem * rem * rem;
num /= 10;
}
if(sum == original)
printf("Armstrong Number");
else
printf("Not Armstrong Number");
return 0;
}
Output
Armstrong Number
Interview Insight
Common follow-up:
“Is 370 an Armstrong number?”
Yes.
*** 35. Reverse a number program
This program reverses digits of a number.
Reverse Number Program
#include <stdio.h>
int main() {
int num = 1234;
int reverse = 0;
int rem;
while(num > 0) {
rem = num % 10;
reverse = reverse * 10 + rem;
num /= 10;
}
printf("Reverse = %d", reverse);
return 0;
}
Output
Reverse = 4321
Logic
1234
-> 4
-> 43
-> 432
-> 4321
Interview Insight
Common follow-up:
“How to check palindrome number?”
Compare original number with reversed number.
*** 36. Pass by value vs pass by reference
| Feature | Pass by Value | Pass by Reference |
|---|---|---|
| What is Passed | Copy of variable | Address of variable |
| Original Value Changes? | No | Yes |
| Memory Usage | More | Less |
| Safety | Safer | Riskier |
Pass by Value Example
void test(int x) {
x = 20;
}
Original variable remains unchanged.
Pass by Reference Example
void test(int *x) {
*x = 20;
}
Original variable changes.
Important Point
C supports:
Pass by value only
Pass by reference is achieved using pointers.
Interview Insight
Very frequently asked question:
“Does C support true pass by reference?”
Answer:
No. It uses pointers to simulate it.
*** 37. What is an array?
An array is a collection of similar data types stored in contiguous memory locations.
Syntax
data_type array_name[size];
Example
int arr[5] = {1, 2, 3, 4, 5};
Features
- Stores multiple values
- Fixed size
- Indexed access
Array Index
arr[0]
arr[1]
arr[2]
Index starts from 0.
Interview Insight
Common question:
“Why are arrays fast?”
Because elements are stored in contiguous memory.
** 38. Difference between arrays and strings?
| Feature | Array | String |
|---|---|---|
| Definition | Collection of elements | Collection of characters |
| Data Type | Any type | Character array |
| Null Character | Not necessary | Ends with '\0' |
| Example | int arr[5] | char str[10] |
Array Example
int arr[3] = {1, 2, 3};
String Example
char str[] = "Hello";
Internally:
H e l l o \0
Interview Insight
Important concept:
Every string is an array, but every array is not a string.
*** 39. What is the null character ('\0')?
'\0' is a special character that marks the end of a string in C.
Its ASCII value is:
0
Example
char str[] = "Hi";
Stored as:
H i \0
Why Important?
String functions stop reading when '\0' is found.
Example
printf("%s", str);
Prints characters until null character appears.
Interview Insight
Common question:
“What happens if string has no null character?”
String functions may read garbage values causing undefined behavior.
*** 40. Difference between strlen() and sizeof()?
| Feature | strlen() | sizeof() |
|---|---|---|
| Type | Function | Operator |
| Returns | Length of string | Total memory size |
Counts '\0'? | No | Yes |
| Header File | string.h | Not required |
Example
char str[] = "Hello";
strlen()
strlen(str)
Output:
5
sizeof()
sizeof(str)
Output:
6
Because:
H e l l o \0
Key Difference
strlen() -> Counts characters
sizeof() -> Counts memory bytes
Interview Insight
Very common interview trap:
“Why does sizeof() return larger value for strings?”
Because it includes the null character '\0'.
*** 41. Reverse a string
This program reverses the characters of a string.
Reverse String Program
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
int len = strlen(str);
for(int i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}
return 0;
}
Output
olleH
Logic
Start printing from last index to first index.
Interview Insight
Common follow-up:
“Can string be reversed without extra space?”
Yes, using two-pointer swapping technique.
*** 42. Palindrome string checker
A palindrome string reads the same forward and backward.
Examples:
madam
level
radar
Palindrome String Program
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "madam";
int start = 0;
int end = strlen(str) - 1;
int isPalindrome = 1;
while(start < end) {
if(str[start] != str[end]) {
isPalindrome = 0;
break;
}
start++;
end--;
}
if(isPalindrome)
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}
Output
Palindrome
Interview Insight
Very common interview optimization:
Use two pointers instead of creating reversed string.
** 43. Remove spaces from string
This program removes all spaces from a string.
Remove Spaces Program
#include <stdio.h>
int main() {
char str[] = "Hello World";
int i, j = 0;
for(i = 0; str[i] != '\0'; i++) {
if(str[i] != ' ') {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
printf("%s", str);
return 0;
}
Output
HelloWorld
Logic
Copy only non-space characters.
Interview Insight
Frequently asked in string manipulation rounds.
** 44. Remove duplicates from string
This program removes repeated characters from a string.
Remove Duplicates Program
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "programming";
for(int i = 0; str[i] != '\0'; i++) {
for(int j = i + 1; str[j] != '\0'; ) {
if(str[i] == str[j]) {
for(int k = j; str[k] != '\0'; k++) {
str[k] = str[k + 1];
}
} else {
j++;
}
}
}
printf("%s", str);
return 0;
}
Output
progamin
Interview Insight
Common follow-up:
“How to optimize duplicate removal?”
Using hashing or frequency arrays.
*** 45. Largest element in array
This program finds the largest element in an array.
Largest Element Program
#include <stdio.h>
int main() {
int arr[] = {10, 45, 7, 89, 23};
int largest = arr[0];
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 1; i < size; i++) {
if(arr[i] > largest) {
largest = arr[i];
}
}
printf("Largest = %d", largest);
return 0;
}
Output
Largest = 89
Time Complexity
O(n)
Interview Insight
Common follow-up:
“How to find second largest element?”
Track both largest and second largest values.
** 46. Merge two arrays
This program combines two arrays into one.
Merge Arrays Program
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int size1 = 3;
int size2 = 3;
int merged[size1 + size2];
for(int i = 0; i < size1; i++) {
merged[i] = arr1[i];
}
for(int i = 0; i < size2; i++) {
merged[size1 + i] = arr2[i];
}
for(int i = 0; i < size1 + size2; i++) {
printf("%d ", merged[i]);
}
return 0;
}
Output
1 2 3 4 5 6
Interview Insight
Interviewers may ask:
“Can arrays be merged without extra array?”
Yes, using shifting techniques.
*** 47. Convert string to integer
This converts numeric string into integer value.
Using atoi()
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "1234";
int num = atoi(str);
printf("%d", num);
return 0;
}
Output
1234
Important Header
#include <stdlib.h>
Interview Insight
Common follow-up:
“Difference between atoi() and strtol()?”
strtol() provides better error handling.
** 48. Convert uppercase to lowercase
This program converts uppercase letters into lowercase.
Program
#include <stdio.h>
int main() {
char str[] = "HELLO";
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32;
}
}
printf("%s", str);
return 0;
}
Output
hello
Logic
ASCII difference:
'A' = 65
'a' = 97
Difference = 32
Interview Insight
Alternative approach:
Use:
tolower()
from ctype.h.
*** 49. What is a pointer?
A pointer is a variable that stores the memory address of another variable.
Syntax
data_type *pointer_name;
Example
int x = 10;
int *p = &x;
Explanation
| Symbol | Meaning |
|---|---|
& | Address of variable |
* | Value at address |
Accessing Value
printf("%d", *p);
Output:
10
Memory Representation
x = 10
p = address of x
Interview Insight
Very frequently asked:
“Why are pointers powerful in C?”
Because they provide direct memory access.
*** 50. Why are pointers used?
Pointers are used for efficient memory handling and advanced programming concepts.
Main Uses of Pointers
1. Dynamic Memory Allocation
malloc(), calloc(), free()
2. Pass by Reference
Allows functions to modify original variables.
3. Arrays and Strings
Arrays internally use pointers.
4. Data Structures
Used in:
- Linked Lists
- Trees
- Graphs
5. Function Pointers
Useful in callbacks and dynamic behavior.
6. Direct Memory Access
Used in:
- Operating systems
- Embedded systems
- Device drivers
Advantages
- Faster operations
- Efficient memory usage
- Supports dynamic programming concepts
Interview Insight
Very common interview question:
“What happens if pointers are misused?”
Possible issues:
- Segmentation fault
- Memory leak
- Undefined behavior
*** 51. Difference between & and *?
| Symbol | Meaning |
|---|---|
& | Address-of operator |
* | Dereference operator |
Example
int x = 10;
int *p = &x;
Explanation
& Operator
Returns memory address of variable.
&p
or
&x
* Operator
Accesses value stored at address.
*p
Output:
10
Memory Representation
x = 10
p = address of x
*p = value at address = 10
Interview Insight
Very common question:
“Can * be used for declaration and dereferencing?”
Yes.
int *p;
Declaration.
*p
Dereferencing.
*** 52. What is dereferencing?
Dereferencing means accessing the value stored at the memory address held by a pointer.
It uses:
*
operator.
Example
int x = 20;
int *p = &x;
printf("%d", *p);
Output
20
Explanation
p -> stores address of x
*p -> accesses value of x
Interview Insight
Common follow-up:
“What happens if invalid pointer is dereferenced?”
It may cause:
- Segmentation fault
- Undefined behavior
*** 53. What is NULL pointer?
A NULL pointer is a pointer that does not point to any valid memory location.
Syntax
int *p = NULL;
Important Point
NULL means:
Pointer contains no valid address.
Why Used?
- Prevents accidental memory access
- Useful for initialization
- Indicates empty pointer
Example
if(p == NULL) {
printf("Pointer is NULL");
}
Interview Insight
Best practice:
Always initialize unused pointers with NULL.
*** 54. What happens when NULL is dereferenced?
Dereferencing a NULL pointer causes undefined behavior.
Usually, program crashes with:
Segmentation Fault
Example
int *p = NULL;
printf("%d", *p);
Why Crash Happens?
Because program tries to access invalid memory location.
Safe Practice
Always check:
if(p != NULL)
before dereferencing.
Interview Insight
Very common interview question:
“Is dereferencing NULL always guaranteed to crash?”
No. Behavior is undefined, but crashes are common.
*** 55. Difference between array and pointer?
| Feature | Array | Pointer |
|---|---|---|
| Meaning | Collection of elements | Stores memory address |
| Memory Allocation | Fixed | Dynamic possible |
| Reassignable | No | Yes |
| Size | Entire array size | Pointer size only |
| Access | Indexing | Dereferencing |
Array Example
int arr[3] = {1, 2, 3};
Pointer Example
int *p = arr;
Important Difference
arr = arr + 1; // Invalid
But:
p = p + 1; // Valid
Interview Insight
Frequently asked concept:
Array name acts like constant pointer to first element.
*** 56. What is pointer arithmetic?
Pointer arithmetic means performing arithmetic operations on pointers.
Supported Operations
- Increment (
p++) - Decrement (
p--) - Addition
- Subtraction
Example
int arr[] = {10, 20, 30};
int *p = arr;
p++;
Now pointer moves to next integer.
Important Point
Pointer increases by:
size of data type
For int:
Usually 4 bytes
Example
Address = 1000
After p++ = 1004
Interview Insight
Very common question:
“Why pointer arithmetic depends on data type?”
Because compiler must move pointer correctly in memory.
** 57. What is a double pointer?
A double pointer is a pointer that stores the address of another pointer.
Also called:
Pointer to pointer
Syntax
int **ptr;
Example
int x = 10;
int *p = &x;
int **pp = &p;
Accessing Values
| Expression | Value |
|---|---|
p | Address of x |
*p | Value of x |
pp | Address of p |
**pp | Value of x |
Output Example
printf("%d", **pp);
Output:
10
Interview Insight
Used heavily in:
- Dynamic 2D arrays
- Command-line arguments
- Linked data structures
*** 58. What is dynamic memory allocation?
Dynamic memory allocation means allocating memory during runtime.
Memory is allocated from:
Heap memory
Why Needed?
- Flexible memory usage
- Runtime-sized arrays
- Efficient memory management
Functions Used
malloc()
calloc()
realloc()
free()
Example
int *p;
p = (int*) malloc(5 * sizeof(int));
Advantages
- Efficient memory usage
- Dynamic data structures possible
Interview Insight
Very common question:
“What happens if allocated memory is not freed?”
It causes:
Memory Leak
*** 59. Difference between stack and heap memory?
| Feature | Stack Memory | Heap Memory |
|---|---|---|
| Allocation | Automatic | Manual |
| Speed | Faster | Slower |
| Memory Size | Limited | Larger |
| Managed By | Compiler | Programmer |
| Lifetime | Function scope | Until freed |
Stack Example
int x = 10;
Heap Example
int *p = (int*) malloc(sizeof(int));
Important Difference
Stack memory is automatically released.
Heap memory must be manually released using:
free()
Interview Insight
Common question:
“Which memory causes memory leaks?”
Heap memory.
*** 60. What are malloc(), calloc(), realloc(), and free()?
These are dynamic memory management functions from:
<stdlib.h>
1. malloc()
Allocates memory block.
Syntax
ptr = (type*) malloc(size);
Example
int *p = (int*) malloc(5 * sizeof(int));
Features
- Memory contains garbage values
- Faster than calloc()
2. calloc()
Allocates multiple memory blocks.
Syntax
ptr = (type*) calloc(n, size);
Example
int *p = (int*) calloc(5, sizeof(int));
Features
- Initializes memory with
0
3. realloc()
Resizes previously allocated memory.
Syntax
ptr = realloc(ptr, new_size);
Example
p = realloc(p, 10 * sizeof(int));
4. free()
Releases dynamically allocated memory.
Syntax
free(ptr);
Example
free(p);
Why Important?
Prevents:
Memory leaks
Key Difference Table
| Function | Purpose |
|---|---|
malloc() | Single memory allocation |
calloc() | Multiple allocation + initialize 0 |
realloc() | Resize memory |
free() | Release memory |
Interview Insight
Very frequently asked:
“Difference between malloc() and calloc()?”
| malloc() | calloc() |
|---|---|
| Single block | Multiple blocks |
| Garbage values | Initializes with 0 |
| Faster | Slightly slower |
*** 61. Difference between malloc() and calloc()?
Both functions are used for dynamic memory allocation in C.
Key Differences
| Feature | malloc() | calloc() |
|---|---|---|
| Full Form | Memory Allocation | Contiguous Allocation |
| Number of Arguments | 1 | 2 |
| Initialization | Garbage values | Initializes with 0 |
| Speed | Faster | Slightly slower |
malloc() Syntax
ptr = (type*) malloc(size);
Example
int *p = (int*) malloc(5 * sizeof(int));
calloc() Syntax
ptr = (type*) calloc(n, size);
Example
int *p = (int*) calloc(5, sizeof(int));
Important Difference
malloc() -> uninitialized memory
calloc() -> zero-initialized memory
Interview Insight
Very common question:
“Which function is safer?”
calloc() is safer because memory is initialized to 0.
*** 62. What is memory leak?
A memory leak occurs when dynamically allocated memory is not released after use.
Example
int *p = (int*) malloc(sizeof(int));
If free(p) is not called, memory remains occupied.
Problems Caused
- Increased memory usage
- Slow performance
- Program crash
Correct Practice
free(p);
Real-World Impact
Memory leaks are serious in:
- Servers
- Long-running applications
- Embedded systems
Interview Insight
Common question:
“How can memory leaks be detected?”
Using tools like:
- Valgrind
- AddressSanitizer
*** 63. What are dangling pointers?
A dangling pointer points to memory that has already been freed or deleted.
Example
int *p = (int*) malloc(sizeof(int));
free(p);
Now:
p becomes dangling pointer
because it still stores invalid address.
Dangerous Because
Accessing dangling pointers causes:
- Undefined behavior
- Crashes
- Data corruption
Safe Practice
After free():
p = NULL;
Interview Insight
Very common interview question:
“Difference between NULL pointer and dangling pointer?”
| NULL Pointer | Dangling Pointer |
|---|---|
| Points to nothing | Points to invalid memory |
| Safer | Dangerous |
*** 64. What is a structure?
A structure (struct) is a user-defined data type used to group different data types together.
Syntax
struct Student {
int id;
char name[20];
};
Example
struct Student s1;
s1.id = 1;
Why Structures?
Used to represent real-world entities like:
- Student
- Employee
- Product
Advantage
Can store multiple related values under one name.
Interview Insight
Common follow-up:
“Can structure contain array and pointer?”
Yes.
** 65. What is a union?
A union is a user-defined data type where all members share the same memory location.
Syntax
union Data {
int i;
float f;
};
Important Point
At a time, only one member holds valid value.
Example
union Data d;
d.i = 10;
Main Benefit
Efficient memory usage.
Interview Insight
Very common question:
“Why are unions memory efficient?”
Because all members share same memory space.
*** 66. Difference between structure and union?
| Feature | Structure | Union |
|---|---|---|
| Memory Allocation | Separate for each member | Shared memory |
| Size | Sum of all members | Size of largest member |
| Simultaneous Access | Possible | Not possible |
| Memory Efficiency | Less | More |
Structure Example
struct Test {
int x;
float y;
};
Union Example
union Test {
int x;
float y;
};
Key Difference
Structure -> separate memory
Union -> shared memory
Interview Insight
Common question:
“When should union be used?”
When memory optimization is important.
*** 67. What is linked list?
A linked list is a linear data structure where elements are connected using pointers.
Each element is called:
Node
Node Structure
struct Node {
int data;
struct Node *next;
};
Features
- Dynamic size
- Efficient insertion/deletion
- Non-contiguous memory allocation
Types of Linked Lists
- Singly Linked List
- Doubly Linked List
- Circular Linked List
Representation
10 -> 20 -> 30 -> NULL
Interview Insight
Very common question:
“Why linked list over array?”
Because insertion/deletion is easier.
*** 68. Reverse a linked list
This program reverses a singly linked list.
Logic
Use three pointers:
-
prev -
current -
next
Program
struct Node* reverse(struct Node* head) {
struct Node *prev = NULL;
struct Node *current = head;
struct Node *next = NULL;
while(current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
Before Reversal
10 -> 20 -> 30 -> NULL
After Reversal
30 -> 20 -> 10 -> NULL
Time Complexity
O(n)
Interview Insight
Very frequently asked coding interview problem.
** 69. What is file handling?
File handling allows programs to:
- Create files
- Read files
- Write files
- Modify files
Why Needed?
Data can be stored permanently.
File Operations
- Open
- Read
- Write
- Append
- Close
Important Header
#include <stdio.h>
File Pointer
FILE *fp;
Interview Insight
Common question:
“Why use file handling?”
To store data permanently instead of temporary memory.
*** 70. Explain fopen() and fclose().
fopen()
Used to open a file.
Syntax
FILE *fp = fopen("file.txt", "mode");
Common Modes
| Mode | Purpose |
|---|---|
"r" | Read |
"w" | Write |
"a" | Append |
"r+" | Read & Write |
Example
FILE *fp = fopen("data.txt", "w");
fclose()
Used to close file.
Syntax
fclose(fp);
Why Important?
Closing file:
- Saves data properly
- Releases resources
Example
fclose(fp);
Interview Insight
Common question:
“What happens if file is not closed?”
Possible:
- Data loss
- Memory/resource leaks
*** 71. Explain fprintf() and fscanf().
These functions are used for formatted file operations.
1. fprintf()
Writes formatted data to file.
Syntax
fprintf(fp, "format", variables);
Example
fprintf(fp, "%d %s", 101, "Jitendra");
Similar To
printf()
but output goes to file.
2. fscanf()
Reads formatted data from file.
Syntax
fscanf(fp, "format", variables);
Example
fscanf(fp, "%d %s", &id, name);
Similar To
scanf()
but input comes from file.
Example Program
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("data.txt", "w");
fprintf(fp, "Hello World");
fclose(fp);
return 0;
}
Interview Insight
Very common question:
“Difference between printf() and fprintf()?”
| printf() | fprintf() |
|---|---|
| Output to console | Output to file |