Docsity

C++ Programming Handouts, Summaries of C programming

Toggle sidebar
bg1
CS201 — Introduction to Programming (C++) | Midterm Notes | VU Pakistan Page 1
CS201
Introduction to Programming (C++)
MIDTERM Notes — Lectures 1 to 22
MCQs | Short Questions | Long Questions | Code Examples
Virtual University of Pakistan — Compact Print-Ready Edition
MID-TERM: Lectures 1–22 | FINAL: Lectures 23 onwards | Reference Book: Deitel & Deitel — C++ How to
Program
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download C++ Programming Handouts and more Summaries C programming in PDF only on Docsity!

CS

Introduction to Programming (C++)

MIDTERM Notes — Lectures 1 to 22

MCQs | Short Questions | Long Questions | Code Examples

Virtual University of Pakistan — Compact Print-Ready Edition

MID-TERM: Lectures 1–22 | FINAL: Lectures 23 onwards | Reference Book: Deitel & Deitel — C++ How to Program

Lectures 1–2 — Introduction to Programming & Software

What is programming | Software types | History of C

What is Programming?

Definition: "A program is a precise sequence of steps to solve a particular problem."

Programming develops: Critical reading | Analytical thinking | Creative synthesis

Skills Needed for Programming:

Pay attention to detail Logic and calculations matter — grammatically correct code can still produce wrong results Think about reusability Write code that can be reused for related problems (e.g., area of circle → reuse for area of ring) Think about user interface

Never assume users are computer literate — make UI self-explanatory

Computers are stupid They do EXACTLY what you tell them — no more, no less. Be explicit. Comment the code Comments are ignored by compiler but help other programmers understand the code

Design Recipe (How to design a program):

  1. Analyze the problem statement carefully
  2. Express its essence abstractly with examples
  3. Formulate statements in precise language (pseudocode/flowchart)
  4. Evaluate and revise through testing
  5. Pay attention to detail

Software Categories:

Category Sub-types Description System Software OS, Device Drivers, Utilities Controls hardware and manages computer resources. OS manages CPU, memory, disk, peripherals. Application Software

Word processors, browsers, games

Performs specific tasks for users. Built on top of system software.

History of C/C++:

1960s BCPL language developed 1970 B language — Ken Thompson (Bell Labs) 1972 C language — Dennis Ritchie (Bell Labs) — developed to write UNIX OS 1983 C++ — Bjarne Stroustrup — added OOP (Object Oriented Programming) to C Development Environment

Editor → Compiler → Linker → Loader → Execute. Common: Turbo C++, Dev C++, Visual Studio

Lecture 3 — First C++ Program, Variables & Data Types

Variables | Data Types | Arithmetic Operators | Precedence

First C++ Program:

#include

Lecture 4 — Expressions, cin/cout & Sample Programs

Input / Output:

int age; cout << "Enter your age: "; // display message cin >> age; // read user input into variable age cout << "Your age is: " << age << endl; // endl = new line

endl = end line (moves cursor to next line). Same as "\n" in cout.

Cascading: cout << "Name: " << name << " Age: " << age; — multiple values in one cout.

Type Casting:

int a = 5, b = 2; float result = (float)a / b; // result = 2.5 (forced float division) // Without cast: 5/2 = 2 (integer division — decimal part lost)

Lecture 5 — Conditional Statements (if / if-else / else-if)

Decision making | Flowcharting | Logical Operators

if Statement Syntax:

