0% found this document useful (0 votes)
3 views22 pages

c

The document provides a comprehensive overview of the C programming language, covering its history, fundamental concepts, data types, control flow, functions, pointers, and advanced topics such as dynamic memory allocation and error handling. It includes real-world applications, coding examples, interview questions, and coding problems from various tech companies. Additionally, it features a section on the C Standard Library and common interview questions related to memory management and pointers.

Uploaded by

mhiiii4808
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)
3 views22 pages

c

The document provides a comprehensive overview of the C programming language, covering its history, fundamental concepts, data types, control flow, functions, pointers, and advanced topics such as dynamic memory allocation and error handling. It includes real-world applications, coding examples, interview questions, and coding problems from various tech companies. Additionally, it features a section on the C Standard Library and common interview questions related to memory management and pointers.

Uploaded by

mhiiii4808
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/ 22

1.

Fundamentals of C

History and Importance

• Developed by Dennis Ritchie at Bell Labs (1972)

• Why C still matters: Used in OS kernels, embedded systems, databases

First C Program with Explanation

Copy

Download

#include <stdio.h> // Standard I/O header

int main() { // Program entry point

printf("Hello World!"); // Output function

return 0; // Exit status

Real-World Application:

• Used in Mars Rover software (NASA)

• Linux kernel is written in C

Compilation Process (Block Diagram)

text

Copy

Download

[Source Code] → [Preprocessor] → [Compiler] →

[Assembler] → [Linker] → [Executable]

Interview Questions (Google)

Q: Why is C called the "mother of all languages"?


A: Because most modern languages (C++, Java, Python) inherit concepts from C.

Q: What is the difference between compiler and interpreter?


A: Compiler translates entire program at once, interpreter executes line by line.
2. Data Types and Variables

Primitive Data Types

int age = 25; // 4 bytes (-2B to +2B)

float price = 99.99; // 4 bytes (6-7 decimal digits)

char grade = 'A'; // 1 byte (-128 to 127)

double pi = 3.14159265; // 8 bytes (15 decimal digits)

Real-World Example: Banking System

#include <stdio.h>

int main() {

long account_no = 1234567890;

char account_type = 'S'; // S for savings

float balance = 25000.50;

printf("Account Details:\n");

printf("Account No: %ld\nType: %c\nBalance: $%.2f",

account_no, account_type, balance);

return 0;

Memory Layout (Diagram)

text

Copy

Download

+-------------+------------+-------+

| Variable | Memory | Value |

+-------------+------------+-------+

| age | 0x7ffe.. | 25 |

| price | 0x7ffe.. | 99.99 |

+-------------+------------+-------+
Interview Questions (Microsoft)

Q: What happens if you assign 300 to a char variable?


A: Integer overflow occurs as char range is -128 to 127.

Q: Why use double instead of float?


A: When higher precision (15 digits) is needed, like in scientific calculations.

3. Operators and Expressions

Operator Types with Examples

Copy

Download

int a = 10, b = 3;

// Arithmetic

int sum = a + b; // 13

int mod = a % b; // 1

// Bitwise

int and = a & b; // 2 (1010 & 0011 = 0010)

Real-World Example: Temperature Conversion

Copy

Download

#include <stdio.h>

int main() {

float celsius = 37.5;

float fahrenheit = (celsius * 9/5) + 32;

printf("%.2f°C = %.2f°F", celsius, fahrenheit);

return 0;

Operator Precedence Table

text
Copy

Download

1. () [] -> .

2. ! ~ ++ -- + - * & (type) sizeof

3. * / %

4. + -

5. << >>

...

Coding Problem (Amazon)

Swap two numbers without temporary variable:

Copy

Download

a = a + b;

b = a - b;

a = a - b;

4. Control Flow

if-else with Real Example: Loan Eligibility

Copy

Download

#include <stdio.h>

int main() {

int age = 22;

float income = 45000.0;

if(age >= 21 && income > 30000) {

printf("Loan Approved");

} else {
printf("Not Eligible");

return 0;

Switch Case: Calculator Program

Copy

Download

switch(operator) {

case '+': result = a + b; break;

case '-': result = a - b; break;

// ... other operations

default: printf("Invalid operator");

Flowchart Diagram

text

Copy

Download

[Start] → [Condition] → [True/False] → [Action] → [End]

Interview Questions (Facebook)

Q: When would you use switch instead of if-else?


A: When testing a single variable against multiple constant values.

Q: What is the danger of missing 'break' in switch?


A: Execution will "fall through" to next case.

5. Functions (Complete Coverage)

5.1 Function Basics

Copy

Download

// Function declaration

int add(int a, int b);


// Function definition

int add(int a, int b) {

return a + b;

// Function call

int result = add(3, 4);

Real-World Example:
Payment processing function in an e-commerce system:

Copy

Download

float process_payment(float amount, float tax_rate) {

float tax = amount * tax_rate;

return amount + tax;

Memory Diagram:

text

Copy

Download

[Stack Frame]

+-------------------+

| Return Address |

| Parameters (a, b) |

| Local Variables |

+-------------------+

Interview Question (Goldman Sachs):


Q: What happens when you call a function recursively too many times?
A: Stack overflow occurs due to unlimited stack frame allocation.

5.2 Parameter Passing Techniques


Pass by Value

Copy

Download

void square(int x) { x = x * x; } // Original unchanged

Pass by Reference

Copy

Download

void square(int *x) { *x = (*x) * (*x); } // Original modified

Real-World Example:
Swapping sensor readings in embedded systems:

Copy

Download

void swap_readings(float *a, float *b) {

float temp = *a;

*a = *b;

*b = temp;

Interview Question (Amazon):


Q: When would you use return-by-pointer vs return-by-value?
A: Return-by-pointer for large structures to avoid copying; return-by-value for primitive types.

5.3 Recursion

Copy

Download

int factorial(int n) {

if (n <= 1) return 1;

return n * factorial(n - 1);

}
Execution Diagram:

text

Copy

Download

factorial(3)

→ 3 * factorial(2)

→ 2 * factorial(1)

→ 1 (base case)

Coding Problem (Google):


Implement Fibonacci recursively and iteratively:

Copy

Download

// Recursive

int fib(int n) {

if (n <= 1) return n;

return fib(n-1) + fib(n-2);

// Iterative

int fib(int n) {

int a = 0, b = 1, c;

for (int i = 2; i <= n; i++) {

c = a + b;

a = b;

b = c;

return b;

6. Arrays & Strings


6.1 1D/2D Arrays

Copy

Download

// Matrix multiplication

void mat_mult(int A[][3], int B[][3], int C[][3]) {

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

for(int j=0; j<3; j++)

for(int k=0; k<3; k++)

C[i][j] += A[i][k] * B[k][j];

Memory Layout:

text

Copy

Download

Row-Major Order:

[ a[0][0] | a[0][1] | a[1][0] | a[1][1] ]

Interview Question (NVIDIA):


Q: How would you optimize 2D array access for cache performance?
A: Access elements row-wise to leverage spatial locality.

7. Pointers Deep Dive

7.1 Pointer Arithmetic

Copy

Download

int arr[] = {10, 20, 30};

int *ptr = arr;

printf("%d", *(ptr + 1)); // Output: 20

Pointer-Array Relationship:

Copy
Download

arr[i] ≡ *(arr + i) ≡ *(ptr + i) ≡ ptr[i]

Interview Question (Microsoft):


*Q: What is *(a + 2) if a is an array?*
A: Equivalent to a[2], accesses the third element.

8. Structures & Unions

8.1 Nested Structures

Copy

Download

struct Address {

char city[20];

int pin;

};

struct Employee {

int id;

struct Address addr;

};

Memory Alignment Diagram:

text

Copy

Download

struct Example {

char c; // 1 byte

// 3 bytes padding

int i; // 4 bytes

}; // Total size: 8 bytes

Coding Problem (Cisco):


Create a network packet structure:

c
Copy

Download

#pragma pack(1) // Disable padding

struct Packet {

uint16_t src_port;

uint16_t dest_port;

uint32_t seq_num;

char data[100];

};

9. File Handling

9.1 Binary File Operations

Copy

Download

// Write struct to file

struct Record r = {101, "John", 95.5};

FILE *fp = fopen("data.bin", "wb");

fwrite(&r, sizeof(struct Record), 1, fp);

// Random access

fseek(fp, 2 * sizeof(struct Record), SEEK_SET);

fread(&r, sizeof(struct Record), 1, fp);

File Pointer Diagram:

text

Copy

Download

[ BOF | Record 1 | Record 2 | ... | EOF ]

File Position
10. Dynamic Memory Allocation

10.1 Custom Memory Manager

Copy

Download

#define POOL_SIZE 1024

char memory_pool[POOL_SIZE];

char *pool_ptr = memory_pool;

void* my_malloc(size_t size) {

if (pool_ptr + size > memory_pool + POOL_SIZE)

return NULL;

void *block = pool_ptr;

pool_ptr += size;

return block;

Heap Fragmentation Diagram:

text

Copy

Download

[ Alloc1 | Free | Alloc2 | Free | Alloc3 ]

11. Advanced Topics

11.1 Function Pointers

Copy

Download

int (*operation)(int, int); // Declaration

operation = add; // Assignment

result = operation(3, 4); // Invocation


Real-World Use:
Plugin architectures in web servers:

Copy

Download

typedef void (*plugin_init)();

void load_plugin(const char *lib) {

void *handle = dlopen(lib, RTLD_LAZY);

plugin_init init = (plugin_init)dlsym(handle, "init");

init();

12. Interview Crack Kit

Top 10 Tricky Questions

1. "What does ((void()())0)(); do?"


A: Calls the function at address 0 (likely causes segmentation fault).

2. "Implement atoi()"

Copy

Download

int my_atoi(const char *s) {

int res = 0;

while (*s >= '0' && *s <= '9')

res = res * 10 + (*s++ - '0');

return res;

Company-Specific Problems

• Facebook: "Reverse a string in place"

• Intel: "Bit manipulation interview questions"

• SpaceX: "Memory-constrained embedded coding challenges"

Complete Appendix
A. Standard Library Cheat Sheet

Copy

Download

// String

strlen(), strncpy(), strncat()

// Math

pow(), sqrt(), abs()

// Memory

memset(), memcpy(), memmove()

B. Compilation Flags

sh

Copy

Download

gcc -Wall -Wextra -O3 -g -o program program.c

C. GDB Quick Reference

sh

Copy

Download

break main

watch variable

backtrace

print *(array@10)

14. Bit Manipulation

Bit Masking & Shifting

Copy

Download

// Set bit
num |= (1 << position);

// Clear bit

num &= ~(1 << position);

// Toggle bit

num ^= (1 << position);

// Check bit

bit = (num >> position) & 1;

Endianness Check:

Copy

Download

int x = 1;

if(*(char*)&x == 1) {

printf("Little Endian");

} else {

printf("Big Endian");

Real-World Example:
Device register configuration (Embedded Systems):

Copy

Download

#define LED_ON (1 << 5)

PORTB |= LED_ON; // Turn on LED at bit 5

Interview Question (Qualcomm):


Q: Count the number of set bits in an integer

Copy

Download
int count_set_bits(int num) {

int count = 0;

while(num) {

count += num & 1;

num >>= 1;

return count;

// Optimized version (Brian Kernighan's):

while(num) {

num &= (num - 1);

count++;

15. Error Handling

Standard Techniques

Copy

Download

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

if(fp == NULL) {

perror("Error");

fprintf(stderr, "Error code: %d\n", errno);

exit(EXIT_FAILURE);

// Assertions

assert(ptr != NULL && "Pointer is NULL");

Robust File Copy:

Copy
Download

void safe_file_copy(const char *src, const char *dest) {

FILE *in = fopen(src, "rb");

if(!in) { /* error handling */ }

FILE *out = fopen(dest, "wb");

if(!out) {

fclose(in);

/* error handling */

char buffer[4096];

size_t bytes;

while((bytes = fread(buffer, 1, sizeof(buffer), in)) > 0) {

if(fwrite(buffer, 1, bytes, out) != bytes) {

/* error handling */

fclose(in);

fclose(out);

Coding Problem (Banking):


Safe Division with Error Checking:

Copy

Download

int safe_divide(int a, int b, int *result) {

if(b == 0) {

errno = EDOM; // Domain error

return -1;
}

if((a == INT_MIN) && (b == -1)) {

errno = ERANGE; // Overflow

return -1;

*result = a / b;

return 0;

16. C Standard Library

Key Libraries

Copy

Download

// math.h

double root = sqrt(25.0);

double sine = sin(3.14159/2);

// time.h

time_t now = time(NULL);

printf("Current time: %s", ctime(&now));

// stdlib.h

int random = rand() % 100; // 0-99

qsort(arr, n, sizeof(int), compare_func);

Random Password Generator:

Copy

Download

char* generate_password(int length) {

char *pass = malloc(length + 1);


const char charset[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

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

int key = rand() % (sizeof(charset) - 1);

pass[i] = charset[key];

pass[length] = '\0';

return pass;

Interview Question (Apple):


Q: How does qsort() work internally?
A: Typically implements QuickSort with:

1. Median-of-three pivot selection

2. Insertion sort for small partitions

3. Stack-based iteration to avoid recursion overflow

50+ C Interview Questions from Top Companies

Memory Management

1. Microsoft: What's the difference between malloc() and calloc()?


→ malloc() allocates uninitialized memory, calloc() initializes to zero.

2. Google: How to detect memory leaks in C?


→ Use tools like Valgrind or custom allocators with logging.

3. Amazon: What is a dangling pointer?


→ Pointer pointing to freed memory. Solution: Set to NULL after free().

Pointers

4. Facebook: Explain void* in C.


→ Generic pointer type that can point to any data type.

5. Goldman Sachs: What is pointer arithmetic?


→ Math operations on pointers considering the size of pointed type.

6. Cisco: Difference between int* p and int *p?


→ Both are equivalent, but int *p emphasizes pointer-ness of p.

Strings

7. Oracle: Implement strcpy().


c

Copy

Download

char* my_strcpy(char *dest, const char *src) {

char *ret = dest;

while((*dest++ = *src++));

return ret;

8. VMware: Why is strncpy() safer than strcpy()?


→ Allows specifying maximum bytes to copy, preventing buffer overflow.

Bit Manipulation

9. Intel: Swap two variables without temporary variable.

Copy

Download

a ^= b; b ^= a; a ^= b;

10. Qualcomm: Check if a number is power of 2.

Copy

Download

(num & (num - 1)) == 0

Data Structures

11. Apple: Reverse a linked list.

Copy

Download

struct Node* reverse(struct Node* head) {

struct Node *prev = NULL, *next = NULL;

while(head) {

next = head->next;

head->next = prev;
prev = head;

head = next;

return prev;

Multithreading

12. Microsoft: What is a race condition?


→ When threads access shared data concurrently without synchronization.

Advanced Concepts

13. SpaceX: Why is volatile used in embedded C?


→ Prevents compiler optimization of hardware register accesses.

14. NVIDIA: What is restrict keyword?


→ Tells compiler that a pointer is the only reference to its data.

Tricky Questions

15. Google: What does ++a++ do?


→ Syntax error (can't modify an rvalue).

16. Meta: Explain "Hello"[2].


→ Returns 'l' (array indexing works on string literals).

Real-World Problems

17. Goldman Sachs: Safe string concatenation.

Copy

Download

strncat(dest, src, dest_size - strlen(dest) - 1);

18. Tesla: Read a file line by line.

Copy

Download

char line[256];

while(fgets(line, sizeof(line), fp)) {

// Process line

Library Functions
19. Apple: Implement memmove().

Copy

Download

void* my_memmove(void *dest, const void *src, size_t n) {

char *d = dest;

const char *s = src;

if(d < s) {

while(n--) *d++ = *s++;

} else {

char *lastd = d + n - 1;

char *lasts = (char*)s + n - 1;

while(n--) *lastd-- = *lasts--;

return dest;

System Programming

20. Cisco: What is errno?


→ Global variable indicating last error number.

You might also like