0% found this document useful (0 votes)
11 views

COMP1511 - Programming Fundamentals Lecture Notes - COMP1511_ Programming Fundamentals Using a - Studocu

The document provides an overview of programming fundamentals using C, including terminal commands, variable types, and basic syntax. It covers essential concepts such as functions, loops, and file operations, along with guidelines for code style and organization. Additionally, it introduces Turing machines and the role of the processor in computing.

Uploaded by

ahab.iqbal08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

COMP1511 - Programming Fundamentals Lecture Notes - COMP1511_ Programming Fundamentals Using a - Studocu

The document provides an overview of programming fundamentals using C, including terminal commands, variable types, and basic syntax. It covers essential concepts such as functions, loops, and file operations, along with guidelines for code style and organization. Additionally, it introduces Turing machines and the role of the processor in computing.

Uploaded by

ahab.iqbal08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

COMP1511: Programming Fundamentals

Using a Terminal
+ The main interface to Linux is a terminal where all our interaction is in text
+ Some commands include:
o ls
Lists all the files in the current directory
o mkdir directoryName
Makes a new directory called directoryName
o cd
Changes the current directory
o pwd
Tells you where you are in the directory structure at the moment
+ gedit
o A basic text editor
o Helps out a little by highlighting C in different colours
+ dcc/gcc
o A compiler – A translator that takes our formal human readable C and turns it into
the actual machine-readable program
o The result of the compiler is something we can “run”

Programming in C
+ C is:
o A clear language with defined rules so that nothing we write in it is ambiguous
o Many modern programming languages are based on C
o A good starting point for learning how to control a computer from its roots

+ Comments
o Put into our code to communicate with others viewing the code
o // in front of a line makes it a comment
o Everything between /* and */ will be comments
o The compiler will ignore comments, so they don’t have to be proper code
o Generally, we will sign off with our name and date for future reference

+ #include
o Asks the compiler to grab another file of code and add it to ours
o stdio.h is the Standard Input Output Library, allowing us to make text appear on the
screen
o the ‘.h’ at the end distinguishes different files which in this case signifies that it is the
header file
+ The “main” Function
o A function is a block of code that is a set of instructions
o Our computer will run this code line by line, executing our instructions
o The first line tells us:
int is the output – this stands for integer, which is a whole number
main is the name of the function
(void) means that this function doesn’t take any input

+ The Body of the Function


o Between the { and } are a set of program instructions
o printf() is actually another function from stdio.h which we included
makes text appear on the screen
communicates with the user
o return is a C keyword that says we are now delivering the output of the function. A
main that returns 0 is signifying a correct outcome of the program
Basically indicates that the code is done

+ Editing and Compilation


o In the Linux terminal we will open the file to edit by typing:
gedit helloWorld.c &
& allows terminal to keep running while editing the code
o We compile the code by typing:
dcc helloWorld.c -o helloWorld
dcc – compile
-o – output
o the -o part tells the compiler to write out a file called “helloWorld” that we then run
by typing:
./helloWorld
o The ./ lets us run the program ‘helloWorld’ that is in our current directory

+ How does a computer remember things?


o Computer memory is literally a big pile of on-off switches known as bits
bit is short for binary digit
o When 8 bits are collected together into a group, these are called bytes

+ Variables
o Our way of asking the computer to remember something for us
o Called a ‘variable’ as its value can be changed
o It is a certain number of bits that we use to represent something
o Two different types of variables:
int – integer, a whole number (e.g. 0, 1, 2, 3)
double – floating point number (e.g. 3.14159, 8.534, 7.11)

+ Naming Variables
o names are a quick description of what the variable is
e.g. “answer” and “diameter”
rather than “a” and “b”
names are usually nouns and we avoid single letter variables as they can
easily become confusing
o we always use lower case letters to start our variable names
o C is case sensitive:
“ansWer” and “answer” are two different variables
o C also reserves some words
“return”, “int” and “double” can’t be used as variable names
o multiple words
words can be split with underscores or capitals: “long_answer” or
“shortAnswer”

+ int
oa whole number
omost commonly uses 32 bits (which is also 4 bytes)
othis gives us exactly 232 different possible values
othis also means the integer is limited, it can’t just hold any value
most of what we will be doing won’t hit the limits
o ranges from -2147483648 to 21474843647

