Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Basic

Terminologies
Computer

Programming Hardware

Intro Software

Program

Programming Language

A Computer
A device that is

programmable

electronic

What is a computer? and

accepts data and instructions via input


devices,

processes the data and

outputs information.
Software Software
2 main categories: Application software
System software
helps users to solve problems and
Application software
accomplish tasks.
System Software

provides a user interface and Examples:


tools which allow the user to access and use efficiently
word processors, spreadsheets,
different components of the computer.
calculators, messaging apps/social
Examples: operating systems, disk formatting programs,
compilers. media apps.

Hardware vs
Programming
Software
A computer program

Hardware? a set of instructions that when run cause the computer to behave
in a predetermined way.

the device. A computer programming language

is used to develop these instructions in a way the computer can


understand.

Software? In order to write a program, you must use a computer language.

Computer Programming

the instructions. writing instructions and giving them to the computer to


complete a task.

In short… In Binary (ANSI/ANSI/UTF-8) :


01001001 01101110 01110100 01110010 01101111 01100100 01110101
01100011 01110100 01101001 01101111 01101110 00100000 01110100
01101111 00100000 01010000 01110010 01101111 01100111 01110010
01100001 01101101 01101101 01101001 01101110 01100111 00100000
01001100 01100001 01101110 01100111 01110101 01100001 01100111
A computer program is a set of 01100101 01110011 00100000

instructions, written in a computer


programming language, which a
computer executes in order to
Introduction to
perform a specific task. Programming
Languages
Language Language
Can a painting or piece
of music "speak to
you"?
Will it say the same
A language is a structured means of thing to every person?
information exchange.
Will it say the same
thing to you, every
time?

Language Language
To be useful and reliable, a language must have
a well defined syntax and semantics.

Syntax:

Not all languages are "reliable" The structure and punctuation of the
means of communication. language.

Semantics:

The meaning of objects (words) and


combination of objects in the language.

Syntax Syntax
An Example using English An Example using English
Structure:
NOTE:
Sentences have a subject (who/what the
sentence is about) and a predicate In order to write a program, you
(information about the subject). must use a computer language.

Punctuation: If you get a "syntax error" in a


All sentences must have a terminating programming language, it is
symbol ( '.' '?' or '!') usually a punctuation error.

E.g.: Ali is reading.


Semantics Semantics
NOTE:
In a language, special symbols and
combinations of symbols have 'meaning'. Programming languages have special
An example using the English language: "reserved words" that have a specific
meaning within the language.
Ali is reading.
E.g.:
Ali —> A (male) persons name.
int
is —> Present tense state of being.
if
reading —> the process of extracting
meaning from a written or printed text.
while

Computer For successful


Programming computer programming
Let there be:
Computers do what we tell them to
Zero ambiguity in program
do, NOT what we want them to do
instructions
A programmer is a person who
Zero possibility of alternative
writes the required computer
interpretations
programs.
One and only one course of action

Programming
Language Levels
Programming Programming
Language Levels Language Levels
High level language instruction:
One Low level language instruction
machine language instruction = 1:M
translates to one instruction the
computer can understand Abstracts from low level processor
operations e.g. memory access
low level language
instruction:machine language User friendly
instruction = 1:1
Practically platform-independent

Evolution of 1GL/Machine
Computer Languages: Languages
1940’s – Machine Languages
What computers understand.
1950’s – Symbolic Languages
every program that you
1960’s through present – High-Level write will be translated to
Languages machine language before
it is executed by a
Present to Future – Natural
computer.
Languages

Strings of 1's
and 0’s stored
as binary
numbers
1GL 1GL

A machine language program can be The off state can be represented by 0


thought of as a stream of 0’s and 1’s. and the on state can be represented by 1.
The reason for this is that the internal Each 0 or 1 digit is referred to as a bit.
circuits of computers are made of
 A bit is a single 0 or 1 in binary code.
switches, transistors, and other
electronic devices that can be in one of A byte is a sequence of 8 bits.
two states… Each byte could also be represented
off or on. as a decimal number from 0 to 255.

CriticalPast. (2014, June 28). Women technicians work on an Electronic Numerical Integrator And
Computer (ENIAC)...HD Stock Footage [Video]. YouTube.

Videos

Early programming

CriticalPast. (2014, June 28). Women technicians work on an Electronic Numerical Integrator And
Computer (ENIAC)...HD Stock Footage [Video]. YouTube. https://www.youtube.com/watch?v=to-50Kydrj4

1GL (First Generation


Programming Language):
Machine Language
Initially…

Digital electronic computers


programmed directly in binary

via punched cards

plug-boards, or

