Decision Making, Loops, and Modular Programming Study Notes
The for Loop and Incremental Control
- Loop Utility: The
for loop is particularly useful for counter-controlled loops where the number of iterations is known in advance. - General Format:
for(initialization; test; update)statement; // or block in { }
- Syntactic Constraints: There should be no semicolon after the update expression or after the closing parenthesis of the
for statement header. - Mechanics of Execution:
- Initialization: Perform the initialization expression (executes only once at the start).
- Evaluate Test: Evaluate the test expression.
- If the result is
true, execute the loop statement/block. - If the result is
false, terminate the loop execution.
- Update: Execute the update expression.
- Re-evaluate: Return to Step 2 to test the expression again.
- Example Implementation:
- Code:
for (count = 1; count <= 5; count++) cout << "Hello" << endl; - This loop assigns
1 to count, checks if count≤5, prints "Hello", increments count, and repeats until count exceeds 5.
- Case Study: Program 5-9 (Squares Table):
- Constants:
MIN_NUMBER=1, MAX_NUMBER=10. - Logic:
for (num = MIN_NUMBER; num <= MAX_NUMBER; num++) performs calculations for values 1 through 10. - Output: Displays a table of numbers and their squares (e.g.,
1 squared is 1, 10 squared is 100).
- Loop Modifications:
- Multiple Initializations/Updates: Multiple statements can be included in the initialization or update expressions, separated by commas.
- Example:
for (x=1, y=1; x <= 5; x++, y++)
- Omission of Expressions:
- The initialization expression can be omitted if the variable is already initialized:
for (; num <= 10; num++)
- Inline Variable Declaration: Variables can be declared within the initialization expression:
for (int num = 0; num <= 10; num++). The scope of num is limited strictly to the for loop.
- Pretest Nature: The
for loop evaluates its test expression before each iteration. If the test is initially false, the loop body will never execute. - Example of non-iterating loop:
for (count = 11; count <= 10; count++)
Keeping a Running Total and Loop Selection
- Running Total: The accumulated sum of numbers gathered from each repetition of a loop.
- Accumulator: A variable specifically used to hold the running total.
- Critical Requirement: An accumulator must be initialized to
0 before being used in the loop.
- Logic Flow:
- Set accumulator to
0. - Check if there is a number to read.
- If true, read the number and add it to the accumulator.
- Repeat until no more numbers remain.
- Program 5-12 Example: This program calculates total sales over a specified number of days.
- Variable
total is initialized to 0.0. - A
for loop iterates from 1 to the number of days entered by the user. - Statement:
total += sales; accumulates the values.
- Deciding Which Loop to Use:
- while Loop: A conditional pretest loop. Use for input validation or reading lists terminated by a sentinel value.
- do-while Loop: A conditional posttest loop. Use when the loop must execute at least once, such as when displaying a menu.
- for Loop: A pretest loop with built-in initialization and update steps. Use when the exact number of iterations is known.
Nested Loops and Control Statements
- Nested Loops: A loop that resides inside the body of another loop.
- Operational Hierarchy:
- The inner loop completes all its repetitions for every single repetition of the outer loop.
- Total iterations calculation:
Total Repetitions=Outer Repetitions×Inner Repetitions.
- Program 5-14 (Student Averages):
- Outer loop iterates through the number of students.
- Inner loop iterates through the number of tests for each specific student to accumulate scores.
- Loop Control Statements:
- break: Terminating execution of a loop immediately.
- In nested loops,
break only terminates the loop it is currently in (e.g., breaking an inner loop returns control to the outer loop). - Recommended use: Sparse, as it can complicate debugging.
- continue: Skips the remaining statements in the current iteration and prepares for the next repetition.
- In
while/do-while: Jumps to the test expression. - In
for: Moves to the update expression before re-testing.
Modular Programming and Function Fundamentals
- Modular Programming: The practice of breaking a large program into smaller, manageable functions or modules to improve maintainability and simplify construction.
- Function Definition: A collection of statements designed to perform a specific task.
- Elements of a Function Definition:
- Return Type: The data type of the value the function sends back to the calling part of the program (e.g.,
int, double, void). - Name: The identifier for the function (follows variable naming rules).
- Parameter List: Variables that receive values passed into the function.
- Body: The set of statements within curly braces
{ }.
- Function Header: The line containing the return type, name, and parameter list (e.g.,
int main()). - Function Call: A statement that causes a function to execute. Control moves to the called function and returns to the point of origin after completion.
- void Functions: Functions that do not return a value.
- Example:
void printHeading() { cout << "Monthly Sales\n"; }
Function Prototypes and Sending Data
- Compiler Notification: The compiler must know the function's name, return type, and parameters before it is called.
- Function Prototype (Declaration):
- Format:
void printHeading(); (identical to the header but ends with a semicolon). - Allows function definitions to be placed anywhere in the source file, typically after the
main function.
- Arguments vs. Parameters:
- Argument: The actual value or variable passed to a function during a call (also called 'actual parameter').
- Parameter: The variable in the function header that receives the argument (also called 'formal parameter').
- Passing Multiple Arguments: Arguments must match the function prototype and definition in number, order, and data type compatibility. The first argument initializes the first parameter, and so on.
- Pass by Value:
- When an argument is passed by value, its content is copied into the parameter.
- Changes made to the parameter inside the function do not affect the original argument in the calling function.
Value-Returning Functions and Boolean Logic
- return Statement: Ends function execution. In
void functions, it can be used to exit early. In value-returning functions, it must return a value compatible with the return type. - Value-Returning Mechanism:
- Example:
int sum(int num1, int num2) { return num1 + num2; } - The calling function can assign the returned value to a variable, output it via
cout, or use it in an expression (e.g., total = sum(v1, v2);).
- Returning Boolean Values:
- Functions can test conditions and return
true or false. - Example:
bool isEven(int number) using if (number % 2 == 0) return true; else return false; - Calling context:
if (isEven(val)) cout << "Even";
Variable Scope, Lifetime, and Initialization
- Local Variables: Defined inside a function. They are hidden from other functions and are destroyed when the function terminates.
- Lifetime: The period of time a variable exists in memory. Local variables are created at the start of the function and destroyed at the end.
- Global Variables: Defined outside all functions. Accessible by any function defined after the global variable.
- Warning: Avoid global variables to prevent difficult debugging. Use global constants instead.
- Initialization: Global variables are automatically initialized to
0 (numeric) or NULL (char). Local variables are NOT automatically initialized.
- Static Local Variables:
- Declared using the
static keyword. - Retain their value between function calls.
- Initialization occurs only once, during the first call.
- Default initialization is
0.
Advanced Function Concepts: Default Arguments and Reference Variables
- Default Arguments: Values passed automatically if arguments are missing in the function call.
- They must be constants and are usually specified in the function prototype.
- Example:
void displayStars(int cols = 10, int rows = 1); - Rules: Parameters without default values must come first in the list. If one argument is omitted in a call, all subsequent arguments must also be omitted.
- Reference Variables: Defined with an ampersand (
&).- Allows a function to access and modify the original argument, rather than a copy.
- Provides a way to "return" multiple values by modifying variables in the calling environment.
- Rules: The
& must appear in both the prototype and the header. Arguments for reference parameters must be variables, not constants or expressions.
Function Overloading and Program Termination
- Function Overloading: Creating multiple functions with the same name but different parameter lists (signatures).
- The compiler chooses the correct function based on the arguments provided (e.g.,
square(int) vs. square(double)).
- The exit() Function:
- Terminates the program immediately from any function.
- Requires the
<cstdlib> header. - Common status constants:
EXIT_SUCCESS and EXIT_FAILURE.
- Stubs and Drivers:
- Stub: A dummy function used as a placeholder during testing.
- Driver: A function designed to test another function by calling it with various arguments and verifying the output.