o Issues:
Overflow and Underflow
If we add two large ints together, we might go over the maximum value,
which will actually roll around the minimum value and possibly end up
negative
Hence we need to be aware of the limits
Ints might not always be 32 bits, this is dependent on the OS

+ double
o A double-sized floating point number
o A decimal value – “floating point” means the point can be anywhere in the number
E.g. 10.567 or 105.67 (the points are in different places in the same digits)
o It’s called “double” because it’s usually 64 bits, hence the double size of our integers
o Issues:
No such thing as infinite precision
We can’t precisely encode a simple number like 1/3
 Floats will run out of digits
If we divide 1.0 by 3.0, we’ll get an approximation of 1/3
 This means that a lot of doubles are approximate numbers
The effect of approximation can compound the more you use them

+ Code for Variables

o printf
Not just for specific messages we type in advance
We can also print variables to our display

%d – where in the output you’d like to put an int


Decimal integer – “number in base 10”
After the comma, you put the name of the variable you want to write
In this case, 7 would be printed
o printf with multiple variables

the variables will match the symbols in the same order as they appear
o printing different types of variables

%d stands for “decimal integer”


%lf stands for “long floating point number” (double)
o scanf
reads input from the user in the same format as printf
note the & symbol that tells scanf where the variable is
A value of 0 is different to an integer without a given value -> might auto give
a “magic number”
scanf is also from the stdio library
scanf finds the 32-bits and inserts the value specified. Can write whether or
not there is already a value -> will write over

+ Constants
o sometimes we will use fixed numbers using a special command, #define
o we name them in all caps so that we remember that they’re not variables
o NB: if typing xPI without any spaces, PI will not be replaced with the number
o Defined above main function

o In this case, the computer will replace PI with the given number anywhere in the
code

+ Maths
o +, -, *, /
o These will happen in their normal mathematical order

+ Division and Variable types


o If either number in the division are doubles, the result will be a double
o If both numbers are ints, the result will be an int
o Ints will always drop whatever fraction exists, they won’t round nicely
o % is called Modulus. It will give us the remainder from a division between integers
Modulus will only give remainders while divisions will only give integers

File Operations
o cp source destination – copy
o mv source destination – move (can also be used to rename)
o rm filename – remove a file (delete)
o the -r tag can be added to cp or rm to recursively go through a directory and
perform the command on all the files -> within that specific directory
o cd.. -> goes back once in directories
o mv printDemo2.c idontwantthishere.c to change the name of printDemo2.c to
idontwantthishere.c
The if statement
o an if is like a question and an answer
o first we ask a question
o if we get the right answer, we run some code
If the answer is wrong then the code will not run

+ else – Adding to if statements

If ‘if’ statement is false, ‘else’ runs


+ Chaining ifs and elses

+ Asking the right Question


o Relational operators work with pairs of numbers:
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equals (we’ve already used “=” to assign values, so we use “==” to ask a
question)
!= not equal to
o All of these will result in 0 if false and a 1 if true

+ Chaining Questions Together


o We use Logical Operators to compare expressions
o Between two expressions
&& AND equates to 1 if both sides equate to 1
|| OR is 1 if either side is 1
o In front of an expression
! NOT is the opposite of whatever the expression was
 Will flip the result (if it is true then 0 will be printed and 1 if false)

Executing the same code more than once


o sometimes we need to repeat our work
o C normally executes in order, line by line
o if statements allow us to “turn on or off” parts of our code
o Copy-pasting the same code again and again is not a feasible solution

+ While Loops

o “while” is a C keyword that lets us loop code


o Format is very similar to an if statement
o The “question” in the (brackets) functions very similarly
o If it’s true, the body of the while loop will run
o If it’s false, the body won’t run and the program will continue
o Once a while reaches the end of its { } it will start again
Will continue while the expression remains true
o Control:
We can use a variable to control how many times a while loop runs
We call this variable a “loop counter”
It’s an int that’s declared outside the loop
It’s “termination condition” can be checked in the while expression
It will be updated inside the loop
We can also use a variable to decide to exit a loop at any time
We call this variable a “sentinel”
It’s like an on/off switch for the loop

 Every time we get to the bottom, the counter increases by one until it
