First Program Compilation and Execution Simplifying Fractions Loops If Statements Writing...

100
Fundamentals First Program

Transcript of First Program Compilation and Execution Simplifying Fractions Loops If Statements Writing...

Page 1: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

FundamentalsFirst Program

Page 2: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Fundamentals

Compilation and Execution Simplifying Fractions

Loops If Statements Writing functions

Variables Operations Using Functions Errors

Page 3: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Running a C Program

C programs consist of a series of instructions written in using the C syntax Usually broken down into a number of

functions▪ And often in different files

A C program needs to be translated into something that a computer can understand This process is called compiling A compiler translates high-level language

code into machine code

Page 4: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Processing a C Project

Source File (.c)

write in a text editor

correct errors

compile Object File (binary)

Other Object Files

Executable File (binary)

testsyntax errors

linker links files

Debugged Executable

link errors

run-time and logic errors

Page 5: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Command Line Compilation

Most OSs include C compilers and allow a program to be compiled and run

To compile and run a program in Linux follow these steps Write the program using a text editor Compile the program using the gcc

compiler Run the program created by compilation

by typing its name

Page 6: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Linux Compilation Example

Assume that we’ve made a C file named test.c

Open a Terminal window in Linux At the command prompt type

gcc –o test test.c▪ The –o switch (or flag) tells the compiler to

name the object file that is being created test▪ test.c is the name of the file to be compiled

To run the newly created file type ./test

Page 7: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Errors

In reality if we’ve just finished writing our first C file it will fail to compile Because it contains compilation errors That is, mistakes in C syntax

The compiler will print a list of errors That we can then fix

More on this later ...

Page 8: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

IDEs

An alternative to using the Terminal to compile programs is to use an IDE Integrated Development Environment

An IDE combines a text editor, a compiler, a debugger and (many) other tools There are many IDEs▪ Visual Studio (Windows)

▪ Code::Blocks (cross-platform)

▪ Xcode (Mac OS)

▪ Eclipse

Page 9: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Simplifying Fractions

Page 10: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Simplifying Fractions

Assume we want to simplify fractions 4/16 =▪ 1/4

105/135 =▪ 7/9

To simplify a fraction Find the greatest common divisor (gcd)

of the numerator and denominator Divide numerator and denominator by

the gcd

Page 11: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Requirements

Saying that "we want to simplify fractions" is a somewhat vague problem description We'll clean up the requirements of the

program later but let's start with a very specific problem

Write a program to simplify 105/135 Steps

Find the gcd of 105 and 135▪ Which I'll refer to as gcd(105,135)

Print 105/gcd(105, 135) a "/" and 135/gcd(105,135)

Page 12: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Solution

/* * Program to simplify a specific fraction * Author: John Edgar * Date: December 2012 */

#include "stdio.h"

int main(){

int a = 105;int b = 135;

// Compute GCD of 105 and 135 using Euclid's algorithmwhile(a != b){

if(a > b){a = a-b;

}else{b = b-a;

}}

printf("%d/%d\n", 105/a, 135/a); // print resultreturn 0;

}

Page 13: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Discussion

The program has a number of sections

Introductory comments That describe the program

An include statement That imports library functions

A main function That actually does the work The main function includes an

implementation of Euclid's algorithm (the while statement)

Page 14: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Comments

Comments document programs They explain what a program does And how it works They are ignored by the compiler A comment starts with /* and ends with */▪ And may include more than one line

Writing comments is an important part of writing a maintainable program And you will lose marks if you don’t write

comments in assignments ...

/*Program to simplify a fractionAuthor: John EdgarDate: August 2011*/

Page 15: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

More Comments

There are two ways of writing comments in C Starting with /* and ending with */ Or single line comments that start with // and

continue to the end of the line▪ These are C++ style comments which can be used

with any recent C compiler Either method of commenting is

acceptable The // style is particularly useful for single

line comments

Page 16: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

