Programming in C and OOP Concepts
What to remember
- C is a structured, procedural, case-sensitive language created by Dennis Ritchie at Bell Labs in the early 1970s. A program starts at `main()` and the compiler turns it into machine code.
- Know data types and sizes, operators and precedence, control statements, loops, functions, arrays, strings, pointers, structures and file handling.
- OOP organises code around objects. Its four pillars are encapsulation, abstraction, inheritance and polymorphism. C++ and Java support OOP; C does not.
1. Basics of C
A C program has: header files (`#include <stdio.h>`), the `main()` function, declarations and statements. Each statement ends with a semicolon. Comments are `//` (single line) and `/* ... */` (multi line). C is case-sensitive and free-form. Steps: write source (.c) → preprocess → compile → assemble → link → executable. A compiler translates the whole program at once; an interpreter translates line by line; an assembler translates assembly code.
Tokens: keywords (reserved words like `int`, `if`, `while`, 32 in classic C), identifiers (names: letters, digits, underscore; cannot start with a digit; cannot be a keyword), constants, strings, operators and punctuators.
Basic data types (typical sizes on a 32/64-bit system): `char` 1 byte, `int` 4 bytes (2 bytes on old 16-bit systems), `float` 4 bytes (about 6 decimal digits), `double` 8 bytes, `short` 2 bytes, `long` 4 or 8 bytes. `void` means no value. Modifiers: `signed`, `unsigned`, `short`, `long`.
Format specifiers: `%d` int, `%f` float, `%lf` double, `%c` char, `%s` string, `%x` hex, `%o` octal, `%u` unsigned, `%p` pointer. `printf()` prints; `scanf()` reads and needs `&` before a simple variable. Escape sequences: `\n` new line, `\t` tab, `\\` backslash.
2. Operators
| Type | Operators | ||
|---|---|---|---|
| Arithmetic | + − * / % | ||
| Relational | < > <= >= == != | ||
| Logical | && \ | \ | ! |
| Assignment | = += −= *= /= %= | ||
| Increment / decrement | ++ −− | ||
| Bitwise | & \ | ^ ~ << >> | |
| Conditional (ternary) | ? : | ||
| Others | sizeof, comma, & (address), * (value at) |
Key points: `%` works only with integers. Integer division drops the fraction: 7/2 = 3. `==` compares, `=` assigns. Pre-increment `++a` changes first then uses; post-increment `a++` uses first then changes. Precedence order (high to low): `()`, unary (`!`, `++`, `−−`), `* / %`, `+ −`, relational, equality, `&&`, `||`, conditional, assignment. Associativity of most binary operators is left to right; assignment is right to left. In `&&` and `||` evaluation stops early (short circuit). Shifts: `x << 1` multiplies by 2; `x >> 1` divides by 2.
Worked example: `int x = 10; x += 5; x %= 4;` gives x = 15 and then x = 3. Another: `int a = 5; int b = a++;` gives b = 5 and a = 6.
3. Control statements and loops
- Decision: `if`, `if-else`, `else if` ladder, nested if, `switch-case`. `switch` works on int or char values; `break` stops fall-through; `default` runs if no case matches.
- Loops: `for` (count known), `while` (entry-controlled, condition first), `do-while` (exit-controlled, runs at least once).
- Jump: `break` leaves a loop or switch; `continue` skips to the next iteration; `goto` jumps to a label; `return` leaves a function.
Example: `for (i = 1; i <= 5; i++) sum += i;` gives sum = 15. A loop `for(;;)` is infinite. In C, any non-zero value is true and zero is false.
4. Functions, arrays and strings
Function: a named block of code. It has a declaration (prototype), a definition and a call. Call by value passes a copy, so the original does not change. Call by reference passes the address (through pointers), so the original can change. Recursion is a function calling itself and needs a base case: `fact(n) = n * fact(n-1)`, `fact(0) = 1`. `fact(5) = 120`. Storage classes: `auto` (default local), `register`, `static` (keeps value between calls), `extern` (global across files). Local variables live inside a function; global variables are declared outside all functions.
Array: a group of same-type elements in continuous memory. Index starts at 0. `int a[5];` has indexes 0 to 4. Size = number of elements × size of type; 5 ints take 20 bytes at 4 bytes each. C does not check array bounds. Two-dimensional arrays are stored row by row (row-major).
String: a character array ending with the null character `\0`. `char s[] = "ABC";` takes 4 bytes. Library functions in `string.h`: `strlen`, `strcpy`, `strcat`, `strcmp` (returns 0 when equal). `ctype.h` has `isalpha`, `toupper`. `math.h` has `sqrt`, `pow`. `stdlib.h` has `malloc`, `free`, `exit`.
5. Pointers, structures and files
A pointer stores the address of another variable. `int *p = &x;` `&` gives the address; `*` gives the value at the address. A pointer to int usually moves by the size of int when incremented. The array name is the address of its first element. A NULL pointer points to nothing. A dangling pointer points to freed memory. Dynamic memory: `malloc` allocates, `calloc` allocates and sets to zero, `realloc` resizes, `free` releases memory (all from `stdlib.h`).
Structure (`struct`) groups items of different types; members are reached with `.` (or `->` with a pointer). Size is at least the sum of its members (padding may add more). A union shares one memory block among members; its size equals the largest member; only one member holds a valid value at a time. An enum gives names to integer constants starting from 0. `typedef` makes a new name for a type.
File handling: `FILE *fp = fopen("a.txt", "r");` Modes: `r` read, `w` write (erases), `a` append, `r+`, `w+`. Functions: `fprintf`, `fscanf`, `fgetc`, `fputc`, `fgets`, `fclose`. `fopen` returns NULL on failure. `EOF` marks end of file. Preprocessor lines start with `#`: `#include`, `#define` (macro), `#ifdef`.
6. Data structures and algorithms basics
A stack is LIFO (push, pop); a queue is FIFO (enqueue, dequeue); a linked list stores nodes with pointers. Linear search checks one by one (worst case n comparisons); binary search needs a sorted array and halves the range (about log₂n comparisons). Simple sorts: bubble, selection, insertion (about n² steps); merge sort and quick sort are faster on average (n log n). An algorithm is a step-by-step solution; a flowchart shows it with symbols (oval for start/stop, parallelogram for input/output, rectangle for process, diamond for decision).
7. Object-oriented programming concepts
OOP models real things as objects. A class is a blueprint; an object is an instance of a class. A class holds data members and member functions (methods).
| Concept | Meaning |
|---|---|
| Encapsulation | Binding data and functions in a class and hiding data using access control (private, public, protected) |
| Abstraction | Showing only essential features, hiding details |
| Inheritance | A child (derived) class gets properties of a parent (base) class; gives reuse |
| Polymorphism | One name, many forms |
Polymorphism: *compile-time* (static) through function overloading and operator overloading; *run-time* (dynamic) through function overriding and virtual functions. Constructor is a special function that runs when an object is created; it has the class name and no return type. A destructor runs when the object is destroyed (in C++ its name starts with `~`). Types of inheritance: single, multiple, multilevel, hierarchical, hybrid. C++ allows multiple inheritance of classes; Java allows it only through interfaces. C++ was created by Bjarne Stroustrup as "C with Classes". Java was created at Sun Microsystems by James Gosling; it is platform independent through the bytecode and the Java Virtual Machine (JVM). A message is a call of an object's method. C++ uses `cout <<` and `cin >>` for output and input; `new` and `delete` manage dynamic memory.
Worked examples
- 1. Loop output: `int i, s = 0; for (i = 1; i <= 4; i++) s = s + i * i;` gives 1 + 4 + 9 + 16 = 30.
- 2. Integer division: `int a = 7, b = 2; float c = a / b;` stores 3.0 (integer division first). `float c = (float)a / b;` gives 3.5.
- 3. Array size: `int a[10];` takes 10 × 4 = 40 bytes when int is 4 bytes; the last element is `a[9]`.
- 4. Pointer: `int x = 5; int *p = &x; *p = 8;` changes x to 8. `p` holds the address of x.
- 5. Switch: with `switch(2) { case 1: a; case 2: b; case 3: c; break; }`, execution starts at case 2 and falls through to case 3 because case 2 has no break, so b and c both run.
- 6. Recursion: `fact(4) = 4 × 3 × 2 × 1 = 24`.
- 7. Binary search: in a sorted array of 16 elements, at most 5 comparisons are needed in the worst case, since log₂16 = 4 and one more for the last step.
Exam traps
- `=` assigns, `==` compares.
- `while` tests first; `do-while` runs at least once.
- Call by value cannot change the caller's variable; pass an address to do so.
- A string of n characters needs n + 1 bytes for the null character.
- Array index starts at 0; the last index is size − 1.
- Struct members have separate memory; union members share memory.
- Overloading is compile time; overriding is run time.
- C is procedural; C++ supports both procedural and OOP.
One-liners
- 1. C was developed by Dennis Ritchie.
- 2. Execution of a C program starts at `main()`.
- 3. `%` gives the remainder.
- 4. `break` exits a loop or switch.
- 5. `\0` ends a string.
- 6. `&` gives an address; `*` gives the value at that address.
- 7. `malloc` allocates memory dynamically.
- 8. A union's size equals its largest member.
- 9. A class is a blueprint of objects.
- 10. Inheritance gives code reuse.
- 11. A constructor runs when an object is created.
- 12. C++ was created by Bjarne Stroustrup.
Practice questions
The C language was developed by
- Linus Torvalds
- James Gosling
- Bjarne Stroustrup
- Dennis Ritchie
Answer
D. Dennis Ritchie
C was created by Dennis Ritchie at Bell Labs.
Execution of every C program begins from the function
- begin()
- printf()
- main()
- start()
Answer
C. main()
The program starts at main().
Which format specifier is used to print an integer?
- %c
- %d
- %f
- %s
Answer
B. %d
%d integer, %f float, %c char, %s string.
Which symbol ends a statement in C?
- Full stop
- Colon
- Comma
- Semicolon
Answer
D. Semicolon
Each C statement ends with a semicolon.
The operator that gives the remainder of integer division is
- *
- &
- /
- %
Answer
D. %
% is the modulus operator.
Which loop is guaranteed to execute its body at least once?
- do-while
- for
- while
- nested if
Answer
A. do-while
do-while tests the condition after the body.
Which keyword is used to leave a loop or switch immediately?
- continue
- break
- goto only
- exit loop
Answer
B. break
break leaves the nearest loop or switch.
A string in C ends with the character
- EOF
- \n
- \0
- \t
Answer
C. \0
The null character marks the end of a string.
The index of the first element of a C array is
- 1
- -1
- Any value chosen by the user
- 0
Answer
D. 0
C arrays are zero-indexed.
In C, the operator that gives the address of a variable is
- &
- %
- *
- ->
Answer
A. &
& gives the address; * gives the value at the address.
A class in OOP is best described as
- a header file
- a blueprint for objects
- a loop statement
- a file type
Answer
B. a blueprint for objects
Objects are instances of a class.
Which OOP feature allows a class to acquire the properties of another class?
- Abstraction
- Overloading
- Inheritance
- Encapsulation
Answer
C. Inheritance
A derived class inherits from a base class.
Binding data and functions together in a class and hiding the data is
- recursion
- encapsulation
- inheritance
- polymorphism
Answer
B. encapsulation
Encapsulation = data hiding plus binding.
Who created C++?
- Bjarne Stroustrup
- Guido van Rossum
- James Gosling
- Dennis Ritchie
Answer
A. Bjarne Stroustrup
Stroustrup developed C++ as C with Classes.
What is the value of x after: int x = 10; x += 5; x %= 4;
- 15
- 3
- 5
- 1
Answer
B. 3
x = 15, then 15 % 4 = 3.
What is stored in float c after: int a = 7, b = 2; float c = a / b;
- 4.0
- 2.0
- 3.5
- 3.0
Answer
D. 3.0
Integer division gives 3, stored as 3.0.
What is the output sum of: for (i = 1; i <= 4; i++) s = s + i * i; (s starts at 0)?
- 10
- 20
- 30
- 16
Answer
C. 30
1 + 4 + 9 + 16 = 30.
An int array a[10] occupies how many bytes when int takes 4 bytes?
- 44
- 10
- 40
- 14
Answer
C. 40
10 × 4 = 40 bytes.
For the declaration int a[10], the last valid index is
- 11
- 8
- 10
- 9
Answer
D. 9
Valid indexes are 0 to 9.
A string "ABC" stored in a char array needs at least how many bytes?
- 3
- 5
- 4
- 6
Answer
C. 4
Three characters plus the null character.
With int x = 5; int *p = &x; the statement *p = 8; will
- change x to 8
- change p to 8
- change the address of x
- cause a compile error
Answer
A. change x to 8
*p is the value at the address stored in p, which is x.
Which of the following is a correct statement about a union?
- Its members share the same memory
- Each member has its own memory
- It can hold only one member
- Its size equals the sum of members
Answer
A. Its members share the same memory
A union's members share memory; size is the largest member.
A function call that passes copies of the arguments is
- recursion
- overloading
- call by reference
- call by value
Answer
D. call by value
Call by value cannot change the caller's variables.
fact(5) computed recursively as n × fact(n−1) with fact(0) = 1 equals
- 60
- 120
- 720
- 24
Answer
B. 120
5 × 4 × 3 × 2 × 1 = 120.
Which function from stdlib.h allocates memory at run time?
- strlen()
- sqrt()
- malloc()
- printf()
Answer
C. malloc()
malloc allocates dynamic memory; free releases it.
Which function compares two strings and returns 0 if they are equal?
- strlen()
- strcat()
- strcpy()
- strcmp()
Answer
D. strcmp()
strcmp returns 0 for equal strings.
Which file mode in fopen() erases the old contents and opens the file for writing?
- "r"
- "w"
- "r+"
- "a"
Answer
B. "w"
w creates or truncates a file; a appends.
Which one is a stack data structure property?
- First in, first out
- Random access only
- Last in, first out
- Sorted order only
Answer
C. Last in, first out
A stack is LIFO; a queue is FIFO.
The maximum number of comparisons for binary search in a sorted array of 16 elements is about
- 16
- 8
- 2
- 5
Answer
D. 5
log2(16) = 4, plus one for the final check gives 5.
Compile-time polymorphism is achieved through
- function overloading
- function overriding
- virtual functions
- destructors
Answer
A. function overloading
Overloading is resolved at compile time; overriding at run time.
A constructor in C++ has
- a name starting with ~
- the same name as the class and no return type
- only a void return type
- no relation to the class name
Answer
B. the same name as the class and no return type
A destructor starts with ~; a constructor shares the class name.
Which statement about the conditional operator is correct?
- It takes two operands
- It takes one operand
- It takes three operands
- It works only with strings
Answer
C. It takes three operands
The form is condition ? a : b.
In C, the loop for(;;) is
- an infinite loop
- a loop that runs once
- a loop that never starts
- a syntax error
Answer
A. an infinite loop
With no condition the loop never ends.
Consider switch(2) { case 1: a; case 2: b; case 3: c; break; case 4: d; }. Which of a, b, c, d are executed?
- b and c
- only b
- a, b and c
- b, c and d
Answer
A. b and c
Execution starts at case 2 and falls through to case 3, where break stops it.
Consider these statements about C. 1. C is case-sensitive. 2. Every identifier may start with a digit. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
A. 1 only
Identifiers cannot start with a digit.
Consider these statements about loops. 1. A while loop tests its condition before the body. 2. A do-while loop tests its condition after the body. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
C. Both 1 and 2
Both are correct.
Consider these statements about functions. 1. Call by reference can change the original variable. 2. Recursion needs a base case. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
C. Both 1 and 2
Both are correct.
Consider these statements about structures and unions. 1. Each member of a structure has its own memory. 2. A union can hold valid values in all members at the same time. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
A. 1 only
Union members share memory, so only one holds a valid value; 2 is wrong.
Consider these statements about OOP. 1. Function overloading is run-time polymorphism. 2. Function overriding is run-time polymorphism. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
B. 2 only
Overloading is compile time; only 2 is correct.
Consider these statements about C and OOP. 1. C is a procedural language. 2. C++ supports object-oriented programming. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
C. Both 1 and 2
Both are correct.
Consider these statements about pointers. 1. A pointer stores the address of a variable. 2. The array name gives the address of its first element. Which is/are correct?
- 1 only
- 2 only
- Both 1 and 2
- Neither 1 nor 2
Answer
C. Both 1 and 2
Both are correct.
Match the item with its meaning. P. malloc Q. free R. sizeof 1. Releases memory 2. Allocates memory 3. Gives size of a type or variable
- P-2, Q-3, R-1
- P-1, Q-2, R-3
- P-3, Q-1, R-2
- P-2, Q-1, R-3
Answer
D. P-2, Q-1, R-3
malloc allocates, free releases, sizeof gives the size.
Match the flowchart symbol with its use. P. Parallelogram Q. Diamond R. Oval 1. Start or stop 2. Input or output 3. Decision
- P-3, Q-2, R-1
- P-2, Q-1, R-3
- P-1, Q-3, R-2
- P-2, Q-3, R-1
Answer
D. P-2, Q-3, R-1
Parallelogram is I/O, diamond is a decision, oval is start/stop.
Match the OOP concept with its meaning. P. Abstraction Q. Polymorphism R. Inheritance 1. One name, many forms 2. Showing only essential details 3. Reusing a parent class's properties
- P-3, Q-1, R-2
- P-2, Q-1, R-3
- P-1, Q-2, R-3
- P-2, Q-3, R-1
Answer
B. P-2, Q-1, R-3
Abstraction hides detail, polymorphism gives many forms, inheritance reuses a parent class.
Which of the following is the destructor of a class named Box in C++?
- !Box()
- ~Box()
- Box()
- delete Box
Answer
B. ~Box()
A destructor name is the class name preceded by ~.