front-panel switches.
1GL (First Generation
Computer
Programming Language):
Machine Language Languages
Later… At the lowest level computers are exchanging
information in binary format (0,1).
Programs written as sequences of Problem:
hexadecimal numbers. Combination’s of 0's and 1's can have
different meanings.
These were input via the terminals’
Depending on the "encoding scheme” used.
keyboards and monitors
E.g.:
Each hexadecimal digit represents a Assembly ! 00001001 ! (Use register 9)
four binary digit sequence. ASCII ! 00001001 ! (Tab character)

1GL (First Generation


Computer
Programming Language):
Languages Machine Language
We can use binary to communicate
if we agree on an "encoding". Lowest level: efficient use of main
An encoding is a like a memory
translation table.
Fastest execution
ASCII & ANSI are two related
ways to have 0's and 1's The computer is programmed in its
represent letters of the alphabet. own native machine code …
More, later.

1GL
2GL – SYMBOLIC
LANGUAGES
Complex and tedious to write.
Created in the 1950’s.
Practical only for very
The idea:
small programs.
have each type of instruction
Not portable. represented by some intuitive
Program for each processor code word, and
type. allow data to be represented
as decimal numbers.
2GL – SYMBOLIC 2GL – SYMBOLIC
LANGUAGES LANGUAGES
pushal 3(r2)
calls #2,SCANF
mull3 –8(fp),-12(fp)
Example 2:
pusha 6(r2)  Mov ax, 1
There are recognisable Mov bx, 2
words, numbers and some
Add bx
other symbols.

2GL: Assembly Language


2GL – SYMBOLIC A symbolic representation (mnemonics)
LANGUAGES of machine code.

Assembly language is a low- Simple mnemonic instructions that


level interface to CPU functions directly map to a sequence of
An assembler is a special program machine language operations e.g.:

used to translate symbolic code MOV moves data into a register


into machine code.
ADD adds the contents of two
Symbolic languages also became
registers together.
known as assembly languages.

1.1 General 1.1 General


Definition Definition
Assume You write the following code:

LDAA $80
you want to carry out a very
simple task LDAB $81

your system has no OS installed ADDB

STAA $55
you have MC 6800 computer
hardware What do these LOC do?
1.1 General 1.1 General
Definition Definition
LDAA $80 —> Loading the number at
memory location 80
We’re simply adding 2 numbers!
LDAB $81 —> Loading the number at
memory location 81 We considered memory locations
and used our hardware knowledge
ADDB —> Adding these two numbers
of the system.
STAA $55 —> Storing the sum to memory
location 55

2GL: Assembly Language 2GL: Assembly Language

Thus has plain natural language


(e.g. English) like words: Cons?

easier to read and write. Still very low-level.

more intuitive and easier to Not suitable for large-scale


program than machine programming.
languages

2GL: Assembly Language 2GL: Assembly Language


Not portable.

each processor has its own assembler


dialect
Assembly:m/c language hence a program for each
instructions still processor type.

approximately 1:1 There needs to be a different


assembly language for each type
of computer.
2GL: Assembly Language

Translators

Must be translated into machine code by


a separate program:

the assembler.

Translators:
Translators
A Simple Summary:

Assembler: a program that takes


basic computer instructions
(Assembly Language) and converts
them into a pattern of bits.
Languages higher than 1GL must be
translated.

Translators:
A Simple Summary:
Compiler: takes input and produces
output:

input: the high level language


source code
Assembler Analogy:
I need to communicate information to two people, McA
(machine A:) and McB output: the machine language code
Each speaks a different language from each other, languages (object code) for the machine on
that I don’t understand.
These two people have their own translators (AsA and AsB) that which it is to be executed
only understand the language I speak and that of their
respective employers.
Class Task

11 volunteers

2 groups: 5 + 6
Compiler Analogy:
I need to communicate information to two people, McA (machine A:) and
Group 1: assembler analogy
McB.
Each speaks a different language from each other, languages that I don’t
understand.
Group 2: compiler analogy
These two people have their own translators (AsA and AsB) that only
understand the language I speak and that of their respective employers.
I get an international multilingual translator CompA2Z, who has access to
AsA and AsB.

Translators:
A Simple Summary:

Interpreter: same as the


Video
compiler except it
translates and executes the
program line by line. Interpreters and Compilers
An animation explaining the difference between
interpreters and compilers.

Translators
A Deeper Delve
Translators Translators
A Deeper Delve A Deeper Delve
Compiling: 3 steps:

1. The compiler translates a program


written in a high level language to a 2. The assembler then translates this
machine-specific assembler language to machine code (object code).

- i.e. low-level machine dependent


instructions.

Translators Translators
A Deeper Delve A Deeper Delve
Compiler Summary:
3. The linker merges object code
Compiler: High Level to Assembly
produced from all the source files Language
composing the program with any
libraries code included in the Assembler: Assembly to object code (m/
c)
program to form a binary
“executable image” of the program. Linker: Object code + library =
executable file