#include stdio.h

The include statement is a pre-processor directive The pre-processor operates before the

compiler #include tells the pre-processor to

include the contents of stdio.h in our program Opens the stdio.h file Copies its contents Pastes it, replacing the include directive

Page 17: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

What’s in stdio?

The stdio.h file contains function(s) that our program need For this program it is the printf function▪ Which prints text to the standard output▪ Usually the monitor

stdio.h contains input and output functions▪ Standard input and output

Programs will frequently need functions from library files

Page 18: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Main

C programs have one main function that executes when the program is run This function has to be called main We will write (lots of) other functions

that we will give different names to The main function always has the

same general form

Page 19: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Skeleton of Main

int main(){/* stuff you want to happen */

return 0;}

the return type of the function

the name of the function, main in this case

the function’s parameter list (empty)

opening and closing curly brackets

return statement, more on this later

semi-colon, you’ll see lots of these

Page 20: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Program Flow

Programs are composed of a series of instructions separated by semi-colons Although not all program lines end with ;s

When main executes it starts with the first line and ends when it reaches the return statement Any instructions after the return statement will

not be executed Various control statements may change

program flow to allow loops or branching

Page 21: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Semi-Colons

Semi-colons show the end of C instructions Most C statements are written on one

line However, the newline character does not

indicate the end of a statement Don't forget semi-colons

As the program won't compile without them

Generally, you need a semi-colon after each statement that does not start or end with { or }

Page 22: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Variables

The simplify program uses two variables Variables are used to store data Values stored in variables can be changed using

the assignment operator, = Both variables have the same type

The type specifies what kind of data is stored▪ Both a and b are type int - used to store whole

numbers

A variable's type is specified when it is declared▪ Thereafter variables are referred to just by name

without indicating the type

int a = 105;int b = 135;

Page 23: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Declaring Variables

int a = 213;declaration and initialization

list of integer variables, separated by commas

int a, b;

type

identifiers (names)

or

Note that it is important to give variables meaningful names; I’ve used a and b because Euclid's algorithm finds the greatest common denominator of two arbitrary integers

Page 24: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Operations on Data

Simplify includes operations on integer data Subtraction and division Assignment

An operation requires an operator and at least one operand a = a – b;

operator right operand?

left operand

assignment is a binary operation since there are two operands, one on the left and one on the right

the right operand is the result of a-b

note that this one statement contains two binary operations with a distinct order

Page 25: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

While Loops

Loops are constructs that perform repetition That is they repeat code inside the body

of the loop until some condition is met▪ If the condition cannot be met the loop will

continue running forever (an infinite loop) In the simplify program the loop

continues to run as long as a and b have different values The code that is repeated is contained

within {}s that come after the condition

Page 26: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

while(a != b){

if(a > b){a = a-b;

}else{b = b-a;

}}

While Loop Anatomy

keyword (while) and conditionthe condition (a is not equal to b) evaluates to true or false

the body of the loop is repeatedly executed until the condition is false

the condition compares values stored in the integer variables

Page 27: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

