Unit Outline Info

Pass Requirements

50+% final mark and submitted assignment

Assessments

TaskValueDate
Mid semester test20%Week 7 (maybe 8 - i.e. week after break) Lecture (Tuesday)
Assignment30%Due week 11
Exam50%Exam period

Basics of C

Sample Code

#include<stdio.h>
#include<stdlib.h>
 
int main() {
	printf("Hello, World!\n");
 
	return 0;
}

#include<stdio.h> - imports the stdio library
return 0 - exit code confirming program run success

Compiling

gcc hello.c -Wall -ansi -pedantic -o myProgram

hello.c - file name
-Wall - shows all warnings
-ansi -pedantic - forces the compiler to compile the code under the C89 standard
-o myProgram - calls the program “myProgram”

Datatypes

  • int
  • float
  • double - (float but bigger - not really needed in UCP)
  • char - (single character)
  • string - (not in c, must use array of char - char[100] stringName)
  • boolean - (not really in c89, just an int: 0=false, else=true)

Example

#include<stdio.h>
#include<stdlib.h>
 
int main() {
	int number = 100;
	float r = 1.2;
	char c = 'a';
	
	printf("Number is %d\n", number);
	return 0;
 
}

Placeholders

  • %d - int
  • %f - float
  • %c - char
  • %s - array of char

Input

scanf(type, address)
type - type of input - e.g. "%d" for int
address - memory address for variable - e.g. &number

#include<stdio.h>
#include<stdlib.h>
 
int main() {
	int number1, number2;
 
	printf("Please enter two ints: ");
	scanf("%d %d", &number1, &number2);
	
	printf("Numbers are %d, %d\n", number1, number2);
	return 0;
 
}

Comments

// Single line comment - DOES NOT EXIST IN C89

/*
Block comments :)
*/

Control Structures

Similar to Java

If, Else If, Else

Example Code

#include<stdio.h>
#include<stdlib.h>
 
int main() {
	int number1, number2;
 
	printf("Please enter two ints: ");
	scanf("%d %d", &number1, &number2);
	
	printf("Numbers are %d, %d\n", number1, number2);
 
	if (number1 > 10) {
		printf("The first number is greater than 10!\n");
	} else {
		printf("The first number is not greater than 10!\n");
	}
	
	return 0;
}

For Loop

for(executed once; boolean - exit if false; executed every iteration end) {}

int i;
for(i = 1; i <= 10; i++){
	printf("%d\n", i)
}

While

while(){ } and do(){ }while();

Functions

int addition(int num1, int num2) {
	return num1 + num2;
}

Order MATTERS so functions must be declared before being called.
Can either move the function above main() or declare the prototype.

int addition(int num1, int num2) /* Prototype or forward declaration */
 
int main() {
	...
}
 
int addition(int num1, int num2) {
	return num1 + num2;
}