L2 - Basic C Elements

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

CS1010E Programming Methodology

Basic C Elements
The building blocks of C.

Lecture Overview

Overview of

Basic C Elements

C language
Run Cycle

Various Statements

Programming Styles

[ CS1010E AY1112S1 Le cture 2 ]

C Language: A brief history

C Programming Language

Originally designed by Dennis Ritchie in 1972


The 1978 book The C Programming Language

Standardized:

by Brian Kernighan and Dennis Ritchie


Gave the first specification of the language
in 1990: ANSI C ( ISO C, C89/C90 )
The most widespread version
Used in this course

Evolved:

in 1999: C99

[ CS1010E AY1112S1 Le cture 2 ]

C Language: Characteristics
C Programming language is a:
Compiled language

Program written in C (source code) must be compiled


into machine code (executable)
Using C Compiler

High Level Programming Language

Follow a set of rules (grammar) to express algorithm

General purpose language

Imperative language

[ CS1010E AY1112S1 Le cture 2 ]

Run Cycle for Compiled Language

Run Cycle:

The process of writing, compiling and


executing a program

Writing

Executing

Compiling

Tool: Editor

Tool: Compiler

Tool: None

Produce:
Source Code

Produce:
Executable

Produce:
Result

Compilation Error
Runtime Error
Logic Error
[ CS1010E AY1112S1 Le cture 2 ]

Environment and Tools in this Course

Environment:

Tools:

Cygwin: Emulate Linux (Unix-like) under


Windows

Editor: vim, nano, etc (You only need one)


Compiler: gcc (GNU C Compiler)

Comments and Rationale:

Tools look primitive but very flexible and powerful


Explicitly show the run cycle step by step

[ CS1010E AY1112S1 Le cture 2 ]

Run Cycle: Writing a Program

Use an editor to write a program following C


syntax

[ CS1010E AY1112S1 Le cture 2 ]

Using vim
editor under
cygwin
7

Run Cycle: Compiling the Source Code

Use a compiler to translate C Source Code


into Machine Code

Source code with syntax errors will fail to compile


Known as Compilation Errors

Using gcc
compiler
under cygwin

[ CS1010E AY1112S1 Le cture 2 ]

Run Cycle: Executing the Executable

The executable can be directly executed

May terminate unexpectedly due to errors

Runtime Error

May terminate successfully but give the wrong result

Logic Error

A successful
run of the an
executable
[ CS1010E AY1112S1 Le cture 2 ]

Run Cycle: A reminder

Run Cycle happens in the Implementation


step of the problem solving process

You should have designed the before you attempt


to write the program
Analysis

Writing

Compiling

Executing

Design
Tool: Editor
Produce:
Source Code

Tool:
Compiler
Produce:
Executable

Tool: None
Produce:
Result

Implementation

Testing

[ CS1010E AY1112S1 Le cture 2 ]

10

Your very first C Program

The famous Hello World! program

Simple program to show a message on screen

Preprocessor
Directive

#include <stdio.h>

