Getting the Computer to Do the Work: Code Blocks
Authors
Section 1: Functions
Whether you’re writing code in a data science notebook or in a text script file, eventually your code will get long enough that it becomes a challenge to keep it understandable and easy to find useful pieces to reuse in other projects.
The most common way of organizing code is to break it into into smaller functions. To make a function, you need to tell the computer:
- The function’s name,
- The inputs (a.k.a “arguments”) that the function needs to do its work, and
- The output (a.k.a. “return value”) that the function will give to whatever code that calls it.
Exercises
int add2(int x, int y) {
int z = x + y;
return z;
}
int result1 = add2(3, 5);Example: Make the sub2() function, which takes two integers and returns another integer. Run the test lines that follow to confirm that the function works (if it says true, it worked!).
int sub2(int x, int y) {
return x - y;
}sub2(5, 3) == 2truesub2(7, 1) == 6trueExercise: Make the div2 function, which takes two double decimal values x and y and returns another double: x / y. Run the test lines that follow to confirm that the function works (if it says true, it worked!).
Solution
double div2(double x, double y) {
return x / y;
}div2(4, 2) == 2truediv2(5, 2) == 2.5truediv2(15, 3) == 5trueIt’s possible for functions to access and modify variables defined outside them, but not inside other functions. Let’s try it out!
Exercise: Define the integer x and give it a value of 0:
Solution
int x = 0;Exercise: Create the function inc(), which takes no inputs and returns no outputs; all it does is increase the x variable by 1 every time it is called. (Note: to say a function has no outputs, put void before its function name).
Solution
void inc() {
x = x + 1;
}Run the code below multiple times. The value of x should change each time it is run:
inc();
x2Section 2: Conditional Blocks-If-Else
If-else blocks allow you to execute different code blocks, depending on some condition. For example, the code below will set the variable j depeding on the value od k. Using a combination of if, else if, and else, you can specify as many conditions as you like. Note that only the first “if” is required.
Exercises
int k = 5;
int j;
if (k > 3) {
j = 1;
} else if (k > 6) {
j = 2;
} else {
j = 3;
}
j1Example: Write a function called isAdult(), that returns true if age is at least 18, else set it to false. Run the test lines that follow to confirm that the function works (if it says true, it worked!).
bool isAdult(int age) {
if (age >= 18) {
return true;
} else {
return false;
}
}isAdult(17) == falsetrueisAdult(18) == truetrueExercise: Write a function void greet(int hour) that prints “Good Morning!” if the hour value is before 12, “Good Afternoon!” if the hour value is between 12 and 18, and “Good Evening!” if the hour value is greater than 18. Then, run the code below to test your function.
HINTS:
voidmeans that the function doesn’t actually return something, it just prints it to the console.printf("")is helpful for printing strings.
Solution
void greet(int hour) {
if (hour > 18) {
printf("Good Evening!");
} else if (hour > 13) {
printf("Good Afternoon!");
} else {
printf("Good Morning!");
}
}greet(19);
greet(15);
greet(5);Good Evening!Good Afternoon!Good Morning!Section 3: While Loops
Computers can also be instructed to repeat running a block of code until some condition is no longer met. One way of doing this is with a while loop, which looks a lot like an if-else block. The example code block below adds 1 to the variable n and prints it while its value is smaller than 1.
Exercises
int n = 0; // initialize a condition variable
while (n < 5){ // the condition that should be met
n = n + 1; // the variable changes as the code runs.
printf("%d\n", n);
}1
2
3
4
5Example: Write the function int runningTotal(int n), adding up all the integers from 1 to n and run the code below to test the function.
int runningTotal(int n) {
int value = 0;
int total = 0;
while (value <= n) {
total = total + value;
value = value + 1;
}
return total;
}runningTotal(5) == 15 // 1+2+3+4+5trueExercise: Write the function int factorial(int n), multipying all the integers from 1 to n. Then, run the code below to test the function.
Solution
int factorial(int n) {
int value = 1;
int total = 1;
while (value <= n) {
total = total * value;
value = value + 1;
}
return total;
}factorial(5) == 120 // = 1*2*3*4*5trueExercis: Write the function int arraySum(int *array, int size), which takes an array of integers and the number of elements in the array and returns the sum of all the elements of the array. Then, run the cell below to test the function.
NOTE: the asterisk * is used to denote a pointer, which we haven’t discussed. The short explanation here is that because C cannot take arrays directly as inputs, we just tell C where the start of the array is, and the extra info of size needs to be given to the function additionally.
Solution
int arraySum(int *array, int size) {
int idx = 0;
int total = 0;
while (idx < size) {
int value = array[idx];
total = total + value;
idx = idx + 1;
}
return total;
}int myArray[3] = {1, 2, 3};
arraySum(myArray, 3) == 6trueSection 4: For Loops
There is a shorter way to write the same kind of loop: a for loop, which contains all three aspects of the condition in the header:
- The statement run before the start of the loop,
- The statement run to check if the loop should continue,
- The statement run at the end of each iteration of the loop.
The example code block below print the variable x for all values from x=0 to x=4.
Exercises
for (int x = 0; x < 5; x = x + 1){
printf("%d\n", x);
}0
1
2
3
4Example: Write the function int runningTotal2(int n), that does the same as int runningTotal(int n) (i.e. adding up all the integers from 1 to n:) but uses a for loop. Then, run the code below to test the function.
int runningTotal2(int n) {
int total = 0;
for (int value = 1; value <= n; value = value + 1) {
total = total + value;
}
return total;
}runningTotal2(6) == 21trueExercise: Write the function int factorial2(int n), that does the same as int factorial(int n) (i.e. multipying all the integers from 1 to n) but uses a for loop. Then, run the code below to test the function.
Solution
int factorial2(int n) {
int total = 1;
for (int value = 1; value <= n; value = value + 1) {
total = total * value;
}
return total;
}factorial2(6) == 720 // 1*2*3*4*5*6trueExercise: Write the function int arraySum2(int *array, int size), which does the same as int arraySum(int *array, int size) (i.e. it takes an array of integers and the number of elements in the array and returns the sum of all the elements of the array) but uses a for loop. Then, run the code below to test the function.
Solution
int arraySum2(int *array, int size) {
int total = 0;
for (int idx = 0; idx < size; idx = idx + 1) {
int value = array[idx];
total = total + value;
}
return total;
}Solution
int myArray2[4] = {1, 2, 3, 4};
arraySum2(myArray2, 4) == 10true