Compile|Link/Load|Execute
A Summary

A compiler generates an intermediate file:


the object file.

A linker combines the object file with built-


in library files (and other user-generated
object files) to make a single executable
file.

The loader loads the executable program


(binary program) into memory for execution.
Translators Translators
A Deeper Delve A Deeper Delve
FYI
Interpreter
Compiled code is typically fastest,
Translates on the fly.
interpreted code is highly portable
First reads a high-level instruction
and quick to implement and test, and
Then executes the necessary set of
a virtual machine is fast and
low-level operations.
portable (best of both).

Translators
Task
A Deeper Delve
Before our next class…
Watch this video: The Java Virtual
Watch video:
Machine and Compilers Explained
The Art of Writing Software
https://www.youtube.com/watch?
v=XjNwyXx2os8 https://www.youtube.com/watch?
v=QdVFvsCWXrA

Objectives
To describe the pros/features of C

LAB
To explain what an IDE is

To create and run your first


program

To edit, build, compile and


execute a program.
The C programming language
C

1972: Dennis Ritchie creates first version


of C

1978: The first edition of “The C


Programming Language” by Kernighan
and Ritchie is published.

C C
1983-1988: A committee of the American
National Standards Institute (ANSI) establishes a
A language that is:
modern, comprehensive definition of C. portable,
Commonly known as ANSI C.

1988: The second edition of “The C


high level,
Programming Language” by Kernighan and structured,
Ritchie is published.
general purpose
imperative.

The C Programming Language


A general-purpose programming language

used to write programs in various


domains

operating systems, numerical computing,


graphical applications etc…

It is a small language

only 32 keywords/reserved words


C Language Keywords (Reserved Words)
e.g. int, float, for, while …
C Features/Pros C Features/Pros
It has many low level capabilities
One of the most widely used programming
e.g. it provides low level access to memory
languages.
C’s constructs map efficiently to typical m/c
Used on all types of computers language instructions

General purpose thus good for progs previously implemented in


assembly language.
Was used to write Linux
Popular for programming embedded systems
Good for writing compilers, drivers, word
Their programs must be efficient
processors, spreadsheets, cellphone apps etc.
e.g. they should utilise minimal memory.

C Features/Pros C Features/Pros
Programmer oriented: you have access to low level
functionalities e.g. you can manipulate the memory.
Is a subset of C++. Hence it’s compact, efficient, and fast … but also
dangerous
Is compact, readable and writable
It’s portable.

A core skill when seeking Some systems come with the C compiler built in.

employment Includes many operators

bit manipulation operators

C Features/Pros How to Write C


Ships with a large library

Is powerful.
Type the instructions using:
E.g. you can easily use it to e.g.:

develop movies’ special effects a text editor (e.g. Notepad)

solve physics and engineering problems. an IDE’s text editor


It’s flexible and used for writing general
purpose applications.
IDE
A common programming platform that …

allows the coder to invoke all the operations


Integrated Development necessary to develop a program:

Environment (IDE) editing,

compiling,

linking

program execution.

IDE IDE Examples


TURBO C/C++,

Microsoft Visual C++ (MSVC),


