Download presentation

Presentation is loading. Please wait.

1
First Program Fundamentals

2
**Fundamentals Compilation and Execution Simplifying Fractions Variables**

Loops If Statements Writing functions Variables Operations Using Functions Errors

3
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

4
**Executable File (binary)**

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

5
**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

6
**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

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

8
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

9
**Simplifying Fractions**

10
**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

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

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

13
**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)

14
**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 fraction Author: John Edgar Date: August 2011 */

15
**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

16
**#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

17
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

18
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

19
**Skeleton of Main int main() { } /* stuff you want to happen */**

the return type of the function the function’s parameter list (empty) int main() { /* stuff you want to happen */ return 0; } the name of the function, main in this case semi-colon, you’ll see lots of these return statement, more on this later opening and closing curly brackets

20
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

21
**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 }

22
**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;

23
**Declaring Variables int a, b; int a = 213; identifiers (names) type**

list of integer variables, separated by commas or int a = 213; declaration and initialization 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

24
**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; assignment is a binary operation since there are two operands, one on the left and one on the right left operand operator right operand? the right operand is the result of a-b note that this one statement contains two binary operations with a distinct order

25
**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

26
While Loop Anatomy keyword (while) and condition while(a != b) { if(a > b){ a = a-b; }else{ b = b-a; } 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

27
**While General Form 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 true the statements in the body of the loop are executed if the condition is false the program jumps to the statement after the loop body's closing bracket

28
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

29
**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

30
**If Statement Anatomy if(a > b) { a = a-b; }else{ b = b-a; }**

keyword (if) and condition if(a > b) { a = a-b; }else{ b = b-a; } the condition (a > b) is true if a is greater than b and false otherwise executed if a is greater than b keyword else, i.e. otherwise ... executed if a is not greater than b if statements are not required to have an else clause

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

32
**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

33
**printf and Format Specifications**

printf("%d/%d\n", 105/a, 135/a); 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 function arguments are separated by commas

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

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

36
**Colours and Indentation**

/* * 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; comments strings keywords indentation

37
**Simplify – the Bad Version**

And here is the same program with no colours or indentation #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;} 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

38
**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

39
**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

40
**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

41
**GCD Function Definition**

int gcd(int a, int b) { while(a != b){ if(a > b){ a = a-b; } else{ b = b-a; return a; 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 exactly the same as the original version

42
**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 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

43
User Input only the main function is shown 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; } scanf gets keyboard input specifies int variable to store input in, preceded by an & this program will simplify any fraction

44
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

45
Variables

46
**Declaring Variables int age; ... age = 23; age = age + 1; type**

identifier (name) declares a variable of type int int age; ... age = 23; age = age + 1; 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

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

48
**Variable Lists and Initialization**

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

49
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

50
**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

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

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

53
**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

54
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

55
**Legal Identifiers? cycle A!star int Score xc-y race#1 my_variable Int**

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 3rdVariable (starting 3)

56
**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

57
**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

58
Operations

59
**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

60
**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

61
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

62
**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

63
**++ 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

64
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

65
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

66
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

67
**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

68
**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;

69
Functions

70
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

71
**Function Call Examples**

printf("hello world"); printf has no return value answer = sqrt(7.9); the result of calling sqrt is assigned to answer area = PI * pow(radius, 2); pow executes, and is replaced by its return value function names function arguments

72
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

73
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

74
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

75
**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

76
**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

77
**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

78
**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

79
Errors

80
**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

81
**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

82
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

83
Intersecting Circles

84
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

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

86
**Some Mathematics When do two circles intersect?**

When the distance between the centres of the circles is less than the sum of their radii r2 r2 r1 r1 d d d > r1 + r2 so no intersection d < r1 + r2 so intersection

87
**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

88
**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 The length of the hypotenuse is (xd2 + yd2) hypotenuse yd xd

89
**Pseudocode Algorithm x1 = user input for x coordinate of first circle**

y1 = user input for y coordinate of first circle r1 = user input for radius of first circle x2 = user input for x coordinate of second circle y2 = user input for y coordinate of second circle r2 = user input for radius of second circle distance = ( (x1 – x2)2 + (y1 – y2)2 ) if (distance < r1 + r2) then print "circles intersect" otherwise print "circles do not intersect"

90
**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 ...

91
**Function Design What functions should we write? Function parameters**

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

92
**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));

93
**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

94
Intersection Program /* * 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; } A function prototype introduces a function that is defined somewhere else in the file so that the compiler recognizes it The rest of the program is on the pages that follow, I'll leave the comments in to make the program easier to follow

95
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

96
Intersection Program 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

97
**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

98
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

99
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

100
**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

Similar presentations

Presentation is loading. Please wait....

OK

Introduction to C Programming

Introduction to C Programming

© 2018 SlidePlayer.com Inc.

All rights reserved.

To make this website work, we log user data and share it with processors. To use this website, you must agree to our Privacy Policy, including cookie policy.

Ads by Google