π Lecture 14 β Pointers
π Overview: This lecture introduces pointers, a special type of variable that stores memory addresses rather than data values. It explains how pointers enable indirect referencing and call-by-reference in functions, which is essential for efficient memory management and modifying variables inside functions.
ποΈ Topics Covered
The lecture covers the concept of pointers as variables that store memory addresses, their declaration syntax using the asterisk operator, and the address-of (&) and dereferencing (*) operators. It includes a detailed bubble sort example demonstrating pointer-based swapping, explains how pointers enable call-by-reference in function calls, and discusses constant pointers and pointers to constant data. A second example shows pointer arithmetic for converting a string to uppercase.
π Lecture Summary
Pointers
Pointers are special variables that store a memory address rather than a data value. They contain the address of another variable, not the variable's value itself. This is analogous to locating a house either by the owner's name (direct reference) or by the house number and street address (indirect reference). In programming, normal variable names provide direct reference to memory locations, while pointers provide indirect reference through memory addresses.
π Definition β Direct Reference: Using a variable's name to access its value (e.g., x = 10).
π Definition β Indirect Reference: Using a pointer variable that contains the memory address of another variable to access that variable's value.
Declaration of Pointers
Pointers are declared with a specific syntax: data_type *pointer_name;. The asterisk (*) indicates that the variable is a pointer, and it is associated with the variable name, not the data type. For example, int *myptr; declares myptr as a pointer to an integer. Multiple pointers on one line require * with each name: int *ptr1, *ptr2, *ptr3;. Pointers can also be declared alongside simple variables: int *ptr, x, a[10];.
π Definition β Address Operator (&): Used to get the memory address of a variable. Example: ptr = &x; assigns the address of x to pointer ptr.
π Definition β Dereferencing Operator (*): Used to access the value stored at the memory address held by a pointer. Example: *ptr gives the value stored at the address ptr points to.
π Formula: ptr = &x; β assigns the memory address of variable x to pointer ptr
π Formula: z = *ptr; β assigns the value stored at the address ptr points to, to variable z
π Example: If x = 10 is stored at memory address 400000, and ptr is a pointer variable stored at address 500000, then after ptr = &x;, ptr holds the value 400000. The expression *ptr evaluates to 10.
Pointers can be initialized by assigning an address with &, or by setting them to 0 or NULL (a null pointer pointing to nothing). A null pointer indicates it currently points to no valid memory location.
Example 1 (Bubble Sort)
Swapping values of two variables requires a temporary variable: temp = x; x = y; y = temp;. However, a function swap(x, y) using call-by-value cannot actually swap the original variables because it only receives copies.
To swap values using a function, call-by-reference with pointers is used. The addresses of variables are passed, and the function receives pointers. The code demonstrates bubble sorting an array x[] = {1,3,5,7,9,2,4,6,8,10}. The swap function uses pointers:
void swap(int *x, int *y) {
int tmp;
if(*x > *y) {
tmp = *x;
*x = *y;
*y = tmp;
}
}
Inside the main loop, swap(&x[j], &x[j+1]); passes addresses to swap array elements.
π Example: The bubble sort program's output shows the array being sorted step by step: 1 3 5 7 2 4 6 8 9 10 β 1 3 5 2 4 6 7 8 9 10 β 1 3 2 4 5 6 7 8 9 10 β 1 2 3 4 5 6 7 8 9 10 β final sorted array.
π‘ Why this matters: Passing large arrays to functions by value copies all elements, which is inefficient. Using pointers (call-by-reference) passes only the starting address, saving memory and time.
Pointers and Call By Reference
When passing an array to a function, only the array's starting address is passed by default (call-by-reference). This is efficient for large data sets. However, the called function can modify the original values, which may be undesirable.
π Definition β Constant Pointer: Declared as int *const myptr = &x;. The pointer itself is constant and cannot point to another variable, but the value it points to can be changed.
π Definition β Pointer to Constant Data: Declared as const int *myptr = &x;. The pointer can point to different variables, but the value at the pointed location cannot be changed through this pointer.
This construct is useful when passing addresses to functions for efficiency but preventing modification of the data. Function declaration: fn (const int *myptr) { ... } ensures the function cannot change the pointed value.
Example 2
This example converts lowercase letters in a string to uppercase using pointers and pointer arithmetic.
The function convertToUppercase(char *sptr) processes a string character by character:
void convertToUppercase(char *sptr) {
while (*sptr != '\0') {
if (islower(*sptr))
*sptr = toupper(*sptr);
++sptr;
}
}
The string "Welcome To Virtual University" is passed to this function. The pointer sptr starts at the first character. *sptr dereferences it to get the character. islower() checks if it's lowercase, and toupper() converts it. ++sptr increments the pointer to move to the next character (pointer arithmetic).
π Example: Input: "Welcome To Virtual University" β Output: "WELCOME TO VIRTUAL UNIVERSITY"
The functions islower and toupper are from the <ctype.h> header file.
β Key Takeaways
A pointer is a variable that stores a memory address, declared with data_type *name;. The address-of operator & gets a variable's address, and the dereferencing operator * accesses the value at a pointer's stored address. Pointers enable call-by-reference, allowing functions to modify original variables instead of copies, which is efficient for large data like arrays. Constant pointers (int *const) cannot be reassigned, while pointers to constant data (const int *) prevent modification of the pointed value. Pointer arithmetic (e.g., ++sptr) allows sequential access to array elements.
π§ Quick Revision Questions
- What is the difference between a normal variable and a pointer variable?
- How do you declare a pointer to a double-precision floating-point number?
- What does the statement
ptr = &x;accomplish? - Why does a simple
swap(x, y)function fail to swap values in the calling function, and how do pointers fix this? - What is the difference between
int *const myptr;andconst int *myptr;?
π Lecture 15 β Pointers and Arrays
π Overview: This lecture explores the powerful relationship between pointers and arrays in C/C++. It covers how array names are constant pointers, pointer arithmetic, pointer comparison, and how to manipulate strings and character arrays using pointers, enabling efficient data access and manipulation.
ποΈ Topics Covered
The lecture introduces the relationship between pointers and arrays, explaining that array names are constant pointers. It then covers pointer expressions and arithmetic, including incrementing pointers based on data type sizes. Pointer comparison using relational operators is discussed, followed by a detailed examination of strings as character arrays, including copying strings using pointers and the use of the const keyword.
π Lecture Summary
Introduction
This lecture builds on the previous discussion of pointers. While topics like pointers are often excluded from newer languages like Java, in C/C++ they offer powerful capabilities. The discussion covers the relationship between pointers and arrays, pointer expressions, arithmetic operations with pointers, and strings.
Relationship between Pointers and Arrays
When you declare int x, a symbolic name is attached to a memory location. With an array like int y[10], memory is reserved for ten integers collectively named y. The identifier y itself represents the memory address of the beginning of this reserved memory space. The first element is accessed as y[0].
π Definition β Array Name as Constant Pointer: "The name of the array is a constant pointer which contains the memory address of the first element of the array."
The key difference between an array name and an ordinary pointer is that the array name is a constant pointer β it always points to the start of the array and cannot be reassigned a different address.
π Example:
int y[10];
int *yptr;
yptr = y; // yptr now holds the same address as y (the first element)
Here, y and yptr both point to the first element, but y is constant while yptr is a variable pointer that can be changed.
π‘ Why this matters: Understanding that an array name is a constant pointer means you cannot do y++ to move through the array; you must use a pointer variable like yptr for that.
Pointer Expressions and Arithmetic
To access array elements, you can use both array notation and pointer arithmetic. For example, to access the fourth element: y[3] or *(yptr + 3).
When a pointer is incremented, it doesn't just increase by 1. The increment amount depends on the data type the pointer points to. For an integer pointer, yptr++ increments the address by the size of an integer (typically 4 bytes).
π Definition β Pointer Increment: "When a pointer is incremented, it actually jumps the number of memory spaces according to the data type that it points to."
π Example Program:
#include<iostream.h>
main()
{
int y[10];
int *yptr;
yptr = y;
cout << "Address before increment: " << yptr << endl;
yptr++;
cout << "Address after increment: " << yptr << endl;
}
Sample output showing a difference of 4 bytes (in hexadecimal):
The memory address of yptr = 0x22ff50
The memory address after incrementing yptr = 0x22ff54
You can also assign the address of a specific element to a pointer: yptr = &y[0]; or yptr = &y[3];.
π Example β Different Ways to Access Array Elements:
int y[10] = {0,5,10,15,20,25,30,35,40,45};
int *yptr;
yptr = y;
cout << y[5] << endl; // 25
cout << *(yptr + 5) << endl; // 25
cout << yptr[5] << endl; // 25
This demonstrates three equivalent ways to access the 6th element (y[5]).
π Example β Stepping Through an Array Using a Pointer:
int y[10] = {10,20,30,40,50,60,70,80,90,100};
int *yptr = y;
for (int i = 0; i < 10; i++)
{
cout << "Value at position " << i << " is " << *yptr << endl;
yptr++;
}
π‘ Why this matters: Pointer arithmetic allows efficient traversal of arrays without using index variables, making code faster and more flexible.
Dereferencing and Increment Distinctions
There is an important distinction between incrementing the pointer and incrementing the value where the pointer points to.
π Example β Program Using Pointer Arithmetic:
int x = 10;
int *yptr;
yptr = &x;
(*yptr)++; // Increments the value at the address (x becomes 11)
cout << "x is now: " << x << endl; // Output: 11
Key distinctions:
(*yptr)++β increments the value pointed to (x becomes 11)*yptr + 3β evaluates the value plus 3 but does NOT change the stored value*yptr += 3β increments the value by 3 (x becomes 13)yptr++β increments the address (pointer moves to next element)
π Important Warning: "When a pointer is used to hold the memory address of a simple variable, do not increment or decrement the pointer. When a pointer is used to hold the address of an array, it makes sense to increment or decrement the pointer."
π‘ Why this matters: Incrementing a pointer that points to a single variable can cause it to point to an invalid memory location, potentially crashing the program. Only increment/decrement pointers when they point to array elements.
Pointer Subtraction
You cannot add two pointers (e.g., yptr1 + yptr2 is invalid), but you can subtract them. Pointer subtraction gives the distance between two pointers in units of the data type they point to.
π Example β Pointer Subtraction:
int y[10], *yptr1, *yptr2;
yptr1 = &y[0];
yptr2 = &y[3];
cout << "Difference = " << yptr2 - yptr1; // Output: 3
The result is 3 because there are 3 array elements between y[0] and y[3].
π Definition β Pointer Subtraction Result: Pointer subtraction tells how many units of the data type (not bytes) are between the two pointers.
A memory diagram shows:
Addresses: 3000 3004 3008 3012 3016
y[0] y[1] y[2] y[3] y[4]
| |
yptr yptr+4
Each integer element occupies 4 bytes in this example.
π‘ Why this matters: Pointer subtraction is useful for determining the number of elements between two positions in an array, which is helpful in sorting algorithms and range checks.
Pointer Comparison
Pointers can be used in conditional statements with all comparison operators (less than, greater than, equal to, etc.).
When comparing dereferenced pointers (*yptr1 > *yptr2), you are comparing the values they point to β this is normal integer comparison.
When comparing the pointers themselves (yptr1 > yptr2), you are comparing their memory addresses.
π Example β Dereference Pointer Comparison:
int x, y, *xptr, *yptr;
cin >> x >> y;
xptr = &x;
yptr = &y;
if (*xptr > *yptr)
cout << "x is greater than y";
else
cout << "y is greater than x";
Sample Run:
Please enter the value of x = 6
Please enter the value of y = 9
y is greater than x
π‘ Why this matters: Pointer comparison allows you to determine which pointer points to a higher memory address, which is useful in sorting and searching algorithms.
Pointer, String and Arrays
Character strings are arrays of characters terminated by a null character ('\0').
π Definition β Null Character: The null character '\0' is a special escape character that marks the end of a string. It is considered a single character by the compiler.
π Example β Manual String Initialization:
char name[20];
name[0] = 'A';
name[1] = 'm';
name[2] = 'i';
name[3] = 'r';
name[4] = '\0'; // Must explicitly add null terminator
A shorter way using double quotes β the compiler automatically adds the null character:
char name[20] = "Amir"; // null character added automatically
π Important Rule: "Arrays must be at least one character space larger than the number of printable characters which are to be stored."
Copying Strings Using Pointers
The lecture presents a complete program that copies one character array into another using pointers.
π Example β String Copy Program:
#include <iostream.h>
main()
{
char strA[80] = "A test string";
char strB[80];
char *ptrA = strA;
char *ptrB = strB;
while(*ptrA != '\0')
{
*ptrB++ = *ptrA++; // Copy character, then increment both pointers
}
*ptrB = '\0'; // Add null terminator to destination
cout << "String in strA = " << strA << endl;
cout << "String in strB = " << strB << endl;
}
Output:
String in strA = A test string
String in strB = A test string
Explanation: The statement *ptrB++ = *ptrA++ works as follows:
- The character
ptrApoints to is assigned to the locationptrBpoints to - Both pointers are then incremented (postfix increment)
- This repeats until
ptrApoints to the null character ('\0') - A null character is explicitly added to the end of
strB
π‘ Why this matters: This technique demonstrates efficient string manipulation without using library functions, and it introduces the concept of passing references through pointers.
Function for String Copy Using Pointers
A reusable function can be created using const to protect the source string from accidental modification:
void myStringCopy(char *destination, const char *source)
{
while(*source != '\0')
{
*destination++ = *source++;
}
*destination = '\0';
}
Alternatively, using array notation:
void myStringCopy(char dest[], char source[])
{
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
i++;
}
dest[i] = '\0';
}
π Key Point: When arrays are passed to functions, a reference to the original array is passed (call by reference). Therefore, the function does not need to return anything β changes are made directly to the original array.
β Key Takeaways
- An array name is a constant pointer that always points to the first element of the array and cannot be reassigned. This is fundamentally different from a pointer variable which can be incremented or changed.
- Pointer arithmetic is type-sensitive β incrementing an integer pointer advances it by the size of an integer (usually 4 bytes), while incrementing a char pointer advances by 1 byte. This allows efficient array traversal.
- Never increment a pointer to a single variable β this can cause the pointer to point to invalid memory. Only increment/decrement pointers that point to array elements.
- Strings are null-terminated character arrays β always allocate at least one extra character for the null terminator (
'\0'). The null character allows functions likecoutand thewhileloop to know where the string ends. - Use
constwith pointers to protect source data β when passing a pointer to a function and you don't want the original data to be modified, useconstto enforce read-only access.
π§ Quick Revision Questions
- What is the difference between an array name (
y) and a pointer variable (yptr) in terms of reassignment? - If
yptris an integer pointer pointing to address 3000 and integers occupy 4 bytes, what will be the value ofyptrafteryptr++? - What is the result of subtracting two pointers that point to
y[0]andy[5]in an integer array? - Why must a null character (
'\0') be added at the end of a character array when manually constructing a string? - What does the expression
*ptrB++ = *ptrA++do in a single statement?
π Lecture 16 β Pointers (continued), Multi-dimensional Arrays, Pointers to Pointers, Command-line Arguments
π Overview: This lecture deepens the understanding of pointers by contrasting them with array names, exploring multi-dimensional array manipulation using pointer arithmetic, introducing pointers to pointers, and explaining how command-line arguments can be passed to a program. A comprehensive case study on card shuffling and dealing demonstrates these concepts in a real-world application.
ποΈ Topics Covered
The lecture begins by comparing array names (constant pointers) with pointer variables, then moves into multi-dimensional array memory layout and pointer-based element access. It introduces the concept of pointers to pointers, demonstrates command-line argument handling via argc and argv, and concludes with a detailed card shuffling and dealing simulation that applies pointer to pointer, array of pointers, and random number generation techniques.
π Lecture Summary
Pointers (continued)
When a character array is declared as char myName[] = "Full Name";, the array name myName becomes a constant pointer β its address cannot be changed. In contrast, char *myNamePtr = "Full Name"; creates a pointer variable that can be reassigned to point to another string. Both store the starting address of the string "Full Name\0", but the array name is immutable, while the pointer variable is mutable.
π Definition β Constant Pointer: A pointer whose memory address cannot be reassigned after initialization. Array names behave as constant pointers.
Multi-dimensional Arrays
Consider a two-dimensional array char multi[5][10];. In memory, elements are stored contiguously in a single linear sequence (row-major order). Unlike a one-dimensional array where adding 1 to the pointer moves to the next element, adding 1 to the name of a two-dimensional array (multi + 1) jumps over an entire row β in this case, 10 bytes (since char is 1 byte). This is because multi is treated as an array of arrays; multi + 1 points to the first element of the second row.
To access multi[1][2] (second row, third column) using pointer notation: *(*(multi + 1) + 2). The first dereference *(multi + 1) gives the address of the first element of row 1, and the second dereference fetches the value at column 2 within that row. This is double dereferencing.
π‘ Why this matters: A function receiving a multi-dimensional array must know all dimensions except the leftmost one to correctly compute element addresses.
π Definition β Double Dereferencing: Using the * operator twice to access a value through a pointer to a pointer (e.g., *(*(multi+row)+col)).
π Formula: array[row][col] β *(*(array + row) + col)
π Example: For int multi[5][10], to access the element at row 3, column 3 using pointer notation: *(*(multi + 3) + 3) is equivalent to multi[3][3].
Pointers to Pointers
A pointer to pointer is a variable that stores the address of another pointer. In the case of double dereferencing, the first pointer contains the address of a second pointer, which contains the address of the variable holding the desired value. This construct is useful when dealing with arrays of strings of variable lengths.
Using a conventional two-dimensional array to store character strings of different lengths wastes memory because all rows must have the same fixed number of columns (based on the longest string). Instead, an array of pointers can be declared: char *myarray[] = {"Amir", "Jehangir"};. Here, myarray is an array of pointers, where each pointer points to a character string. The compiler allocates exactly the required space for each string: 5 bytes for "Amir\0" and 9 bytes for "Jehangir\0", eliminating memory waste.
π Definition β Array of Pointers: An array where each element is a pointer, often used to store strings of varying lengths efficiently.
π Example: char *myarray[10]; declares an array of 10 pointers to characters.
Command Line Arguments
Programs can accept input from the command line using parameters inside the main() function: void main(int argc, char **argv).
- argc (argument count): an integer representing the number of command-line arguments, including the program name.
- argv (argument vector): a pointer to an array of character strings (pointer to pointer to char) containing the arguments.
The first argument (*(argv + 0) or argv[0]) is always the program name. Arguments are typically used to specify file names or options. If a program requires command-line arguments but none are provided, it should print an error message and instructions.
π Formula: main(int argc, char **argv) β argc is the count, argv is the array of argument strings.
π Example: Running C:\>Program-name 10 display sets argc = 3, argv[0] = "Program-name", argv[1] = "10", argv[2] = "display". The integer value can be extracted using the atoi() function: atoi(argv[1]) returns 10.
Case Study: A Card Shuffling and Dealing Simulation
This real-world example demonstrates pointer to pointer and array of pointers concepts.
Problem: Randomly shuffle a 52-card deck and deal all cards.
Design:
- Declare constant arrays of pointers for suits and faces:
const char *suite[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};const char *face[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
- Represent the deck as a 2D integer array:
int deck[4][13] = {0};(initialized to all zeros, meaning no card has been placed yet).
Shuffle function: Uses a loop (card number 1 to 52) to randomly select a row (suit) and column (face) using rand() % 4 and rand() % 13. The do-while loop ensures that a slot is only filled if it hasn't been occupied yet (wDeck[row][column] != 0). Each card is assigned its sequential number in the deck array.
Deal function: Uses nested loops to search for each card number (1 to 52) in the deck array. When found, it prints the card using the face and suit arrays: wFace[column] << " of " << wSuit[row].
Random number seeding: The srand(time(0)) function seeds the random number generator with the current time (seconds elapsed since 1970), ensuring a different sequence of random numbers each time the program runs.
π Definition β srand(): A function that seeds the random number generator to produce different sequences of random numbers on each program execution.
π Example: srand(time(0)); uses the current time as a seed for rand(), making the shuffle truly random.
β Key Takeaways
Array names are constant pointers whose address cannot be changed, unlike pointer variables which can be reassigned. For multi-dimensional arrays, pointer arithmetic jumps entire rows β adding 1 to the array name skips one complete row, and elements are accessed via double dereferencing. Pointers to pointers enable efficient storage of variable-length strings through arrays of pointers, avoiding memory waste. Command-line arguments allow programs to accept input at execution time, with argc storing the count and argv providing the argument strings. The card shuffling case study integrates all these concepts β arrays of pointers for suits/faces, a 2D array for the deck, random number generation with seeding, and nested loops for dealing.
π§ Quick Revision Questions
- What is the difference between
char myName[] = "Hello";andchar *myNamePtr = "Hello";regarding pointer mutability? - If
int arr[4][6];is declared, how many bytes doesarr + 1jump? Explain why. - Write the pointer notation equivalent of
multi[2][5]for a two-dimensional arraymulti. - Why does using an array of pointers to store strings of different lengths save memory compared to a 2D character array?
- In the command line
C:\> myprog 25, what are the values ofargcandargv?
π Lecture 17 β Lecture No. 17
π Overview: This lecture explores how to handle and manipulate strings in C/C++ programming. It covers the fundamental character representation (ASCII), built-in functions for character testing and conversion, string copy/concatenation/comparison operations, string conversion functions, and search functions, enabling efficient text processing.
ποΈ Topics Covered
This lecture covers String Handling concepts and evolution, detailed explanation of String Manipulation Functions, Character Handling Functions from the ctype.h library with a sample program demonstrating character analysis, String Conversion Functions from stdlib.h for converting strings to numbers, String Functions from string.h including strcpy, strcat, strcmp, and strlen, Search Functions for locating characters and substrings, and concludes with examples and exercises.
π Lecture Summary
String Handling
The lecture begins with the historical context of string handling, tracing back to the development of text processing tools at BELL Laboratories alongside C language and UNIX. Scientists needed a way to format and publish articles using text editors and in-line commands before modern word processors existed. The lecture then introduces the fundamental building block of strings: the character. Characters are stored inside computers as numbers, primarily using the ASCII (American Standard Code for Information Interchange) code. The char data type stores a single character, while int stores whole numbers. A character occupies one byte (8 bits), allowing 256 different values.
π Definition β ASCII: A standard code used by computers to represent characters as numbers in memory.
π The relationship between integers and characters is direct: when an integer value (0-255) is assigned to a char variable, it displays the corresponding ASCII character.
π Example: The lecture provides a program that displays the ASCII code table. It uses a loop from i=0 to i<255, and inside the loop, the statement c = i assigns the integer value to the character variable, then displays both the integer and its character representation. The output shows that values for 'a'-'z' and 'A'-'Z' are continuous ranges.
Character Handling Functions
C provides many functions for testing and manipulating character data, found in the header file ctype.h. Any program using these functions must include this header. Each function in ctype.h receives a character (as an int) or EOF (End of File) as an argument. These functions have self-explanatory names and return true (non-zero) or false (zero).
π Definition β EOF (End of File): A special character that indicates the end of a file or input stream.
Key functions from this library:
- int isdigit( int c ): Returns true if c is a digit (0-9), false otherwise.
- int isalpha( int c ): Returns true if c is a letter (a-z, A-Z), false otherwise.
- int isalnum( int c ): Returns true if c is a digit or a letter, false otherwise.
- int islower( int c ): Returns true if c is a lowercase letter, false otherwise.
- int isupper( int c ): Returns true if c is an uppercase letter, false otherwise.
- int tolower( int c ): If c is an uppercase letter, returns its lowercase equivalent; otherwise returns c unchanged.
- int toupper( int c ): If c is a lowercase letter, returns its uppercase equivalent; otherwise returns c unchanged.
- int isspace( int c ): Returns true if c is a white-space character (newline '\n', space ' ', form feed '\f', carriage return '\r', horizontal tab '\t', or vertical tab '\v'), false otherwise.
- int iscntrl( int c ): Returns true if c is a control character, false otherwise.
- int ispunct( int c ): Returns true if c is a printing character other than a space, digit, or letter, false otherwise.
- int isprint( int c ): Returns true if c is a printing character (including space ' '), false otherwise.
- int isgraph( int c ): Returns true if c is a printing character other than space ' ', false otherwise.
- int isxdigit( int c ): Returns true if c is a hexadecimal digit character (0-9, a-f, A-F), false otherwise.
The tolower and toupper functions are conversion functions that change the case of alphabetic characters while leaving non-alphabetic characters unchanged.
π‘ Why this matters: Character handling functions are essential for validating user input, parsing text, and processing strings character-by-character in programs.
Sample Program
A complete sample program demonstrates the use of ctype.h functions by prompting the user to enter a string, then counting different types of characters (lowercase letters, uppercase letters, digits, white space, punctuation, and others). This program uses the getchar() function (from stdio.h) instead of cin to read a single character at a time from the input buffer. The loop continues until the user presses ENTER, which produces the newline character '\n'.
// Key structure of the program
while ((c = getchar()) != '\n')
{
if (islower(c)) lc++;
else if (isupper(c)) uc++;
else if (isdigit(c)) dig++;
else if (isspace(c)) ws++;
else if (ispunct(c)) pun++;
else oth++;
}
π Example: For input "Sixty Five = 65.00", the output shows:
- Lower case letters = 7 (i,x,t,y,i,v,e)
- Upper case letters = 2 (S, F)
- Digits = 4 (6,5,6,5)
- White space = 3 (spaces between words)
- Punctuation = 2 (= and .)
- Others = 0
String Conversion Functions
The header file stdlib.h includes functions for converting strings to different numeric types. These are essential when dealing with command-line arguments (which are always stored as character strings) or when input is received as a string but needs to be used as a number.
π Definition β Command-line arguments: Parameters passed to a program when it is executed from the command line, stored as character strings in argv[].
Key conversion functions:
- double atof( const char *nPtr ): Converts the string nPtr to double.
- int atoi( const char *nPtr ): Converts the string nPtr to int.
- long atol( const char *nPtr ): Converts the string nPtr to long int.
- **double strtod( const char *nPtr, char endPtr ): Converts the string nPtr to double.
- **long strtol( const char *nPtr, char endPtr, int base ): Converts the string nPtr to long.
- **unsigned long strtoul( const char *nPtr, char endPtr, int base ): Converts the string nPtr to unsigned long.
π Example: The lecture provides a program that uses atoi to validate user input. It prompts for an integer between 10-100, reads it as a string (myInt), then checks if (atoi(myInt) == 0) to detect non-numeric input. If valid, it converts and checks if the integer is within range. Output for input "45.5" shows "OK, you have entered 45" because atoi converts until it encounters a non-digit character.
String Functions
The header file string.h provides functions for manipulating strings (character arrays terminated by null character '\0'). These functions handle copying, concatenation, comparison, and length determination.
Key string functions:
- char *strcpy( char *s1, const char *s2 ): Copies string s2 into character array s1. Returns s1. s2 (source) remains unchanged, while s1 (destination) receives the copy. The const keyword prevents modification of the source string.
- char *strncpy( char *s1, const char *s2, size_t n ): Copies at most n characters of string s2 into array s1. Returns s1. s1 must be large enough to hold the copied characters.
- char *strcat( char *s1, const char *s2 ): Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. Returns s1.
- char *strncat( char *s1, const char *s2, size_t n ): Appends at most n characters of string s2 to array s1. Returns s1.
- int strcmp( const char *s1, const char *s2 ): Compares string s1 to s2 lexicographically. Returns a negative number if s1 < s2, zero if s1 == s2, or a positive number if s1 > s2.
- int strncmp( const char *s1, const char *s2, size_t n ): Compares up to n characters of string s1 to s2. Returns negative, zero, or positive as with strcmp.
- int strlen( const char *s ): Determines the length of string s. Returns the number of characters preceding the terminating null character.
π‘ Why this matters: String comparison considers spaces and case sensitivity. For example, "Hello", "hello", and "He llo" are all different strings because of case differences and spaces.
Examples
Example 1 (strcpy and strncpy): This program demonstrates string copy operations. Two strings are initialized as "String1" and "String2". After strcpy(string2, string1), both strings become "String1". Then strncpy(string3, string1, 3) copies only the first 3 characters ("Str") into string3.
π Example output:
Before the copy:
String 1: String1
String 2: String2
After the copy:
String 1: String1
String 2: String1
strncpy (string3, string1, 3) = Str
Example 2 (strcat and strncat): This program demonstrates string concatenation. s1 = "Welcome to", s2 = "Virtual University", s3 = "" (empty). After strcat(s1, s2), s1 becomes "Welcome to Virtual University". Then strncat(s3, s1, 6) copies the first 6 characters ("Welcom") into s3. Note that the output shows 7 characters ("Welcome") as mentioned in the output.
π Example output:
s1 = Welcome to
s2 = Virtual University
s3 =
strcat( s1, s2 ) = Welcome to Virtual University
strncat( s3, s1, 7 ) = Welcome
Example 3 (Comprehensive string manipulation): This program demonstrates multiple string functions together. It initializes four strings: s1="Welcome to", s2="Virtual University", s3="Welcome to Karachi", city="Karachi", province="Sind", and an empty string s[80].
strlen(s1)returns 11 (including the space, but not the null terminator)strlen(s2)returns 18strlen(s3)returns 18strcpy(s, "Hyderabad")copies "Hyderabad" into s- Multiple
strcatcalls build the sentence: "Hyderabad and Karachi are in Sind." strcmp(s1, s2)returns non-zero (not equal), so it outputs "s1 and s2 are not identical"strncmp(s1, s3, 7)compares first 7 characters ("Welcome") and returns zero (equal), so it outputs "First 7 characters of s1 and s3 are identical"
π Example output:
s1 = Welcome to
s2 = Virtual University
s3 = Welcome to Karachi
The length of s1 = 11
The length of s2 = 18
The length of s3 = 18
The nearest city to Karachi is Hyderabad
Hyderabad and Karachi are in Sind.
s1 and s2 are not identical
First 7 characters of s1 and s3 are identical
Search Functions
C provides a set of search functions for locating characters and substrings within strings. These functions are also defined in string.h.
Key search functions:
- char *strchr( const char *s, int c ): Locates the first occurrence of character c in string s. Returns a pointer to c in s if found, otherwise returns NULL.
- size_t strcspn( const char *s1, const char *s2 ): Returns the length of the initial segment of s1 consisting of characters NOT in s2.
- size_t strspn( const char *s1, const char *s2 ): Returns the length of the initial segment of s1 consisting only of characters IN s2.
- char *strpbrk( const char *s1, const char *s2 ): Locates the first occurrence in s1 of any character from s2. Returns a pointer to that character in s1, or NULL.
- char *strrchr( const char *s, int c ): Locates the last occurrence of c in string s. Returns a pointer to that character in s, or NULL.
- char *strstr( const char *s1, const char *s2 ): Locates the first occurrence of string s2 in string s1. Returns a pointer to the beginning of the substring in s1, or NULL.
- char *strtok( char *s1, const char *s2 ): Breaks string s1 into tokens (logical pieces like words) separated by delimiter characters in s2. The first call uses s1 as the first argument; subsequent calls use NULL to continue tokenizing the same string. Returns a pointer to the current token, or NULL if no more tokens exist.
π‘ Why this matters: Search functions enable powerful text processing operations like finding words in documents, parsing command-line arguments, and breaking strings into components.
β Key Takeaways
The most critical concepts from this lecture are understanding that characters are stored as numeric ASCII codes and can be tested or converted using ctype.h functions like isdigit(), isalpha(), and toupper(). String manipulation functions in string.h (strcpy, strcat, strcmp, strlen) provide essential operations for handling character arrays, while conversion functions in stdlib.h (atoi, atof, atol) convert string input to numeric types. Search functions like strstr and strtok enable locating substrings and parsing text into components. The getchar() function is useful for character-by-character input processing, and always remember that string comparison is case-sensitive and space-sensitive.
π§ Quick Revision Questions
- What does the
isalnum()function return when given the character '5'? What about the character '#'? - Write the C++ code using strcmp to determine if two character arrays "Hello" and "hello" are identical. What value would strcmp return?
- Explain the difference between
strcpy(s1, s2)andstrncpy(s1, s2, n). When would you use one over the other? - What does the
atof()function do, and from which header file does it come? What wouldatof("3.14")return? - Describe how the
strtok()function works for breaking a sentence into words. What special argument is used in subsequent calls after the first call?
π Lecture 18 β File Handling
π Overview: This lecture introduces file handling in C++, explaining how to permanently store data on disk rather than in volatile memory. It covers the fundamental operations of opening, reading, writing, and closing text files, along with different file access modes and practical examples for input/output file processing.
ποΈ Topics Covered
The lecture begins by explaining the importance of files for permanent data storage versus volatile memory. It then covers text file handling fundamentals including the fstream header, ifstream and ofstream streams, and the open/read/write/close cycle. The discussion extends to file opening modes, error checking mechanisms, and various reading techniques including the get() function and the more efficient getLine() function. The lecture concludes with practical examples demonstrating file processing including salary calculations using strtok() and atoi() functions.
π Lecture Summary
Files
Computer memory is volatile, meaning data is lost when the computer is turned off. To store data permanently, we need files on disk. Files come in two primary types: text files containing readable English characters (plain text like source code or formatted text like Word documents), and executable program files containing non-printable binary information. For programming purposes, we need to learn how to create files on disk, read from them, write into them, and manipulate the data they contain β this is known as file handling.
π‘ Why this matters: Without file handling, every program would lose its data when closed, making applications like payroll systems impractical.
Text File Handling
The basic steps of file handling are: Open the file, Read and write, then Close the file. C++ uses streams for file handling, similar to how cin and cout work for console input/output. The required header file is <fstream.h> (file stream). Three stream types are available: ifstream (input file stream) for reading files, ofstream (output file stream) for writing files, and fstream for reading and writing the same file.
π Definition β File Stream: An object that acts as a handle or internal variable to refer to files on disk, enabling data transfer between the program and the file.
Declaring file streams:
ifstream inFile; // object for reading from a file
ofstream outFile; // object for writing to a file
Opening a file:
myFile.open(filename);
The filename argument is a character string in double quotation marks. It can be a simple name like "payroll.txt" if the file is in the current directory, or a fully qualified path like "C:\\myprogs\\payroll.txt".
Reading from a file:
myFile >> c; // reads one word into variable c (stops at spaces)
Multiple words can be read at once: myFile >> c1 >> c2 >> c3;
Closing a file:
myFile.close();
Error checking is essential before file operations:
if (!myFile) {
cout << "File cannot be opened" << endl;
exit(1);
}
The function eof() returns true when the end of file is reached, commonly used in while loops.
Example 1
A program reads from "myfile.txt" containing employee data (name, salary, department) and prints it to the screen.
π Example: Input file "myfile.txt" contains:
Name Salary Department
Aamir 12000 Sales
Amara 15000 HR
Adnan 13000 IT
Afzal 11500 Marketing
The program code:
#include <iostream.h>
#include <fstream.h>
main() {
char name[50], sal[10], dept[30];
ifstream inFile;
char inputFileName[] = "myfile.txt";
inFile.open(inputFileName);
if (!inFile) {
cout << "Can't open input file named " << inputFileName << endl;
exit(1);
}
while (!inFile.eof()) {
inFile >> name >> sal >> dept;
cout << name << "\t" << sal << " \t" << dept << endl;
}
inFile.close();
}
Output: Displays the same data as the input file with tabs between columns.
Output File Handling
The actual syntax of the open() function with mode is: open(filename, mode)
The file-opening modes determine how a file is accessed:
| Mode | Meaning |
|---|---|
ios::in | Open for extraction (input) |
ios::out | Open for insertion (output); creates new file or deletes existing contents |
ios::app | Append; each write goes to end of existing file |
ios::trunc | Discards file contents if exists (similar to default) |
ios::ate | Open without truncating; allows writing anywhere in file |
ios::binary | Treat file as binary rather than text |
π Definition β ios::out mode: When opening a file for output with this mode, a new file is created if it doesn't exist, but if the file already exists, its contents are deleted.
π Example: Program to create a file "myFileOut.txt" and write "Welcome to VU":
#include <iostream.h>
#include <fstream.h>
main() {
ofstream outFile;
char outputFileName[] = "myFileOut.txt";
char ouputText[100] = "Welcome to VU";
outFile.open(outputFileName, ios::out);
if (!outFile) {
cout << "Can't open input file named " << outputFileName << endl;
exit(1);
}
outFile << ouputText;
outFile.close();
}
Alternative Reading Functions
The >> operator does not read newline characters, so we need to add them explicitly in output. The get() function reads individual characters from a file:
char c;
while ((c = inFile.get()) != EOF) {
// process each character
outFile.put(c); // write character to output file
}
For efficiency, reading lines rather than characters is better because disk access is much slower than processor/memory (hard disk average access time is ~7 milliseconds vs processor GHz speed). The getLine() function reads complete lines:
char name[100];
int maxChar = 100;
int stopChar = 'o';
inFile.getLine(name, maxChar, stopChar);
π Definition β getLine(): Reads a line from a file into a character array. First argument is the array, second is maximum characters to read, third (optional) is the stop character (default is newline). The newline character is NOT read.
π Example: For input "Hello World", using inFile.getLine(str, 20, 'W') reads "Hello " into str.
Example 2
Problem: Read an input file containing employee names and salaries (one space between them). Calculate total salaries and write to an output file.
Solution: Use getLine() to read each line, then strtok() to split the line into tokens using space as delimiter. Use atoi() to convert salary string to integer.
π Definition β strtok(): String token function that takes a string and a delimiter character, returning the first token. Subsequent calls with strtok(NULL, " ") return the next token from the same string.
π Definition β atoi(): Function that converts a character string to an integer value.
π Example: Input file "salin.txt":
Aamir 12000
Amara 15000
Adnan 13000
Afzal 11500
Program code:
#include <iostream.h>
#include <fstream.h>
#include <cstring>
#include <cstdlib>
main() {
ifstream inFile;
char inputFileName[] = "salin.txt";
ofstream outFile;
char outputFileName[] = "salout.txt";
const int MAX_CHAR_TO_READ = 100;
char completeLineText[MAX_CHAR_TO_READ];
char *tokenPtr;
int salary, totalSalary;
salary = 0;
totalSalary = 0;
inFile.open(inputFileName);
outFile.open(outputFileName);
if (!inFile || !outFile) {
cout << "Can't open file" << endl;
exit(1);
}
while (!inFile.eof()) {
inFile.getline(completeLineText, MAX_CHAR_TO_READ);
tokenPtr = strtok(completeLineText, " "); // First token is name
tokenPtr = strtok(NULL, " "); // 2nd token is salary
salary = atoi(tokenPtr);
totalSalary += salary;
}
outFile << "The total salary = " << totalSalary;
inFile.close();
outFile.close();
}
Output file "salout.txt": The total salary = 51500
β Key Takeaways
Always close files with the close() function and open them explicitly using the open() function. Error checking is critical when handling files β always verify that a file opened successfully before attempting to read or write. The >> operator reads word by word and does not capture newlines, while get() reads individual characters including newlines, and getLine() reads complete lines for better efficiency. File-opening modes like ios::out, ios::app, and ios::ate control whether files are created, truncated, or appended to. For processing structured data from files, use strtok() to parse tokens and atoi() to convert string numbers to integers.
π§ Quick Revision Questions
- What are the three basic steps of file handling in C++ and what functions are used for each step?
- How do you check if a file was opened successfully before performing read/write operations?
- What is the difference between the
>>operator, theget()function, and thegetLine()function for reading from files? - What is the purpose of the
strtok()function and how is it used to parse space-delimited data from a file? - Explain the difference between
ios::out,ios::app, andios::atefile opening modes β when would you use each?