Lecture 5 - Flow Control and Modularization
Overview
- Flow control helps a program decide which steps to take next instead of always executing sequentially.
- Sometimes a sequential program isn’t sufficient to solve a problem; you need to branch or repeat.
- Quadratic equation example (context for flow/light discussion):
- If A = 0, it is not a quadratic equation.
- For a quadratic equation with discriminant D:
- If the discriminant is 0, there is one real root.
- If the discriminant is negative, there are no real roots (the roots are complex).
- General quadratic form: ax2+bx+c=0 with discriminant D=b2−4ac. If a<br/>=0, the equation is quadratic and roots depend on D as above.
- These examples illustrate how conditionals and looping structures allow us to handle different outcomes and edge cases in solutions.
Conditional Statements
- Purpose: decision making; actions depend on a condition being true or false.
- Syntax concept in C:
- If statement:
- if (condition) {
// block of code
} - The block executes only when the condition is true.
- Conditions are represented by relational and logical expressions (e.g., ==, !=,
- Practical example described: write a program that decides which of two numbers is largest and prints a message when X > Y.
- DIY Step 1: A simple solution is available for download on Canvas named as L6_example1.c.
- DIY Step 2: If you need to handle the case where the condition is NOT true, you use an if … else structure:
- if (condition) {
// true block
} else {
// false block
} - The complete code for this approach is available as L6_example2.c on Canvas.
- DIY Step 3: For multiple branching, you can use an else if chain:
- if (condition) {
// first block
} else if (condition) {
// second block
} else {
// all previous false
} - The complete code for this approach is L6_example3.c on Canvas.
- Summary: use if when a single condition decides, use else for the opposite case, and use else if for multiple mutually exclusive conditions.
Switch Case
- Switch-case evaluates one expression and selects a matching case value; if none match, default executes (default is optional).
- Structure:
- switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
- Key points:
- break ends the switch block for a given case.
- default executes when none of the cases match.
- Example note: An example code file is available on Canvas named L6_example4.c.
- Real-world use: mapping numeric course numbers to course names or instructor information, with a fallback when there is no match.
Loops
- Purpose: repeat a block of code based on a condition.
- Types:
- For loop: runs a determined number of times.
- While loop: runs an undetermined number of times (until condition becomes false).
- Do-while loop: like a while loop but guaranteed to execute at least once because the condition is checked after the block.
- The general loop structures in C:
- For loop: for (initialization; condition; increment) {
// code block
} - While loop: while (condition) {
// code block
} - Do-while loop: do {
// code block
} while (condition);
- Classic algorithm example used in class: obtain four integer numbers and print whether each is even or odd.
- Read a number.
- Test if the number is even or odd.
- Print a message like "Number XXX is even!" or "Number XXX is odd!".
- Repeat for the next number.
- Stop after the 4th iteration (for a fixed count).
- These steps illustrate loop control for a fixed iteration count (a for loop) or a loop that continues until a condition is met (while/do-while).
- Common demonstrated loop skeletons (conceptual):
- Initialization happens before the first check in a for loop.
- The condition is checked before each iteration.
- The increment/decrement happens at the end of each iteration.
- The loop body executes only when the condition is true.
For Loops (Detailed)
- Anatomy:
- for (initialize; condition; (de|in)crement) {
// code block to be executed
}
- Component explanations:
- Initialize: runs once, before the loop starts.
- Condition: logical expression that must be true for the block to execute.
- Increment/Decrement: updates the control variable toward meeting the condition after each iteration.
- The loop may terminate when the condition becomes false.
- Practical takeaways:
- Use for loops when the number of iterations is known ahead of time or can be expressed with a control variable.
While Loops (Detailed)
- Structure:
- while (condition) {
// block of code
}
- Semantics: checks condition before each iteration; if false on first check, the block may not execute at all.
- Examples typically show evaluating a condition such as whether a user has provided acceptable input or whether a counter has reached a limit.
Do-While Loops (Detailed)
- Structure:
- do {
// block of code
} while (condition);
- Semantics:
- The block runs at least once regardless of the condition, because the condition is evaluated after the block executes.
- Common use: cases where an operation must happen at least once (e.g., prompting for input at least once before checking a termination condition).
Flow Control: Exit and Jump Statements
- We must define conditions that exit loops; commonly used mechanisms include:
- Break: exits the innermost loop immediately.
- Continue: skips the remainder of the current iteration and proceeds with the next iteration.
- Both have associated syntax inside loops, e.g.,
- if(condition)break; inside a loop to terminate early.
- if(condition)continue; to skip to the next iteration.
- In this course, there is a policy note:
- Do not use break and continue statements in your loops for the Flow Control topics covered.
- Do not use while(true) { … } as a technique to avoid writing a proper condition.
- Rationale:
- Encourages writing clearer, well-structured loop exit conditions rather than using control flow jumps.
- Helps practice designing correct termination criteria and avoiding infinite loops.
- Discussion prompt: debates exist on whether break/continue are bad practice; in this course you’ll be encouraged to craft explicit conditions instead of relying on these jumps.
Do Now and Practice Activities
- Flow Control Worksheet: pair up with a partner (max 3 participants).
- Q2.7 Flow Control Quiz: individual activity.
- Practical goal: reinforce the use of conditionals and loops, and become comfortable with reading and writing small control-flow programs.
Practical Notes and Tips
- When solving problems:
- Start by identifying the decision points (what must be true for a given branch to execute).
- Decide between if/else and switch based on the number of discrete cases and readability.
- For repeating tasks, assess whether a for, while, or do-while loop best fits the iteration count and condition semantics.
- References to downloadable example files (for self-study):
- L6_example1.c (simple largest-number program)
- L6_example2.c (if-else structure)
- L6_example3.c (else-if chain)
- L6_example4.c (switch-case example for Ana’s courses)
- Formula recap: Quadratic discriminant and roots as a contextual example of how conditions affect problem-solving pathways:
- Quadratic equation: ax2+bx+c=0,extwitha<br/>=0
- Discriminant: D=b2−4ac
- Real roots: if D
vert > 0, two real roots; if D=0, one real root; if D < 0, complex roots. - If a=0, the equation is not quadratic (reduces to linear or degenerate).
- Ethical/practical implication: writing clear and maintainable control flow improves collaboration and reduces debugging time, which is a practical consideration when designing algorithms and software.
Quick Reference: Key Syntax Snippets
- If statement:
- if (condition) {
// code when condition true
}
- If-else:
- if (condition) {
// true branch
} else {
// false branch
}
- Else-if ladder:
- if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// else block
}
- Switch-case:
- switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
- For loop:
- for (initialize; condition; increment) {
// code
}
- While loop:
- while (condition) {
// code
}
- Do-while loop:
- do {
// code
} while (condition);