Make it easier for the coder to
debug the program: CODE::BLOCKS (free C/C++ and Fortran IDE at
https://www.codeblocks.org)
They provide help facilities
Dev-C++ (www.bloodshed.net)
through menu selection.
NB:

CODE::BLOCKS and Dev C++ are compact, free


and come with the MinGW Compiler

How to Write C Coding Online


Many online editors and compilers

When typing instructions… to write and execute your code


even from your phone.
Use the correct syntax
For instance:
Save as a .c file.
https://www.jdoodle.com/c-online-
compiler/
Using the Code::Blocks IDE Using the Code::Blocks IDE
The BUILD and COMPILE The BUILD and COMPILE
Phases Phases
Create a new project.

File > New > Project Get rid of the sample file (main.c).

Console application > C language Under the Projects tab:


Give it the name my_1st_project
open Sources,
Note: a project has a .cbp extension.
right click main.c and
Use the default configurations (the compiler
should be GNU GCC Compiler)
select Remove file from project.
Finish

Using the Code::Blocks IDE Using the Code::Blocks IDE


The BUILD and COMPILE The BUILD and COMPILE
Phases Phases
Create a new file in the project: Save the empty file as my_1st_prog.c

Still under the Projects tab: Don’t omit the extension (.c)

Select the project Ensure the “Files of type:” is C/


C++ files
File > New > Empty files (or
Ctrl+Shift+New) If asked to select the targets the file
should belong to click OK if both
Add it to the active project Debug and Release are checked.
Using the Using the
Code::Blocks IDE Code::Blocks IDE
Build > Build (or Ctrl + F9). Still in the output window, select the Build log tab.

The compile command is [name of compiler] (e.g.,


compiles and links the source file mingw32-gcc.exe) with some compiler flags.
you’ve created.
The command’s input is my_1st_prog.c - the source
file.
Check the output window (usually at the
bottom of screen). It links this input and compiles and generates
(my_1st_prog.o) - the object file.
You are building the project with its The output is my_1st_prog.exe - the executable file
one file. (i.e., the file that runs).

Using the Using the


Code::Blocks IDE Code::Blocks IDE
You can now run the program.
Press any key to close the output
Build > Run (or Ctrl + F10)
console window.
When asked if you want to build the
project, select No. File > Close Workspace

If you select Yes it will repeatedly Do not save your work.


ask if you want to build the project.
There’s nothing to save!
You will be taken to the console output.

Hello World!
Create a new project called hello_world.

File > New > Project > Console application

Our First (Real) Get rid of the main.c file that is automatically created for
you.

Program In Sources, under the Projects tab.

Create your own source file named hello_world.

File > New > Empty File

Type the code on the next slide …

PS: Indent as demonstrated


Hello World! Hello World!
#include <stdio.h> Build > Build (or Ctrl + F9).

int main() compiles and links the source file


you’ve created.
{
Check the output window (usually at the
printf ("Testing testing!”); bottom of screen).

return 0; You are building the project with its


one file.
}

Hello World! Hello World!


The compile command is [name of Run the program.
compiler] e.g., mingw32-gcc.exe with some
Build > Run (or Ctrl + F10)
compiler flags.
What do you get?
The command’s input is hello_world.c
which it links and compiles and generates The output Testing testing! is displayed on
the object file (hello_world.o). the standard output stream

The output is hello_world.exe which is the (aka the console/terminal/command line


executable (the file that runs). interface).

Hello World! Hello World!


The build log window displays the command
Change the output to display this message: Hello
that was used to run the executable file.
World!

It will also show any compilation errors. (Hint: modify the printf() statement).

Note Compile, link and execute the program.

From now henceforth you can simultaneously


When your program has an error the Build and run (F9)
status returned is not 0 (not zero).
The words Hello World! should display on the
(cf “Process terminated with status console window.

0”)
/* First C program: Hello World

A program that displays text to the screen*/

// Created by [insert your name] on [today’s date].

// Copyright © 20XX [your class]. All rights reserved.

#include <stdio.h>

int main()
Edit, Recompile…
{

printf("Hello, World!\n”);

return 0;

Edit, Recompile… Edit, Recompile…

change printf to pirntf

Change the words Hello, World! to Build and run.


Goodbye, World!
What happens?
What happens?
Check the build log messages in the
output window.

Edit, Recompile… Edit, Recompile…

When you have errors, simply:


Delete the last curly brace.
Edit your source code
What happens?
Recompile/Rebuild
Once more check the build log
messages in the output window.
Run
Edit, Recompile…

Again:

Edit your source code Dealing with Errors


Recompile/Rebuild

Run

Dealing with Errors


Create a new program

in a new project error.cbp

aka Debugging Name your source file error.c

Type the 6 LOC on the next slide exactly as


is.

Ensure they are 6 LOC with no spaces


between them.

#include <stdio.h>
Dealing with Errors
int main()

{
Compile/build it
printf(“Oh no! Error! :( \n”)
Run it.
return 0;

}
Dealing with Errors Dealing with Errors

Sample error message:


You will get an error message.
error.c: In function `main’:
Depends on the IDE you’re using.
error.c:5: parse error before “return”

Dealing with Errors


Whatever your compiler, you can piece together some
information:

error.c: In function `main’:

??!! error.c:5: parse error before “return”

error.c: the source code file with the error

Line 5: the problematic line (hopefully!)

a parse error or syntax error etc: The type of error

before [the word] return: the error’s location

Dealing with Errors Dealing with Errors


error.c:5: parse error: also useful

very useful message! A parse/syntax error —> incorrect C


punctuation.
Tells you the error is in line 5.

Not exactly though (it’s actually in line 4)… A semi-colon is missing hence two
statements ran into each other.
The compiler doesn’t realise something is
wrong until Line 5. No semicolon at the end of Line 4.
Dealing with Errors Dealing with Errors
With Code::Blocks:

Line 4 has a big red block to its left With Xcode:


The Build log has the following message:

… error: expected ';' before ‘return’ Line 4 is highlighted with the


following message:
printf(“Oh no! Error! :( \n”) ^

; Expected ';' after expression

return 0;
Very friendly :)
Very friendly :)

Dealing with Errors Helpful Hints


Edit your source code:
Every programmer gets errors.
Insert the missing semi colon

Change In C, missing semicolons are the


printf(“Oh no! Error :( \n”) most common.
To
Always sort the first error listed
printf(“Yes! No more errors! :) \n”);
and then recompile.
Recompile/Rebuild

Run You may be lucky.

#include <stdio.h>
Dealing with Errors int main()

printf(“Oh no! Error! :( \n”);


In the error.c file,
retun 0;
Change lines 4 and 5 as per the
next slide: }

Note the spelling of the word “return”


Dealing with Errors Dealing with Errors
C assumes that retun is not a typo.

The compiler ignores it.


Save
However, the linker checks its libraries for
retun.
Compile/build it
It comes up with nothing.
Run it.
Thus it catches the error

The linker gives an error message…

Dealing with Errors Dealing with Errors


E.g.: You may get:

Line 5 is highlighted. temporary_filename.o: In function ‘main’:

Code::Blocks: temporary_filename.o: undefined


reference to ‘retun’
‘retun’ undeclared (first use of this
function)
Or:
Xcode’s Error Message:
temporary_filename.o(etc):error.c:
Use of undeclared identifier ‘retun’ undefined reference to ‘retun’

Dealing with Errors Dealing with Errors


Linker errors harder to understand Some IDEs:
than compiler errors.
temporary_filename.o:
E.g. for this program, for some IDEs the
linker shows the error refers to retun. The compiler

May not show the line number. creates a temporary object code
(.o) file
In such a case, just search for the
incorrect text. deletes it
Types of Errors

Syntax/Compiler

Types of Errors Linker

Runtime

Logical

Types of Errors Types of Errors


Compiler errors: Linker errors involve:

Mainly misspelled commands.


The most common error
Missing modules:
Discovered by the compiler as it translates
if you have a large program with several source files or
modules
Easy to find
Inability to link files:
self-explanatory e.g. with line numbers
If the linker requires and can't find a library file

The program is NOT built before the errors are Pieces of the program are built, but errors prevent them
caught being merged.

Types of Errors Types of Errors


Run-time errors:
Logical errors:
Generated by the program when it runs.
The compiler builds the program, it
The compiler/linker don’t catch them.
runs, but…
E.g.:

a null pointer assignment (common error).


The program does unintended
things.
The program is built and will run, but:

will probably be shut down by the OS Usually the hardest to resolve.


Delve Deeper into
Errors
r

Task

Visit the following site, that also gives example code


https://www.geeksforgeeks.org/errors-in-cc/

END OF LAB Translation… (cont)

Back to the Source Code to Execution Process

The C source code-to- The C source code-to-


execution process execution process
A Summary A Summary

The programmer (aka the coder)


.obj object files are passed to the
creates .c source files
linker/loader.
These are passed to the compiler
If there are no errors, the linker
includes all necessary library files
If there are no errors a .obj object
to produce .exe executable files ().
file is generated.
The C source code-to-
execution process
A Summary

The .exe file is loaded into the


memory. & Loader

It is executed by the user whenever


they need to perform their tasks.
The C source code-to-execution
process…
A Summary

High Level High Level


Languages Languages
Clearer program algorithmic
structure:
Introduced in the 1950’s and 60s.
there are mechanisms that make it
E.g. Fortran and Algol. easier to understand program flow

(i.e. the order in which the


instructions are being executed).

High Level High Level


Languages Languages
Mechanisms allowing easier
understanding of program flow: The mechanisms are an abstraction
of the underlying machine
subroutines instructions

conditional looping constructs. They are not tied to any platform


==> portability.
As opposed to spaghetti code.
High Level High Level
Languages Languages
Increased programmer productivity
Compiled (e.g. C, C++) or hence time saving
interpreted (e.g. Matlab, Python).
ratio of High to Low level LOC =
The higher the level —> the more 1:M
efficient, faster and user friendly.
—> fewer lines of code/less effort)

High Level High Level Languages:


Languages 3GL

Code modules can be designed to


More human programmer friendly
“plug” together piece-by-piece
Transition between assembly and
large programs can be built out of
natural languages.
small, comprehensible parts.

High Level Languages: 2GL vs 4GL


4GL An Assembly Language program that adds 10 data
bytes. Data is stored in the memory location that
To select all columns
starts from 4460H. The result is 8 bits only and
in stored in 4480H.
from a table called
LXI H, 4460H ; (HL register pair points at memory
location 4460H)
Students for rows
MVI C, 0A H ; (Sets up a decrement counter)
Non-procedural languages MVI A, 00H ; (Clears Accumulator)
where the Last_Name
MOV B, M ; (Moves content of memory location to column has Onyango
B)

ADD B ; (Adds A and B and stores result at A)


for its value:
INX H ; (HL pair points at M+1 memory location)

See next slide … DCR C ; (Decreases C counter by one)


SELECT * FROM
JNZ jump1: ; (Until C is not control jumps
to jump1:)
Students WHERE
STA 4480H ; (Stores result at 4480H (when C=0))

HLT ; (Terminates the program)


Last_Name = ‘Onyango';
High Level Languages: High Level Languages:
4GL 5GL
Non-procedural language Based on AI.
English like sentences
The ideal situation is humans using natural
Closer than 3GLs to human languages to communicate with computers.

language, form of thinking and conceptualisation. We could just tell the computer what to do
using natural language, and it would do it.
Portable and easily expandable
A lot of interest and research into Natural
Designed to reduce the overall time, effort and cost of
Language Processing.
software development.

Examples include query languages for extracting data E.g. Prolog, OPS5 and Mercury
from databases, data warehouses and big data.

High Level Languages: High Level Languages:


Pros Pros

More user friendly More powerful instructions;


Simpler to understand and use
each may translate to several
machine language instructions.
needs less programming time
Portable
easier to develop a program

High Level Languages: High Level Languages:


Cons Examples
FORTRAN C

COBOL C++
Slower
PL/I LISP
Need more resources
BASIC Prolog

PASCAL Logo

Name 1o others.
C Sidenote…
On the one hand…

The C language supports assembly language.


Sidenote on C We can access memory directly (using
pointers)

C has “low-level” capabilities.

E.g. we can manipulate bytes and addresses.

C Sidenote… C Sidenote…
On the other hand…

C supports high level language features Though C is categorised as a high


level language…
It has structured programming
constructs. it is easy to create machine code
using C.
E.g. statement grouping, decision
making, and looping.

C Sidenote… C Sidenote…

Hence, C is sometimes aka a middle Mid-level languages


level language
provide some high-level
abstractions to make the
It bridges the gap between
programmer's life easier,…
traditional machine/assembly
languages and conventional high
while still providing access to
level languages.
low-level operations.
C Sidenote… C Sidenote…
They are often used to write operating
systems Mid-level languages

hence aka system programming C is an example.


languages.
So are:
Programs written in mid-level languages
can perform as well, or nearly as well, as C++, Ada, Nim, and Rust.
programs written in assembly language.

LAB Programming in C

What is programming?
Series of instructions to a computer to
accomplish a task
Revision
Instructions must be written in a way the
computer can understand

A few reminders Programming languages are used to write


programs
What does programming 

What is a programming look like?
language? Examples of an instruction to print the word
Set of commands that a computer has been “taught” to HI
understand Logo PR [HI]
JavaScript alert(“HI”);
Some are low level e.g. FORTRAN PRINT “HI”
82A8: jsr r5,@#82AE 82AC: sob r0,8296)
BASIC PRINT “HI”
COBOL DISPLAY ‘HI’.
High level languages look like English C++ printf(“HI”);
PRINT “HELLO”
Pascal WRITELN(‘HI’);
Assembly Language XPRNT MESSAGE1
MESSAGE1 DC ‘HI’

C C
1972:
1983-1988:
Dennis Ritchie creates first version
ANSI C
of C
A modern, comprehensive
1978:
definition of C
First edition of “The C Programming
Established by an ANSI committee.
Language” by Kernighan and Ritchie

C C

1988:
C is a high level language
Second edition of “The C
must be converted to machine
Programming Language” by
language before it can be executed.
Kernighan and Ritchie
C

Source file

The file containing your C code.


C Programming
Compiler

The program which converts your


source code to machine language.

C Programming C Programming
Consists of variables and functions.
These functions could be either
We shall delve deeper into these later

A function consists of a list of statements, functions that you write yourself


either: or
single instructions that are part of the C
functions that are provided with
language itself, or
the C language.
calls to functions

C Programming C Programming
ANSI C includes several libraries of
To call such library functions, you
functions that are provided to
must tell the compiler which
programmers.
libraries you are going to use.
These libraries
There must be a program that will
provide important functionality and attach these libraries to your
executable.
simplify programming.
C Programming
Linker

a program which combines libraries A C Program’s


and the machine code generated
from a program into a single Structure
executable.

Normally a single programme does


both compiling and linking.

Objective

To explain the Hello World! Program


Hello World!
To clearly describe the general
Explanation
format of a C programme

Hello World!
Hello World! Explained
#include <stdio.h> #include

main() aka a preprocessor directive.

{ It tell the compiler to “include” text


from another file into your source
printf(“Hello World!\n”); code.

} Else you will have errors.


Hello World! Hello World!
Explained Explained
<stdio.h>
#include <stdio.h>
A filename.
Tells the compiler to
.h as it’s a “header” file.
copy text from the file STDIO.H and
Contains information about STanDard Input/
Output functions.
insert it into your source code…
These functions are required by most C
programs. … before the source code is compiled.

Hello World!
A C Program
Explained
int main

When you run a program, the operating


#include <stdio.h>
system allocates it the CPU.
/*tells the compiler that we are
The microprocessor starts at a specific
using the stdio library, and that
starting point.
this library should be linked to our
executable. */ In all C programs, the starting point is
the main() function.

Hello World! Explained



A C Program
Function Body
A function is a set of instructions The compiling is such that the first
that does ONE thing. statement of the “main” function is
executed first.
C programs can have many functions.
The statements following the first
main() is the first (or primary) one are then executed sequentially…
function.
UNLESS there are specific commands
It’s REQUIRED in every C program. that change the flow of execution.
Hello World!
A C Program
Explained
int main ()

int identifies the function main as In C, functions are followed by


an integer function. parentheses.

On completion, main() must return The parentheses may be empty,


an integer value. depending on the function.

Hello World! Explained
 Hello World! Explained



Function Body Function Body
{
The function name comes first
}
Then its contents enclosed by { }
Each function body is enclosed in
curly braces.
These are the body: what is required
to perform the function’s job
The function’s statements are listed
in between the curly braces.

Hello World! Hello World!


Explained Explained
main()

printf(“Hello World!\n”); Here, the entire function consists of


just one statement:
}
printf(“Hello World!\n”);
/*Every C program contains at least one
function called “main”.

A function is a list of statements, including calls


to other functions.*/
Hello World! Hello World!
Explained Explained
printf(“Hello World!\n”); You don’t have to write the function
“printf()” yourselves.
printf is the name of a C language
function. It is provided as part of a library

Since it’s a function, write it as This library consists of input and


printf(). output routines.

It displays information on the screen. Used to print strings…

Hello World! Hello World!


Explained Explained
printf() printf(“Hello World!\n”);

The parentheses encloses text, or a The string is “passed” to the


“string” of characters. function as a “parameter”.
This statement is a call to a function
Everything between the double quote
called “printf”
characters (“) is part of printf’s text
This function prints a string to output. string…

Hello World! Hello World!


Explained Explained
printf(“Hello World!\n”); \n
\n is interpreted as a single special
Causes the print routine to output an
character…
end-of-line character to the monitor
the end-of-line character…
(or whatever the standard output of
the one produced when you press the
Enter key.
the computer is).

It’s called a newline in C. The next piece of output will start on


the next line.
Hello World! Hello World!
Explained Explained
; It informs the C compiler where to
separate statements.
The semicolon is C language
punctuation. All C statements require
semicolons…
If omitted —> compile error.
Even if it’s a one statement
It’s a terminator… program/function.

Hello World! Hello World!


Explained Explained
Forgetting semicolons = one of the
most common errors you’ll make. return

Fortunately, compilers easily detect This command sends the value 0


them and warn you about them. (zero) back to the operating system
when the main() function is done.
Thus they’re usually easy to catch.

Hello World! Hello World!


Explained Explained
return;
C is flexible when it comes to
The main() function must return a whitespace.
value.
spaces, tabs, newline characters…
Note:
… pretty much anything you can’t
; still required even if this is the see.
last command in the program.
Hello World! Hello World!
Explained Explained
After saving the file;
Once you’ve created the source code,
Compile it.
file, execute it.
Execute it
When naming your files, use the
extension .c e.g. “hello_world.c”. The words “Hello World!” should be
printed on one line.

Hello World!
Explained
The new command prompt will be on the
line below.

Because of the “\n” at the end of the string.

If it was omitted, the new command prompt


END OF LAB
would be directly after the exclamation
mark after the words “Hello World!” on the
screen.

Doesn’t look good.

Assignment 2 (10 Marks)


• You now want the words “Hello World!” to be
printed to the screen three times instead of once.
• That is, each instance is on it’s own line:
– Hello World!
Assignment – Hello World!
– Hello World!
• With C, there are often multiple ways to solve the
same problem.
• Use only what we have learnt so far to solve this
problem.
234
Assignment 2 (10 Marks)
• In the same groups as Assignment 1: Assignment 2 (10 MARKS)
• Provide two possible solutions.
• Type the code for the first solution into an IDE of your choice Summary of documents you will send to my email:

(e.g. Dev C++/Code::Blocks) file. 1. A spreadsheet named [CourseCode]Prog Group Members


• Save it as hello_world_1.c.
2. A C file named hello_world_1.c
• Type the code for the second solution.
A second c file named hello_world_2.c
• Save it as hello_world_2.c. 3.

• Send both a spreadsheet with your member details and the REMEMBER

two .c files to my email address, latest one day before our 1. Send these documents to my email address latest one day before our
next class. next class.
• The subject of the email must be [CourseCode]Prog The subject of the email must be [CourseCode]Prog Assignment2
Assignment2
2.

235

The General Format


of a C Programme
Preprocessor Directives

Global Declarations

int main (void)


The C Program
{
Structure
Local Declarations

Statements

Optionally other functions with similar structure to


“main”

The C Program
Structure

i.e.:

the main components of a C


program and

how they are organised.


i. Documentation i. Documentation
Section Section
Comments

e.g. program name,

the author,
Comments are not compiled:
date,

program version, their syntax is NOT checked.


algorithms, methods used …

/* This program displays natural numbers from 1 to


10 */

i. Documentation i. Documentation
Section Section
If not compiled, what’s the point of having them?
Comments at the top of the program
Several reasons - we use them to:

describe what a particular variable is for, provide information about the


describe the purpose of a function and how it works, program.
document the name, version number, purpose, and
programmer of an entire program,
The rest

explain any tricky or hard to understand parts of a


clarify the code where necessary
program.

i. Documentation
Section

Two ways of commenting in C:


Slight but related diversion…
/*..*/ for multiple line
comments

// for single line comments Readability


Readability Readability
1. Have a sensible amount of comments.

Self-documenting code reduce the need for


Crucial. comments.

That is, code


Two quick and simple ways:
with a clear and clean structure and
1. Have a sensible amount of
meaningful identifiers
comments.
e.g., for variables and functions
2. Utilise whitespace/indentations
You wouldn’t need a separate
comment to explain the purpose of a
function called add_two_numbers()

Readability/Dependencies
Readability int main()

printf("Hello, World!\n");
2.Whitespace/Indentations vs
return 0;
C ignores white space.
}
E.g. the compiler doesn’t care about indentation.

Whitespace/Indentations are components of code int main(){printf("Hello, World!\n"); return 0;}


quality - they:
This runs. Sure. But.
improve readability.
It’s hard to see what is inside what.
show dependencies.
i.e., which statements are inside this function?

(remember a function can have many statements)

ii. Link/Header ii. Link/Header


Declaration Section Declaration Section
#include<stdio.h>
Has instructions to the compiler:
Notice the chevrons (angle brackets < >) enclosing the stdio.h

link the programmer’s functions To include them (using the #include preprocessor directive),
enclose the file name in either <> for standard library files or " "
with files from the C library. for the ones you've created yourself (user defined files).

tells the preprocessor to look for the file in a system directory


(normally a standard library that contains C functionality - the one
#include<stdio.h> that is available to you when you install the C programming
language).

Notice the chevrons (angle " " (double quote) tells the preprocessor to first look in the current
directory for your user defined header file i.e., the one that you
brackets < >) enclosing the stdio.h created yourself.
ii. Link/Header ii. Link/Header
Declaration Section Declaration Section
#include<stdio.h> #include<stdio.h>

Basically instructs the compiler to


An instruction to the compiler to
take text from the header file stdio.h …
link your program with pre-written
IO functions e.g.: place it into your source code …

before the source code is compiled.


printf()
stdio.h has standard I/O information needed
scanf() by most C programs.

Most of C’s functionality comes from


libraries.

The standard library is a set of functions e.g.:

printf(),

Header Files scanf(),

clrscr(),

getch().

It’s available on all systems conforming to the


ISO C standard

Header Files Header Files

printf() is an inbuilt function in the are .h files defined in the C library


standard library and

It is declared in the header file contain the information necessary


stdio.h. to use these libraries
Header Files Header Files
“contain the information necessary to use these
libraries” … #define -> macros (short form of
“macroinstructions”).
1.function prototypes (function definitions/
declarations for functions included in the symbols, names, or keys representing a list of
libraries. commands, actions, or keystrokes.

2.structure declarations Non C example: omw for on my way!

3.typedef statements C example:

4.#define directives #define square(x) ((x) * (x))

int num = square(5);

ii. Link/Header
Header Files
Declaration Section
Are a software reuse technique. #include<xxx.h>

When you include header files in your


Their names are in lower case
program
letters
you are giving the compiler advance
C is case sensitive to their names information

on which library functions you will use


“Header” files as they are usually at
the top (head) of the source file and the relevant codes to be executed.

ii. Link/Header iii. Definition


Declaration Section Section
This advance information is aka:

compiler directives
Define any symbolic constants here.
preprocessor directives

pre-information
iv. Global v. Main() Function
Declaration Section Section
Declare Special function in C that is invoked
when you run a C program.
any global variables here.
Any C program must have one and only
variables used by more than one one main() function in order to execute.
function.
This is where the program starts
execution from.
all functions you will define in
your program. It is the entry point to the program.

vi. Subprogram Structure of a


Section Function
int main() //defines a function

Contains the functions you write


{ //specifies the beginning of a function
(user-defined functions)

} //specifies the end of a function

Note
All C statements are terminated with a semi colon.

The following are NOT considered to be statements:

the preprocessor directive e.g. when you are including a


library

the function header e.g. int main()

rather than being a statement of code, it defines the


function

the curly braces

these specify the start and end of the function

You might also like