equals 10  then the program will leave the loop and continue
running the rest of the code
o Termination
It is very easy to make a program that goes forever
Consider the following while loop:

 Using an expression that is never false, the loop will never finish
 Every time we create a loop, we need to figure out how it is going to
stop  to avoid the program never finishing
o Using a Sentinel Variable with While Loops
A sentinel is a variable we use to decide when to exit a while loop

 This program will keep running until the user types in an odd number
 endLoop becomes 1 when the user types an odd number and thus the
while loop will not run
o While Loops inside While Loops
each time a loop runs
it runs the other loop
the inside loop ends up running a lot of times

+ A loop within a loop

o sets up a loop using y


o in each loop of y, sets up a loop using x
o the x loop writes multiple *s to the terminal
o then the y loop finishes, writing \n so the line ends
the loop inside will run 100 times in total

+ new C syntax

o ++ adds one to the variable which is known as incrementing

+ output percentage

o The code outputs 0 percent a lot more than it should


o This is even after we know it’s counting the successes correctly
o After a division, the integers will throw away any fractions
o Since our “numSuccesses/numRolls” will always be between zero and 1
o Our result can only be the integers 0 or 1
o And anything less than 1 will end up having its fraction dropped

+ using doubles
o Result of a division will be a double if one of the variables in it is a double
o We could change one of the variables in our division to a double
o This could be done in the declaration of the variable
o But we can also just do it at the point it is used

Code Style
o Indentation and bracketing
o Names of variables and functions
o Repetition (or not) of code
o Clear comments
o Consistency

+ Keeping your code clean


o Write comments before code
o Name your variables before you use them
o { everything inside gets indented 4 spaces
o } line up your closing brackets vertically with the line that opened them
o one expression per line
o maintain consistency in spacing

+ Comments before code


o making plans with comments
o you can fill them out with correct code later
o some of these comments can stay even after you’ve written the code

+ Naming variables
o Variable names are for humans
o Can you describe what a variable is in a word or two?
o If your lab partner was to read this name, would it make sense?
o Does it distinguish well against the other variables

+ Indentation
o A common convention is to use 4 spaces for indentation

+ One expression per line

+ Spacing
Functions
o A separate piece of code identified by a name
o It has inputs and an output
o If we “call” a function it will run the code in the function

+ Function Syntax
o We write a function with (in order left to right):
An output (known as the function’s type)
A name
Zero or more input(s) (also known as function parameters)
A body of code in curly brackets

+ Return
o return will deliver the output of a function
o return will also stop the function running and return to where it was called from
o finishing the function that it is in and then delivers the output and stops the function
from running again. Only if it is at the end of the main function, it will stop the whole
code

+ Using functions
o we can use a function by calling it by name
o and providing it with input(s) of the correct types)

o Expecting that output of this code would be 10 due to the add function

+ Compilers and Functions

o A compiler will process our code, line by line, from top to bottom
o If it has seen something before, it will know its name
o Thus, variables must be declared before it can be used since the compiler does not
know this variable
o Since otherNumber in this case is declared after it is used, the compiler would warn
the user of an error

+ Declaring Functions
o All functions must be declared before they can be used

+ Void Functions
o We can also run functions that return no output
o We can use a void function if we don’t need anything back from it
o The return keyword will be used without a value in a void function
Turing Machines
Originally a theoretical idea of computation
o There is a tape that can be infinitely long
o We have a “head” that can read or write to this tape
Can write a 0 or a 1
o We can move the head along to any part of the tape
o There’s a “state” in which the machine remembers its current status
The memory component
o There’s a set of instructions that say what to do in each state

o Theoretically will never run out of memory (unlike our computers which have limited
storage)
o Everything that our computer can do, this machine can do (given the necessary
amount of time)

+ The Processor
o Known as Central Processing Units (CPUs)
Maintains a “state”
Works based on a current set of instructions
Can read and write from/to memory
Basically the brain of the computer
o In C:
State – where are we up to in the code right now
Instructions – compiled from our lines of code
Reading/Writing – Variables