while(condition){

//loop body}

While General Form

the condition is a comparison that evaluates to true or falseconditions can be more complex and may not involve comparisons

the loop body consists of the statements that are to be repeated

the condition is tested before each iteration of the loop

if the condition is false the program jumps to the statement after the loop body's closing bracket

If the condition is true the statements in the body of the loop are executed

Page 28: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

If Statements

If statements are constructs that allow decisions to be made One set of statements is performed if the

condition is true Another set of statements is performed if the

condition is false Unlike loops, if statements do not

perform repetition One set of statements is performed and the

program continues from the end of the if statement

Page 29: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Conditions

Both while loops and if statements use conditions A condition is a Boolean expression that

evaluates to true or false Boolean expressions compare two

values with a comparison operator One of <, <=, >, >=, == (equal to), !=

(not equal to) More complex conditions are possible

and these will be discussed later in the course

Page 30: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

if(a > b){

a = a-b;}else{

b = b-a;}

If Statement Anatomy

keyword (if) and condition

the condition (a > b) is true if a is greater than b and false otherwise

if statements are not required to have an else clause

executed if a is greater than b

executed if a is not greater than b

keyword else, i.e. otherwise ...

Page 31: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Printing Data

The last line of the program prints the result using the printf function The printf function must be given the

text that you want it to print Text is written as a double-quoted string▪ e.g. printf("hello world");

A string is a sequence of characters Strings can be of any length And must be enclosed in ""s

printf("%d/%d\n", 105/a, 135/a);

Page 32: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Arguments

Many functions need input Data passed to a function are referred to

as arguments The number and type of arguments must

match what is expected by the function Failing to give appropriate

arguments results in a compilation error The printf function usually has a string

as an argument but often also takes other arguments

Page 33: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

printf and Format Specifications

printf("%d/%d\n", 105/a, 135/a);

function arguments are separated by commas

int values

format specifications, % and a lettereach %d represents a decimal integer and must be matched by an integer argument that follows the string

Page 34: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Format – Colour

A text editor designed for use with C colours words to aid readers Different text editors use different

colours The Linux text editor uses different

colours from those presented in this presentation

It is common to colour the following Keywords (blue in presentation) Strings, i.e. words enclosed by ""s (red) Comments (green)

Page 35: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Format – Indentation

Indentation is used to indicate flow of control Everything in the main function’s brackets is indented

underneath the word main The body of the while loop is farther indented under the

while statement Indentation helps the reader, not the compiler

Even though indentation is ignored by the compiler it is still very important

Our goal is not just to produce programs that work but to produce programs that are easy to maintain

▪ i.e. that are easy for people to understand

Page 36: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

/* * Program to simplify a specific fraction * Author: John Edgar * Date: December 2012 */

#include "stdio.h"

int main(){

int a = 105;int b = 135;

// Compute GCD of 105 and 135 using Euclid's algorithmwhile(a != b){

if(a > b){a = a-b;

}else{b = b-a;

}}

printf("%d/%d\n", 105/a, 135/a); // print resultreturn 0;

}

Colours and Indentation

indentation

keywords

strings

comments

Page 37: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Simplify – the Bad Version

#include "stdio.h"int main(){int a, b;a = 105;b = 135;while(a != b){if(a > b){a = a-b;}else{b = b-a;}}printf("%d/%d\n", 105/a, 135/a); return 0;}

And here is the same program with no colours or indentation

This program compiles and runs but is very difficult to readImportant note – if the above program was submitted as a solution to an assignment it would lose a lot of marks, even though it worksThere is a lot more to writing a good program than producing something that works

Page 38: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Why isn't this program very good?

It only simplifies one fraction It would be better if the user was asked

what fraction should be simplified Then it could simplify any fraction!

It isn't modular The greatest common denominator

calculation is potentially useful for other purposes

It would be better to separate it from the rest of the program

Page 39: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Improving the Simplify Program

Get user input for the numerator and denominator of the fraction

Put the greatest common denominator calculation in a function

We could make other improvements Which will be discussed later

Page 40: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Functions

The simplify program used two functions The main function A call to (use of) the printf function▪ A function call is also referred to as a function

invocation In addition to main and library

functions we can write our own functions And use them in our programs It is good design to break a program

down into many small functions

Page 41: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

int gcd(int a, int b){while(a != b){

if(a > b){a = a-b;

}else{

b = b-a;}

}return a;

}

GCD Function Definition

exactly the same as the original version

function headerreturn type, name, parameter listthis function needs 2 integers for input and produces a result that is also an integer – its return value

Page 42: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Simplify with GCD Function#include "stdio.h"

int gcd(int a, int b){

while(a != b){if(a > b){

a = a-b;}else{

b = b-a;}

}return a;

}