if (condition) { // executes if condition is TRUE }

if (condition) { // executes if TRUE } else { // executes if FALSE }

if (marks >= 80) { cout << "A"; } else if (marks >= 70) { cout << "B"; } else if (marks >= 60) { cout << "C"; } else { cout << "Fail"; }

Relational Operators (used in conditions):

Operator Meaning Example == Equal to a == b != Not equal to a != b > Greater than a > b < Less than a < b

>= Greater than or equal a >= b <= Less than or equal a <= b

Logical Operators:

Operator Meaning Example Result && AND — BOTH must be true a>0 && b>0 True only if BOTH conditions true || OR — at least ONE true a>0 || b>0 True if ANY condition is true ! NOT — reverses condition !(a==b) True if a is NOT equal to b

Common mistake: Using = (assignment) instead of == (comparison) inside if condition. if(x = 5) always true! Use if(x == 5)

Lectures 6–7 — Loops (while / do-while / for)

Repetition structure | Overflow | Increment/Decrement operators

3 Types of Loops:

// 1. WHILE loop — condition checked BEFORE body executes // May execute ZERO times if condition is false from start int i = 1; while (i <= 10) { cout << i; i++; // increment — prevents infinite loop }

// 2. DO-WHILE loop — body executes AT LEAST ONCE // Condition checked AFTER body int i = 1; do { cout << i; i++; } while (i <= 10); // NOTE: semicolon at end

// 3. FOR loop — most compact, used when iterations known // for(initialization; condition; update) for (int i = 1; i <= 10; i++) { cout << i; }

Loop Comparison:

Loop Type Condition Check Min Executions Best Used When while BEFORE body 0 times Number of iterations unknown; may skip entirely do-while AFTER body At least 1 time Body must execute at least once (e.g., menu)

switch vs if-else: Switch can only test for EQUALITY (==). Cannot use ranges like >50 or <100. For ranges, use if-else. Switch works with int and char only (not float/string).

Lectures 9–10 — Functions

Structure | Declaration | Definition | Call by Value | Call by Reference | Header Files | Scope

What is a Function?

A function is a reusable block of code that performs a specific task. C++ is a function-oriented language. Concept: Top-Down Design / Divide and Conquer — break big problem into smaller manageable tasks.

Function Structure:

// DECLARATION (Prototype) — tells compiler function exists // Written BEFORE main() or in header file returnType functionName(dataType param1, dataType param2);

// DEFINITION — actual code of function int add(int a, int b) { return a + b; // return sends result back to caller }

// CALL — using the function int main() { int result = add(5, 3); // result = 8 cout << result; return 0; }

Call by Value vs Call by Reference:

Call by VALUE Call by REFERENCE How it works COPY of variable passed to function ADDRESS of variable passed (using &) Effect on original Changes inside function DO NOT affect original Changes inside function AFFECT original variable Use case When you want to protect original variable When function needs to modify the original Syntax void func(int x) void func(int &x)

Scope of Variables:

Local Variable Declared INSIDE a function/block. Only accessible within that function. Destroyed when function ends. Global Variable Declared OUTSIDE all functions. Accessible by ALL functions. Exists throughout program. Avoid overuse. Static Variable Declared with keyword static. Keeps its value between function calls. Only initialized once.

Header Files:

A header file (.h extension) contains function prototypes and constants. Avoids rewriting prototypes in every file. System headers: , , . Custom: create your own .h file and use #include "myfile.h"

Lectures 11–13 — Arrays (1D, 2D, Character Arrays, Sorting &

Searching)

What is an Array?

An array is a collection of elements of the SAME data type stored in contiguous memory locations. Used when multiple values of same type needed (e.g., 100 student ages).

// Declaration: dataType arrayName[size]; int ages[10]; // 10 integers — index 0 to 9 float marks[5] = {90.5, 85.0, 78.3, 92.1, 88.0}; // initialization

// Accessing elements — index starts from 0 ages[0] = 20; // first element ages[9] = 25; // last element (size-1) cout << ages[0]; // output first element

// Traversing with loop for(int i=0; i<10; i++) { cin >> ages[i]; // input all elements }

Key rule: Array index starts at 0. For array of size n, valid indices are 0 to n-1. Accessing out-of-bound index = undefined behavior (bug!).

2D Arrays (Matrix):

// Declaration: dataType arrayName[rows][cols]; int matrix[3][4]; // 3 rows, 4 columns

// Access: arrayName[row][col] matrix[0][0] = 10; // row 0, col 0 matrix[2][3] = 99; // row 2, col 3

// Nested loop to traverse 2D array for(int i=0; i<3; i++) { // rows for(int j=0; j<4; j++) { // cols cout << matrix[i][j] << " "; } cout << endl; }

Character Arrays (Strings):

In C++, strings are stored as character arrays. Last character is always null character \0 (ASCII 0) — marks end of string.

char name[100]; // declare char array

int x = 10; int *ptr; // pointer to int ptr = &x; // & = address-of operator — gives address of x

cout << x; // prints value: 10 cout << &x; // prints address of x: e.g., 0x cout << ptr; // prints address stored in ptr: 0x cout << *ptr; // * = dereference — prints VALUE at that address: 10

*ptr = 20; // changes value of x to 20 through pointer cout << x; // now prints 20

Key Pointer Operators:

& (Address-of) Gets the memory ADDRESS of a variable. Example: &x; gives address of x *** (Dereference)** Gets the VALUE stored at the address. Example: ptr gives value at address in ptr *** in declaration* Declares a pointer variable. Example: int *ptr declares ptr as pointer to int

Pointers and Arrays:

"The name of the array is a constant pointer which contains the memory address of the first element of the array." int arr[5] = {10, 20, 30, 40, 50}; int *p = arr; // p points to arr[0]

cout << *p; // 10 (arr[0]) cout << *(p+1); // 20 (arr[1]) — pointer arithmetic cout << *(p+2); // 30 (arr[2])

// arr[i] is same as *(arr + i)

Pointer Arithmetic:

When you add 1 to a pointer, it moves to the NEXT element (not next byte). It moves by the SIZE of the data type.

Example: int pointer + 1 = moves 4 bytes forward. char pointer + 1 = moves 1 byte forward.

Pointers to Pointers:

int x = 10; int *p = &x; // p stores address of x int **pp = &p; // pp stores address of p (pointer to pointer)

cout << **pp; // dereference twice to get value: 10

Command Line Arguments:

// argc = argument count, argv = argument values (array of strings) int main(int argc, char *argv[]) { cout << "Program name: " << argv[0]; cout << "Argument 1: " << argv[1]; }

Lecture 17 — String Handling & String Functions

#include | Character functions | Search functions

String Manipulation Functions (from ):

Function Purpose Example strlen(s) Returns LENGTH of string (not counting \0)

strlen("Hello") = 5

strcpy(dest, src) COPIES src into dest strcpy(b, a) — copies a into b strcat(dest, src) CONCATENATES src to end of dest strcat(s1, s2) — joins s2 to s strcmp(s1, s2) COMPARES two strings. Returns 0 if equal, <0 if s10 if s1>s

if(strcmp(a,b)==0) — equal

strchr(s, c) Finds FIRST occurrence of char c in string s

strchr(s, 'a')

strstr(s1, s2) Finds FIRST occurrence of s2 in s1 strstr("Hello World", "World") strupr(s) Converts to UPPERCASE strupr("hello") = "HELLO" strlwr(s) Converts to LOWERCASE strlwr("HELLO") = "hello" strrev(s) REVERSES the string strrev("Hello") = "olleH"

Character Functions (from ):

Function Returns true if... isalpha(c) Character is a letter (a-z or A-Z) isdigit(c) Character is a digit (0-9) isspace(c) Character is whitespace (space, tab, newline) isupper(c) Character is uppercase islower(c) Character is lowercase toupper(c) Converts to uppercase tolower(c) Converts to lowercase

Lectures 18–19 — File Handling (Sequential & Random Access

Files)

File Handling Basics:

Files allow permanent storage of data on disk. Without files, all data is lost when program ends. Two main types: Text files (readable characters) and Binary files (non-printable data).

#include // required for file operations

// Writing to file (Output File Stream) ofstream outFile; outFile.open("data.txt"); // open for writing (overwrites) outFile.open("data.txt", ios::app); // open in APPEND mode outFile << "Hello" << endl; // write to file

// Access members using DOT operator (.) strcpy(s1.name, "Ali"); s1.rollNo = 101; s1.gpa = 3.8; cout << s1.name << " " << s1.gpa;

// Array of structures Student class1[50]; // 50 student records class1[0].rollNo = 1;

Passing Structures to Functions:

// Pass by value — copy made void display(Student s) { cout << s.name; }

// Pass by reference — original can be modified void update(Student &s;) { s.gpa = 4.0; }

// Call display(s1); update(s1);

sizeof Operator:

sizeof(variable) or sizeof(dataType) returns number of bytes. Example: sizeof(int) = 4, sizeof(Student) = total bytes of all members.

Unions:

Similar to struct BUT all members SHARE the same memory location. Size of union = size of its LARGEST member. Only one member can hold value at a time.

union Data { int i; float f; char c; }; // Size = size of largest (float = 4 bytes)

Lectures 21–22 — Bit Manipulation & Complete Midterm Review

Bit Manipulation Operators:

Bits are the smallest unit of memory. Bit manipulation allows working at bit level — very memory efficient. Used in OS, file attributes, embedded systems.

Operator Sign Name Operation Example Bitwise AND & AND 1 & 1 = 1; anything & 0 = 0 5 & 3 = 1 (101 & 011 = 001) Bitwise OR | OR 0 | 0 = 0; anything | 1 = 1 5 | 3 = 7 (101 | 011 = 111) Bitwise XOR ^ Exclusive OR

Same bits = 0; Different = 1 5 ^ 3 = 6 (101 ^ 011 = 110)

Bitwise NOT ~ Complement Flips all bits ~5 = – Left Shift << Shift left Shifts bits left, fills 0 on right = multiply by 2

x << 1 = x * 2

Right Shift >> Shift right Shifts bits right = divide by 2 x >> 1 = x / 2

Truth Tables:

Bit1 Bit2 AND (&) OR (|) XOR (^) 1 1 1 1 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0

Compound Bitwise Assignment Operators:

a &= b; // same as a = a & b a |= b; // same as a = a | b a ^= b; // same as a = a ^ b // Note: ~ has NO compound assignment (it is unary)

Bit Flags and Masking:

Bit Flag: Using individual bits as on/off switches. A "1" bit = ON (flag set), "0" bit = OFF (flag clear).

Masking: Using AND/OR/XOR with a mask value to set, clear, or check specific bits.

// Check if bit 3 is set if (x & 0x08) // 0x08 = 00001000 in binary

// Set bit 3 x |= 0x08;

// Clear bit 3 x &= ~0x08;

MCQ PRACTICE — Lectures 1 to 22

Most repeated exam MCQs

Q: Array index in C++ starts from? Ans: 0 (zero) Q: What is the null character in C++? Ans: \0 (ASCII value = 0) Q: Which loop executes at least once? Ans: do-while loop Q: & operator with variables means? Ans: Address-of — gives memory address Q: * operator with pointer means? Ans: Dereference — gives VALUE at address Q: What does strlen("Hello") return? Ans: 5 (null char not counted) Q: strcpy(a, b) copies which to which? Ans: Copies b INTO a Q: sizeof(int) =? Ans: 4 bytes Q: What ends every C++ statement? Ans: Semicolon (;) Q: What does break do in a switch? Ans: Exits the switch block immediately

A variable is a named memory location that stores a value which can change during program execution. Declared as: dataType variableName; Example: int age; float gpa = 3.5; Rules: must start with letter or underscore, no spaces, case-sensitive.

Q: Differentiate between while and do-while loop.

while loop: condition is checked BEFORE loop body — body may execute zero times if condition is false initially. do-while loop: condition is checked AFTER loop body — body always executes AT LEAST ONCE regardless of condition. Syntax difference: do-while has semicolon after closing parenthesis.

Q: What is the difference between Call by Value and Call by Reference?

Call by Value: A COPY of the variable is passed to the function. Changes inside function do NOT affect original variable. Call by Reference: The ADDRESS of the variable is passed (using &). Changes inside function DIRECTLY affect the original variable. Use reference when you want to modify the original value.

Q: What is a pointer? Explain the & and * operators.

A pointer is a variable that stores the memory ADDRESS of another variable. & (address-of operator): gives the memory address of a variable. Example: ptr = &x; assigns address of x to ptr. * (dereference operator): gives the VALUE stored at the address. Example: *ptr gives value at address stored in ptr. In declaration: int *ptr means ptr is a pointer to integer.

Q: What is an array? How is it declared and accessed?

An array is a collection of elements of the SAME data type stored in contiguous memory locations. Declaration: int arr[10]; — creates array of 10 integers. Access: arr[0] is first element, arr[9] is last (index starts at 0). Elements accessed using index: arr[i]. Traversal using for loop. Key rule: valid indices are 0 to size-1.

Q: What is the purpose of break and continue statements?

break: immediately EXITS the enclosing loop or switch statement. Control transfers to the statement after the closing brace. continue: SKIPS the remaining code in the current iteration and goes back to check the loop condition. Does NOT exit the loop — just skips to next iteration.

Q: What is a structure in C++? How does it differ from an array?

Structure: a user-defined data type that groups DIFFERENT data types under one name. Example: Student struct with name (char), rollNo (int), and gpa (float). Accessed using dot operator (.). Array: stores SAME data type only. Structure: can store DIFFERENT data types related to one entity. Declaration: struct Student {...}; Variable: Student s1; Access: s1.name, s1.rollNo.

Q: What are string manipulation functions? Name any four.

String manipulation functions are built-in functions in for handling character arrays: 1. strlen(s) — returns length of string. 2. strcpy(dest, src) — copies src into dest. 3. strcat(s1, s2) — concatenates s2 to end of s1. 4. strcmp(s1, s2) — compares two strings, returns 0 if equal. Also: strupr, strlwr, strrev, strchr, strstr.

Q: What is file handling? Difference between ifstream and ofstream.

File handling allows reading/writing data to/from files on disk for permanent storage. ifstream (Input File Stream): used for READING from files. Default mode is input (ios::in). ofstream (Output File Stream): used for WRITING to files. Default mode destroys existing content; use ios::app to append. Both require #include . Always close file after use with close().

Q: Explain bit manipulation operators with truth table.

C++ provides bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift). AND: 1&1=1, 1&0=0, 0&0=0. OR: 0|0=0, 0|1=1, 1|1=1. XOR: same bits=0, different=1. NOT: flips all bits. Left shift multiplies by 2; right shift divides by 2. Used in OS-level programming, bit flags, and masking operations.

LONG ANSWER QUESTIONS — Lectures 1 to 22

Q: Explain all three types of loops in C++ with syntax and an example program.

C++ provides three types of loops: 1. while loop — checks condition before executing body. Used when iterations unknown. Syntax: while(condition) { body; }. Example: print 1 to 10 using while. 2. do-while loop — checks condition AFTER body. Body executes at least once. Syntax: do { body; } while(condition); Useful for menus. Example: ask user to enter positive number. 3. for loop — most compact, used when exact iterations known. Syntax: for(init; condition; update) { body; }. Example: for(int i=1; i<=10; i++) { cout << i; }. Comparison: while and for may execute 0 times; do-while always at least 1 time. for is best when loop count is known. Infinite loop occurs when condition never becomes false — always update loop variable. Overflow can occur with large loops — variable wraps around.

Q: What are functions? Explain with examples of function declaration, definition, call, and the difference between call by value and call by reference.

A function is a reusable named block of code that performs a specific task. C++ is function-oriented — every program uses functions. Advantages: avoids repetition, improves readability, easier to debug and maintain. Structure: Declaration (prototype) — tells compiler about function before use. Must match definition signature. Written before main() or in header file. Definition — actual code body. Call — invoking the function from main or another function. Call by Value: a COPY of variable is passed. Original not affected. Example: void square(int x) { x = xx; } — original unchanged. Call by Reference: ADDRESS is passed using &. Original variable is modified. Example: void square(int &x;) { x = xx; } — original changes. Scope: Local variables are created inside a function and destroyed when it ends. Global variables are accessible throughout the program. Header files store function prototypes for reuse across files.

Q: Explain arrays in C++ — declaration, initialization, traversal, sorting (bubble sort), and searching (linear search).

An array is a data structure that stores multiple elements of the SAME data type in contiguous memory locations. Declaration: int arr[5]; creates array of 5 integers. Initialization: int arr[5] = {10,20,30,40,50}; Index starts from 0. Last index is size-1. Traversal: use for loop — for(int i=0; i<5; i++) cout << arr[i]; 2D array: int matrix[3][4]; use nested loops. Character arrays store strings — terminated by null char \0. Bubble Sort: compares adjacent elements and swaps if out of order. Outer loop: n-1 passes. Inner loop: n-i-1 comparisons. After each pass, largest element "bubbles" to end. Time complexity O(n²). Linear Search: check each element from start. Return index if found, -1 if not. Simple but slow for large arrays (O(n)). Key rules: const for array size, arrays passed to functions by reference by default, array name = constant pointer to first element.

Q: What are pointers in C++? Explain pointer declaration, initialization, dereferencing, pointer arithmetic, and the relationship between pointers and arrays.

A pointer is a special variable that stores the MEMORY ADDRESS of another variable. They provide indirect access to memory. Declaration: int *ptr; — ptr is pointer to integer. Initialization: ptr = &x; assigns address of x to ptr. & = address-of operator. Dereferencing: *ptr gives the VALUE at the stored address. * = dereference operator. Changing *ptr changes original variable. Pointer arithmetic: adding 1 to pointer moves it to NEXT element (not next byte). Depends on data type size. int pointer +1 moves 4 bytes. char pointer +1 moves 1 byte. Pointers and Arrays: array name is a constant pointer to first element. arr[i] is same as *(arr+i). Pointer to pointer: int **pp stores address of a pointer. Call by reference using pointers: pass address, modify original through dereference. Pointers are powerful but dangerous — accessing wrong address causes runtime errors. Null pointer (ptr = NULL) = pointer to nothing — safe initialization.