int main( )
{
Main
function

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

function
body

[ CS1010E AY1112S1 Le cture 2 ]

11

C Elements: Preprocessor Directive


Specific instructions for the preprocesor
(part of the compiler)
SYNTAX

#directive_name [additional information]

USAGE

#include XXXX
Meaning:
Add the file XXXX for compilation
Example:
#include <stdio.h>

We will introduce other directives when we


encounter them in future

[ CS1010E AY1112S1 Le cture 2 ]

12

C Elements: Preprocessor Directive

Another commonly used directive

USAGE

#define Name Value


Meaning:
Substitute all occurrences of Name in the source
code with Value
Example:
#define MAXIMUM 5000

This directive is useful when:


There is a constant value used multiple time in the code
Allow easy modification in future
We will introduce other directives when we encounter them
in future

[ CS1010E AY1112S1 Le cture 2 ]

13

C Elements: The main Function

The main function is the starting point of


your program

SYNTAX

Execution starts from here


a special case of function (lecture 3)
int main( )
{
[0 or more statements]
return 0;
}

Caution:

C is case sensitive, e.g. Main is not the same as main


Pay attention to the braces: ( ) and { }

[ CS1010E AY1112S1 Le cture 2 ]

14

C Elements: Statements

Statements form the major element of a C


program:

Basically represent a step in algorithm

In this course, we categorise the C


statements as:
1.
2.
3.
4.

Declaration Statements
Assignment Statements
Function Call Statements
Control Structure (Control Flow) Statements

[ CS1010E AY1112S1 Le cture 2 ]

15

C Statement: Function Call Statement

Function Call Statement:

A Function:

SYNTAX

Use (invoke) a function


Is a well defined program unit that performs a task
can be predefined (already written) or user defined
more in lecture 3

function_name (

[function_arguments] );

Function arguments:
Information needed by the function to perform
the task

[ CS1010E AY1112S1 Le cture 2 ]

16

The printf() function: Brief look

The printf( ) function is a:

predefined function provided by C standard


library
defined in the <stdio.h> header file

Purpose:

SYNTAX

This is why we have the #include <stdio.h> directive


prepare and show a message on the output device
(usually your screen)

printf ( " message_to_be_shown " );

[ CS1010E AY1112S1 Le cture 2 ]

17

C Statement: Control-Flow Statement

Control flow statement changes the default


sequential execution of the program
There are a number of control flow statements
we have a return statement in the sample
program

Return Statement:
SYNTAX

return value;

Terminates the current function

Give (return) the value to the caller (user) of this function

[ CS1010E AY1112S1 Le cture 2 ]

18

Programming Style: The role of Spaces

White spaces:

Generally ignored by compiler, as long as:

space, empty line, tab

You place them between elements in the program


They are not part of a message (i.e. in between )

We use them to improve program readability


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

[ CS1010E AY1112S1 Le cture 2 ]

The same Hello World Program,


but a lot harder to read.

19

Variables and Arithmetic


Expressions

Problem: Area and Circumference of a Circle

Problem Description:

Given the radius R, calculate the area and


circumference of the corresponding circle

A simple algorithm:
1. Get the radius R from user
2. Area PI * R * R
3. Circumference 2 * PI * R
4. Print the result Area and Circumference

However, our C knowledge is not enough to


implement it at this point

[ CS1010E AY1112S1 Le cture 2 ]

21

C Statement: Declaration Statement

Variable:

A C variable is specified by:

Storage for temporary result (data) during execution

Identifier: Name of the variable


Data Type: Type of value stored in the variable

Visualization:

variable is like a box to store data

result
Identifier

[ CS1010E AY1112S1 Le cture 2 ]

12345

Actual Value
Data Type describe
what kind of value you
can find in the box
22

C Statement: Declaration Statement

Declaration Statement

Specify the information of a variable to the compiler


Variable must be declared before usage

SYNTAX

datatype identifier;
datatype identifier1, identifier2, ...;
datatype identifier = initial_value;

Data Type

int

Description
Integer (whole number) with no fractional part

double

Real number with fractional part

Other

To be covered later in the course

[ CS1010E AY1112S1 Le cture 2 ]

23

C Statement: Declaration Statement

Identifier:

Can be declared only once in a function


Must follow naming rule

Identifier Naming rule:

Consists of only letters, digits and underscores


Cannot begin with a digit
Cannot use keywords (words with special
meaning in C)

E.g. return, int, double,

Should not redefine identifiers defined in C library

[ CS1010E AY1112S1 Le cture 2 ]

24

C Statement: Declaration Statement

Examples:

Check for validity


Can you figure out the meaning?

double area;
double area, circumference;
double area = 0.0;
double area = 0.0, circumference = 1.0;
double 1area;
double area_of_circle;
double return;
double printf;
[ CS1010E AY1112S1 Le cture 2 ]

25

Programming Style: Meaningful Identifiers

Additional requirement when naming


identifier for readability:

The name should be short and meaningful


Identifier with multiple words should be avoided
If you must use identifier with multiple words, use
one of the following styles consistently:

Separate word with _ (underscore)

E.g. radius_of_circle

Capitalise the first letter of each word beyond the first:

E.g. radiusOfCircle

[ CS1010E AY1112S1 Le cture 2 ]

26

Programming Style: Declare Together!


In a function, you should place all the
declaration statements together before other
types of statements
SYNTAX

int main( )
{
[0 or more declaration statements]
[0 or more other statements]
return 0;
}

You can easily find out all the variable used


in a function at the top part of function in this
way

[ CS1010E AY1112S1 Le cture 2 ]

27

C Element: Assignment Statement

Assignment Statement:
The main way to change the value stored in a
variable

SYNTAX

variable = value;
variable = expression;

Execution:
1.

2.

Evaluate (calculate) the Right Hand Side


(R.H.S) to a single value V
Place V in the variable on L.H.S.

[ CS1010E AY1112S1 Le cture 2 ]

28

C Element: Assignment Statement

Simple Examples:

Assume variables are declared


area = 1.23;
result = x + y;
result = result + 4;

The expression can be quite complicated:


answer = (x + y) * 5 / 1.23;

Lets look at the expression in depth:

Operator
Precedence, Associative Rule and Bracket

[ CS1010E AY1112S1 Le cture 2 ]

29

Assignment Statement: Operators

Binary Operators:

Works on two arguments: arg1 op arg2


Example:

+, * (multiplication)
/ (dividision)
% (modulo, remainder, only for whole numbers)

Unary Operators:

Works on one argument: op arg1


Example:

+ (positive): +1
- (negative): -7.14

[ CS1010E AY1112S1 Le cture 2 ]

30

Assignment Statement: Operators

Operators are ordered by precedence:


+, -

Unary +, -

Remainder

*, /

Multiplication, Division

+, -

Addition, Subtraction

Operators with the same precedence are


ordered by associative rule
Binary Operator: Left Associative
a + b + c (a + b ) + c

Unary Operator: Right Associative


x- -y x (-y)

[ CS1010E AY1112S1 Le cture 2 ]

31

Assignment Statement: Brackets

Precedence and Associative rule can be


tricky:

It is best to avoid them

You can either:

Break a complicated expression into several


statements

OR, use brackets to avoid logical error

[ CS1010E AY1112S1 Le cture 2 ]

32

Assignment Statement: Conversion

Datatype conversion will happen automatically


during evaluation and assignment

Example:

Safe Conversion:

intVar = 1 / 2;
doubleVar = 1 / 2;
doubleVar = 1 / 2.0;

No information is lost during conversion


e.g. 123 123.0

Unsafe Conversion:

Information is lost during conversion


e.g. 123.45 123

[ CS1010E AY1112S1 Le cture 2 ]

33

Simple Input and Output


(I/O)

#include <stdio.h>

SYNTAX

You need to include the above header file in order to


use the function
scanf( "format_string" [, input_list] );

Example

HEADER

scanf(): Predefined Function for Input

scanf( "%d", &integerVar );

Placeholder to
indicate what
datatype to expect
from user
[ CS1010E AY1112S1 Le cture 2 ]

Variable to store the


value entered by user.
Note the (&) symbol.

35

scanf(): Predefined Function for Input

Placeholder:
%d

for integer value

%lf

for double floating point value

Variable:

Must match the datatype specified by the placeholder


Need a & symbol in front

A single scanf() can read in multiple values:


Example

Will be explained in lecture 6

scanf( "%d%d", &intVar1, &intVar2 );

[ CS1010E AY1112S1 Le cture 2 ]

36

SYNTAX

#include <stdio.h>

printf( "format_string" [, print_list] );

Example

HEADER

printf(): Predefined Function for Output

printf( "Answer is %d", intVar );

Note the usage of placeholder in the format


string

[ CS1010E AY1112S1 Le cture 2 ]

37

printf(): Predefined Function for Output

By using placeholder, we can show


computed values to the user:

Example

Value stored in a variable


Value evaluated by an expression

printf( "%d, %lf", intVar, 3.14 * 1.23);

Value stored in
intVar will be
printed

[ CS1010E AY1112S1 Le cture 2 ]

Result of this
expression will be
printed

38

printf(): Predefined Function for Output

Special Control Characters:

\n

go to newline

\t

jump to next tab

\\

to print out \

to print out (the double quote character)

Try it out:
Example

also known as escape sequence


mainly used to control the movement of cursor

printf( "To print \" you need to \\\"\n");

[ CS1010E AY1112S1 Le cture 2 ]

39

The Circle Program

1. Get the radius R from user


2. Area PI * R * R
3. Circumference 2 * PI * R
4. Print the result Area and Circumference

From Algorithm to Code

Convert the "Circle algorithm" to code:


#include <stdio.h>
#define PI 3.14159
int main( )
{
double radius, area, circumference;
printf( Enter Radius = " );
scanf( "%lf", &radius );
area = PI * radius * radius;
circumference = 2 * PI * radius;
printf( The area is %lf, Circumference is %lf\n",
area, circumference);
return 0;
}

[ CS1010E AY1112S1 Le cture 2 ]

41

C Elements: Comments

You can add descriptive messages in the


code for explanation and extra information
SYNTAX

// a single line comment

Comments are for humans only

/* a multiple
lines comment
*/

ignored by compiler

You can also comment off a chunk of actual code


to hide them from compilation

Useful when you are looking for errors in a big


program

[ CS1010E AY1112S1 Le cture 2 ]

42

Programming Style: Useful Comments

We expect you to write useful comments in


your code:

Explain a piece of complicated logic


Explain the purpose of a function (more on this
later)

Dont overdo it:

There is no need to comment on every line of


code
Excessive comment is actually bad programming
style

[ CS1010E AY1112S1 Le cture 2 ]

43

2. Another Example Program


preprocessor
directives

standard header file

constant
reserved
words
comments

variables
standard identifiers
special
symbols

punctuations
[ CS1010E AY1112S1 Le cture 2 ]

44

Problem 1: What time is it?

Problem statement:

Given a start time ST and end time ET, expressed


by the hour (0 to 23) and minute (0 to 59)
Show the total elapsed time (hour and minute)
between start time and end time

For simplicity:

You can assume that ST and ET are in the same


day, so ST is always smaller than ET

[ CS1010E AY1112S1 Le cture 2 ]

45

Summary
C Elements

Declaration Statements
Assignment Statements
- arithmetic expressions
Control Flow Statements
- return statement

Programming Style

Function Call statements


Use white space for readability
Place declarations before other type of
statements
Use meaningful identifiers
Use comments

[ CS1010E AY1112S1 Le cture 2 ]

46

You might also like