+ Memory
o From registers (tiny bits of memory on the CPU) through Random Access Memory
(RAM) and to the Hard Disk Drive. All of these are used to store information
o How does C use memory?
On the Hard Drive
Our C source code files are stored on our Hard Drive
dcc compiles our source into another file, the executable program
In Random Access memory
When we run our program, all the instructions are copied into RAM
Our CPU will work through memory executing our instructions in order
Our variables are stored in RAM as well
Reading and writing to variables will change the numbers in
RAM
o What happens in memory when we run a program?
Our Operating System gives us a chunk of memory
Our program copies its instructions there
Some space is reserved for declared variables
The Stack is used to track the current state
The stack grows and shrinks as the program runs
The Heap is empty and ready for use
We can use the heap to store data while the program is running

Arrays
o Using arrays, we will be able to access integers as a group and loop
through and access each individual element

+ What is an array?
o A variable is a small amount of memory
o An array is a larger amount of memory that contains multiple variables
o All of the elements (individual variables) in an array are the same type
o Individual elements don’t get names, they are accessed by an integer index

+ Declaring an Array
o int – the type of the variables stored in the array
o [10] – the number of elements in the array
So in this case we will be using 320 bits of memory for our array since there will
be 10 integers
o – {0} – initialises the array as all zeroes
Can only do this with 0, cannot do this with any other number
o – {0,1,2,3,4,5,6,7,8,9} – initialises the array with these values
+ Array Elements
o An element is a single variable inside the array
o They are accessed by their index, an int that is like their address
o Indexes start from 0
Basically tells us how far into the array we need to go to access the number we
want
We start from 0 as we do not have to move along to get the first element. To
access the second element we ‘step in’ once
o Trying to access an index outside of the array will cause errors
In this example, element 2 of arrayOfMarks is 44 and element 6 is 62

+ Accessing elements in C

o Printf and scanf with arrays


We can’t printf a whole array
We also can’t scanf a line of user input text into an array
We can do it for individual elements
The trick then becomes looping to access all individual elements one by one

+ New Syntax
o += is used for accumulating values in a variable
+ Input into an array
o We can’t access the whole array, only individual elements
o But we can loop through the array entering values

Memory
o Let’s start with an idea of a neighbourhood
o Each house is a piece of memory (a byte)
o Every house has a unique address that we can use to find it
o We could think of our entire computer’s memory as a big array of bytes

+ A neighbourhood of memory
o Every block of memory has an address
The address is actually an integer
o Houses and addresses
A variable is a house
the house is in a certain location in memory
the house contains the bits and bytes that decide what the value of the
variable is
the address is an integer
 in a 64 bit system, we’ll usually use a 64 bit integer to store an address
 we can address 264 bytes of memory

Pointers
o variables that hold memory addresses
o created to point at the location of variables
o if a variable was a house, the pointer would be the address of that house
o pointers are usually created with the intention of “aiming at” a variable (storing a
particular variable’s address)

+ Pointers in C
o use a * to declare a variable as a pointer
o a pointer is most often “aimed” at a particular variable
o that means the pointer stores the address of that variable
o we use & to find the address of a variable
+ Initialising Pointers
o Should be initialised like other variables
o Generally, pointers will be initialised by pointing at a variable
o “NULL” is a #define from most standard C libraries (including stdio.h)
o If we need to initialise a pointer that is not aimed at anything, we will use NULL

+ Using Pointers
o Looking at the variable that a pointer “points at”
We can use * on a pointer to access (dereference) the variable it points at
Using the address analogy, this is like asking what’s inside the house at that
address
%p in printf will print the address stored in a pointer

ip is the address of the integer while *ip is the actual integer itself
to go from integers to pointers we use & and to go from pointers to integers we
use *

+ Pointers and Functions


o Pointers allow us to pass around an address instead of a variable
o We can create functions that take pointers as input
o All functions inputs are always passed in “by value” which means they’re copies, not
the same variable
o But if I have a copy of the address of a variable, I can still find exactly the variable I’m
looking for

+ Function variables pass in “by value”

o In this case, the copy of the variable can’t every change the value of the variable,
because it is just a copy
+ Pointers also pass in “by value”

o The function has a copy of the pointer


o However, even a copy of a pointer contains the address of the original variable,
allowing the function to access it

+ Pointers and Functions in code

o a variable passed to a function is a copy and has no effect on the original


o A pointer passed to a function gives us the address of the original

+ Pointers and Functions


o Pointers mean we can give multiple variables to a function
o This means one function can now change multiple variables at once

+ Pointers and Arrays