int main(){

int numerator, denominator, divisor;numerator = 105;denominator = 135;

divisor = gcd(numerator, denominator);

printf("%d/%d\n", numerator/divisor, denominator/divisor);return 0;

}

the main function is much cleanerthe variable names in main have been made more meaningfulthe program now includes the definition of two functions – note how this is suggested by the indentationComments omitted for brevity

Page 43: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

User Input

int main(){

int numerator, denominator, divisor;

printf("Enter the numerator: ");scanf("%d", &numerator);printf("Enter the denominator: ");scanf("%d", &denominator);

divisor = gcd(numerator, denominator);

printf("%d/%d = ", numerator, denominator);printf("%d/%d\n", numerator/divisor, denominator/divisor);return 0;

}

only the main function is shown

scanf gets keyboard input

variable to store input in, preceded by an &

specifies int

this program will simplify any fraction

Page 44: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Further Improvements

Let’s assume we wanted to perform other fraction related tasks Such as arithmetic If so, simplifying fractions is likely to be

part of other calculations The program could be made more

useful by creating two more functions A function to simplify a fraction and

return a result A function to print fractions

Page 45: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Variables

Page 46: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Declaring Variables

int age;...age = 23;...age = age + 1;

declares a variable of type int

stores the value 23 in age

this compound statement actually does three things:

retrieves the value stored in age (23)calculates the sum of 23 and 1 (24)stores 24 in age

type identifier (name)

Page 47: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Rules for Declaring Variables

A variable is declared only once Variables must be declared before they

are used By convention variables are declared

at the start of a function before other statements This was required by older C compilers

Variables may be declared in a list Variables may be assigned a value

when declared Known as initialization

Page 48: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Variable Lists and Initialization

int days = 213; declaration and initialization

list of integer variables, separated by commas

int hours, minutes, seconds;

Page 49: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Duplicating Names

Declaring a variable reserves space for the variable’s data in main memory A variable can only be declared once Repeating a declaration is an attempt to

declare a new variable with the same name

Which is illegal Variables with the same name are

allowed as long as their scope is different

Page 50: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Initializing Variables

Variables should be initialized before first being used That is, given sensible starting values This can be done at the same time as

they are declared Forgetting to initialize variables can

result in unexpected and unwanted results Note that a memory location can never

be empty▪ Since it is a sequence of bits

Page 51: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Reserved Words

The age variable was declared as type int, and int is a reserved word or keyword Part of the C language

There are other keywords, many of which we will encounter in this course A text editor designed for writing C

programs will usually indicate keywords by colour

Keywords cannot be used as variable names Fortunately …

Page 52: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Tokens

A token is the smallest unit of a program

Tokens include Reserved words: parts of the C language Identifiers: names defined by the user▪ Variables▪ Functions▪ Constants▪ Structures

Page 53: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

C Identifiers

User created names must only contain Letters, both upper and lower case Digits (0 to 9) The underscore character (_)

Identifiers must begin with a letter or _ By convention variables usually start with a

lower case letter C is case sensitive

age and aGe are different identifiers

Page 54: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Naming Things

Identifiers should be descriptive to make programs easier to understand Names should be a reasonable length,

and Give information about the identifier's

purpose Say we want to store a rectangle's

height height, or rect_height, or rectHeight are

fine ht, or, even worse, a, are not descriptive variableForTheHeightOfARectangle is too

long

Page 55: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Legal Identifiers?

cycle

A!star (!)

int (reserved word)

Score (though upper case

not recommended for a variable)

xc-y (-)

race#1 (#)

my_variable (but not descriptive)

Int (but horrible – why?)

cmpt128variable (but not descriptive)

3rdVariable (starting 3)

Page 56: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Variables Names Summary

A variable declaration should begin with the type of the variable

A variable name should Be legal ▪ Only contain a-z, A-Z, 0-9 or _▪ Not be a reserved word

Start with a lower case letter Convey meaning

Page 57: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

What is a Variable?

