π Lecture 19 β Sequential Access Files (Continued) and Random Access Files
π Overview: This lecture completes the discussion of sequential access files and introduces random access files in C++. It covers how to navigate within files using seekg(), tellg(), seekp(), and tellp() functions, explains the concept of file positioning, and demonstrates efficient reading/writing with read() and write() functions. Understanding random access is crucial for building efficient file-based applications where data needs to be updated without rewriting entire files.
ποΈ Topics Covered
The lecture reviews sequential file handling functions (open, close, get, put, getline, stream operators) and the default behaviors of ifstream and ofstream. It then introduces random access files, explaining file position pointers, the tellg()/tellp() functions for determining current position, and seekg()/seekp() functions for setting position. The lecture covers determining file length, the problem of inserting data in the middle of a sequential file, the merge method solution, and the concept of fixed-length records. It also discusses efficient file I/O using read() and write() functions, copying files in reverse order, and includes two sample programs demonstrating these concepts.
π Lecture Summary
Sequential Access Files (Continued)
Sequential access files are simple character files where data is written and read in sequence, not randomly. The lecture reviews that open() is used to open files and close() to close them. open() takes parameters (filename, mode) while close() has no parameters.
For ifstream (Input File Stream), the default mode is for reading/input, so simply providing the filename is sufficient. We can also provide an additional argument like open("filename", ios::in), but this is not mandatory due to the default behavior.
For ofstream (Output File Stream), opening a file for writing in default mode destroys previous contents. To preserve contents, use append mode (ios::app). The ios::trunc value causes the contents of a preexisting file to be destroyed and the file is truncated to 0 length. To open a file for writing at random positions forward and backward, use ios:ate β the file opens and positions at the end, and anything written is appended.
π Definition β ios::app: A file opening mode that appends data to the end of an existing file without destroying its contents.
π Example: ofstream out("test"); opens file for output in default mode (destroys previous contents). ofstream out("test", ios::app); opens file in append mode.
File reading and writing can be done character by character using get() (read one character) and put() (write one character). The stream extraction operator (>>) and stream insertion operator (<<) also work with files. The getline() function reads one line at a time β you provide how many characters to read and the delimiter. If reading 10 characters, it reads 9 and adds a null character (\0).
π Definition β getline(): A function used to read one line at a time from a file, treating lines as character strings, automatically adding a null character.
π Syntax: getline(buffer, size, delimiter) β reads up to size-1 characters or until delimiter
π Example: Reading an integer, float, and character from a file created by a previous program:
ifstream in("test");
if(!in) { cout << "Cannot open file"; return 1; }
in >> i; // reads integer
in >> f; // reads float
in >> ch; // reads character (white spaces are ignored by default)
π‘ Why this matters: Understanding the default behaviors of file stream modes is critical. Accidentally using output mode on a file with important data can destroy it. The append mode provides safe data preservation.
Random Access Files
To access files randomly (forward and backward), the file position (a pointer into the file) must be understood. While reading from or writing to a file, we must know from which location the process will start. Two functions determine the file pointer position: tellg() and tellp().
π Definition β tellg(): Returns the current get position of the file pointer as a long integer β the position of the next character to be read from the file. π Definition β tellp(): Returns the next position to write a character while writing to a file, also as a long integer.
π Example: myfile.tellg() gives the current get position of the file pointer for an input file stream.
Setting the Position β To move within a file, use seekg() for reading (getting) and seekp() for writing (putting). These functions require a long argument indicating how many bytes to move and an optional direction specifier.
π Definition β seekg(): Sets the get position in a file for reading, taking a long argument for bytes to move and an optional direction flag. π Definition β seekp(): Sets the put position in a file for writing, taking a long argument for bytes to move and an optional direction flag.
The movement is always relative to some position:
- From the beginning: can only move forward with positive values
- From current position: can move forward (positive) or backward (negative)
- From the end: can only move backward with negative values
π Formulas:
aFile.seekg(10L, ios::beg)β move 10 bytes forward from beginningaFile.seekg(20L, ios::cur)β move 20 bytes forward from current positionaFile.seekg(-10L, ios::cur)β move 10 bytes backward from current positionaFile.seekg(-100L, ios::end)β move 100 bytes backward from end
π Example β Saving and restoring position in a file:
streampos original = aFile.tellp(); // save current position
aFile.seekp(0, ios::end); // reposition to end of file
aFile << x; // write value to file
aFile.seekp(original); // return to original position
Determining File Length: By combining seekg() and tellg(), we can find the actual data length of a file:
inFile.seekg(0, ios::end); // go to the end of the file
long inSize = inFile.tellg(); // get the file pointer position (total bytes)
π Definition β File length determination: Using seekg(0, ios::end) followed by tellg() returns the actual number of data bytes in the file, regardless of the physical disk block size.
π‘ Why this matters: The physical file size on disk can be larger than the actual data length because disks store data in logical blocks (clusters). Knowing the actual data length is essential for accurate file processing.
Data Insertion in the Middle of a File
Inserting data in the middle of a sequential file is problematic. If a word like "Sukkur" needs to be replaced with "Rawalpindi", the new data is longer and would overwrite subsequent data, corrupting the file structure.
The Merge Method (from COBOL era) solves this:
- Open the data file and a new empty file
- Copy data from beginning to the insertion point into the new file
- Append new data to the new file
- Skip the data to be replaced in the original file
- Copy remaining data to the new file
- Delete old file, rename new file
This method is wasteful for large files (hundreds of megabytes or gigabytes) since the entire file must be copied just to change one word.
π Definition β Constant record length: The key to resolving insertion issues β each record in the file occupies the same amount of space, large enough to accommodate any future updates without disturbing file structure.
Fixed-Length Records Solution: Make each record the same size. For example, if student records are 100 bytes each:
- First 10 bytes: student ID number
- 40 bytes: student name
- 40 bytes: city
- 10 bytes: date of birth
If IDs are sorted with no gaps (1 to 50), we can calculate exact positions. For student ID 23:
- 22 students Γ 100 bytes = 2200 bytes
- Record 23 starts at byte 2201 and goes to 2300
- Use
seekg(2200L, ios::beg)to jump directly β no loops, no comparisons
π Definition β Key field: A unique identifier (like student ID or roll number) used to locate records quickly, making numeric comparisons faster than string comparisons.
Dual-Mode File Opening: A file opened with fstream can be used for both input and output. Use ios::in || ios::out as the mode flag β the OR operation combines the bits of both flags.
π Example β Replacing part of a string in a file (same length):
ofstream outfile;
outfile.open("test.txt");
outfile.write("This is an apple", 16); // Write the string
pos = outfile.tellp(); // Get position (should be 16)
outfile.seekp(pos - 7); // Move 7 positions backward
outfile.write(" sam", 4); // Write 4 chars β changes "apple" to " sam"
outfile.close();
Efficient Way of Reading and Writing Files
Reading a file character by character with getc() and writing with putc() is inefficient. Processing in chunks is much faster. The read() and write() functions are binary functions that handle multiple bytes at once.
π Definition β read(): A binary stream function that reads a specified number of bytes from a file into a memory location.
π Definition β write(): A binary stream function that writes a specified number of bytes from memory to a file.
π Syntax: read(buffer, numberOfBytes) β reads into buffer; write(buffer, numberOfBytes) β writes from buffer
π Example β Efficient file copying using read() and write():
char str[10000];
fi.open("inFilename", ios::in);
fo.open("outFilename", ios::out);
fi.seekg(0, ios::end);
j = fi.tellg(); // Get total file size
fi.seekg(0, ios::beg); // Go to beginning
for(i = 0; i < j/10000; i++) {
fi.read(str, 10000); // Read 10000 bytes
fo.write(str, 10000); // Write 10000 bytes
}
fi.read(str, j - (i * 10000)); // Read remaining bytes
fo.write(str, j - (i * 10000)); // Write remaining bytes
Using sizeof() with write(): Instead of specifying byte count directly, use sizeof() for type independence and portability:
aFile.write(&i, sizeof(i)); // Writes integer i to file
π Definition β sizeof() operator: Returns the number of bytes occupied by a data type or variable, making code compiler-independent and portable across systems with different internal representations.
Copying a File in Reverse Order
To copy a file in reverse (last byte becomes first byte), position the file pointer one byte before the end using seekg(-1, ios::end). After reading a byte, the pointer automatically moves forward. To read the previous byte, move two positions back from the current position: seekg(-2, ios::cur).
π Example β Loop structure for reverse file copying:
aFile.seekg(-1L, ios::end); // Position one byte before end
while(aFile) {
aFile.get(c); // Read current byte
aFile.put(c); // Write to output
aFile.seekg(-2L, ios::cur); // Move two back to read previous byte
}
π‘ Why this matters: seekg() is much faster than sequential reading. To reach the 100th location sequentially takes 100 reads, but seekg() jumps directly. Similarly, read() and write() are the fastest file handling methods as they reduce the number of function calls and physical disk accesses.
β Key Takeaways
- File positioning functions β
tellg()/tellp()get the current file pointer position, whileseekg()/seekp()set it. Movement can be relative to the beginning (ios::beg), current position (ios::cur), or end (ios::end), with positive values moving forward and negative values moving backward. - Random access requires fixed-length records β To insert or update data in the middle of a file without corruption, each record must have a constant size large enough to accommodate the largest possible data value. This allows direct calculation of record positions using arithmetic.
- The merge method is the traditional approach for inserting into sequential files β copying everything up to the insertion point, inserting new data, then copying remaining data β but is inefficient for large files.
- read() and write() are more efficient than get()/put() for file I/O because they process data in chunks rather than character by character, reducing function calls and physical disk access operations.
- fstream with ios::in || ios::out allows a single file stream to be used for both reading and writing simultaneously, enabling direct updates to file contents without creating separate input and output streams.
π§ Quick Revision Questions
- What is the difference between
seekg()andseekp(), and when would you use each function? - How can you determine the actual data length of a file using
seekg()andtellg()? - Why does inserting data in the middle of a sequential file cause problems, and what is the constant record length solution?
- In the reverse file copy algorithm, why must you move 2 positions backward (
seekg(-2, ios::cur)) instead of 1 position backward after reading each character? - What is the advantage of using
read()andwrite()functions over character-by-character I/O withget()andput()?
π Lecture 20 β Structures and Unions
π Overview: This lecture introduces the concept of structures in C/C++ as a way to group related variables of different types under a single name, creating user-defined data types. It also covers unions, which allow different data types to share the same memory location, and demonstrates practical applications through sample programs.
ποΈ Topics Covered
The lecture covers the declaration, initialization, and manipulation of structures, including how to access data members using dot and arrow operators, pass structures to functions, create arrays of structures, and use the sizeof operator. It also explains unions as a memory-sharing construct with syntax similar to structures, and presents two complete sample programs demonstrating structure usage for student data processing and file I/O operations.
π Lecture Summary
Structures
Structures are a fundamental concept in C/C++ that allow grouping related data about a single entity. For example, a student has properties like name, address, GPA, and courses β all of which belong to the same student. Similarly, a car has a model, manufacturer, and number of seats. Without structures, each piece of data must be handled separately. With structures, we create a new user-defined data type that bundles related variables together.
A structure is defined as βa collection of variables under a single name. These variables can be of different types, and each has a name that is used to select it from the structure.β
π‘ Why this matters: Structures enable us to model real-world entities in code, making programs more organized and intuitive. They are the foundation for classes in object-oriented programming.
Declaration of a Structure
Structures are syntactically defined with the keyword struct, followed by the structure name. The data members are defined inside curly braces. For example:
struct student {
char name[60];
char address[100];
float GPA;
};
The variables inside the structure are called data members. Once declared, student becomes a new data type that can be used like built-in types:
student std1, std2;
This is equivalent to int x, y; β we have extended the language by creating a custom type.
Structures can be defined and variables declared simultaneously:
struct student {
char name[60];
char address[100];
float GPA;
} std1, std2;
π Definition β Structure Declaration Syntax: The struct keyword followed by a name, then data members in curly braces, optionally followed by variable names in a comma-separated list.
Structures can contain pointers and other structures as data members. However, a structure cannot contain an instance of itself. For example:
struct address {
char streetAddress[100];
char city[50];
char country[50];
};
struct student {
char name[60];
address stdAdd; // Another structure as member
float GPA;
};
A pointer to a structure holds the memory address where the structure's data begins. We can define:
- Simple variables of the new structure type
- Pointers to structures
- Arrays of structures
card fullSet[52]; // Array of 52 card structures
student s[100]; // Array of 100 student structures
student *sptr; // Pointer to student structure
Limitations: We cannot use operators like + with structures (e.g., card1 + card2 is invalid). However, assignment works β if s1 and s2 are of the same structure type, s1 = s2 copies all data members.
Initializing Structures
Initialization can occur at the time of declaration using curly braces with comma-separated values:
student s1 = {"Ali", "CS201", 19, 2002};
The values are assigned in order: "Ali" to name, "CS201" to course, 19 to age, and 2002 to year.
To access data members, the dot operator (.) is used:
s1.age = 20;
s1.year = 2002;
cout << "The name of s1 = " << s1.name;
π Definition β Dot Operator (.): Used to access data members of a structure variable. Syntax: structureVariable.memberName.
Functions and Structures
Structures can be passed to functions by value (a copy is created on the stack) or by reference (by passing the address). When passed by value, even if the structure contains an array, the entire array is copied β this protects the original data but can use significant memory.
Functions can also return structures. The structure is copied onto the stack and then assigned to the receiving variable.
Accessing structures through pointers: When using a pointer to a structure, the arrow operator (->) is used instead of the dot operator.
student s1 = {"Ali", "CS201", 22, 2002};
student *sptr;
sptr = &s1;
// Using arrow operator
cout << sptr->name; // Displays "Ali"
// Equivalent using dereference and dot operator
cout << (*sptr).name; // Parentheses required due to operator precedence
π Definition β Arrow Operator (->): Used to access data members through a pointer to a structure. Syntax: pointer->member.
π Important Rule: When accessing through a simple variable, use dot operator (s1.name). When accessing through a pointer to structure, use arrow operator (sptr->name).
Arrays of Structures
Arrays of structures are declared like arrays of built-in types:
student s[100];
This creates an array of 100 student structures, indexed from 0 to 99. Access elements using array index with dot operator:
s[0].name; // Name of first student
s[1].age; // Age of second student
π Important: The array index belongs to the array name (s), not the data member.
sizeof Operator
The sizeof operator can be used with structures to determine the total memory they occupy. It automatically accounts for all data members:
cout << "The structure s1 occupies " << sizeof(s1) << " bytes in the memory";
For the student structure with char name[64], char course[128], int age, and int year, the output would be 200 bytes (64 + 128 + 4 + 4).
π‘ Why this matters: sizeof is particularly useful when writing structures to files using functions like
write().
Summary of what we can do with structures:
- Define the structure
- Declare variables of that structure type
- Declare pointers to structures
- Declare arrays of structures
- Take the size of a structure
- Perform simple assignment between two variables of the same structure type
Sample Program 1
Problem: For ten students (with name, course, age, and GPA), get input from the user to populate the array, calculate average age and average GPA, determine the class grade, and find the student with maximum GPA.
Solution: The program declares a student structure, populates an array of 10 students using a loop, calculates totals for age and GPA while tracking the maximum GPA and its index, then computes averages and determines the class grade based on average GPA.
π Example Output: For 3 students (Ali with GPA 3.5, Faisal with GPA 3.6, Jamil with GPA 3.3):
The average age is : 24
The average GPA is : 3.46667
Student with max GPA is : Faisal
The average Grade of the class is : B
The program uses a condition chain:
averageGPA == 4β Grade AaverageGPA >= 3β Grade BaverageGPA >= 2β Grade C- Otherwise β Grade F
Sample Program 2
Problem: Read student data from a file, populate the structure, and write the structure to another file.
Solution: The program uses two functions β getData() which reads from a file and returns a student structure, and writeData() which writes a student structure to a file. The file handles (ifstream and ofstream) are declared globally for accessibility.
π Function Prototypes:
student getData(); // Returns a student structure read from file
void writeData(student); // Writes a student structure to file
The getData() function creates a local tempStudent structure, reads data line by line using getline(), converts strings to integers and floats using atoi() and atof(), and returns the structure. The writeData() function uses the extraction operator to write each data member to the output file.
π Example: For input file containing:
nasir
CS201
23
3
The output file will contain the same data formatted with each field on a new line.
Unions
A union is a construct that allows different data types to share the same memory location. The syntax is similar to structures:
union intOrChar {
int i;
char c;
};
The size of a union is the size of its largest data member. For intOrChar, if int is 4 bytes and char is 1 byte, the union occupies 4 bytes.
π Definition β Union: A memory location that can be accessed using different data type names. All data members share the same starting memory address.
Data members of unions are accessed using the dot operator:
intOrDouble uval;
uval.ival = 10;
cout << uval.ival; // Displays 10
β οΈ Important: When one member of a union is written, other members become invalid. If you write
uval.ival = 10and then readuval.dval, you get undefined behavior β the bytes are interpreted as a double, not as the integer 10.
Practical Example β Byte Shifting with Union: The lecture demonstrates using a union containing 4 characters and an integer to show how memory is shared:
union intOrChar {
char c[4];
int x;
} u1;
u1.x = 'a'; // ASCII value 97 stored as integer
u1.x *= 256; // Shift left by one byte (multiply by 256)
u1.x += 'b'; // Add 'b' (ASCII 98)
π Output progression:
Initial: c = a, , , x = 97
After 'b': c = b,a, , x = 24930
After 'c': c = c,b,a, x = 6382179
After 'd': c = d,c,b,a x = 1633837924
Characteristics of Unions:
- Share the same memory location among all data members
- Size equals that of the largest member
- Only one member can be active at a time
- Rarely used but important for memory-efficient programming
β Key Takeaways
Structures are user-defined data types that group related variables under one name, declared using the struct keyword with data members in curly braces. Data members are accessed using the dot operator (.) for structure variables and the arrow operator (->) for pointers to structures. Structures can be passed to functions by value or by reference, and functions can return structures. Arrays of structures and the sizeof operator for structures provide powerful data management capabilities. Unions, which share memory among different data types, have syntax similar to structures but occupy only enough memory for their largest member, making them useful for memory-efficient programming though rarely needed in typical applications.
π§ Quick Revision Questions
- What is the difference between a structure and a union in terms of memory allocation?
- How do you access a data member of a structure using a pointer? What operator is used and why is it necessary?
- What happens when you pass a structure containing an array to a function by value β is the array passed by value or by reference?
- In Sample Program 1, what is the purpose of storing the index variable when tracking the maximum GPA?
- For the union
intOrCharwithint(4 bytes) andchar(1 byte), how many bytes of memory does it occupy, and why?
π Lecture 21 β Bit Manipulation
π Overview: This lecture introduces the concept of bit manipulation, which involves working directly with individual bits (the smallest unit of memory) rather than bytes. It covers the essential bitwise operators in C++, their truth tables, and practical applications like checking or setting bits, encryption, and data recovery, which are crucial for efficient memory use and low-level programming.
ποΈ Topics Covered
The lecture begins by defining a bit and the concept of bit manipulation. It then details six bit manipulation operators: AND (&), OR (|), Exclusive OR (^), NOT (~), Left Shift (<<), and Right Shift (>>). Each operator is explained with its truth table and examples. Practical applications discussed include using AND to check if a bit is set, OR to set a bit, and Exclusive OR for encryption/decryption and data recovery via RAID. The lecture also covers the use of unsigned integers for bit operations, provides a sample program for password encryption, and explains shift operators as efficient alternatives to multiplication and division.
π Lecture Summary
Bit Manipulation
The lecture begins by defining a bit as the basic unit of memory, with eight bits forming a byte. Bit manipulation is the process of working directly with individual bits, turning them on (1) or off (0). This is contrasted with the usual manipulation of bytes using data types like integers. Bit manipulation is memory-efficient and particularly useful in operating systems for managing file attributes and other low-level tasks.
π Definition β Bit: The smallest unit of memory that can hold a value of 0 or 1.
Bit Manipulation Operators
This section introduces the operators used for bit manipulation.
| Operator | Operator Sign |
|---|---|
| Bitwise AND Operator | & |
| Bitwise OR Operator | | |
| Bitwise Exclusive OR Operator | ^ |
| NOT Operator | ~ |
| Left Shift Operator | << |
| Right Shift Operator | >> |
The lecture emphasizes that these are not the same as the logical AND (&&) and OR (||) operators.
AND Operator ( & )
The AND operator (&) compares two bits and returns 1 only if both bits are 1. It is used to determine whether a specific bit is set (1) or not.
π Truth Table for AND (&):
| Bit1 | Bit2 | Bit1 & Bit2 |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 0 | 0 | 0 |
π Concept: Matching bit patterns. Each bit of the first number is compared with the corresponding bit of the second number.
π Example: Determine if the fourth bit (value 8) of a number is set.
int number = 12; // binary 1100
if (number & 0x8) // 0x8 is hexadecimal for 8 (binary 1000)
cout << "The fourth bit of the number is set" << endl;
else
cout << "The fourth bit of the number is not set" << endl;
Since the result of 1100 & 1000 is 1000 (non-zero), the condition is true.
π Definition β Set: A bit is said to be 'set' if its value is 1 and 'not set' if it is 0.
OR Operator ( | )
The OR operator (|) compares two bits and returns 1 if either one of the bits is 1. It is used to set a specific bit to 1.
π Truth Table for OR (|):
| Bit1 | Bit2 | Bit1 | Bit2 |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 0 | 0 | 0 |
π Example: Set the first bit of a number.
If number = 8 (binary 1000), then number = number | 1 results in 1000 | 0001 = 1001, which is 9. This ensures the first bit is now 1.
π‘ Why this matters: The & operator is used to check a bit, while the | operator is used to set a bit.
Exclusive OR Operator ( ^ )
The Exclusive OR operator (^), also called XOR, returns 1 only when the two input bits are different (one is 1, the other is 0).
π Truth Table for Exclusive OR (^):
| Bit1 | Bit2 | Bit1 ^ Bit2 |
|---|---|---|
| 1 | 1 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 0 | 0 | 0 |
π Key Property: A key strength of the XOR operator is that applying it twice with the same value returns the original value. If c = a ^ b, then c ^ b = a.
π Example: 8 ^ 1 = 9 (since 1000 ^ 0001 = 1001). Then 9 ^ 1 = 8 (since 1001 ^ 0001 = 1000).
This property makes XOR very useful for encryption and decryption of passwords and for data recovery in RAID systems.
NOT Operator ( ~ )
The NOT operator (~) is a unary operator that inverts all the bits of a number. 1 becomes 0, and 0 becomes 1.
π Truth Table for NOT (~):
| Bit1 | ~Bit1 |
|---|---|
| 1 | 0 |
| 0 | 1 |
π Example: ~8 will invert 1000 to 0111, which is 7.
Bit Flags
Bit flags are a practical use of bit manipulation, particularly in operating systems. They represent the state of a feature or an attribute (e.g., read-only, archive for a file). Each attribute is assigned a specific bit; if the bit is set (1), the attribute is active; if the bit is cleared (0), it is not. This is more memory-efficient than using multiple boolean variables.
Masking
Masking is a technique used with bitwise operators. In the context of XOR, it is used for data security.
π Definition β Masking: The process of using a set of bits (a mask) to selectively enable, disable, or invert other bits. The lecture uses the example of password encryption where a password is masked (XORed) with a secret number to create an encrypted form.
- Example (Encryption):
encrypted_char = original_char ^ secret_key; - Example (Decryption):
original_char = encrypted_char ^ secret_key;
The lecture also explains how XOR works in RAID (Redundant Array of Inexpensive Devices). Data bits are written across multiple disks, and a parity bit (the XOR of all data bits) is stored on an extra disk. If one disk fails, the missing bit can be recovered by XORing all remaining bits, allowing for "hot plug" replacement.
π Example (Swapping Numbers without a temp variable):
To swap two unsigned integers a and b:
a = a ^ b;
b = b ^ a;
a = a ^ b;
Unsigned Integers
Bit manipulations are best performed on unsigned integers. The most significant bit (MSB) of a signed integer is used as a sign bit (0 for positive, 1 for negative), which can cause unexpected behavior during bit shifts or other operations. Using the unsigned keyword ensures the number is treated as positive only.
π Definition β Unsigned Integer: An integer declared with the unsigned keyword (e.g., unsigned int i;) that can only represent non-negative values.
Sample Program
The lecture includes a sample program that demonstrates password encryption and decryption using the XOR operator.
π Example Code:
#include <iostream.h>
main() {
char password[10];
char *passptr;
cout << "Please enter a password(less than 10 character): ";
cin >> password;
passptr = password;
// Encryption
while (*passptr != '\0') {
*passptr = (*passptr ^ 3);
++passptr;
}
cout << "The encrypted password is: " << password << endl;
// Decryption
passptr = password;
while (*passptr != '\0') {
*passptr = (*passptr ^ 3);
++passptr;
}
cout << "The decrypted password is: " << password << endl;
}
π Output:
Please enter a password(less than 10 character): zafar123
The encrypted password is: ybebq210
The decrypted password is: zafar123
Shift Operators
Shift operators allow shifting the bits of a number to the left or right.
- Left Shift Operator (<<): Shifts bits to the left, filling the vacated rightmost bits with zeros. This is equivalent to multiplying the number by 2 for each shift.
- Right Shift Operator (>>): Shifts bits to the right, filling the vacated leftmost bits with zeros (for unsigned numbers). This is equivalent to dividing the number by 2 for each shift.
π Example:
- Left shift of 2 (binary
0010) by one position gives 4 (binary0100). - Right shift of 12 (binary
1100) by one position gives 6 (binary0110).
The lecture notes that shift operators are more efficient than arithmetic multiplication and division.
π Formula for Left Shift: number << n is equivalent to number * 2^n (for non-negative numbers without overflow).
π Formula for Right Shift: number >> n is equivalent to number / 2^n (for positive integers).
π Example:
int number = 12;
cout << (number << 1); // Output: 24 (12 * 2)
cout << (number >> 1); // Output: 6 (12 / 2)
β Key Takeaways
The most critical concepts from this lecture are the six bit manipulation operators and their specific uses: AND (&) for checking bits, OR (|) for setting bits, XOR (^) for toggling bits and encryption, NOT (~) for inverting bits, and left/right shift (<</>>) for efficient multiplication/division by powers of two. The XOR operator's ability to revert an operation (a ^ b ^ b = a) is a powerful concept for data security and recovery, as seen in the password encryption and RAID examples. Finally, it is essential to use unsigned integers for bit manipulation to avoid issues with the sign bit.
π§ Quick Revision Questions
- What is the difference between the logical AND operator (
&&) and the bitwise AND operator (&)? - Which bitwise operator would you use to set the third bit of an integer variable
xto 1? - Explain the key property of the Exclusive OR (XOR) operator that makes it useful for encryption and data recovery.
- What is a left shift operation equivalent to in arithmetic terms, and why is it often preferred?
- Why is it recommended to use
unsignedintegers when performing bit manipulation?
π Lecture 22 β Recap of Course Topics
π Overview: This lecture serves as a comprehensive review of all major topics covered in the first half of the CS201 course, serving as preparation for the mid-term examination. It begins with bitwise manipulation and assignment operators, then systematically recaps design recipes, variables, data types, operators, programming constructs, decisions, loops, functions, arrays, pointers, and file I/O.
ποΈ Topics Covered
The lecture covers bitwise manipulation and assignment operators, design recipes, variables, data types, operators (arithmetic, logical, bitwise), programming constructs (sequential, decisions, loops), decisions (if statement, nested if statement), loops (while, do-while, for), switch/break/continue statements, functions (calling, top-down methodology), arrays, pointers, and file I/O.
π Lecture Summary
Bitwise Manipulation and Assignment Operator
C/C++ provide compound assignment operators for bitwise operations, similar to arithmetic compound operators. The statement a = a & b; can be written as a &= b;. Similarly, a = a | b; becomes a |= b; and a = a ^ b; becomes a ^= b;. However, the ~ (NOT) operator is unary (requires only one operand), so there is no compound assignment operator for it. For example, ~a is written directly.
π Definition β Compound Assignment Operator: An operator that combines an arithmetic or bitwise operation with assignment, e.g., +=, &=, |=.
π Formula: a = a op b; β a op= b; (where op is an arithmetic or bitwise operator)
π Example: a = a & b; can be rewritten as a &= b;
Design Recipe
Problems are expressed in words (e.g., company payroll). As programmers, we analyze and express the problem in a reduced, brief manner. We then create examples to formulate it. For instance, to calculate annual net salary, we take an example employee X. Later, we refine the problem, write the program, test it, and review if objectives are met. A key heading is "Pay attention to the detail" β computers are very dumb machines that perform exactly what we tell them.
π‘ Why this matters: This systematic problem-solving approach ensures we understand the problem before coding, reducing errors.
Variables
Computer memory can be thought of as pigeon holes with addresses. Instead of using hard-coded memory addresses, symbolic names called variables are used, which can contain different values at different times. For example, int i; and double interest; declare variables i (int type) and interest (double type).
π Definition β Variable: A symbolic name that represents a memory location and can hold different values during program execution.
Data Types
The int type stores whole numbers, with varieties short and long. The unsigned qualifier is for non-negative numbers. For real numbers, float is used, and double for larger real numbers. char stores one character, enclosed in single quotation marks. Generally, int is 4 bytes and char is 1 byte. The ASCII table contains numeric values for chars. Arrays aggregate variables of the same data type.
π Definition β Data Type: A classification that specifies which type of value a variable can hold and what operations can be performed on it.
π Example: char grade = 'A'; stores the character A (ASCII value 65) in memory.
Operators
Three types of operators are discussed: arithmetic, logical, and bitwise.
Arithmetic Operators
+ adds numbers, - subtracts, * multiplies, / divides, and % (modulus) returns the remainder. For example, c = 7 % 2; stores 1 (remainder of 7 divided by 2) in variable c. Compound arithmetic operators include +=, -=, *=, /=, and %= β with no space between these operators.
π Definition β Modulus Operator (%): Returns the remainder when one integer is divided by another.
π Formula: a % b β remainder of a divided by b
π Example: 7 % 2 = 1 (7 divided by 2 gives quotient 3, remainder 1)
Logical Operators
The result is always true or false. && is AND, || is OR. Comparison operators include <, <=, ==, >, >=. Important: Do not confuse == (equality) with = (assignment). In C/C++, the assignment statement itself has a value (the value assigned). For example, if (a = b) will execute the if block if b is non-zero, which may be a logical error. The correct comparison is if (a == b).
π Definition β Assignment vs Equality: = assigns a value to a variable; == compares two values for equality.
π Example: if (a = b) will always execute if b β 0; the intended code is if (a == b)
Bitwise Operators
& is bitwise AND, | is bitwise OR, ^ is bitwise Exclusive OR, and ~ is bitwise NOT. The ~ operator is unary (one operand), while &, |, and ^ are binary (two operands).
Programming Constructs
Three fundamental constructs are required for programming:
- Sequential execution β statements execute from first to last
- Decisions β conditional execution using
ifstatements - Loops β repetitive structures for executing code multiple times
Decisions
If Statement
Syntax: if (condition) { // if code block } else { // else code block }. The condition evaluates to true or false. Braces are mandatory for multiple statements but optional for single statements. The else part is optional. As a programming practice, using braces all the time is recommended for readability.
Nested If Statement
For complex conditions, logical connectives like && and || are used. For example: if (a > b && a < c). Nested if-statements are used for multiple decision levels. Proper indentation improves readability. The lecture introduced structured flowcharting, where we never go to the left of the straight line joining Start and Stop β equivalent to code where we can't move left of the left margin.
π‘ Why this matters: Structured flowcharting ensures a one-to-one correspondence between flowcharts and code, making complex problems easier to translate into programs.
Loops
While Loop
Syntax: while (condition) { // while code block }. The condition is a logical expression returning true or false. Statements inside execute 0 to n times β if the condition is false initially, the loop body never executes.
Do-While Loop
Syntax: do { // do-while code block } while (condition);. The key difference is that the loop body executes at least once before the condition is evaluated.
For Loop
Syntax: for (initialization statements; condition; incremental statements) { //for code block }. Example: for (int i = 0; i < 10; i++) { }. The loop executes while the condition is true. Braces are optional for single statements but recommended.
switch, break and continue Statements
For multi-way decisions, we can use nested if-statements, separate if-statements, or switch statement. The break statement is necessary in each case β without it, if a case matches, all subsequent cases execute. break jumps out of the switch or loop. continue skips remaining statements in the current loop iteration and goes to the next iteration.
π Definition β break statement: Causes immediate termination of the nearest enclosing switch or loop. π Definition β continue statement: Skips the rest of the current loop iteration and proceeds to the next iteration.
Functions
In C/C++, functions modularize code by breaking larger problems into manageable parts. Normally, one function's length should not exceed one screen. Function calling can be call by value or call by reference. The default in C is call by value, meaning the function gets a copy of the value, and the original remains unchanged. Call by reference (using pointers) allows the function to modify the original variable.
π Definition β Call by Value: When a function receives a copy of the argument's value; changes inside the function do not affect the original. π Definition β Call by Reference: When a function receives the address of the argument; changes inside the function affect the original.
Top-Down Methodology
Top-down design identifies major portions of a problem at a high level, then breaks each portion into smaller parts to implement as functions.
Arrays
Arrays aggregate variables of the same data type. For example, storing students' ages uses an array instead of separate variables. Array indexing starts at 0 β for an array a of 10 ints, a[0] is the first element and a[9] is the last. In C, arrays are stored in row major order (a row is stored after the previous row). When passing arrays to functions, it is always call by reference by default (unlike ordinary variables). Multi-dimensional arrays require specifying all dimensions except the leftmost in function parameters. Arrays are almost always used with loops.
π Definition β Array: A collection of variables of the same data type accessed by an index.
π Example: int ages[10]; declares an array of 10 integers; ages[0] accesses the first element.
Pointers
Pointers are variables that contain memory addresses instead of values. They are essential for implementing call by reference. For swapping two numbers, passing variables normally (call by value) won't work because only copies are swapped. Passing their addresses to pointer parameters allows swapping the original variables. Pointers and arrays are inter-linked β the array name itself is a constant pointer to the first element (cannot be incremented like normal pointers).
π Definition β Pointer: A variable that stores the memory address of another variable.
π Example: int x = 5; int *p = &x; β pointer p stores the address of variable x
File I/O
Files are used for sequential and random access. Important functions include seek functions (seekg and seekp) to move within a file, and tell functions (tellg and tellp) to get the current file position. Files can be opened in several modes.
β Key Takeaways
The most critical concepts are: bitwise compound assignment operators exist for &, |, and ^ but not for ~; the difference between assignment (=) and equality (==) operators is crucial to avoid logical errors; arrays use 0-based indexing and are always passed by reference to functions; pointers store memory addresses and enable call by reference; and the three programming constructs (sequential, decision, loop) form the foundation of all programs. Remember that structured flowcharting maintains a left-margin boundary, and proper indentation improves code readability. For the exam, ensure you understand how switches require break statements, the difference between while (0-to-n times) and do-while (at least once), and that array names are constant pointers.
π§ Quick Revision Questions
- What are the compound assignment operators for bitwise AND, OR, and XOR? Give examples.
- How does the assignment operator
=differ from the equality operator==, and what logical error can arise from confusing them? - Explain the difference between a while loop and a do-while loop in terms of when the condition is evaluated.
- What is the default method of passing arguments to functions in C? How does this change when arrays are passed?
- What is the purpose of
breakandcontinuestatements inside loops?