o Arrays are blocks of memory
o The array variable is actually a pointer to the start of the array
o This is why arrays as input to functions let you change the array
+ Using Pointers to swap variable values
o This function doesn’t even know whether the ints are in arrays or not
o It sees two memory locations containing ints
o And uses a temporary int variable to swap them

o The equals means ‘take this and put it into that’ so for the last line, we are putting
the value of temp into *num2

Debugging
o The process of finding and removing software bugs
o Errors in code are called ‘bugs’
Something we have written (or not written) in our code
Any kind of error that stops the program from running as intended
Includes syntax and logical errors

+ Syntax Errors
o C is more specific than most human languages
o Slight mistakes in the characters we use can result in a different behaviour
o Some syntax errors are obvious, and your compiler will find them
o Some are more devious, and the error message will be the consequence of the bug,
rather than the bug itself

+ Logical Errors
o We can write a functional program that still doesn’t solve our problem
o Logical errors can be syntactically correct
o But the program might not do what we intended
sometimes we read the problem specification wrongly
sometimes we forget the initial goal of the program
sometimes we solve the wrong problem
sometimes we forget how the program might be used

+ Finding bugs
o compilers can sometimes catch some syntactical bugs
the compiler can be trusted to understand the language better than us
the simplest thing we can do is run dcc and see what happens
 if dcc runs and we don’t get any syntax errors, there might still be
errors within and get errors later on when we run the program
 errors found by the compiler are known as ‘compiler-time errors’
when dcc gives errors and warnings
 always start with the first error
 subsequent errors might just be a consequence of that first line
 an error is the result of an issue, not necessarily the cause
 at the very least, you will know a line and character where something
has gone wrong
 warning says it is possible to compile but there might be a problem
when you end up running the program
o we need to learn how to use compilers to correct our code
look for a line number and character (column) in the error message
sometimes knowing where it is is enough for you to solve it
read the error message and try to interpret it
remember that the error message is from a program that reads code
it might not make sense initially
sometimes it’s an expectation of something that’s missing
sometimes it’s confusion based on something being incorrect syntax
sometimes after fixing just one bug in the code, we might be moving the error
somewhere else and end up with more error messages
o code reviews and pair programming help for logical bugs
discussing different ways of doing things and shortening our code
easier to spot our own logical errors
o testing is always important
run the code
try different types of inputs to see different situations (autotest)
try using inputs that are not what is expected
use output to show information as the program runs
check different sections of the code to see where errors are

+ Characters
o new type of variable called char
o characters are what we think of as letters , like ‘a’, ‘b’, ‘c’ etc
o they can also represent numbers, like ‘0’, ‘1’, ‘2’ etc
o they are actually 8 bit integers
o we use them as characters, but they’re actually encoded numbers
o ASCII (American Standard Code for Information Interchange)
o We will not be using char for individual characters, but we will in arrays
o ASCII specifically uses values 0-127 and encodes
Upper and lower case English letters
Digits 0-9
Punctuation symbols
Space and newline
o It is not necessary to memorise ASCII, rather it’s important to remember that
characters can be treated like numbers sometimes
o Use of %c in the printf will format the variable as a character

+ Functions with characters


o getchar() is a function that will read a character from input
reads a byte from standard input
reads one character’s worth of input
usually returns an int between 0 and 225 (ASCII code of the byte it read)
can return a -1 to signify end of input, EOF (which is why we use an int, not a
char)
o char variable cannot store the variable -1 so we wouldn’t see the -1 so
we always use int to see the -1 to signify EOF
sometimes getchar won’t get its input until a newline(\n) is entered
o putchar() is a function that will write a character to input
will act very similarly to printf(“%c”, character);

+ Invisible Characters
o there are other ASCII codes for “characters” that can’t be seen
o there is no visible character on terminal when we run the program
o newline (\n) is a character
o space is a character
o there’s also a special character, EOF (End of File) that signifies that there’s no more
input
o EOF has been #defined in stdio.h, so we use it like a constant
o We can signal the end of input in a Linux terminal by using Ctrl-D

+ Working with multiple characters

+ More character functions


o <ctype.h> is a useful library that works with characters
o int isalpha (int c) will say if the character is a letter
o int isdigit (int c) will say if it is a numeral
o int islower (int c) will say if a character is a lower case letter
o int toUpper (int c) will convert a character to upper case