A variable is a value stored in main memory Main memory = RAM = Random Access

Memory Values are encoded in binary A variable is therefore a sequence of

binary digits (bits) of a particular length

Variables have: A type – the kind of data the variable

stores A value – the data stored in the variable An address – the location of the variable

Page 58: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Operations

Page 59: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Operations

In the example program we saw two types of operations Numeric operations Assignments

Sometimes the meaning of an operator may be dependent on the type of the operands e.g. division

Page 60: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Numeric Operations

C uses normal arithmetic operators These can be used wherever it is legal to

use a value of the type produced by an expression

The result of the operators varies somewhat based on the type of the operands

The +, -, and * operations perform addition, subtraction, and multiplication The result of division is determined by

type

Page 61: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Integer Division

When both operands are integers the / operator performs integer division The number of times the RHS goes into

the LHS 11 / 3 is equal to 3

The % (modulus) operator returns the remainder in integer division 11 % 3 is equal to 2

Page 62: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Increment

It is common to add one to (some) variables C provides the increment operator, ++▪ count++; // adds one to count

This is typically used with ints but can be used with other numeric types

There is also a decrement operator, -- There are two ways to use increment

prefix and postfix x++ may have a different result from ++x

Page 63: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

++ Prefix and Postfix ++

The increment operator can be used before or after a variable Before is the prefix version: ++x After is the postfix version: x++

The prefix ++ increments the variable before other operations in the statement

The postfix ++ increments the variable after other operations in the statement

Page 64: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Assignment

The assignment operator, =, is used to assign values to variables The value on the right side is stored in

the variable on the left side▪ The bit representation of the left operand is

copied to the memory address of the right operand

The type of the right operand must be compatible with the left operand More on this later

Page 65: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Assignment And ...

C has shorthand operators that combine assignment and arithmetic count += 2; // count = count+2 cost -= rebate; /* cost = cost–rebate */ bonus *= 2; // bonus = bonus*2 time /= speed; /* time = time/speed */

These operators are just typing shorthand They still retrieve the value of the variable,

perform the operation and then store the result in it

Page 66: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Precedence

In a complex expression operations are performed one at a time in order The order is determined by precedence

rules▪ Expressions in ()s are evaluated first▪ Then function calls▪ Then normal arithmetic precedence (*,/) then

(+,-)▪ Assignment is usually last

More complete precedence rules will be provided later in the course

Page 67: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Constants

A constant is a special kind of variable Used to represent a value that does not

change▪ such as the value of pi

Use constants to name values in a program that won’t change To avoid “magic numbers” in a program▪ Numbers whose origin is unclear

This makes a program easier to understand and easier to modify

Page 68: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Declaring Constants

Constants are declared using the #define directive #define is a preprocessor directive The constant must be given a value, and

cannot be changed in the program By convention constants are written in

capitals Assume that there are 10 branches in a

program to maintain bank information #define BRANCH_COUNT = 10;

Page 69: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Functions

Page 70: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Using Functions

To use a function write the name of the function followed by its arguments The arguments must be in parentheses If there are no arguments the function

name must be followed by empty parentheses

The arguments must be of the appropriate type

Some functions return values And are usually assigned to a variable Or used in a calculation

Page 71: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Call Examples

area = PI * pow(radius, 2);

function names

function arguments

pow executes, and is replaced by its return value

printf("hello world"); printf has no return value

answer = sqrt(7.9); the result of calling sqrt is assigned to answer

Page 72: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Precedence

Function calls in statements have precedence over most other operations Such as arithmetic or comparisons A function is executed and its result

returned before other operations are performed

The function call is replaced by its return value Which may then be used in a calculation

Page 73: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Execution

When a function is called program execution switches to the function Each statement in the function is

executed in turn until▪ The last line is reached, or▪ A return statement is processed

Execution then returns to the line of code where the function was called from The function call is replaced by the

return value

Page 74: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

What is a Function?

