MTRN2500 has two possible prerequisite courses: COMP1531 and COMP2521. COMP1511 is also a relevant course that is not technically a prerequisite; note that it is a prerequisite of COMP1531/COMP2521 and is a requirement of the mechatronics (MTRNAH) engineering major.
Revision questions specifically related to C (taught in COMP1511) are also included — however, most C-specific concepts will be revisited in the course (albeit at a faster pace and in context of learning C++).
Programming Fundamentals
- Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Sample output:
1
2
Fizz
4
Buzz
...
Note: whilst the following code snippets are provided in multiple languages, you by no means have to know all of them. You should be able to understand the logic and translate it to the language you are most comfortable with.
// C #include <stdio.h> int main() { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { printf("FizzBuzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else { printf("%d\n", i); } } return 0; }// C++ #include <iostream> int main() { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { std::cout << "FizzBuzz\n"; } else if (i % 3 == 0) { std::cout << "Fizz\n"; } else if (i % 5 == 0) { std::cout << "Buzz\n"; } else { std::cout << i << '\n'; } } return 0; }# Python for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)// JavaScript for (let i = 1; i <= 100; i++) { if (i % 3 === 0 && i % 5 === 0) { console.log("FizzBuzz"); } else if (i % 3 === 0) { console.log("Fizz"); } else if (i % 5 === 0) { console.log("Buzz"); } else { console.log(i); } }
- Complete the following function which returns the sum of all the elements squared in a given array. The function should have the following signature (choose the language you are most comfortable with):
// C
int sumSquares(int arr[], int length);
// JavaScript/TypeScript
function sumSquares(arr: number[]): number;
# Python
def sumSquares(arr: List[int]) -> int:
// C++
int sumSquares(std::vector<int> arr);
// C int sumSquares(int arr[], int length) { int total = 0; for (int i = 0; i < length; i++) { total += arr[i] * arr[i]; } return total; }// JavaScript/TypeScript function sumSquares(arr) { return arr.reduce((acc, curr) => acc + curr * curr, 0); } // Alternatively function sumSquares(arr) { let total = 0; for (let i = 0; i < arr.length; i++) { total += arr[i] * arr[i]; } return total; }# Python def sumSquares(arr): total = 0 for i in arr: total += i * i return total// C++ int sumSquares(std::vector<int> arr) { int total = 0; for (int i : arr) { total += i * i; } return total; }
- Write a function that returns the third largest element in an array/list of integers. You may assume that the array/list has at least 3 elements. The function should have the following signature (choose the language you are most comfortable with):
// C
int thirdLargest(int arr[], int length);
// JavaScript/TypeScript
function thirdLargest(arr: number[]): number;
# Python
def thirdLargest(arr: List[int]) -> int:
// C++
int thirdLargest(std::vector<int> arr);
The approach shown below is to keep track of the first, second, and third largest elements as you iterate through the array.
Note that an alternative method (that is slightly less efficient but simpler to implement) is to sort the array in descending order and return the element at index 2.
// C int thirdLargest(int arr[], int length) { int first = INT_MIN, second = INT_MIN, third = INT_MIN; for (int i = 0; i < length; i++) { if (arr[i] > first) { third = second; second = first; first = arr[i]; } else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) { third = arr[i]; } } return third; }// JavaScript/TypeScript function thirdLargest(arr) { let first = Number.MIN_SAFE_INTEGER; let second = Number.MIN_SAFE_INTEGER; let third = Number.MIN_SAFE_INTEGER; for (let i = 0; i < arr.length; i++) { if (arr[i] > first) { third = second; second = first; first = arr[i]; } else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) { third = arr[i]; } } return third; }# Python def thirdLargest(arr): first = second = third = float('-inf') for i in arr: if i > first: third = second second = first first = i elif i > second: third = second second = i elif i > third: third = i return third// C++ int thirdLargest(std::vector<int> arr) { int first = INT_MIN, second = INT_MIN, third = INT_MIN; for (int i : arr) { if (i > first) { third = second; second = first; first = i; } else if (i > second) { third = second; second = i; } else if (i > third) { third = i; } } return third; }
C
- What steps are required in order to run a C program.
- Write the program in a text editor.
- Save the file with a
.cextension.- Compile the program using a C compiler (e.g.
dcc(UNSW only),gcc,clang).- Run the compiled program.
- Which of these variables have valid names?
int V3RX;
int var;
int 3var;
int _3;
int __var;
V3RX,var,_3, and__varare valid variable names. Variable names cannot start with a number.
- What is a pointer? What is a memory address?
A pointer is a variable that stores the memory address of another variable.
Every variable in a program is stored in memory at a specific location, which is known as its memory address.
- Complete the following function:
void swap(int *a, int *b) {
// TODO: implement a function that swaps the values at addresses a and b
}
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
- What is the difference between stack and heap memory? How would you allocate memory on the stack or heap?
Stack memory is used for static memory allocation and is managed by the compiler. Heap memory is used for dynamic memory allocation and is managed by the programmer.
To allocate memory on the stack, you can declare a variable. To allocate memory on the heap, you can use
malloc(C).
- What is an array? How would you declare an array on the stack and on the heap?
An array is a collection of elements of the same type stored in contiguous memory locations.
To declare an array on the stack, you can use:
int arr[5];To declare an array on the heap, you can use:
int *arr = malloc(5 * sizeof(int));
- What is a struct?
A struct is a user-defined data type that allows you to group multiple variables of different types together.
struct Point { int x; int y; };
- What is a linked list?
A linked list is a data structure that consists of nodes where each node contains a value and a reference to the next node in the sequence.
struct node { int data; struct node *next; };
- What is ASCII?
ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents text in computers. Each character is represented by a 7-bit binary number.
- Identify code which has bad style. Explain how this could be improved.
#include <stdio.h>
#define CONST 10
int main(){
int VAR=3 *CONST;
printf("%d\n", VAR);
VAR = 4;
printf("%d\n", VAR);
}
Fix the indentation and spacing inconsistencies, and the case of the variable names. camelCase or snake_case is generally preferred (choose one and stay consistent) over SCREAMING_SNAKE_CASE, which is reserved for constants.
#include <stdio.h> #define CONST 10 int main() { int var = 3 * CONST; printf("%d\n", var); var = 4; printf("%d\n", var); }
-
Usually array indexing would be done like
arr[i]. Explain why this code works as well?
int arr[4] = {42, 52, 62, 72};
for (int i = 0; i < 4; i++) {
printf("%d\n", i[arr]);
}
An array in C is ‘equivalent’ to a pointer to the first element of the array. Array indexing is equivalent to pointer arithmetic (i.e., adding some number to the memory address of the first element to get the address of later elements).
arr[i]is equivalent to*(arr + i), which is the same as*(i + arr). Therefore,i[arr]is equivalent to*(i + arr), which is the same as*(arr + i), which is the same asarr[i].A nice program that allows you to see this in action:
#include <stdio.h> int main() { int arr[4] = {42, 52, 62, 72}; printf("arr = %p\n", arr); printf("&arr[0] = %p\n", &arr[0]); printf("&arr[1] = %p\n", &arr[1]); printf("&arr[2] = %p\n", &arr[2]); printf("&2[arr] = %p\n", &2[arr]); }
- What is the difference between a compiler warning and error?
A compiler warning is a message that indicates a potential issue in the code but does not prevent the program from compiling. A compiler error is a message that indicates a problem that prevents the program from compiling.
Git Commands
- Create a git repository.
git init
- Clone an existing git repository.
git clone <repository-url>
- Show the status of the repository.
git status
- Stage changes for commit.
git add <file>
git add .(to add all changes in the current directory)
git add -A(to add all changes in the repository)
- Commit changes.
git commit -m "Commit message"
- Checkout to a branch
git checkout <branch-name>(checkout to an existing branch)
git checkout -b <branch-name>(to create and checkout a new branch)
- Merge a branch into the current branch.
git merge <branch-name>It is recommended to create a merge request / pull request on GitHub or GitLab to merge branches.
- Push changes to a remote repository (e.g. GitHub or GitLab)
git push
- Amend the last commit message.
git commit --amend -m "New commit message"
- Check the changes that have been made but not yet committed.
git diff
- Show the commit history.
git log
- Reset to a previous commit.
git reset --hard <commit-hash>(where the commit hash can be found usinggit log)
- Reset the git history to a previous commit but keep the current code.
git reset --soft <commit-hash>