←
Computer Science and Electronics for Digital Assistant · Chapter 6

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

TypeOperators
Arithmetic+ − * / %
Relational< > <= >= == !=
Logical&& \\!
Assignment= += −= *= /= %=
Increment / decrement++ −−
Bitwise& \^ ~ << >>
Conditional (ternary)? :
Otherssizeof, 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).

ConceptMeaning
EncapsulationBinding data and functions in a class and hiding data using access control (private, public, protected)
AbstractionShowing only essential features, hiding details
InheritanceA child (derived) class gets properties of a parent (base) class; gives reuse
PolymorphismOne 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

  1. The C language was developed by

    1. Linus Torvalds
    2. James Gosling
    3. Bjarne Stroustrup
    4. Dennis Ritchie
    Answer

    D. Dennis Ritchie

    C was created by Dennis Ritchie at Bell Labs.

  2. Execution of every C program begins from the function

    1. begin()
    2. printf()
    3. main()
    4. start()
    Answer

    C. main()

    The program starts at main().

  3. Which format specifier is used to print an integer?

    1. %c
    2. %d
    3. %f
    4. %s
    Answer

    B. %d

    %d integer, %f float, %c char, %s string.

  4. Which symbol ends a statement in C?

    1. Full stop
    2. Colon
    3. Comma
    4. Semicolon
    Answer

    D. Semicolon

    Each C statement ends with a semicolon.

  5. The operator that gives the remainder of integer division is

    1. *
    2. &
    3. /
    4. %
    Answer

    D. %

    % is the modulus operator.

  6. Which loop is guaranteed to execute its body at least once?

    1. do-while
    2. for
    3. while
    4. nested if
    Answer

    A. do-while

    do-while tests the condition after the body.

  7. Which keyword is used to leave a loop or switch immediately?

    1. continue
    2. break
    3. goto only
    4. exit loop
    Answer

    B. break

    break leaves the nearest loop or switch.

  8. A string in C ends with the character

    1. EOF
    2. \n
    3. \0
    4. \t
    Answer

    C. \0

    The null character marks the end of a string.

  9. The index of the first element of a C array is

    1. 1
    2. -1
    3. Any value chosen by the user
    4. 0
    Answer

    D. 0

    C arrays are zero-indexed.

  10. In C, the operator that gives the address of a variable is

    1. &
    2. %
    3. *
    4. ->
    Answer

    A. &

    & gives the address; * gives the value at the address.

  11. A class in OOP is best described as

    1. a header file
    2. a blueprint for objects
    3. a loop statement
    4. a file type
    Answer

    B. a blueprint for objects

    Objects are instances of a class.

  12. Which OOP feature allows a class to acquire the properties of another class?

    1. Abstraction
    2. Overloading
    3. Inheritance
    4. Encapsulation
    Answer

    C. Inheritance

    A derived class inherits from a base class.

  13. Binding data and functions together in a class and hiding the data is

    1. recursion
    2. encapsulation
    3. inheritance
    4. polymorphism
    Answer

    B. encapsulation

    Encapsulation = data hiding plus binding.

  14. Who created C++?

    1. Bjarne Stroustrup
    2. Guido van Rossum
    3. James Gosling
    4. Dennis Ritchie
    Answer

    A. Bjarne Stroustrup

    Stroustrup developed C++ as C with Classes.

  15. What is the value of x after: int x = 10; x += 5; x %= 4;

    1. 15
    2. 3
    3. 5
    4. 1
    Answer

    B. 3

    x = 15, then 15 % 4 = 3.

  16. What is stored in float c after: int a = 7, b = 2; float c = a / b;

    1. 4.0
    2. 2.0
    3. 3.5
    4. 3.0
    Answer

    D. 3.0

    Integer division gives 3, stored as 3.0.

  17. What is the output sum of: for (i = 1; i <= 4; i++) s = s + i * i; (s starts at 0)?

    1. 10
    2. 20
    3. 30
    4. 16
    Answer

    C. 30

    1 + 4 + 9 + 16 = 30.

  18. An int array a[10] occupies how many bytes when int takes 4 bytes?

    1. 44
    2. 10
    3. 40
    4. 14
    Answer

    C. 40

    10 × 4 = 40 bytes.

  19. For the declaration int a[10], the last valid index is

    1. 11
    2. 8
    3. 10
    4. 9
    Answer

    D. 9

    Valid indexes are 0 to 9.

  20. A string "ABC" stored in a char array needs at least how many bytes?

    1. 3
    2. 5
    3. 4
    4. 6
    Answer

    C. 4

    Three characters plus the null character.

  21. With int x = 5; int *p = &x; the statement *p = 8; will

    1. change x to 8
    2. change p to 8
    3. change the address of x
    4. cause a compile error
    Answer

    A. change x to 8

    *p is the value at the address stored in p, which is x.

  22. Which of the following is a correct statement about a union?

    1. Its members share the same memory
    2. Each member has its own memory
    3. It can hold only one member
    4. 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.

  23. A function call that passes copies of the arguments is

    1. recursion
    2. overloading
    3. call by reference
    4. call by value
    Answer

    D. call by value

    Call by value cannot change the caller's variables.

  24. fact(5) computed recursively as n × fact(n−1) with fact(0) = 1 equals

    1. 60
    2. 120
    3. 720
    4. 24
    Answer

    B. 120

    5 × 4 × 3 × 2 × 1 = 120.

  25. Which function from stdlib.h allocates memory at run time?

    1. strlen()
    2. sqrt()
    3. malloc()
    4. printf()
    Answer

    C. malloc()

    malloc allocates dynamic memory; free releases it.

  26. Which function compares two strings and returns 0 if they are equal?

    1. strlen()
    2. strcat()
    3. strcpy()
    4. strcmp()
    Answer

    D. strcmp()

    strcmp returns 0 for equal strings.

  27. Which file mode in fopen() erases the old contents and opens the file for writing?

    1. "r"
    2. "w"
    3. "r+"
    4. "a"
    Answer

    B. "w"

    w creates or truncates a file; a appends.

  28. Which one is a stack data structure property?

    1. First in, first out
    2. Random access only
    3. Last in, first out
    4. Sorted order only
    Answer

    C. Last in, first out

    A stack is LIFO; a queue is FIFO.

  29. The maximum number of comparisons for binary search in a sorted array of 16 elements is about

    1. 16
    2. 8
    3. 2
    4. 5
    Answer

    D. 5

    log2(16) = 4, plus one for the final check gives 5.

  30. Compile-time polymorphism is achieved through

    1. function overloading
    2. function overriding
    3. virtual functions
    4. destructors
    Answer

    A. function overloading

    Overloading is resolved at compile time; overriding at run time.

  31. A constructor in C++ has

    1. a name starting with ~
    2. the same name as the class and no return type
    3. only a void return type
    4. 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.

  32. Which statement about the conditional operator is correct?

    1. It takes two operands
    2. It takes one operand
    3. It takes three operands
    4. It works only with strings
    Answer

    C. It takes three operands

    The form is condition ? a : b.

  33. In C, the loop for(;;) is

    1. an infinite loop
    2. a loop that runs once
    3. a loop that never starts
    4. a syntax error
    Answer

    A. an infinite loop

    With no condition the loop never ends.

  34. Consider switch(2) { case 1: a; case 2: b; case 3: c; break; case 4: d; }. Which of a, b, c, d are executed?

    1. b and c
    2. only b
    3. a, b and c
    4. b, c and d
    Answer

    A. b and c

    Execution starts at case 2 and falls through to case 3, where break stops it.

  35. Consider these statements about C. 1. C is case-sensitive. 2. Every identifier may start with a digit. Which is/are correct?

    1. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    A. 1 only

    Identifiers cannot start with a digit.

  36. 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. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    C. Both 1 and 2

    Both are correct.

  37. 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. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    C. Both 1 and 2

    Both are correct.

  38. 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. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    A. 1 only

    Union members share memory, so only one holds a valid value; 2 is wrong.

  39. Consider these statements about OOP. 1. Function overloading is run-time polymorphism. 2. Function overriding is run-time polymorphism. Which is/are correct?

    1. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    B. 2 only

    Overloading is compile time; only 2 is correct.

  40. Consider these statements about C and OOP. 1. C is a procedural language. 2. C++ supports object-oriented programming. Which is/are correct?

    1. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    C. Both 1 and 2

    Both are correct.

  41. 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. 1 only
    2. 2 only
    3. Both 1 and 2
    4. Neither 1 nor 2
    Answer

    C. Both 1 and 2

    Both are correct.

  42. 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

    1. P-2, Q-3, R-1
    2. P-1, Q-2, R-3
    3. P-3, Q-1, R-2
    4. P-2, Q-1, R-3
    Answer

    D. P-2, Q-1, R-3

    malloc allocates, free releases, sizeof gives the size.

  43. Match the flowchart symbol with its use. P. Parallelogram Q. Diamond R. Oval 1. Start or stop 2. Input or output 3. Decision

    1. P-3, Q-2, R-1
    2. P-2, Q-1, R-3
    3. P-1, Q-3, R-2
    4. 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.

  44. 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

    1. P-3, Q-1, R-2
    2. P-2, Q-1, R-3
    3. P-1, Q-2, R-3
    4. 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.

  45. Which of the following is the destructor of a class named Box in C++?

    1. !Box()
    2. ~Box()
    3. Box()
    4. delete Box
    Answer

    B. ~Box()

    A destructor name is the class name preceded by ~.

Page 1 of 1
‹
›