You are on page 1of 23

10/12/2022

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

1
10/12/2022

What does programming


What is a programming look like?
language?
Set of commands that a computer has been "taught" to Examples of an instruction to print the word 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 of C ANSI C

1978: A modern, comprehensive definition of


C
First edition of "The C Programming
Language" by Kernighan and Ritchie Established by an ANSI committee.

2
10/12/2022

C C

1988: C is a high level language

Second edition of "The C Programming must be converted to machine language


Language" by Kernighan and Ritchie before it can be executed.

Source file

The file containing your C code. C Programming


Compiler

The program which converts your


source code to machine language.

3
10/12/2022

C Programming C Programming

Consists of variables and functions.

We shall delve deeper into these later


These functions could be either

A function consists of a list of statements, either: functions that you write yourself or
single instructions that are part of the C functions that are provided with the C
language itself, or
language.
calls to functions

C Programming C Programming

ANSI C includes several libraries of functions


that are provided to programmers. To call such library functions, you must
tell the compiler which libraries you are
These libraries going to use.

provide important functionality and There must be a program that will


attach these libraries to your executable.
simplify programming.

4
10/12/2022

Summary of Tasks Undertaken


C Programming in Creating a C Program

The following are the tasks undertaken when you create a C


Linker program:

1. Edit
a program which combines libraries and
2. Preprocess
the machine code generated from a
program into a single executable. 3. Compile

4. Link
Normally a single programme does both
5. Load
compiling and linking.
6. Execute

1. Edit
4. Link
2. Preprocess

3. Compile

4. Link

5. Load 5. Load
6. Execute

6. Execute
Source: www.tutorialsspace.com Source: www.tutorialsspace.com

5
10/12/2022

Flow of C
Program
Execution

A C Program’s
Structure

Source: Horton, Beginning C

Objective

To explain the Hello World! Program


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

6
10/12/2022

Hello World!
Hello World! Explained
#include <stdio.h>
#include
main()
aka a preprocessor directive.
{ It tells the compiler to "include" text from
another file into your source code.
printf("Hello World!\n");
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.

7
10/12/2022

Hello World!
A C Program
Explained
int main

When you run a program, the operating


#include <stdio.h> system allocates this program the CPU.

/*tells the compiler that we are using The microprocessor starts at a specific
the stdio library, and that this library starting point.
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

The compiling is such that the first


A function is a set of instructions that
statement of the "main" function is
does ONE thing.
executed first.
C programs can have many functions. The statements following the first one are
then executed sequentially…
main() is the first (or primary) function.
UNLESS there are specific commands
It’s REQUIRED in every C program.
that change the flow of execution.

8
10/12/2022

Hello World!
A C Program
Explained

int main ()

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


integer function. parentheses.

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


integer value. depending on the function.

Hello World! Explained Hello World! Explained


Function Body Function Body
{
The function name comes first
}

Each function body is enclosed in curly Then its contents enclosed by { }


braces. These are the body: what is required to
The function’s statements are listed in perform the function’s job
between the curly braces.

9
10/12/2022

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
You don’t have to write the function
printf("Hello World!\n"); "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 printf(). This library consists of input and output
routines.
It displays information on the screen.
Used to print strings…

10
10/12/2022

Hello World! Hello World!


Explained Explained
printf() printf("Hello World!\n");
The parentheses encloses text, or a "string" The string is "passed" to the function as a
of characters. "parameter".
This statement is a call to a function called
Everything between the double quote
"printf"
characters (") is part of printf’s text
This function prints a string to output. string…

Hello World! Hello World!


Explained Explained
\n
printf("Hello World!\n");

\n is interpreted as a single special character… Causes the print routine to output an end-of-
line character to the monitor
the end-of-line character…
(or whatever the standard output of the
the one produced when you press the Enter key.
computer is).
It’s called a newline in C.
The next piece of output will start on the next
line.

11
10/12/2022

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 them This command sends the value 0 (zero)
and warn you about them. back to the operating system when the
main() function is done.
Thus they’re usually easy to catch.

12
10/12/2022

Hello World! Hello World!


Explained Explained
return;
C is flexible when it comes to whitespace.
The main() function must return a value.

Note: spaces, tabs, newline characters…

… pretty much anything you can’t see.


; still required even if this is the last
command in the program.

Hello World! Hello World!


Explained Explained
After saving the file;
Once you’ve created the source code file,
Compile it.
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.

13
10/12/2022

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

END OF LAB
below.

Because of the "\n" at the end of the string.

If it was omitted, the new command prompt


would be directly after the exclamation mark after
the words "Hello World!" on the screen.

Doesn’t look good.

The General Format of


a C Programme
Preprocessor Directives

Global Declarations The C Program


Structure
int main (void)

Local Declarations

Statements

Optionally other functions with similar structure to "main"

14
10/12/2022

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, Comments are not
the author,
compiled:
date,
program version, their syntax is NOT
algorithms, methods used …
checked.
/* This program displays natural
numbers from 1 to 10 */

15
10/12/2022

i. Documentation i. Documentation
Section Section
If not compiled, what’s the point of having them? Comments at the top of the
Several reasons - we use them to: program
describe what a particular variable is for,
provide information about the
describe the purpose of a function and how it program.
works,
document the name, version number, purpose, and The rest
programmer of an entire program,
explain any tricky or hard to understand parts of clarify the code where necessary
a program.

i. Documentation i. Documentation
Section Section
Two ways of commenting You’ll often see something like this for multiline comments:

in C: /*

* Author: WWW

/*..*/ for multiple line * Purpose: To show a multiline comment

comments * with many fancy stars.

// for single line * Language: C

comments */

The only syntactically required asterisks are the ones enclosing the
comment; the others are just for style.

16
10/12/2022

Readability

Crucial.
Two quick and simple ways:
Slight but related diversion…
1. Have a sensible amount of
comments.
Readability 2. Utilise
whitespace/indentations

Readability
Readability
1. Have a sensible amount of comments. 2.Whitespace/Indentations
Self-documenting code reduces the need for
comments. C ignores white space.
That is, code E.g. the compiler doesn’t care about
with a clear and clean structure and indentation.
meaningful identifiers Whitespace/Indentations are
E.g., for variables and functions components of code quality - they:
You wouldn’t need a separate comment to improve readability.
explain the purpose of a function called
add_two_numbers()
show dependencies.

17
10/12/2022

Readability/Dependencies
ii. Link/Header
Declaration Section
int main()

Has instructions to the


printf("Hello, World!\n");
vs
return 0;

} compiler:

int main(){printf("Hello, World!\n"); return 0;}


link the programmer’s
This runs. Sure. But. functions with files from the
It’s hard to see what is inside what. C library.
#include<stdio.h>
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> #include<stdio.h>
Notice the chevrons (angle brackets < >) Tells the preprocessor to look for the file in a
enclosing the stdio.h system directory (normally a standard
To include a file (using the #include library that contains C functionality - the
preprocessor directive), enclose the file one that is available to you when you install
the C programming language).
name in either
" " (double quote) tells the preprocessor to
<> for standard library files or
first look in the current directory for your
" " for the ones you've created yourself user defined header file i.e., the one that you
(user defined files). created yourself.

18
10/12/2022

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
take text from the header file stdio.h …
to 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
scanf() needed 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

19
10/12/2022

Header Files Header Files

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


function in the standard C library and
library
contain the information
It is declared in the necessary to use these
header file stdio.h. libraries

Header Files
Header Files
"contain the information necessary
#define -> macros (short form of
to use these libraries" …
"macroinstructions").
1.function prototypes (function symbols, names, or keys representing a
definitions/declarations for list of commands, actions, or keystrokes.
functions included in the libraries.
They are programmable patterns that
2.structure declarations translate a sequence of input into a
preset sequence of output.
3.typedef statements
Non C example: omw for On my way!
4.#define directives

20
10/12/2022

Header Files
C example: Header Files
#define square(x) ((x) * (x))
Are a software reuse technique.
int num = square(5);
/* Their names are in lower case
letters
is the same as writing:
int num = ((5) * (5)); C is case sensitive to their names
…which will declare an integer type Called "Header" files as they are
variable called num, and set its value to 25. usually at the top (head) of the
source file.
*/

ii. Link/Header ii. Link/Header


Declaration Section Declaration Section
This advance information is
#include<xxx.h>
known as:
When you include header files in your
program compiler directives or
you are giving the compiler advance preprocessor directives (this is
information
the most common name) or
on which library functions you will use
pre-information
and the relevant codes to be executed.

21
10/12/2022

iv. Global Declaration


iii. Definition Section
Section
Declare
any global variables here.
Define any symbolic variables used by more than
constants here. one function.
all functions you will define in
your program.

v. Main() Function vi. Subprogram


Section Section
Special function in C that is invoked
when you run a C program.
Any C program must have one and only
Contains the functions
one main() function in order to execute. you write (user-defined
This is where the program starts functions)
execution from.
It is the entry point to the program.

22
10/12/2022

Structure of a Note
Function All C statements are terminated with a semi colon.
The following are NOT considered to be statements:
int main() //defines a function the preprocessor directive e.g. when you are
including a library
the function header e.g. int main()
{ //specifies the beginning of a function
rather than being a statement of code, it defines
the function
the curly braces
} //specifies the end of a function
these specify the start and end of the function

23

You might also like