Strings
o when we have multiple characters together, we call it a string
o strings in C are arrays of char variables containing ASCII code
o strings are basically words, while chars are letters
o strings have a helping element at the end, a ‘\0’
o it’s often called the ‘null terminator’ and it is an invisible character
o this helps us know if we’re at the end of the string
everything after is not read by the computer

+ strings in Code
o strings are arrays of type char, but they have a convenient shorthand

We generally don’t fix the length of a string as it can change a lot


Double quotes around any text acts like a null terminator
o Both of these strings will be created with 6 elements. The letters h, e, l, l, o
and the null terminator \0
+ reading and writing strings
o fgets(array[], length, stream) is a useful function for reading strings
takes the whole line of input
o it will take up to length number of characters
o they will be written into the array

o the characters will be taken from a stream


o our most commonly used stream is called stdin, “standard input”
o stdin is our user typing input into the terminal

When fgets cant read anything in then it will return NULL


While fgets can read, the while loop will print the line of inputs
o fputs(array, stream) works very similarly to printf
o it will output the string stored in the array to a stream
o we can use stdout which is our stream to write to the terminal
+ Helpful Functions in the String Library
o <string.h> has access to some very useful functions
o Note that char *s is equivalent to char s[]
o int strlen(char *s) – return the length of the string (not including \0)
* is like giving the memory address of where a string startsll,I
o strcpy and strncpy – copy the contents of one string into another
o strcat and strncat – attach one string to the end of another
o strcmp and variations – compare two strings
o strchr and strrchr – find the first or last occurrence of a character

Structs
o A new way of collecting variables together
o Structs(short for structures) are a way to create custom variables
o Structs are variable that are made up of other variables
o There are not limited to a single type like arrays
o They are also able to name their variables
o Structs are creating our own variable type
We need to declare this type before any of the functions that use it
We declare what a struct is called and what the fields(variables) are

+ Creating a struct variable and accessing its fields


o Declaring and populating a struct variable
Declaring a struct: “struct structname variablename;”
Use the . to access any of the fields inside the struct by name

+ Accessing structs through pointers


o Pointers and structs go together so often that they have a shorthand
o We use -> to access fields when we have a pointer to a struct
o We often pass pointers to structs into functions

+ Structs as Variables
o Arrays of structs are possible
o Structs can be some of the variables inside other structs
o Once a struct has been defined, it can be used like any other variable

Memory
+ Functions and Memory
o Everything gets passed ‘by value’
o Variables are copied by the function
o The function will then work with their own versions of the variables

+ Functions and Pointers


o Everything gets passed ‘by value’
o But the value of a pointer is a memory address
o The memory address will be copied into the function
o This means both pointers are accessing the same variable

+ Functions and Arrays


o An array is a variable
o Not actually a variable containing all the elements
o When we use the array variable (no []), it’s actually the memory address of the start
of the elements
o This is why we had access to the integers in the arrays within functions
o When we don’t use square brackets in the array, we are talking about the whole
array but when we do use square brackets, we are only using that one element
within the array
o Arrays and pointers act the same

+ Memory in Functions
+ Memory Allocation

o A function called malloc(bytes)returns a pointer to memory


o Allows us to take control of a block of memory
o This won’t automatically be cleaned up when a function ends
o To clean up the memory, we call free(pointer)
o free()will use the pointer to find our previous memory to clean it up
o We can assign a particular amount of memory for use
the function sizeof()allows us to see how many bytes a variable needs
we can us sizeof()to allocate the correct amount of memory

+ Cleaning up

o every pointer that is aimed at allocated memory must be freed

o We don’t want to use too much memory


o dcc –leak-check can be used to tell you if you have any memory leaks

Multi-File Projects
o we can #include our own files, allowing us to join projects together
o we will often make some code that we can use again
o if we make it in its own file, with its own interface we can #include it in our projects

+ Header Files and C(Implementation) Files


o Header and C files usually go together in pairs
o Header *.h file
Shows the capabilities of a code file
Enough to use it without needing to understand what’s in it
o C Implementation *.c file
Contains the underlying implementation of the H file

