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;
}
Sample solution for printing_and_scanning.c
// This program was written by Sophie Moeskops 6/6/26
// 
// 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) {

	int people;
	char calculate;
	int serving_size;
    int answer = 0;

    printf("Would you like to calculate servings per person or calculate overall food from servings given (p/o)? ");
    scanf(" %c", &calculate);
    printf("How many people are present? ");
    scanf("%d", &people);

    if (calculate == PER_PERSON) {
        printf("How much food do you have to split? ");
        scanf("%d", &serving_size);
    } else if (calculate == OVERALL_SERVING) {
        printf("How big is the serving per person? ");
        scanf("%d", &serving_size);     
    }

	if (calculate == OVERALL_SERVING) {
		answer = serving_size * people;
        printf("The amount of food needed is %d\n", answer);
	} else {
		answer = serving_size / people;
        printf("The serving per person is %d\n", 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.

Sample solution for moving_into_doubles.c
// This program was written by Sophie Moeskops 6/6/26
// This program will scan in a character (o/p) and will scan in a number (integer)
// and will print the int multiplied or divided by the last scanned in integer.

#include <stdio.h>

//When naming #defines use all capital letters
#define OVERALL_SERVING 'o'
#define PER_PERSON 'p'

int main(void) {

	int people;
	char calculate;
	double serving_size;
    double answer = 0;
    int children;

    printf("Would you like to calculate servings per person or calculate overall food from servings given (p/o)? ");
    scanf(" %c", &calculate);
    printf("How many people are present? ");
    scanf("%d", &people);
    printf("How many children are present? ");
    scanf("%d", &children);
    
    if (calculate == PER_PERSON) {
        printf("How much food do you have to split? ");
        scanf("%lf", &serving_size);
    } else if (calculate == OVERALL_SERVING) {
        printf("How big is the serving per person? ");
        scanf("%lf", &serving_size);     
    }

	if (calculate == OVERALL_SERVING) {
		answer = serving_size * people + 0.5 * serving_size * children;
        printf("The amount of food needed is %.2lf\n", answer);
	} else {
		answer = serving_size / (people + (children * 0.5));
        printf("The serving per person is %.2lf\n", answer);
	}
    return 0;
}

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;
}

Sample solution for getting_lost_with_if_statements.c
// 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 % 5 == 0){
        printf("The largest number between 1-5 that %d is divisible by is 5\n", number);
    } else if (number % 4 == 0) {
        printf("The largest number between 1-5 that %d is divisible by is 4\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 % 2 == 0) {
        printf("The largest number between 1-5 that %d is divisible by is 2\n", number);
    } else {
        printf("The largest number between 1-5 that %d is divisible by is 1\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;
}

Sample solution for hvac.c
// 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
#define SUPER_THRESHOLD 5

enum state {
    COOLING,
    HEATING,
    OFF,
    SUPER_COOL,
    SUPER_HEAT
};

struct system {
	enum state state;
	int set_temp;
	int actual_temp;
};

int main(void) {
	struct system system;
	
	printf("What temp do you want to set the room to? ");
	scanf("%d", &system.set_temp);
	system.actual_temp = ACTUAL_TEMP;
	
	if (system.actual_temp - system.set_temp >= SUPER_THRESHOLD) {
		system.state = SUPER_COOL;
	} else if (system.set_temp - system.actual_temp >= SUPER_THRESHOLD) {
		system.state = SUPER_HEAT;
	} else if (system.actual_temp > system.set_temp){
		system.state = COOLING;
	} else if (system.actual_temp < system.set_temp) {
		system.state = HEATING;
	} else {
		system.state = OFF;
	}
	
	printf("State of system:\n");
	printf("Outside temp: %d\n", system.actual_temp);
	printf("Set temp: %d\n", system.set_temp);
	printf("System state: ");
	
	if (system.state == SUPER_COOL) {
		printf("SUPER_COOL\n");
	} else if (system.state == SUPER_HEAT) {
		printf("SUPER_HEAT\n");
	} else if (system.state == COOLING){
		printf("COOLING\n");
	} else if (system.state == HEATING) {
		printf("HEATING\n");
	} else {
		printf("OFF\n");
	}
	
	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
*
**
***
****
*****
******
*******
********
*********
**********

Sample solution for half_pyramid.c
// This program will print out a half pyramid with a height of 10 rows.

#include <stdio.h>

#define MAX 10

int main(void) {
    
	for(int i = 0; i < MAX; i++) {
        for(int j = 0; j <= i; j++) {
            printf("*");
        }
        printf("\n");
    }

	return 0;
}

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
Sample solution for baking_ratios.c
// Baking Ratios
// baking_ratios.c
//
// This program was written by Sophie Moeskops (5587745)
// on 20/6/26
//
// This program will scan in a double representing the final weight of a cooking
// batter in grams. Using the provided ratios, the program should calculate the
// required weight of each ingredient to make up the given batter amount and
// print it to the terminal to two decimal places.

#include <stdio.h>

#define FLOUR_RATIO 0.08
#define SUGAR_RATIO 0.35
#define EGG_RATIO 0.2
#define CHOCOLATE_RATIO 0.12
#define BUTTER_RATIO 0.25

int main(void) {

	// Declare the double to hold the weight in grams
	double total_weight;

	// Print user prompt
	printf("Please enter the final batter weight in grams: ");

	// Scan in the weight from the terminal
	scanf("%lf", &total_weight);

	// Calculate the ingredient weights using the provided ratios and print these values
	printf("The flour weight needed is: %.2lf\n", total_weight * FLOUR_RATIO);
	printf("The sugar weight needed is: %.2lf\n", total_weight * SUGAR_RATIO);
	printf("The egg weight needed is: %.2lf\n", total_weight * EGG_RATIO);
	printf("The chocolate weight needed is: %.2lf\n", total_weight * CHOCOLATE_RATIO);
	printf("The butter weight needed is: %.2lf\n", total_weight * BUTTER_RATIO);

	return 0;
}

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, c or h as 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
Sample solution for carnival.c
// Carnival
// carnival.c
//
// This program was written by Sophie Moeskops (5587745)
// on 21/6/26
//
// This program should create a carnival struct containing the booth
// information. The snack offered should be scanned in by the user, while the
// remaining information is provided as constants and all booth information
// should then be printed.

#include <stdio.h>

#define TICKET_PRICE 5.00
#define BOOTH_NUMBER 124

struct carnival {
	double ticket_price;
	char snack_offered;
	int booth_number;
};

int main(void) {
    //declare a variable of type struct carnival
    struct carnival carnival;

    //assign the ticket price and booth number
    carnival.ticket_price = TICKET_PRICE;
    carnival.booth_number = BOOTH_NUMBER;

    //scan in snack offered (p for popcorn, c for chips and h for hotdogs
    printf("Booth snack offered (p = popcorn, c = chips, h = hotdogs): ");
    scanf("%c", &carnival.snack_offered);

    //print student details
    printf("Carnival Booth Details:\n");
    printf("Ticket price is %.3lf\n", carnival.ticket_price);
    printf("Booth number is %d\n", carnival.booth_number);
	  
    if (carnival.snack_offered == 'p') {
        printf("Carnival booth snack offered is: POPCORN\n");
    } else if (carnival.snack_offered == 'c') {
        printf("Carnival booth snack offered is: CHIPS\n");
    } else {
        printf("Carnival booth snack offered is: HOTDOGS\n");
    }

	return 0;
}

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
Sample solution for number_challenge.c
// Number Challenge
// number_challenge.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 21/6/26
//
// This program 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. 

#include <stdio.h>

int main(void) {
    
    // Prompts the user to enter a number 
    printf("Welcome to the Number Challenge.\n");
    printf("What number do you want to check? ");
    
    int num;
    // Repeatedly scan the number into an integer variable using a while loop
    while(scanf("%d", &num) == 1) {
        
        // Use if statements to check if the number works
        if (num % 300 == 0) {
            printf("The number does not work\n");
        } else if (num % 3 == 0) {
            printf("That number works!\n");
        } else {
            printf("The number does not work\n");
        }

        //Reprint the prompt from to the user
        printf("What number do you want to check? ");
    } 
    
    printf("\n");

	return 0;
}

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
Sample solution for upside_down_pyramid.c
// Upside Down Pyramid
// upside_down_pyramid.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 21/6/26
//
// This program should print an upside down left triangle with a height
// of 10 rows strictly using for loops.

#include <stdio.h>

#define MAX 10

int main(void) {
    
    for (int i = 0; i < MAX; i++) {
        for(int j = 0; (i + j) < MAX; j++) {
            printf("x");
        }
        printf("\n");
    }
    
	return 0;
}

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
Sample solution for upside_down_pyramid_two.c
// upside_down_pyramid_two
// upside_down_pyramid_two.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 21/6/26
//
// This program should print an upside down left triangle with a height
// of 10 rows strictly using while loops.

#include <stdio.h>

#define MAX 10

int main(void) {
    
    int i = 0;
    while (i < MAX) {
        
        int j = 0;
        while((i + j) < MAX) {
            printf("x");
            j++;
        }

        printf("\n");
        i++;
    }
    
	return 0;
}

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
Sample solution for solar_car.c
// Solar Car Debug
// solar_car.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 26/6/26
//
// This program 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.

#include <stdio.h>

enum state {
    DRIVE,
    SOLAR,
    OFF,
    MAINTENANCE_MODE,
    CRUISE_MODE
};

struct car {
    enum state state;
    double speed;
    int distance;
};

int main(void) {
    int state;
    struct car solar_car; // BUG: Incomplete struct data type given

    printf("What mode is the car in (DRIVE = 0, SOLAR = 1, OFF = 2, MAINTENANCE_MODE = 3, CRUISE_MODE = 4)? ");
    scanf("%d", &state); // BUG: Missing & for scanf

    // BUG: All if statements using = instead of ==
    if (state == 0) {
		solar_car.state = DRIVE;
	} else if (state == 1) {
		solar_car.state = SOLAR;
	} else if (state == 2){
		solar_car.state = OFF;
	} else if (state == 3) {
		solar_car.state = MAINTENANCE_MODE;
	} else {
		solar_car.state = CRUISE_MODE;
	}

    printf("What speed is the car going? ");
    scanf("%lf", &solar_car.speed); // BUG: Used %d instead of %lf
    // BUG: && instead of ||
    if (solar_car.state == MAINTENANCE_MODE || solar_car.state == OFF) {
        printf("No no silly, the speed is 0\n");
        solar_car.speed = 0;
    }

    printf("Please enter the 5 distances between the chargers that the car has traveled? ");
    int i = 0;
    int sum = 0;
    solar_car.distance = 0; // BUG: Distance not initialised
    while (i < 5) {
        scanf("%d", &sum);
        solar_car.distance = solar_car.distance + sum;
        i++; // BUG: Missing increment
    }

    printf("Solar Car Information:\n");
    printf("Speed: %.2lf\n", solar_car.speed);
    printf("Distance travelled: %d\n", solar_car.distance);
    printf("State: ");
    if (solar_car.state == DRIVE) {
        printf("DRIVE\n");
    } else if (solar_car.state == SOLAR){
        printf("SOLAR\n");
    } else if (solar_car.state == OFF) {
        printf("OFF\n");
    } else if (solar_car.state == MAINTENANCE_MODE){
        printf("MAINTENANCE_MODE\n");
    } else {
        printf("CRUISE_MODE\n");     
    }

	return 0;
}

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
Sample solution for counting_chickens.c
// Counting Chickens
// counting_chickens.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 21/6/26
//
// Counts eggs laid in a week and calculates what can be baked and cooked

#include <stdio.h>

#define DAYS 7

int main(void) {
    char laid;
    
    printf("Did the chicken lay this week (y/n)? ");
    
    while(scanf(" %c", &laid) == 1 && laid == 'y') {
        
        int sum = 0;
        printf("Amount of eggs laid each day: ");
        for(int i = 0; i < DAYS; i++) {
            int num;
            scanf("%d", &num);
            sum = sum + num;
        }
        
        printf("This Week's Baking:\n");
        
        int quiche = sum / 6;
        printf("Quiches: %d\n", quiche);

        int pies = (sum % 6) / 3;
        printf("Pies: %d\n", pies);

        int cupcakes = (sum % 3) / 2;
        printf("Cupcakes: %d\n", cupcakes);

        int omelette = ((sum % 3) % 2);
        printf("Omelettes: %d\n", omelette);
        
        printf("End of the week\n\n");
        printf("Did the chicken lay this week (y/n)? ");
    }

	return 0;
}

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
Sample solution for weather_problems.c
// Problems with the weather
// weather_problems.c
//
// This program was written by Sophie Moeskops (z5587745)
// on 21/6/26
//
// This program scans in information about the weather including the temperature,
// whether it is rainy or sunny and whether it is windy. The program should then 
// print the recommended clothing for that weather!

#include <stdio.h>

#define TEMP_THRESHOLD 22
#define RAIN 'r'
#define SUN 's'
#define WIND 'y'
#define NO_WIND 'n'

int main(void) {
    int temp;
    char windy;
    char rain;

    printf("What is the temperature? ");
    scanf("%d", &temp);
    printf("Is it rainy or sunny (r/s)? ");
    scanf(" %c", &rain);
    printf("Is it windy (y/n)? ");
    scanf(" %c", &windy);

    if (temp >= TEMP_THRESHOLD && rain == SUN && windy == NO_WIND) {
        printf("Wear shorts and a t-shirt.\n");
    } else if (temp >= TEMP_THRESHOLD && rain == SUN && windy == WIND) {
        printf("Wear a light jacket.\n");
    } else if (temp >= TEMP_THRESHOLD && rain == RAIN && windy == WIND) {
        printf("Wear a light raincoat.\n");
    } else if (temp < TEMP_THRESHOLD && rain == SUN && windy == NO_WIND) {
        printf("Wear jeans and a warm jacket.\n");
    } else if (temp < TEMP_THRESHOLD && rain == SUN && windy == WIND) {
        printf("Wear a heavy coat and a scarf.\n");
    } else if (temp >= TEMP_THRESHOLD && rain == RAIN && windy == NO_WIND) {
        printf("Bring an umbrella.\n");
    } else if (temp < TEMP_THRESHOLD && rain == RAIN && windy == NO_WIND) {
        printf("Bring an umbrella and jacket.\n");
    } else {
        printf("Wear a heavy raincoat.\n");       
    }

	return 0;
}