C / CHAPTER 02
Functions and bounded loops
BeginnerDecompose a calculation and prove that a loop visits the intended inputs.
By the end of this chapter
- Declare a function contract
- Trace a loop boundary
- Keep accumulation within its stated range
The idea
Enter with initialized variables and arithmetic. A function receives arguments through parameters and returns a result with return. Parameters passed by value are separate objects: changing an integer parameter does not change the caller’s integer. Give each function a narrow job, and state which inputs it accepts. The example below assumes a small nonnegative limit so every accumulated value fits in int.
A for loop combines initialization, a continuation test, and an update. The test is checked before each iteration, so a false first test produces no iterations. Trace a short table containing the loop counter and accumulator rather than trying to infer the final number from punctuation. For larger or untrusted inputs, revisit overflow and termination instead of assuming that a loop which works on three values is safe for every integer.
#include <stdio.h>
int sumThrough(int limit){int total=0; for(int i=1;i<=limit;i++) total+=i; return total;}
int main(void){printf("%d\n",sumThrough(4));}10
The counter takes 1, 2, 3, and 4. The initial zero also makes a limit of zero return zero without entering the loop.
Try it yourself
Write a function that counts multiples of three from 1 through a small nonnegative limit.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING