π Lecture 9 β Functions
π Overview: This lecture introduces functions, a fundamental programming construct that enables code reuse and modular design. It explains how to break complex problems into smaller, manageable subtasks using top-down design methodology, and covers function declaration, definition, calling mechanisms, and practical examples.
ποΈ Topics Covered
The lecture begins with an introduction to functions and the concept of top-down design, then explains the structure of a function including return-value-type, function-name, argument-list, and body. It covers declaration versus definition of functions, calling mechanisms, and provides three sample programs: calculating integer power, calculating area of a ring using a circleArea function, and testing whether a number is even.
π Lecture Summary
Introduction
Functions are a major programming construct in C, which is a function-oriented language. Every program is written in different functions. In daily life, we divide tasks into subtasks. For example, making a laboratory stool involves making a seat and three legs, where legs can be identical and reused. This is the concept of functional design or top-down designing. Top-down design follows the principle of 'divide and conquer' β we divide a big task into smaller tasks and accomplish them. For example, to find how many students are logged in LMS, the request is delegated to a network administrator who performs the task while the caller can do other work. This demonstrates information hiding, where some information is hidden from the caller.
π‘ Why this matters: Functions enable parallel processing and modular programming, allowing complex problems to be broken into manageable pieces.
Functions
Functions are like subtasks that receive some information, do some process, and provide a result. Functions are invoked through a calling program, which does not need to know what the function is doing internally. There is a specific function-calling methodology. The main() function is also a function. Functions are very important in code reusing.
There are two categories of functions:
- Functions that return a value
- Functions that do not return a value
For example, a function that calculates the square of an integer returns the square, while a function that displays information on screen does not return any value.
Structure of a Function
The declaration syntax of a function is:
return-value-type function-name( argument-list )
{
declarations and statements
}
return-value-type: Function may or may not return a value. If a function returns a value, it must be of a valid data type (int, float, char, etc.). The keyword return is used to return a value β it does two things: returns a value to the calling program and exits from the function. For functions that do not return any value, the return-value-type is void. The default return-value-type is int.
Function-name: Same rules as variable naming; should be self-explanatory like square, squareRoot, circleArea.
argument-list: Contains information passed to the function. Some functions need no information, so argument list is empty. Arguments must be of valid data types.
declarations and statements: The body of the function where the task is performed.
π Example:
int square(int number)
{
int result = 0;
result = number * number;
return result;
}
Calling Mechanism
The calling program writes the function name and provides its arguments (without data types). While calling a function, we don't write the return value data type or the data types of arguments.
π Example:
result = square(number);
Functions can be used as stand-alone statements or on the right-hand side of assignment statements:
result = 10 + square(5);result = square(number + 10);result = square(number) + square(number + 1) + square(3 * number);cout << "The square is " << square(number);
Functions that do not return any value cannot be used in assignment statements; they are written as stand-alone statements.
Declaration and Definition of a Function
Declaration is the prototype of the function, including return type, name, and argument list. It is also known as signature of a function. Definition is the actual function code with complete statements.
If functions are written after the calling function or in a different file, they must be declared before use. Function declaration is a one-line statement with return type, function name, and data types of arguments (argument names are optional). The definition starts with the declaration statement plus argument names, followed by braces and statements.
π Definition β Function Declaration (Prototype): A one-line statement that tells the compiler about a function's return type, name, and parameter types before the function is defined or used. Example: int square(int);
π Definition β Function Definition: The complete code of a function including the header with argument names and the body with declarations and statements. Example: int square(int number) { return (number * number); }
Functions can be called using call by value, where a copy of the argument values is passed to the function, and the original values remain unchanged.
Sample Program 1
Problem: Calculate the integer power of some number (x^n).
Solution: There is no operator for power in C, so we write a function raiseToPow. Input: a number (double) and power (int). Output: double. The function multiplies x by itself power times using a loop.
π Formula:
double raiseToPow(double x, int power)
{
double result = 1.0;
for (int i = 1; i <= power; i++)
{
result *= x;
}
return result;
}
π Example:
// Calling program
double x;
int i;
cout << "Please enter the number: ";
cin >> x;
cout << "Please enter the integer power: ";
cin >> i;
cout << x << " raise to power " << i << " is equal to " << raiseToPow(x, i);
The function call uses call by value β copies of x and i are passed, so original values remain unchanged.
Sample Program 2
Problem: Calculate the area of a ring.
Solution: A ring consists of a small circle and a big circle. Area of ring = area of big circle - area of small circle. Area of any circle = Ο * rΒ². We write a circleArea function and reuse it.
π Formula:
double circleArea(double radius)
{
return (3.1415926 * radius * radius);
}
π Example:
double rad1, rad2, ringArea;
cout << "Please enter the outer radius value: ";
cin >> rad1;
cout << "Please enter the radius of the inner circle: ";
cin >> rad2;
ringArea = circleArea(rad1) - circleArea(rad2);
cout << "Area of ring: " << ringArea;
π‘ Why this matters: The circleArea function is reused twice without rewriting code, demonstrating code reuse and modular design.
Sample Program 3
Problem: Write a function that tests whether a given number is even or not. Return true (non-zero) if even, false (zero) if odd.
Solution: In C, zero is considered false, and any non-zero value is considered true. Return type is int.
π Definition β isEven function: A function that returns 1 (true) if a number is even and 0 (false) if odd. Declaration: int isEven(int);
π Example:
int isEven(int number)
{
if (2 * (number / 2) == number)
{
return 1;
}
else
{
return 0;
}
}
// Usage in main:
if (isEven(number))
{
cout << "The number entered is even" << endl;
}
else
{
cout << "The number entered is odd" << endl;
}
Functions can be used directly in conditional statements like if (isEven(number)).
β Key Takeaways
Functions are essential for code reuse and modular design using top-down methodology. A function has a header (return type, name, parameter list) and a body. Declaration (prototype) tells the compiler about the function before it is defined or used, while definition contains the actual code. Functions communicate via arguments and return values, with call by value protecting original variables. Functions can be used in assignment statements, expressions, and conditional statements. The three sample programs demonstrate practical function usage: mathematical computation (power), code reuse (circle area), and boolean testing (even check).
π§ Quick Revision Questions
- What is the difference between a function declaration and a function definition?
- What does the
returnkeyword do in a function? - In Sample Program 1, why do the original values of x and i remain unchanged after calling
raiseToPow? - How is the
circleAreafunction reused in Sample Program 2? - In Sample Program 3, what value does
isEvenreturn if the number is even, and how is this used in the if statement?
π Lecture 10 β Header Files, Scope of Identifiers, Functions
π Overview: This lecture explains how to organize C++ programs using header files and
#defineconstants. It then covers the scope (visibility) of variables at global, function, and block levels, followed by the two fundamental function calling mechanisms: call by value and call by reference. Finally, it introduces recursive functions. This is critical for writing modular, safe, and efficient code.
ποΈ Topics Covered
This lecture covers header files as a mechanism to organize function prototypes and constant definitions using #define. It details the three scopes of identifiers: global, function-level, and block-level scope, with examples of variable hiding. It then explains the default call-by-value mechanism, contrasts it with call-by-reference using pointers (& and *), and demonstrates recursion with the factorial example.
π Lecture Summary
Header Files
The lecture explains that instead of listing many function prototypes before every function, you can place all prototypes in a separate text file with a .h extension (a header file). Using the #include directive, this file is included in your program, which is equivalent to writing those prototypes manually. Header files are also used for defining constants. Instead of declaring a double pi variable, you can use the preprocessor directive #define:
#define pi 3.1415926
This does not create a variable. During compilation, the preprocessor replaces every occurrence of pi with 3.1415926 before the code is compiled. This makes code more readable (e.g., 2 * pi * radius is clearly the circumference formula) and avoids repeating the literal number.
π Definition β Header File: A text file (usually with .h extension) containing function prototypes and #define constants that can be included in a program using the #include directive.
π Definition β #define Directive: A preprocessor command that associates a name with a value; during compilation, the name is replaced by its value. The name cannot be used on the left-hand side of an assignment (it is not a variable).
Scope of Identifiers
An identifier (name of a variable, function, or label) has a scope that defines where it is visible. This discussion focuses on variable scope.
- Function-Level Scope: A variable declared inside a function body is local to that function. It is not visible in other functions. For example,
int i;insidefunc1()cannot be accessed fromfunc2(). - Block-Level Scope: A variable declared inside a code block (between
{and}), such as inside aforloop, is local to that block.
Code Example with Variable Hiding:
void increment() {
int num; // Function-level scope
{
int num; // Bad practice! Block-level scope with same name
num++; // This increments the inner 'num', not the outer one.
}
}
If a variable with the same name is declared in an inner block, the outer variable is hidden inside that block, and the inner variable is used.
Global Scope (File Scope): A variable declared outside of any function has global scope (or file scope). It is visible to all functions in that file.
#include <iostream.h>
int i; // Global variable
main() {
i = 10;
f();
cout << i; // Output will be 20
}
void f() {
cout << i; // Output will be 10
i = 20; // Modifies the global variable
}
π‘ Why this matters: Minimizing the use of global variables is a key principle of Encapsulation and Data Hiding. They can be accidentally changed by any function, leading to hard-to-find bugs. Prefer to use local variables as much as possible.
Functions β Call by Value
The default calling mechanism in C is call by value. When a function is called, a copy of the argument's value is passed to the function. The original variable in the calling function remains unchanged.
Example:
#include <iostream.h>
void f(int); // Prototype
main() {
int i = 10;
f(i); // A copy of i (value 10) is passed to f
cout << i; // Output: 10 (original i unchanged)
}
void f(int i) {
i *= 2;
cout << i; // Output: 20 (the copy is doubled)
}
π Formula: f(argument) β The function f receives a copy of argument. Any changes made to the copy inside f do not affect the original variable.
Functions β Call by Reference
In call by reference, the address (memory location) of the variable is passed to the function. The function can then directly modify the original variable at that address. This is achieved using the address-of operator & and dereference operator *.
Example (Square function that modifies the original):
#include <iostream.h>
void square(double *); // Prototype: accepts a pointer to double
main() {
double x = 123.456;
square(&x); // &x passes the address of x
cout << x; // Output: 15241.4 (original x changed)
}
void square(double* x) { // x is a pointer (stores an address)
*x = *x * *x; // *x accesses the value at the address (dereference)
}
π Definition β Pointer: A variable that stores the memory address of another variable. double* x means "x is a pointer to a double".
π Definition β Address-of Operator (&): Returns the memory address of a variable (e.g., &x).
π Definition β Dereference Operator (*): Accesses the value stored at the address held by a pointer (e.g., *x).
π‘ Why this matters: Call by reference is powerful but risky due to side-effects (unexpectedly changing a variable). It should only be used when essential (e.g., to modify the original argument) or for efficiency when passing a large data structure.
Recursive Functions
A recursive function is a function that calls itself. It is useful for problems that can be broken down into smaller, self-similar sub-problems (e.g., calculating power x^n, factorials).
Example (Factorial):
long fact(long n) {
if (n <= 1) // Base case: stop recursion
return 1;
else
return n * fact(n-1); // Recursive call
}
A recursive function must have:
- Base Case: A condition that stops the recursion (e.g.,
n <= 1). - Recursive Step: The function calls itself with a smaller or simpler argument.
π Example (Calculation of fact(3)):
fact(3)β3 * fact(2)fact(2)β2 * fact(1)fact(1)β returns1(base case)- Back-substitution:
fact(2)=2 * 1=2,fact(3)=3 * 2=6
π‘ Why this matters: Recursion can produce elegant code, but it adds memory and stacking overhead (many function calls are placed on the call stack). Iterative solutions are often more efficient. Use recursion when elegance is a priority and resources are not constrained; otherwise, prefer iteration.
β Key Takeaways
- Header files are essential for organizing code. Use
#includeto include a.hfile containing function prototypes and constants defined with#define. - Remember the three scope levels: global (file-wide), function-level (inside
{ }of a function), and block-level (inside nested{ }). A variable is only visible within its declared scope. - Call by value is the safe default: a copy is passed, and the original variable is protected. Call by reference (using
&and*) allows a function to alter the original variable. Use it only when necessary. - Recursive functions call themselves and must have a base case to terminate. They offer elegant code for repetitive patterns but can be less efficient than iterative solutions.
- Minimize the use of global variables. Prefer local variables to promote encapsulation and prevent accidental side-effects.
π§ Quick Revision Questions
- What is the purpose of a header file? Give two examples of what you might put inside it.
- A variable declared inside a
forloop's code block has which scope? Is it visible outside that block? - Explain the difference between call by value and call by reference. Which one protects the original variable from being modified?
- What is the output of a program that uses a global variable
int i = 5;and a functionvoid f() { i = 10; }called frommain()? What is the value ofiinmain()afterf()is called? - Identify the base case in the recursive factorial function
long fact(long n) { if (n <= 1) return 1; else return n * fact(n-1); }. What happens if the base case is missing?
π Lecture 11 β Arrays
π Overview: This lecture introduces the concept of arrays in C programming as a data structure for storing collections of identical data types. It covers array declaration, initialization, manipulation through loops, and practical applications including linear search and copying arrays, which are essential for handling large amounts of related data efficiently.
ποΈ Topics Covered
This lecture begins with an introduction to arrays as a solution for storing multiple values of the same type without declaring individual variables. It covers array declaration syntax, memory layout with contiguous storage, and index-based access starting from zero. The lecture explains multiple array initialization methods, demonstrates sample programs for reading input and calculating sums, discusses array copying techniques, introduces linear search algorithms, shows how to use the rand() function, and emphasizes the const keyword for declaring array sizes.
π Lecture Summary
Introduction
Arrays are introduced as a solution to the problem of storing many variables of the same type. For example, calculating the average age of 100 students would require 100 separate variables without arrays. Arrays provide a data structure where identical data types are stored in contiguous memory locations, making it possible to handle large collections efficiently.
Arrays
In C, every array has a data type, name, and size. The data type can be any valid C data type, and variable naming conventions apply to array names. The size must be a precise number. Arrays occupy memory depending on their size and have a contiguous area of memory. Array elements are accessed using an index (also called subscript), which starts from zero and goes up to one less than the array's size.
Declaration:
data_type array_name [size] ;
For example:
int ages[10];
An array int C[10] of integer type with name 'C' and size ten can contain ten elements. In memory, this array occupies forty bytes (one int = 4 bytes Γ 10). The index of the last element is always size minus one.
π Definition β Array Index: The numeric position used to access individual elements of an array, starting from 0 and ending at size-1.
π Definition β Contiguous Memory: Array elements are stored in consecutive memory locations, meaning element C[1] is located immediately after C[0] in memory.
Memory Image of Array C:
C[0] β value 24
C[1] β value 59
C[2] β value 35
C[3] β ...
...
C[7]
C[8]
C[9]
Index 6 ([6]) means the seventh element, and index 7 means the eighth element. The index of the last element is always one less than the array size.
Usage of Arrays: Arrays can be declared with simple variables in a single line:
int i, age [10];
int height [10], length [10] ;
Individual elements are accessed using the index mechanism, not the whole array at once. age[5] refers to a single element, not the entire array.
Example β Reading ages into an array using a loop:
for (i = 0 ; i < 10 ; i++ )
{
cout << "Please enter the age of the student ";
cin >> age [i];
}
Example β Calculating total of array elements:
int totalAge = 0;
for (i = 0 ; i < 10 ; i++ )
{
totalAge += age [i];
}
The loop index must be an integer, either a literal like 4, 5, or an integer variable like i.
π‘ Why this matters: Arrays allow processing of multiple related values using loops, eliminating the need to write separate code for each individual variable. This becomes crucial when dealing with hundreds or thousands of data items.
Initialization of Arrays
Arrays should always be explicitly initialized rather than relying on default compiler initialization. There are several methods:
Method 1 β Using a loop:
int i, age [10];
for ( i = 0; i < 10 ; i++ )
{
age[i] = 0;
}
Method 2 β At declaration with initialization list:
int age [10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Method 3 β Shortcut with single value:
int age [10] = { 0 };
This initializes all elements to zero.
Method 4 β Without specifying size:
int age [ ] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
The compiler detects the initialization list has ten zeros and creates an array of 10 integers.
π Definition β Initialization List: A comma-separated list of values enclosed in curly braces used to set initial values of array elements at declaration time.
π‘ Why this matters: Loop-based initialization is preferred for large arrays because writing explicit initialization lists becomes impractical for arrays with hundreds or thousands of elements.
Sample Program 1
Problem Statement: Write a program which reads positive integers from the user and stores them in an array. User can enter a maximum of 100 numbers. Stop taking input when user enters -1.
Solution:
An integer array of size 100 is declared. A do-while loop is used because the loop executes at least once. Two termination conditions exist: either 100 numbers entered or user enters -1. The logical AND operator && enforces both conditions must be true for loop continuation.
#include <iostream.h>
main( )
{
int c [ 100 ] ;
int z , i = 0 ;
do
{
cout << "Please enter the number (-1 to end input) " << endl;
cin >> z ;
if ( z != -1 )
{
c[ i ] = z ;
}
i ++ ;
} while ( z != -1 && i < 100 ) ;
cout << " The total number of positive integers entered by user is " << i - 1;
}
The assignment statement c[i] = z is inside the if block to prevent storing -1. The counter i is incremented in each repetition. After loop termination, the actual count of positive integers is i - 1.
Sample Output:
Please enter the number (-1 to end input) 1
2
3
4
5
6
-1
The total number of positive integers entered by user is 6
π Example: When user enters 1, 2, 3, 4, 5, 6, and then -1, the loop terminates. The variable i has been incremented to 7 (one for each input including -1), so the count is 7 - 1 = 6 positive integers.
Copying Arrays
To copy an array, both arrays must be of the same data type and same size. Arrays cannot be assigned directly with a single statement like b = a.
Using element-by-element assignment:
b[0] = a[0] ;
b[1] = a[1] ;
...
b[9] = a[9] ;
Using a loop (preferred method):
for (i = 0; i < 10 ; i ++)
{
b[i] = a[i];
}
π Definition β Array Copy: The process of assigning each element of one array to the corresponding element of another array of the same type and size.
Example β Sum of squares program:
#include <iostream.h>
main()
{
int a[10];
int sumOfSquares = 0 ;
int i =0;
cout << "Please enter the ten numbers one by one " << endl;
for (i = 0 ; i < 10 ; i++ )
{
cin >> a [i];
}
for ( i = 0 ; i < 10 ; i ++ )
{
sumOfSquares = sumOfSquares + a[ i ] * a[ i ] ;
}
cout << "The sum of squares is " << sumOfSquares << endl;
}
Sample Output:
Please enter the ten numbers one by one
1
2
3
4
5
6
7
8
9
10
The sum of squares is 385
π Example: For numbers 1 through 10, the calculation is 1Β² + 2Β² + 3Β² + ... + 10Β² = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100 = 385.
Linear Search
Linear search is a method to find a specific value in an array by comparing each element one by one. A flag variable (typically named found) indicates whether the target was found.
#include <iostream.h>
main()
{
int z, i ;
int a [ 100 ] ;
for ( i =0 ; i < 100 ; i ++ )
{
a [ i ] = i ;
}
cout << " Please enter a positive integer " ;
cin >> z ;
int found = 0 ;
for ( i = 0 ; i < 100 ; i ++ )
{
if ( z == a [ i ] )
{
found = 1 ;
break ;
}
}
if ( found == 1 )
cout << " We found the integer at index " << i ;
else
cout << " The number was not found " ;
}
Sample Output:
Please enter a positive integer 34
We found the integer at index 34
π Definition β Linear Search: A sequential search algorithm that checks each element of an array until the target value is found or all elements have been examined.
Using the rand() function:
The rand() function generates random numbers between 0 and 32767. It requires including <stdlib.h>. The random number can be limited to a range using the modulus operator.
x = rand ( );
Generating a die roll (1 to 6):
1 + rand ( ) % 6;
Guessing game using rand():
#include <iostream.h>
#include <stdlib.h>
main()
{
int z, i ;
int a [ 100 ] ;
for ( i =0 ; i < 100 ; i ++ )
{
a [i] = rand() ;
}
cout << " Please enter a positive integer " ;
cin >> z ;
int found = 0 ;
for ( i = 0 ; i < 100 ; i ++ )
{
if ( z == a [ i ] )
{
found = 1 ;
break ;
}
}
if ( found == 1 )
cout << " We found the integer at position " << i ;
else
cout << " The number was not found " ;
}
Sample Output:
Please enter a positive integer 34
The number was not found
π‘ Why this matters: Linear search is the simplest searching algorithm and works on unsorted data. The maximum number of comparisons equals the array size, making it suitable for small to medium-sized datasets but inefficient for very large arrays.
The Keyword 'const'
The const keyword creates an identifier whose value cannot be changed during program execution. It is used to declare array sizes, making code maintenance easier.
const int arraySize = 100;
Using const in array declaration:
int age [arraySize];
Using const in loop condition:
for ( i = 0; i < arraySize ; i ++)
π Definition β const: A keyword that declares a variable as read-only, preventing its value from being modified after initialization.
π Example: If const int arraySize = 100; is declared, changing only this single line to const int arraySize = 200; automatically updates all array declarations and loop conditions throughout the program.
π‘ Why this matters: Using const for array size is a good programming practice because it centralizes size management. Changing the array size requires modification in only one location, reducing the risk of errors from inconsistent updates across the program.
Tips
- Initialize the array explicitly
- Array index (subscript) starts from 0 and ends one less than the array size
- To copy an array, the size and data type of both arrays should be same
- Array subscript may be an integer or an integer expression
- Assigning another value to a
constis a syntax error
β Key Takeaways
Students must remember that arrays are data structures for storing multiple elements of the same type in contiguous memory, with indices starting at 0 and ending at size-1. Array elements are accessed individually using subscript notation and can be processed using loops. Arrays can be initialized at declaration using initializer lists or through loops at runtime. Copying arrays requires element-by-element assignment since direct assignment is not allowed. Linear search sequentially compares each element until a match is found or all elements are exhausted. The const keyword should be used for array sizes to improve code maintainability and prevent accidental modification, and assigning a new value to a const variable is a syntax error.
π§ Quick Revision Questions
- Why does array indexing in C start from 0 instead of 1, and what is the index of the last element in an array of size
n? - What are the four different methods to initialize an array, and which one is most suitable for large arrays?
- In the sample program that reads numbers until -1, why is the count of positive integers
i - 1instead of justi? - What are the two requirements for copying one array to another, and why can't you use a simple assignment statement like
b = a? - How does the modulus operator
%help in generating random numbers within a specific range, such as simulating a die roll (1-6) or a coin toss (0-1)?
π Lecture 12 β Character Arrays, Array Comparison, Sorting, Searching, Functions and Arrays, Multidimensional Arrays
π Overview: This lecture introduces character arrays for storing strings and explains their special properties, including null termination. It covers essential array operations like comparison, sorting (selection sort), and searching (linear and binary search). The lecture also explains how arrays are passed to functions (by reference), and introduces multidimensional arrays for handling matrices and higher-dimensional data.
ποΈ Topics Covered
Character arrays and their declaration, initialization, and null-terminated storage. Reading and displaying strings using cin and cout with loops. Comparing two arrays element-by-element. Sorting arrays using the selection sort (brute force) method. Searching arrays using linear search and the more efficient binary search algorithm. Passing arrays to functions β call by reference behavior. Multidimensional arrays (2D, 3D) and their population using nested loops.
π Lecture Summary
Character Arrays
Character arrays are used to store strings (sequences of characters). A simple char variable can hold only a single character, so a character array is needed for names or sentences. To declare one: char name[100];. A key property of character arrays is that C/C++ marks the end of a string with a null character (\0), which has an ASCII code of zero. When reading a string with cin >> name;, the computer reads characters until the Enter key is pressed and automatically appends a null character after the last character. Therefore, the array must be at least one element larger than the maximum number of characters intended to be stored.
π Definition β Null Character (\0): A special character with ASCII code 0 that marks the termination point of a string in a character array. The compiler uses it to know where the string ends, preventing the display of garbage data beyond it.
π Formula for Array Size: Array Size = (Number of characters in string) + 1 (for the null terminator).
π Example: To store the string "imran" (5 characters), declare char name[100] = "imran"; or char name[] = "imran"; which automatically allocates 6 elements (5 letters + 1 null). When using a loop to display characters, it must stop at the null character: for(i=0; i<100; i++) { if(name[i]=='\0') break; cout << name[i]; }.
π‘ Why this matters: Without proper null termination, functions that process strings will read past the intended end into garbage memory, causing unpredictable behavior or crashes.
Initialization Of Character Arrays
Character arrays can be initialized in two main ways: either as a list of individual characters enclosed in single quotes and curly braces (char name[100] = {'i','m','r','a','n'};), or more conveniently, as a string literal in double quotes (char name[100] = "imran";). If the array size is omitted in the declaration (e.g., char name[] = "Hello World";), the compiler automatically allocates the exact number of characters needed, plus one for the null character. This is the preferred method for safety and accuracy.
π‘ Why this matters: Omitting the size prevents off-by-one errors. The compiler ensures the array is exactly sized for the string and its null terminator.
Arrays Comparison
Two arrays are considered equal only if they have the same size and every corresponding element matches exactly. This is done element-by-element, often within a loop. A flag variable (e.g., int equals = 0;) tracks the result. Using the not-equal operator (!=) is efficient: if at any position the elements differ, the loop breaks immediately, setting the flag to indicate inequality. If all elements match, the flag is set to indicate equality. This process applies to both integer and character arrays. For character arrays (strings), note that C++ is case-sensitive: 'A' is not equal to 'a'.
π Definition β Flag: A variable (often an integer, 0 or 1) used to signal a condition or status, such as whether two arrays are found to be equal.
π Example: In the provided code, two arrays of 5 integers are compared. The loop for (i = 0; i < 5; i++) checks if (num1[i] != num2[i]). If a mismatch is found at index 2 (e.g., 5 vs 4), it prints "The arrays are not equal", sets equals=0, and breaks. If no mismatches occur, equals is set to 1 and "Both arrays are equal" is printed.
Sorting
The lecture covers a brute-force sorting technique (a form of selection sort) to arrange an array in ascending order. The process finds the smallest element in the entire array and swaps it with the element at the first position. It repeats this process: finding the smallest element in the remaining portion (starting from the second position) and swapping it with the element at the second position, and so on, until the entire array is sorted. Swapping is a critical technique that requires a temporary variable to hold one value during the exchange, preventing data loss.
π Definition β Swapping: The process of exchanging two values using a temporary storage variable. For example, to swap num[0] and num[15]: int x = num[0]; num[0] = num[15]; num[15] = x;.
Searching
Linear search is a simple but potentially slow method: it compares the target value against every element of the array sequentially until found. It is applicable to unsorted arrays but may require as many comparisons as there are elements.
The binary search algorithm is much more efficient but requires the array to be sorted. It uses a "divide and conquer" strategy. The algorithm repeatedly divides the search interval in half. It compares the target value to the middle element. If the target is greater, the search continues only in the right half; if smaller, only in the left half. This halving process continues until the value is found or the interval is empty.
π Definition β Binary Search: An efficient search algorithm that works on sorted arrays by repeatedly dividing the search space in half, significantly reducing the number of comparisons.
π Formula for Maximum Iterations: For an array of N elements, the maximum number of comparisons is logβ(N). For 1000 elements (β 2ΒΉβ°), binary search requires no more than 10 comparisons, compared to up to 1000 for linear search.
Functions And Arrays
C++ uses call by value by default for simple variables: a copy of the variable's value is passed to the function. However, when an array is passed to a function, the default mechanism is call by reference. This is because the name of an array (e.g., name) represents the address (memory location) of its first element. Passing this address gives the function direct access to the original array's memory. Consequently, any modifications a function makes to the array's elements directly affect the original array in the calling program.
π Definition β Call by Reference (Arrays): When an array name is passed to a function, the function receives the memory address of the array's first element, allowing it to modify the original array directly.
π Example: The provided code demonstrates this. The getvalues function receives an array parameter. Within it, the statement num[i] = i; modifies the original array declared in main. When main displays the array after the function call, it shows the values assigned within getvalues (0, 1, 2... 9).
π‘ Why this matters: Passing a single element of an array (e.g., fn(x[3])) uses call by value for that single integer, leaving the original array unchanged. Understanding this distinction is crucial for designing robust functions.
Multidimensional Arrays
Multidimensional arrays extend the concept of arrays to multiple dimensions, like rows and columns. A two-dimensional array is declared as int matrix[2][3]; which defines 2 rows and 3 columns (a 2x3 matrix). Elements are accessed using two indices (row, column), starting from 0. To populate or display a 2D array, nested loops are used: the outer loop iterates over rows, and the inner loop iterates over columns. C++ supports arrays of any number of dimensions (e.g., a 3D array: int num[3][5][7];).
π Definition β Multidimensional Array: An array that uses multiple indices to access its elements. A 2D array is visualized as a table of rows and columns.
π Example: To fill a 2x3 matrix from the user, the code uses:
for (row = 0; row < 2; row++) {
for (col = 0; col < 3; col++) {
cin >> matrix[row][col];
}
}
The inner loop runs 3 times for each single iteration of the outer loop, filling positions [0,0],[0,1],[0,2] first, then [1,0],[1,1],[1,2].
β Key Takeaways
- Character arrays must be null-terminated with
\0, and their declared size should be at least one more than the string's length. - Comparing arrays requires element-by-element comparison. Using the
!=operator allows for an efficient early exit upon mismatch. - Binary search is a powerful, efficient algorithm that works only on sorted arrays, reducing search time from linear (N steps) to logarithmic (log N steps).
- Arrays are passed to functions by reference by default, meaning modifications within the function affect the original array. Single array elements are passed by value.
- Multidimensional arrays (e.g., 2D for matrices) are processed using nested loops, and C++ supports arrays of any dimension.
π§ Quick Revision Questions
- What is the purpose of the null character (
\0) in a character array, and why is it automatically added? - Explain the brute-force sorting method described in the lecture. How does the swapping technique prevent data loss?
- What is the key precondition for using binary search on an array, and why does it make the algorithm significantly faster than linear search for large datasets?
- Why is passing an array to a function considered a call by reference? What is the underlying reason related to the array's name?
- How do you access the element in the second row and third column of a 2D integer array named
matrix? What is its index?
π Lecture 13 β Array Manipulation, Real World Problem and Design Recipe
π Overview: This lecture explores advanced array manipulation techniques, focusing on two-dimensional arrays and matrix operations like flipping and transposing. It then applies the design recipe methodology to solve a real-world tax anomaly problem, demonstrating how to break down complex problems into functional units.
ποΈ Topics Covered
The lecture covers the processing of two-dimensional arrays using nested loops, matrix flipping (reversing row order), matrix transposition with careful handling of triangular swapping, and the application of the design recipe to a real-world problem involving tax brackets and unlucky employees who take home less pay despite higher gross salaries.
π Lecture Summary
Array Manipulation
Two-dimensional arrays store data in rows and columns, similar to mathematical matrices. Identical or similar values are stored in arrays based on context β for example, height and age of individuals cannot be mixed in one array. Processing arrays naturally involves loops, where single-dimensional arrays use one loop and two-dimensional arrays use nested loops.
The lecture demonstrates reading a 3Γ3 matrix using nested loops. The outer loop iterates over rows while the inner loop iterates over columns for each row.
π Definition β Two-dimensional array: A data structure with rows and columns, accessed as arrayName[rowIndex][columnIndex].
π Code structure for inputting a 2D array:
for (row = 0; row < maxRows; row++) {
for (col = 0; col < maxCols; col++) {
cin >> a[row][col];
}
}
π Example: For a 3Γ3 array, the outer loop runs with row=0,1,2. For row=0, the inner loop reads columns 0,1,2. Then row becomes 1, and columns 0,1,2 are read again, continuing until all 9 elements are entered.
Flipping a Matrix (Reversing Row Order)
To display a matrix with rows in reverse order, the lecture shows that we can start the row loop from maxRows - 1 and decrement down to 0. The column loop remains unchanged (starting from 0 to maxCols-1). This avoids creating a new matrix and saves memory.
π Key technique: Loops can start from a higher value and decrement instead of always incrementing from zero.
π Code for displaying flipped matrix:
for (row = maxRows - 1; row >= 0; row--) {
for (col = 0; col < maxCols; col++) {
cout << a[row][col] << '\t';
}
cout << '\n';
}
The '\t' character displays a tab (spaces) on the screen, while '\n' moves the cursor to a new line.
π‘ Why this matters: This approach is memory-efficient because it does not require declaring a separate array to store the flipped version β it simply changes the order of printing.
Transpose of a Square Matrix
Transpose means interchanging rows and columns: element A(i,j) is replaced with A(j,i). For a square matrix (equal number of rows and columns), the diagonal elements remain unchanged because row and column indexes are the same.
π Definition β Transpose: An operation where rows become columns and columns become rows.
π Formula: A(i,j) β A(j,i)
β οΈ Critical issue: When transposing, simple nested loops running through all rows and columns will swap elements twice (once in the upper triangle, once in the lower triangle), leaving the matrix unchanged.
Solution: Process only one triangle (the upper triangle) and swap it with the lower triangle. Start the inner loop from the current row number (col = row) instead of from zero.
π Correct code for transpose using upper triangle:
for (row = 0; row < arraySize; row++) {
for (col = row; col < arraySize; col++) {
temp = a[row][col];
a[row][col] = a[col][row];
a[col][row] = temp;
}
}
π‘ Why this matters: Starting col = row ensures each pair of elements is swapped only once. For row 0, columns 0,1,2 are processed. For row 1, processing starts from column 1 (not column 0), avoiding re-swapping the element already swapped with row 0.
Real World Problem and Design Recipe
The problem involves a company with up to 100 employees where tax brackets create an anomaly: some employees with higher gross salaries take home less pay than those with lower gross salaries due to tax rate jumps.
Tax brackets:
- Rs. 0 β Rs. 5,000: 0% tax
- Rs. 5,001 β Rs. 10,000: 5% tax
- Rs. 10,001 β Rs. 20,000: 10% tax
- Rs. 20,001 and above: 15% tax
π Example: A person earning Rs. 10,000 per month pays 5% tax (Rs. 500), taking home Rs. 9,500. A person earning Rs. 10,001 per month falls into the 10% bracket, paying Rs. 1,000.10 in tax, taking home only Rs. 9,000.90 β which is less than the person earning Rs. 10,000.
Design Recipe Steps:
- Analysis: Precise problem statement β "Given tax brackets and given employees' gross salaries, determine those employees who actually get less take-home salary than others with lower initial income."
- Input determination: Number of employees (up to 100) and their gross salaries.
- Storage design: Use a 2D array
sal[arraySize][2]β column 0 stores gross salary, column 1 stores net salary. Use a 1D arraylucky[arraySize]initialized to 0, where 0 means lucky and 1 means unlucky. - Functional decomposition into four parts:
getInput()β reads gross salariescalcNetSal()β calculates net salaries based on tax bracketsfindUnluckies()β identifies unlucky employeesprintUnluckies()β displays unlucky employee numbers
π Key concept β Array passing to functions: By default, arrays are passed by reference in C++. For 2D arrays, the number of columns must be specified in the function parameter (e.g., double sal[][2]). Variables like numEmps can be passed by value or by reference using &.
π Code structure for main program:
const int arraySize = 100;
double sal[arraySize][2];
int lucky[arraySize] = {0};
int numEmps;
cin >> numEmps;
getInput(sal, numEmps);
calcNetSal(sal, numEmps);
findUnluckies(sal, numEmps, lucky);
printUnluckies(lucky, numEmps);
π‘ Why this matters: The design recipe provides a systematic approach to problem-solving β from analysis through implementation β ensuring all requirements are addressed before coding begins.
β Key Takeaways
The most critical points to remember from this lecture are: two-dimensional arrays require nested loops for processing, with the outer loop controlling rows and the inner loop controlling columns. For matrix flipping, reverse the row loop direction without changing column processing. For matrix transposition, only swap the upper triangle with the lower triangle by starting the inner loop at the current row index to avoid double-swapping. The real-world problem demonstrates the complete design recipe: precise problem statement, input/output analysis, storage planning, functional decomposition, and implementation. Arrays are always passed by reference to functions, but integer variables like employee count must be explicitly passed by reference using & if changes need to persist outside the function.
π§ Quick Revision Questions
- Why must the inner loop start at
col = rowwhen transposing a square matrix, rather thancol = 0? - What is the difference between flipping a matrix and transposing a matrix?
- How does the
markIfUnlucky()function determine whether an employee is unlucky? - Why must the number of columns be specified when passing a 2D array to a function?
- In the real-world problem, what happens if
numEmpsis declared inside thegetInput()function instead of inmain()?