Programming Fundamentals
Check in week
Reminder: This week is a check-in week, so please make sure to stay around in the lab time for your one-on-one with one of your Tutors.
Part 0: Welcome & Assignment 1
Great job getting through Assignment 1 (or almost getting through if you are in a Monday class)!
Part 1: The parts of a pointer
In this section, tutors will lead a short revision section on pointers, and then walk through a demonstration simulating how pointers manipulate memory.
This tool will be used to further explore pointers:
-
What will happen when each of the following statements is executed (in order)?
int n = 42; int *p; int *q; p = &n; *p = 5; *q = 17; q = p; *q = 8;
Fill in the values of each variable in the below visual at each point in the code execution.
01: int n = 42;02: int *p;03: int *q;04: p = &n;05: *p = 5;06: *q = 17;07: q = p;08: *q = 8;Type:Name:Value:
Part 2: Coding with Functions and Pointers
Have a quick look at the following code:
#include <stdio.h>
void increment_time(int days, int hours, int minutes);
int main(void) {
int days = 3;
int hours = 4;
int minutes = 59;
increment_time(days, hours, minutes);
printf("Current time: %d days, %d hours and %d minutes", days, hours, minutes);
return 0;
}
// increments the time by 1 minute
void increment_time(int days, int hours, int minutes) {
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
if (hours == 24) {
hours = 0;
days++;
}
}
Note that function increment_time
doesn't seem to be working correctly.
Part 3: Struct pointers
Have a quick look at the following code which is slightly different from part 2 using a struct:
#include <stdio.h>
struct time {
int days;
int hours;
int minutes;
};
void increment_time(struct time current_time);
int main(void) {
struct time current_time;
current_time.days = 3;
current_time.hours = 4;
current_time.minutes = 59;
increment_time(current_time);
printf("Current time: %d days, %d hours and %d minutes",
current_time.days, current_time.hours, current_time.minutes);
return 0;
}
// increments the time by 1 minute
void increment_time(struct time current_time) {
current_time.minutes++;
if (current_time.minutes == 60) {
current_time.minutes = 0;
current_time.hours++;
}
if (current_time.hours == 24) {
current_time.hours = 0;
current_time.days++;
}
}
Note that function increment_time
in this example also doesn't seem to be working correctly.
Part 4: Malloc and Arrays
In this section we'll have a look at how we can create arrays using malloc
struct pet { int age; int weight; char name[100]; }; int main(void) { int i; double d; int array1[10]; char array2[4]; struct pet coco; struct pet class_pets[5]; }
Part 5: EOF Loops (Optional)
In this section, you'll be revising the different ways we can read input until EOF.
We'll be using this starter code:
#include <stdio.h> #define MAX_LETTERS 100 int main (void) { char my_var; while (scanf(" %c", &my_var) == 1) { printf("Input: %c\n", my_var); } return 0; }