Week 03 Tutorial Sample Answers
Tutorial Overview:
- Part 1: While Loops
- Part 2: 2D While Loops
- Part 3: Scanning in Loops
- Part 4: Structs and Enums
Part 1: While Loops (15 mins)
In the lectures we have seen 3 types of loops: count, sentinel and conditional.
In this activity your tutor will run through the structure of a while loop, hand-execute a loop and then will convert to a flowchart to working C code.
Tutor demo (8 mins)
The structure of a while loop
while (/* some condition is true */) {
// loop body
// execute some code
}
// rest of program
Programming a while loop
Convert the following flowchart to C code and hand execute the program.
counter
an initial value of 0
.
While doing this:
- Ensure you take suggestions on how to write the program from the class.
- Hand execute the code on the whiteboard.
- Emphasise the usefulness of diagramming code and hand executing programs for
solving problems and debugging.
Solution below:
// part1_while_loops.c
//
// Written by Sofia De Bellis (z5418801)
// on February 2024
//
// This program is a simple demonstration of a count loop in c
#include <stdio.h>
int main(void) {
printf("Start of loop!");
int counter = 0;
while (counter < 10) {
printf("%d\n", counter);
counter++;
}
printf("End of loop!");
return 0;
}
Your Turn! (7 mins)
In groups of 3-4 hand execute the following loops writing down what would be output to the terminal:
A
#include <stdio.h>
int main(void) {
int i = 0;
while (i < 32) {
printf("%d\n", i);
i = i + 2;
}
return 0;
}
|
B
#include <stdio.h>
int main(void) {
int i = 5;
while (i >= 0) {
printf("%d\n", i);
i--;
}
return 0;
}
|
C
#include <stdio.h>
int main(void) {
int i = 0;
int keep_going = 1;
while (keep_going == 1) {
if (i > 3) {
keep_going = 0;
}
i++;
}
printf("%d\n", i);
return 0;
}
|
D
#include <stdio.h>
int main(void) {
int i;
while (i > 0) {
printf("%d\n", i);
i--;
}
return 0;
}
|
E
#include <stdio.h>
int main(void) {
int i = 0;
int max = 32;
while (i < max) {
printf("%d\n", i);
max = max + 2;
}
return 0;
}
|
F
#include <stdio.h>
int main(void) {
int i = 0;
int keep_going = 0;
while (keep_going == 1) {
if (i > 3) {
keep_going = 0;
}
i++;
}
printf("%d\n", i);
return 0;
}
|
A
0 2 4 [...] 28 30 |
B
5 4 3 2 1 0 |
C
5 |
D
Error: Accessing Uninitialized Variable |
E
0 0 0 0 [...] |
F
0 |
Part 2: 2D Loops (15 mins)
In this activity your tutor will run through the structure of a 2D while loop, hand-execute a loop and then will convert to a flowchart to working C code.
Tutor demo (8 mins)
The structure of a 2D while loop
Programming a 2D while loop
Convert the following flowchart to C code and hand execute the program.
row
an initial value of 0
and col
and initial value of 0.
While doing this:
- Ensure you take suggestions on how to write the program from the class.
- Hand execute the code on the whiteboard.
- Emphasise the usefulness of diagramming code and hand executing programs for
solving problems and debugging.
Solution below:
// part2_2d_while_loops.c
//
// This program was writtn by Sofia De Bellis (z5418801)
// on Febuarary 2024
//
// This program is a simple deonstration of a 2D while loop
#include <stdio.h>
#define MAX_ROW 5
#define MAX_COL 5
int main(void) {
int row = 0;
int col = 0;
printf("Start of outer loop!\n\n");
while (row < MAX_ROW) {
col = 0;
printf("Start of inner loop!\n");
while (col < MAX_COL) {
printf("%d ", col);
col++;
}
printf("\nEnd of inner loop!\n\n");
row++;
}
printf("End of outer loop!\n");
return 0;
}
Your Turn! (7 mins)
In groups of 3-4 match the following patterns to their code snippets:
A
OXXX XOXX XXOX XXXO |
B
OXOX OXOX OXOX OXOX |
C
OXOO XXXX OXOO OXOO |
D
XXXX XOOX XOOX XXXX |
1
#include <stdio.h>
#define SIZE 4
int main(void) {
int row = 0;
while (row < SIZE) {
int col = 0;
while (col < SIZE) {
if (col != 1 && row != 1) {
printf("O");
} else {
printf("X");
}
col++;
}
row++;
printf("\n");
}
return 0;
}
|
2
#include <stdio.h>
#define SIZE 4
int main(void) {
int row = 0;
while (row < SIZE) {
int col = 0;
while (col < SIZE) {
if (row == col) {
printf("O");
} else {
printf("X");
}
col++;
}
row++;
printf("\n");
}
return 0;
}
|
3
#include <stdio.h>
#define SIZE 4
int main(void) {
int row = 0;
while (row < SIZE) {
printf("X");
int col = 1;
while (col < SIZE - 1) {
if (row == 0 || row == SIZE - 1) {
printf("X");
} else {
printf("O");
}
col++;
}
printf("X");
row++;
printf("\n");
}
return 0;
}
|
4
#include <stdio.h>
#define SIZE 4
int main(void) {
int row = 0;
while (row < SIZE) {
int col = 0;
while (col < SIZE) {
if (col % 2 == 0) {
printf("O");
} else {
printf("X");
}
col++;
}
row++;
printf("\n");
}
return 0;
}
|
Matching activity solutions
A 2 | B 4 |
C 1 | D 3 |
Part 3: Scanning and Loops (15 mins)
In this section, we'll examine several problems that require scanning and loops. We'll then determine what type of loop involving scanning is required and write the loop condition for each program.
A: Enter a series of integers until you reach a negative number. Then, stop and calculate the sum. | B: Enter characters until the user presses 'q'. Then, display the count of characters entered. |
C: Scan for numbers until end of input and display all even numbers entered. | D: Scan for integers keeping a cumulative sum, until the sum of entered integers reaches or exceeds the target sum provided by the user. Print the final sum. |
Explain that scanf returns the number of things successfully scanned in.
Split the class into groups of around 4 students per group.
Ask groups to write to loop condition for each of the problems.
If groups finish early, get them to write c-like pseudocode for one of the programs.
Note, this activity can be done as a tutor demo. If so it is recommended you write any program in combination with program C to completion.
Solutions below:
A:
// A: Enter a series of integers until you reach a negative number. Then, stop and calculate the sum.
// Written by Sofia De Bellis (z5418801)
// on May 2024
#include <stdio.h>
int main(void) {
int num = 0;
int sum = 0;
printf("Please enter a number: ");
scanf("%d", &num);
while (num >= 0) {
sum += num;
printf("Please enter a number: ");
scanf("%d", &num);
}
printf("Sum: %d\n", sum);
return 0;
}
|
B:
// B: Enter characters until the user presses 'q'. Then, display the count of characters entered.
// Written by Sofia De Bellis (z5418801)
// on May 2024
#include <stdio.h>
int main(void) {
int count = 0;
char character = 0;
printf("Please enter a character: ");
scanf("%c", &character);
while (character != 'q') {
count++;
printf("Please enter a character: ");
scanf(" %c", &character);
}
printf("Count: %d\n", count);
return 0;
}
|
C:
// C: Scan for numbers until end of input and display all even numbers entered.
// Written by Sofia De Bellis (z5418801)
// on May 2024
#include <stdio.h>
int main(void) {
int num = 0;
printf("Please enter a number: ");
while (scanf("%d", &num) == 1) {
if (num % 2 == 0) {
printf("%d\n", num);
}
printf("Please enter a number: ");
}
return 0;
}
|
D:
// Scan for integers keeping a cumulative sum, until the sum of entered integers
// reaches or exceeds the target sum provided by the user. Print the final sum.
// Written by Sofia De Bellis (z5418801)
// on May 2024
#include <stdio.h>
int main(void) {
int num = 0;
int sum = 0;
int target = 0;
printf("Please enter a target sum: ");
scanf("%d", &target);
printf("Please enter a number: ");
scanf("%d", &num);
sum += num;
while (sum < target) {
printf("Please enter a number: ");
scanf("%d", &num);
sum += num;
}
printf("Sum: %d\n", sum);
return 0;
}
|
Part 4: Structs and Enums (15 mins)
In this section we will create a program Coffee Shop
which:
- Creates a
struct coffee
that stores the coffee type (an enum), the number of sugars and the size of a coffee - Creates an
enum coffee_type
which defines the different types of drinks that can be ordered. - The program will then take in a coffee order and store it in the struct.
- The program will then determine the price of the coffee based on the users order, outputting the price to the terminal (
stdout
).
The cost of the coffee will be determined by the following rules:
- The base price is always
4.5
. - A
LARGE
coffee incurs an additional charge. - A
LATTE
,CAPPUCCINO
orMATCHA
incurs an additional charge. - Every sugar added incurs an additional charge.
You will be working off of the starter code below:
// coffee_shop.c
//
// Written by YOUR-NAME (zID)
// on TODAYS-DATE
//
// This program is a simple coffee shop used to demonstrate the use of
// structs and enums in C. This program takes user input for a coffee order
// and outputs the cost of the order.
#include <stdio.h>
#define LARGE 'L'
#define REGULAR 'R'
#define ADDED_COST 0.5
#define BASE_COST 4.5
// TODO: Define an enum `coffee_type` that stores the different types of coffees
// the shop sells. These are: LATTEE, CAPPUCCINO, ESPRESSO, AMERICANO & MATCHA.
// TODO: Define a struct `coffee` that stores
// 1. the coffee type (an enum)
// 2. the number of sugars
// 3. the size of a coffee
int main(void) {
// TODO: Initalise a variable for the struct
printf("Enter coffee type (0: LATTE, 1: CAPPUCCINO, 2: ESPRESSO, \
3: AMERICANO, 4: MATCHA): ");
// TODO: take user input
printf("Enter number of sugars: ");
// TODO: take user input
printf("Enter size (L for Large, R for Regular): ");
// TODO: take user input
// TODO: Calculate cost of order
printf("Total cost: %.2lf\n", total_cost);
return 0;
}
- Explain the syntax of defining a
struct
, thatstruct
is short for structure, which is a user-defined data type that allows you to group together variables of different data types under a single name. - Explain the synatx of defining an
enum
, thatenum
is short for enumeration and is a user-defined data typed used to define a set of named constants. - Disucss the key limitation of enums in this program, i.e., let's say I receive this order, how can I remember that 3 is some particular coffee type.
- Talk about how this is a demonstration of using an enum very briefly and that that students will see more of a use for them flater in the course.
Note, you do not need to complete the program and can get part way then display the solution. The important thing to highlight in this activity is how to work with structs and enums not to get a fully working program.
Solution below:
// coffee_shop.c
//
// This program was written by Sofia De Bellis (z5418801)
// on Febuarary 2024
//
// This program is a simple coffee shop used to demonstrate the use of
// structs and enums in C. This program takes user input for a coffee order
// and outputs the cost of the order.
#include <stdio.h>
#define LARGE 'L'
#define REGULAR 'R'
#define ADDED_COST 0.5
#define BASE_COST 4.5
enum coffee_type {
LATTE,
CAPPUCCINO,
ESPRESSO,
AMERICANO,
MATCHA
};
struct coffee {
enum coffee_type type;
double num_sugars;
char size;
};
int main(void) {
struct coffee order;
printf("Enter coffee type (0: LATTE, 1: CAPPUCCINO, 2: ESPRESSO, "
"3: AMERICANO, 4: MATCHA): ");
int type;
scanf("%d", &type);
if (type == 0) {
order.type = LATTE;
} else if (type == 1) {
order.type = CAPPUCCINO;
} else if (type == 2) {
order.type = ESPRESSO;
} else if (type == 3) {
order.type = AMERICANO;
} else {
order.type = MATCHA;
}
printf("Enter number of sugars: ");
scanf("%lf", &order.num_sugars);
printf("Enter size (L for Large, R for Regular): ");
scanf(" %c", &order.size);
double total_cost = BASE_COST;
if (order.size == LARGE) {
total_cost += ADDED_COST;
}
if (order.type == LATTE ||
order.type == CAPPUCCINO||
order.type == MATCHA) {
total_cost += ADDED_COST;
}
total_cost += ADDED_COST * order.num_sugars;
printf("Total cost: %.2lf\n", total_cost);
return 0;
}