Download presentation

Presentation is loading. Please wait.

Published byAlfred Bollom Modified about 1 year ago

1

2
First Program

3
Compilation and Execution Simplifying Fractions Loops If Statements Writing functions Variables Operations Using Functions Errors

4
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

5
Source File (.c) write in a text editor correct errors compile Object File (binary) Other Object Files Executable File (binary) test syntax errors linker links files Debugged Executable link errors run-time and logic errors

6
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

7
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

8
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...

9
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

10

11
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

12
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)

13
/* * 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 algorithm while(a != b){ if(a > b){ a = a-b; }else{ b = b-a; } printf("%d/%d\n", 105/a, 135/a); // print result return 0; }

14
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)

15
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 fraction Author: John Edgar Date: August 2011 */ /* Program to simplify a fraction Author: John Edgar Date: August 2011 */

16
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

17
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

18
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

19
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

20
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) 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

21
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

22
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 }

23
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; int a = 105; int b = 135;

24
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

25
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

26
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

27
while(a != b) { if(a > b){ a = a-b; }else{ b = b-a; } keyword (while) and condition the 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

28
while(condition) { //loop body } the condition is a comparison that evaluates to true or false conditions 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

29
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

30
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

31
if(a > b) { a = a-b; }else{ b = b-a; } 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...

32
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);

33
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

34
printf("%d/%d\n", 105/a, 135/a); function arguments are separated by commas int values format specifications, % and a letter each %d represents a decimal integer and must be matched by an integer argument that follows the string

35
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)

36
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

37
/* * 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 algorithm while(a != b){ if(a > b){ a = a-b; }else{ b = b-a; } printf("%d/%d\n", 105/a, 135/a); // print result return 0; } indentation keywords strings comments

38
#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 read Important note – if the above program was submitted as a solution to an assignment it would lose a lot of marks, even though it works There is a lot more to writing a good program than producing something that works

39
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

40
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

41
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

42
int gcd(int a, int b) { while(a != b){ if(a > b){ a = a-b; } else{ b = b-a; } return a; } exactly the same as the original version function header return type, name, parameter list this function needs 2 integers for input and produces a result that is also an integer – its return value

43
#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 cleaner the variable names in main have been made more meaningful the program now includes the definition of two functions – note how this is suggested by the indentation Comments omitted for brevity

44
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

45
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

46

47
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)

48
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

49
int days = 213; declaration and initialization list of integer variables, separated by commas int hours, minutes, seconds;

50
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

51
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

52
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 …

53
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

54
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

55
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

56
ccycle AA!star (!) iint (reserved word) SScore (though upper case not recommended for a variable) xxc-y (-) rrace#1 (#) mmy_variable (but not descriptive) IInt (but horrible – why?) ccmpt128variable (but not descriptive) 33rdVariable (starting 3)

57
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

58
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

59

60
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

61
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

62
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

63
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

64
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

65
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

66
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

67
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

68
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

69
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;

70

71
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

72
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

73
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

74
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

75
It may be helpful to think of a function as a black box That has inputs and produces output through some process input output

76
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

77
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

78
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

79
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

80

81
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

82
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

83
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

84

85
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

86
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!

87
When do two circles intersect? When the distance between the centres of the circles is less than the sum of their radii r1r1 r2r2 d d > r 1 + r 2 so no intersection r1r1 r2r2 d d < r 1 + r 2 so intersection

88
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

89
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 yd hypotenuse The length of the hypotenuse is (xd 2 + yd 2 )

90
1. x 1 = user input for x coordinate of first circle 2. y 1 = user input for y coordinate of first circle 3. r 1 = user input for radius of first circle 4. x 2 = user input for x coordinate of second circle 5. y 2 = user input for y coordinate of second circle 6. r 2 = user input for radius of second circle 7. distance = ( (x 1 – x 2 ) 2 + (y 1 – y 2 ) 2 ) 8. if (distance < r 1 + r 2 ) then 1. print "circles intersect" 9. otherwise 1. print "circles do not intersect"

91
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...

92
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

93
// 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));

94
// 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

95
/* * Program to determine if two circles intersect * Author: John Edgar * Date: September 2011 */ #include "stdio.h" #include "math.h" // Function Prototypes float 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 circles float 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

96
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

97
int main(){ //... // Print result if (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

98
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

99
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

100
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

101
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

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google