+ File.h
o Header Files show you what the code’s functions are
o This file shows a programmer all they need to know to use our code
o typedef (Type Define) is a way of allowing us to create our own C Type out of
another Type
o this protects our struct from access and keeps our data safe
o Function Declarations with no definitions
o Comments that describe how the functions can be used
o No running code

+ File.c
o Implementation Files show you how the code runs in detail
o We can hide the complicated running code in this file
o Has includes, especially #include “File.h” (joins the two files together)
o If we have the file we use “ “ but when it is a file within the compiler like our
standard libraries we use <>
o Implements the struct mentioned in the typedef from the header
o Implements all the functions declared in the header

+ Main.c and other Files


o Our Entry Point into our code
o The main function is always what runs first
o For any code file (*.c) to use the functionality provided by another file, it must
#include that file

+ Compiling a Project with Multiple Files


o We need to compile all *.c files that we will use
o The *.c files will #include the necessary *.h files
o Amongst the *.c files there should be exactly one main()function
o The compiled program will run from the start of the main() function
Command Line Arguments
o Sometimes we want to give information to our program at the moment when we run
it
o The “Command Line” is where we type in commands into the terminal
o Arguments are another word for input parameters

o This extra text we type after the name of our program can be passed into our
program as strings

+ Main functions that accept arguments


int main doesn’t have to have void input parameters

o argc will be an “argument count”


o this will be an integer of the number of words that were typed in (including the
program name)
o argv will be “argument values”
o this will be an array of strings where each string is one of the words

+ Arguments in argv are always strings


o we can read the strings in, but we might want to process them

o in this example, how do we read 1 2 3 as numbers?


o We can use a library function to convert the strings to integers
o strtol() – “string to long integer” is from the stdlib.h
+ Nodes
o a new kind of struct
o contains some information and a pointer to another node of the same type

o a chain of nodes – a Linked List

Linked Lists
o not one continuous block of memory
o items can be shuffled around by changing where pointers aim
o length is not fixed when created
o you can add or remove items from inside the list

o Building a list from createNode()


+ How it works
o createNode makes a node with a NULL next and we point head at it

o the 2nd node points its “next” at the old head, then it replaces head with its own
address

+ Looping through a Linked List

o we can’t loop through them in the same way as arrays


o we have to follow the links from node to node
o if we reach a NULL node pointer, it means we’re at the end of the list
+ Inserting Nodes into a Linked List
o we can do this by simply aiming next pointers to the right places
o we find two linked nodes that we want to put a node between
o we take the next of the first node and point it at our new node
o we take the next of the new node and point it at the second node
Abstract Data Types
o stop us from accessing the data incorrectly

+ Typedef - Type Definition


o We declare a new Type that we’re going to use
o typedef <original Type> <new Type Name>
o Allows us to use a simple name for a possible complex structure
o Hides the structure details from other parts of the code

o we can use Beat as a Type without knowing anything about the struct underlying it
o in a Header file
we can put this in a header (*.h) file along with functions that use it
allows someone to see a Type without knowing exactly what it is
the details go in the *.c file which is not included directly
can see the functions without knowing how they work
able to see the header and use the information
hide the implementation that we don’t need to know about

+ Queue

o an idea of how things should be organised


o there is a structure but no implementation
o we can have a header saying how the Queue is used
o the implementation could use an array or a linked list to store the objects but we
wouldn’t know
o adding items to the Queue

loop through all the elements until the next pointer is NULL
add something to the end, pointing the NULL pointer at the new node
we could keep track of the last element in the list using a struct
connect the new object to the current tail
move the tail pointer to the new last object

o removing an item from the Queue


the only item that can be removed is the head

+ Stacks
o a ‘last in first out’ structure
o can put something on the top of a stack and take something off the top of a stack
o anything underneath cannot be accessed
o similar to how functions run
o Implementation
It can be a linked list or an array
Should be invisible to whoever includes the stack.h file
Keep track of where the top is with an int
o Array implementation
Data is stored in an array with a large maximum size
The top is a particular index which signifies where the data ends and is the
number of elements in the stack

Push and Pop


 Push should add an element after the end of the stack and then move the
top index to that new element

 Pop should return the element on the top of the stack and then move the
top index down one
o Linked list implementation
Add elements to the end
Remove elements from the same end
Push and Pop
 Push adds an element to the top of the list and top will then point at that
element

 Pop removes the top element and returns it then point at the next
element

You might also like