It may be helpful to think of a function as a black box That has inputs and produces output

through some process

input

output

Page 75: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Calls

Consider this line of code: x = sqrt(y);

What is necessary for this to work? x and y must be existing variables sqrt must be a valid function name

But that's not all! The sqrt function must Return a value, that is compatible with

x's type Require input of a type compatible with

y's type

Page 76: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

A Function Call Example

Here is another example x = sqrt(y) + 4;

There are a number of steps here The program switches execution to sqrt

function Which computes the return value The return value replaces the function call 4 gets added to the result of calling sqrt And the result of the sum is assigned to x

Page 77: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Using Functions

We will use many functions in this course Including ones we have written

ourselves When using a function, it must be

given the appropriate arguments Arguments are information that the

function needs to perform its task They are given to (passed to) the

function in the brackets following the function’s name

Page 78: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Format Specifications

This is an incomplete list of format specifications for scanf and printf %d – integer (signed decimal number) %c – single character %f – floating point number in fixed-point notation %s – a character string, terminated by

whitespace The meanings differ slightly for printf and

scanf and there are additional specifications Which we will discuss later

Page 79: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Errors

Page 80: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Errors

Most programs contain errors Most large working programs contain

errors A substantial amount of time is spent

finding and fixing errors (known as debugging)

We can categorize errors into three very broad types Compilation and Linker errors Run-time errors Logic errors

Page 81: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Compilation Errors

These errors prevent a program from being compiled

Compilers are very picky and complain at the slightest mistake, some common errors are Misspelled words, C is case sensitive, so

int is different from Int Missing semi-colons, or brackets, or

quotes Incorrect arguments for functions

You will spend a lot of time looking for errors

Page 82: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Other Errors

Once a program compiles and runs there is still testing (and work) to do

Run-time errors cause programs to crash As a result, for example, of input type errors▪ These need to be predicted and handled in some

way Logic errors cause programs to return

incorrect results And need to be caught by rigorous testing

Page 83: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersecting Circles

Page 84: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersecting Circles

As a second example let's look at whether or not two circles intersect

This example will introduce input Using scanf

The example will also illustrate the use of more library functions This time from the maths library

Page 85: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Problem Description

Before getting into the design let's make sure we understand the problem

Do these circles intersect? No

Do these circles intersect? Yes

We need to come up with some way of determining whether or not circles intersect – one that isn't just look at them and figure it out!

Page 86: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

When do two circles intersect? When the distance between the centres

of the circles is less than the sum of their radii

Some Mathematics

r1 r2d

d > r1 + r2 so no intersection

r1 r2

d

d < r1 + r2 so intersection

Page 87: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Input

At this point we know what the problem is And we know how to calculate a solution

But we are still missing some information about the problem What is the input to the program?

We need to know the radius of the two circles and the distance between them Let's assume that the user will enter the

radius And the position of the circles

Page 88: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Distance Between 2 Points

The position of the circles will be specified as the x and y coordinates of their centres

The distance between the two points can then be calculated

xd

ydhypotenuse

The length of the hypotenuse is (xd2 + yd2)

Page 89: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Pseudocode Algorithm

1. x1 = user input for x coordinate of first circle

2. y1 = user input for y coordinate of first circle

3. r1 = user input for radius of first circle

4. x2 = user input for x coordinate of second circle

5. y2 = user input for y coordinate of second circle

6. r2 = user input for radius of second circle

7. distance = ( (x1 – x2)2 + (y1 – y2)2 )

8. if (distance < r1 + r2) then

1. print "circles intersect"

9. otherwise

1. print "circles do not intersect"

Page 90: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Programming Issues

How do we get user input? Use scanf

How do we find the square root of values? There is a square root function in the

math.h library How do we decide what to print?

We will use an if statement What types should x, y and radius

be? Discuss ...

Page 91: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Function Design

What functions should we write? One function to find the distance

between points And another function to determine

