C# / CHAPTER 04
Decisions, loops, and methods
BeginnerTurn requirements into conditions and reusable computations.
By the end of this chapter
- Trace exclusive branches
- Write a terminating loop
- Return a computed result
The idea
An if/else chain selects one alternative, while independent if statements can both execute. Put conditions in an order that matches the requirement and test values at the boundaries. Boolean operators && and || short-circuit, so a preliminary validity check can prevent an unsafe operation on the right. A method should describe its inputs and the result it returns rather than rely on hidden global state.
A loop maintains a result while making progress through input. For an array, its Length property gives the number of elements, and the last valid index is one less. A foreach loop is convenient when only values matter. Keep printing outside a calculation method when callers need to reuse the returned value in other computations.
using System;
static int PositiveTotal(int[] values) {
int total = 0;
foreach (int value in values)
if (value > 0) total += value;
return total;
}
Console.WriteLine(PositiveTotal(new[] {3, -2, 5, 0}));8
The method adds three and five, ignoring zero and the negative value. Returning the total lets the caller decide how to display it.
Try it yourself
Return the number of values at or above a threshold without printing inside the method.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING