Programming Fundamentals
Information
- This page contains additional revision exercises for week 04.
- These exercises are not compulsory, nor do they provide any marks in the course.
- You cannot submit any of these exercises, however autotests may be available for some them (Command included at bottom of each exercise if applicable).
Exercise — individual:
Printing and scanning (Revision Session Exercise)
You will complete the below program with the tutor.
Starter Code:
// This program scans in a character (either 'p' or 'o') indicating whether
// to calculate the serving size per person or the total amount of food
// required. It also scans in the number of people present.
//
// Depending on the selected calculation, the program prompts for additional
// information, performs the calculation, and prints the result.
#include <stdio.h>
// When naming #defines, use SHOUTING_SNAKE_CASE
// (i.e all capital letters separated by underlines)
#define OVERALL_SERVING 'o'
#define PER_PERSON 'p'
int main(void) {
// Declare the variables
// Prompt the user and scan in input to initalise the variables
printf("Would you like to calculate servings per person or calculate overall food from servings given (p/o)?");
printf("How many people are present?");
// Check the conditions on these print statements
printf("How big is the serving per person? ");
printf("How much food do you have to split? ");
// Muliply or divide based off the entered character
// Print the answer
return 0;
}
Exercise — individual:
Moving Into Doubles (Revision Session Exercise)
Using the answer you wrote for the program above edit the numbers scanned in to be doubles. Also extend the program to accept children present as a separate variable who will only need a half serving.
Exercise — individual:
Getting Lost with If Statements (Revision Session Exercise)
The if statements in the starter code below are in the wrong order. The program is intended to print out the largest number that the scanned integer is divisible by from 1-5. Work through the code and reorder the if statements into the correct configuration.
Starter Code:
// This program should scan in a number and then print out the largest number
// between 1 and 5 (inclusive) that this number is divisible by.
#include <stdio.h>
int main(void) {
int number;
printf("Scan in a number: ");
scanf("%d", &number);
if (number % 2 == 0){
printf("The largest number between 1-5 that %d is divisible by is 2\n", number);
} else if (number % 1 == 0) {
printf("The largest number between 1-5 that %d is divisible by is 1\n", number);
} else if (number % 3 == 0) {
printf("The largest number between 1-5 that %d is divisible by is 3\n", number);
} else if (number % 4 == 0) {
printf("The largest number between 1-5 that %d is divisible by is 4\n", number);
} else {
printf("The largest number between 1-5 that %d is divisible by is 5\n", number);
}
return 0;
}
Exercise — individual:
Arithmetic, Logic and Comparative Operators (Revision Session Exercise)
The programs below are missing their operators. Discuss what operators should fill each _?_ gap according to the description at the top of each program, and describe what each operator does.
Program 1
// This program should scan in a number from the user, check if the number is
// divisible by 3 and if so add 10 to the number otherwise, leave the number as
// is. The resulting number should then be printed.
//
// The required operators to make this program run are missing. Replace the
// question marks (_?_) with the necessary logic, comparison or arithmetic
// operators to complete the program.
#include <stdio.h>
int main(void) {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num _?_ 3 _?_ 0) {
num = num _?_ 10;
}
printf("The resuting number is %d.", num);
return 0;
}
Program 2
// This program should scan in the age of a student and their marks.
// If they have a grade over 85 and they are 11 or 12 years old,
// they should be accepted into the science program.
//
// The required operators to make this program run are missing. Replace the
// question marks (_?_) with the necessary logic, comparison or arithmetic
// operators to complete the program.
#include <stdio.h>
#define MIN_MARK 85
#define AGE_ELEVEN 11
#define AGE_TWELVE 12
int main(void) {
int age;
int grade;
printf("What is your age? ");
scanf("%d", &age);
printf("What is your overall score in school? ");
scanf("%d", &grade);
if ((age _?_ AGE_ELEVEN _?_ age _?_ AGE_TWELVE) _?_ (grade _?_ MIN_MARK)) {
printf("Congratulations, you meet the requirements for the science program!\n");
} else {
printf("I am afraid that you do not meet the requirements this year.\n");
}
return 0;
}
Program 3
// This program scans in the amount of sleep a student gets and prints the
// corresponding message based on that amount.
//
// The required operators to make this program run are missing. Replace the
// question marks (_?_) with the necessary logic, comparison or arithmetic
// operators to complete the program.
#include <stdio.h>
#define FULL_SLEEP 10
#define RECOMMENDED_SLEEP 8
#define LITTLE_SLEEP 6
#define TOO_LITTLE_SLEEP 4
int main(void) {
int sleep_hours;
printf("Enter how many hours you slept last night: ");
scanf("%d", &sleep_hours);
if (sleep_hours _?_ FULL_SLEEP) {
printf("Wow, you must feel rested!\n");
} else if (sleep_hours _?_ RECOMMENDED_SLEEP) {
printf("Good job - You got above the recommended hours of sleep!\n");
} else if (sleep_hours _?_ LITTLE_SLEEP){
printf("Maybe try to sleep more tomorrow.\n");
} else if (sleep_hours _?_ TOO_LITTLE_SLEEP) {
printf("You might need a coffee.\n");
} else {
printf("How are you standing?\n");
}
return 0;
}
Exercise — individual:
While Loops and 2D While Loops (Revision Session Exercise)
Step through each of the following programs to explore how variables change as each instruction is executed.
While counter
#include <stdio.h>
#define MAX 10
int main(void) {
int i = 0;
while (i < MAX) {
printf("%d\n", i);
i++;
}
return 0;
}
For counter
#include <stdio.h>
#define MAX 10
int main(void) {
for (int i = 0; i < MAX; i++) {
printf("%d\n", i);
}
return 0;
}
Sentinel loop
#include <stdio.h>
#define GOAL 10
int main(void) {
int input = 0;
printf("Enter a number: ", input);
scanf("%d", &input);
while (input != GOAL) {
printf("Enter a number: ", input);
scanf("%d", &input);
}
return 0;
}
Conditional loop
#include <stdio.h>
#define GOAL 10
int main(void) {
int input = 0;
printf("Enter a number: ", input);
scanf("%d", &input);
while ((input != GOAL) && (input % 2 != 0)) {
printf("Enter a number: ", input);
scanf("%d", &input);
}
return 0;
}
2D for loop
#include <stdio.h>
#define MAX 10
int main(void) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
printf("o");
}
printf("\n");
}
return 0;
}
2D while loop
#include <stdio.h>
#define MAX 10
int main(void) {
int i = 0;
while (i < MAX) {
int j = 0;
while (j < MAX ) {
printf("o");
j++;
}
printf("\n");
i++;
}
return 0;
}
2D loop with conditionals
#include <stdio.h>
#define MAX 10
int main(void) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
if ((i + j) % 2 == 0) {
printf("o");
} else {
printf("-");
}
}
printf("\n");
}
return 0;
}
Exercise — individual:
Structs and Enums — HVAC
Copy the starter code below and complete the program hvac.c which models an air conditioning and heating system. The system should enter a given state depending on the degree difference between the set temperature and the current temperature.
The enum state entered is defined by the following:
SUPER_HEAT: When the current temperatue is 5 or more degrees colder than the set temperature.SUPER_COOL: When the current temperatue is 5 or more degrees hotter than the set temperature.HEATING: When the current temperatue is less than 5 degrees colder than the set temperature.COOLING: When the current temperatue is less than 5 degrees hotter than the set temperature.OFF: When the current temperature matches the set temperature.
Starter Code:
// This program should scan in the set temperature for the air conditioning
// system and store it in the corresponding struct field. It should then
// determine the state of the system depending on the degree difference
// between the set temperature and the current temperature.
#include <stdio.h>
#define ACTUAL_TEMP 30
enum state {
COOLING,
HEATING,
OFF,
SUPER_COOL,
SUPER_HEAT
};
struct system {
enum state state;
int set_temp;
int actual_temp;
};
int main(void) {
// Declare the struct
// Prompt user for the set temperature
// Determine and set the system state
// Print the details of the HVAC system
return 0;
}
Exercise — individual:
2D Loop Pyramid
Write a program half_pyramid.c that prints the following half pyramid which has
a height of 10 rows.
dcc half_pyramid.c -o half_pyramid ./half_pyramid * ** *** **** ***** ****** ******* ******** ********* **********
Exercise — individual:
Output Questions
For each program below, look at the code and determine what output will be printed to the terminal. If you are struggling, try stepping through each program line by line.
Question 1
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main(void) {
int walking = TRUE;
int dogs_seen = 0;
while (walking == TRUE) {
while (dogs_seen < 10) {
dogs_seen = dogs_seen + 1;
}
walking = FALSE;
}
printf("%d\n", dogs_seen);
return 0;
}
Question 2
#include <stdio.h>
int main(void) {
int i = 0;
int j = 1;
while (i < 10 && j % 2 == 0) {
j = 0;
while(j < 10) {
printf("(%d, %d)", i, j);
j++;
}
printf("\n");
i++;
}
printf("i = %d, j = %d\n", i, j);
return 0;
}
Question 3
#include <stdio.h>
struct vector{
int x;
int y;
int z;
};
int main(void) {
struct vector vector;
vector.x = 0;
vector.y = 0;
vector.z = 0;
while(vector.x < 10) {
while(vector.y < 10) {
while(vector.z < 10) {
vector.z = vector.z - 1;
}
vector.y = vector.y + 1;
}
vector.x = vector.x + 1;
}
printf("Vector is:\n");
printf("x = %d", vector.x);
printf("y = %d", vector.y);
printf("z = %d", vector.z);
return 0;
}
Exercise — individual:
Baking Ratios (Revision Session Exercise)
Download baking_ratios.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity baking_ratios
Write a program called baking_ratios.c that scans in a number (in grams) from
the user representing the final weight of the cooking batter. Calculate the weight
of each ingredient needed to make that batter using the provided constant ratios.
The resulting weight should then be printed to two decimal places.
Examples
dcc baking_ratios.c -o baking_ratios ./baking_ratios Please enter the final batter weight in grams: 50 The flour weight needed is: 4.00 The sugar weight needed is: 17.50 The egg weight needed is: 10.00 The chocolate weight needed is: 6.00 The butter weight needed is: 12.50 ./baking_ratios Please enter the final batter weight in grams: 1 The flour weight needed is: 0.08 The sugar weight needed is: 0.35 The egg weight needed is: 0.2 The chocolate weight needed is: 0.12 The butter weight needed is: 0.25
Assumptions/Restrictions/Clarifications
- You can assume negative numbers are not entered.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest baking_ratios
Exercise — individual:
Carnival (Revision Session Exercise)
Download carnival.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity carnival
This program includes a provided struct, which can be used to store the carnival
booth's information. The definition of struct carnival can be seen below.
struct carnival {
double ticket_price;
char snack_offered;
int booth_number;
};
Complete the program carnival.c by scanning in the booth snack offered and
storing this in the struct along with the remaining booth information which has
been provided as constants. The booth information should then be printed out to
the terminal.
Examples
dcc carnival.c -o carnival ./carnival Booth snack offered (p = popcorn, c = chips, h = hotdogs): h Carnival booth Details: Ticket price is 5.000 Booth number is 124 Carnival booth snack offered is: HOTDOGS ./carnival Booth snack offered (p = popcorn, c = chips, h = hotdogs): p Carnival booth Details: Ticket price is 5.000 Booth number is 124 Carnival booth snack offered is: POPCORN
Assumptions/Restrictions/Clarifications
- You may assume that the user will only ever enter
p,corhas input for the booth snack.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest carnival
Exercise — individual:
Number Challenge (Revision Session Exercise)
Download number_challenge.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity number_challenge
Write a program called number_challenge.c, which scans in a number and determines if that number satisfies the number challenge. For a number to satisfy the challenge, it has to be divisible by 3 but not by 300.
The program should continually prompt the user until Ctrl+D is pressed.
Examples
dcc number_challenge.c -o number_challenge ./number_challenge Welcome to the Number Challenge. What number do you want to check? 300 The number does not work What number do you want to check? 4 The number does not work What number do you want to check? 3 That number works! What number do you want to check? ./number_challenge What number do you want to check?
Assumptions/Restrictions/Clarifications
- No error checking is required.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest number_challenge
Exercise — individual:
Upside Down Pyramid
Write a program called upside_down_pyramid.c which prints an upside down left pyramid with a height of 10 rows strictly using for loops.
Examples
dcc upside_down_pyramid.c -o upside_down_pyramid ./upside_down_pyramid xxxxxxxxxx xxxxxxxxx xxxxxxxx xxxxxxx xxxxxx xxxxx xxxx xxx xx x
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest upside_down_pyramid
Exercise — individual:
Upside Down Pyramid Two
Write a program called upside_down_pyramid_two.c which prints an upside down left pyramid with a height of 10 rows strictly using while loops.
Examples
dcc upside_down_pyramid_two.c -o upside_down_pyramid_two ./upside_down_pyramid_two xxxxxxxxxx xxxxxxxxx xxxxxxxx xxxxxxx xxxxxx xxxxx xxxx xxx xx x
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest upside_down_pyramid_two
Exercise — individual:
Solar Car Debug
Download solar_car.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity solar_car
The following program solar_car.c should scan in information about a solar car
including it's mode, speed and the distances between chargers that it has travelled
and print out the solar car's information to the terminal.
However, this program has many bugs, look through the program and try fix them so that the program works as expected!
Examples
dcc solar_car.c -o solar_car ./solar_car What mode is the car in (DRIVE = 0, SOLAR = 1, OFF = 2, MAINTENANCE_MODE = 3, CRUISE_MODE = 4)? 3 What speed is the car going? 2 No no silly, the speed is 0 Please enter the 5 distances between the chargers that the car has traveled? 1 2 3 4 5 Solar Car Information: Speed: 0.00 Distance travelled: 15 State: OFF
Assumptions/Restrictions/Clarifications
- No error checking required.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest solar_car
Exercise
(●●◌)
:
Counting Chickens
You family recently purchased a number of chickens and you are struggling to keep up with the amount of eggs being laid. Write a program called counting_chickens.c that scans in the amount of eggs laid on each day of the week, then outputs the amount of cooked and baked goods that can be made that week. Ensure the program keeps checking if the user would like to count a week until 'n' is pressed. The cooked and baked goods egg requirements are below:
- Quiche uses 6 eggs
- Pie uses 3 eggs
- Cupcakes use 2 eggs
- Omelette uses one egg
Items that use more eggs are prioritised.
Examples
dcc counting_chickens.c -o counting_chickens ./counting_chickens Did the chicken lay this week (y/n)? y Amount of eggs laid each day: 1 2 3 6 8 2 5 This Week's Baking: Quiches: 4 Pies: 1 Cupcakes: 0 Omelettes: 0 End of the week Did the chicken lay this week (y/n)? n
Assumptions/Restrictions/Clarifications
- You may assume that only integers will be entered.
- No error checking is required.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest counting_chickens
Exercise
(●●◌)
:
Problems with the weather
It is difficult to figure out what to wear depending on the weather sometimes, write a program named weather_problems.c to help make this decision easier.
The program should prompt the user and then scan in the answers to the following questions:
What is the temperature?Is it rainy or sunny (r/s)?Is it windy (y/n)?
Depending on the answers the following outputs will occur:
- Hot + Sunny + Not Windy : Wear shorts and a t-shirt
- Hot + Sunny + Windy: Wear a light jacket
- Hot + Rainy + Windy: Wear a light raincoat
- Hot + Rainy + Not Windy: Bring an umbrella
- Cold + Sunny + Not Windy: Wear jeans and a warm jacket
- Cold + Sunny + Windy: Wear a heavy coat and a scarf
- Cold + Rainy + Windy: Wear a heavy raincoat
- Cold + Rainy + Not Windy: Bring an umbrella and jacket
Examples
dcc weather_problems.c -o weather_problems ./weather_problems What is the temperature? 22 Is it rainy or sunny (r/s)? s Is it windy (y/n)? n Wear shorts and a t-shirt.
Assumptions/Restrictions/Clarifications
- No error checking is required.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest weather_problems