whether or not two circles intersect Function parameters

The distance function needs to know the x and y coordinates of each point

The intersection function needs to know the position and radius of each circle

Page 92: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Distance Function

// Returns the distance between two points// PARAM: x1, y1 coordinates of first point// x2, y2 coordinates of second point

float distance(float x1, float y1, float x2, float y2){

result =(pow(x1 – x2, 2));result += (pow(y1 – y2, 2));result = sqrt(distance);return distance;

} I've separated the calculation into three lines

Partly to make it more readable, and partly to show the use of += and to stress how assignment works, I could have written it all one line, like this:result = sqrt(pow(x1 – x2, 2) + pow(y1 – y2, 2));

Page 93: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersection Function

// Returns 1 if two circles intersect, 0 otherwise// PARAM: x1, y1 coordinates of centre of circle 1// r1 – radius of circle 1// x2, y2 coordinates of centre of circle 2// r2 – radius of circle 2

int intersect(float x1, float y1, float r1, float x2, float y2, float r2)

{float dist = distance(x1, y1, x2, y2);if (dist < r1 + r2){

return 1;}else{

return 0;}

}1 and 0 represent the Boolean values true and false, which can be used in conditions

Page 94: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersection Program

/* * Program to determine if two circles intersect * Author: John Edgar * Date: September 2011*/

#include "stdio.h"#include "math.h"

// Function Prototypesfloat distance(float x1, float y1, float x2, float y2)int intersect(float x1, float y1, float r1,

float x2, float y2, float r2)

int main(){int x1, y1, x2, y2; // centres of circlesfloat radius1, radius2;

// Get user input // Print result

return 0;}

The rest of the program is on the pages that follow, I'll leave the comments in to make the program easier to follow

A function prototype introduces a function that is defined somewhere else in the file so that the compiler recognizes it

Page 95: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersection Program

int main(){

// ...

// Get user input

printf("Enter the x coordinate of circle 1: ");

scanf("%f", &x1);

printf("Enter the y coordinate of circle 1: ");

scanf("%f", &y1);

printf("Enter the radius of circle 1: ");

scanf("%f", &r1);

printf("Enter the x coordinate of circle 2: ");

scanf("%f", &x2);

printf("Enter the y coordinate of circle 2: ");

scanf("%f", &y2);

printf("Enter the radius of circle 2: ");

scanf("%f", &r2);

The instructions are a bit terse to make them fit on the page!

I'd prefer something like : Please enter the x coordinate of the centre of the first circle

Page 96: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Intersection Program

int main(){// ...// Print resultif (intersect(x1, y1, r1, x2, y2, r2)){

printf("The circles DO intersect");}else{

printf("The circles do NOT intersect");}

return 0;}

// Definitions of distance and intersect go here

Page 97: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Keyboard Input with scanf The scanf function gets input from the

keyboard, and take two arguments A format specification that indicates what

format the data being typed is in The address of the variable that the data

is to be assigned to Why the address (of the variable)?

We are telling the program where to store the data

Page 98: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Math Functions

In addition to scanf and printf the intersection program uses two mathematical functions The pow function, and The sqrt function

The pow function returns the value of the first argument raised to the power of the second

The sqrt function returns the square root of its argument

Page 99: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Compiling with math.h

C programs that contain the math.h library must be compiled with a specific flag -lm

If the program was called intersect.c compile by typing gcc –o intersect intersect.c -lm▪ Note that I don’t have to call the executable file

intersect, it just seems like a sensible name To run the newly created file:

./ intersect

Page 100: First Program  Compilation and Execution  Simplifying Fractions  Loops  If Statements  Writing functions  Variables  Operations  Using Functions.

Compiling with C99 Standard

In this course we will want gcc to use the 1999 C standard Rather than earlier version of the

language Use the std flag to do this:

gcc –o a1 a1.c –std=c99 If this program included math.h

gcc –o a1 a1.c –std=c99 -lm