Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

Similar documents
Lecture 5: C programming

COSC121: Computer Systems: Runtime Stack

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 13 Control Structures

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators

Chapter 13 Control Structures

Chapter 13. Control Structures

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators

Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Chapter 14 Functions

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

Smaller, simpler, subcomponent of program Provides abstraction

Fundamental of Programming (C)

UNIT- 3 Introduction to C++

printf( Please enter another number: ); scanf( %d, &num2);

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

1 Lexical Considerations

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Fundamentals of Programming

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Programming for Engineers Introduction to C

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Full file at

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Course Outline Introduction to C-Programming

C: How to Program. Week /Mar/05

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Lexical Considerations

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Basic Types and Formatted I/O

Lexical Considerations

Maciej Sobieraj. Lecture 1

The C++ Language. Arizona State University 1

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Full file at C How to Program, 6/e Multiple Choice Test Bank

Unit 3. Operators. School of Science and Technology INTRODUCTION

Basics of Java Programming

Introduction. C provides two styles of flow control:

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Objectives. In this chapter, you will:

INTRODUCTION 1 AND REVIEW

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Lecture 3. More About C

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Informatica e Sistemi in Tempo Reale

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

DaMPL. Language Reference Manual. Henrique Grando

Lecture 2: C Programming Basic

Fundamentals of Programming

Variables and literals

BITG 1233: Introduction to C++

Scope: Global and Local. Concept of Scope of Variable

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Fundamentals of Programming Session 4

Work relative to other classes

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

C Programming

Chapter 2 - Introduction to C Programming

Computer Components. Software{ User Programs. Operating System. Hardware

JAVA Programming Fundamentals

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Computers Programming Course 5. Iulian Năstac

Computer Components. Software{ User Programs. Operating System. Hardware

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Programming for Engineers Iteration

CSCI 1061U Programming Workshop 2. C++ Basics

BASIC ELEMENTS OF A COMPUTER PROGRAM

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Preview from Notesale.co.uk Page 6 of 52

C++ Programming Basics

Basics of Programming

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

Pace University. Fundamental Concepts of CS121 1

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

C Programming Basics

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

The C language. Introductory course #1

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Transcription:

Introduction to C Part 1 HLL s and the Basic Syntax (Ch11 & 12) 1

C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations do not depend on instruction set example: can write a = b * c, even though LC-3 doesn t have a multiply instruction Provides expressiveness use meaningful symbols that convey meaning simple expressions for common control patterns (if-thenelse) Enhances code readability Safeguards against bugs can enforce rules or conditions at compile-time or run-time 2

Compilation vs. Interpretation Different ways of translating high-level language Interpretation interpreter = program that executes program statements generally one line/command at a time limited processing easy to debug, make changes, view intermediate results languages: BASIC, LISP, Perl, Java, Matlab, C-shell Compilation translates statements into machine language does not execute, but creates executable program performs optimization over multiple statements change requires recompilation can be harder to debug, since executed code may be different languages: C, C++, Fortran, Pascal 3

Compilation vs. Interpretation Consider the following algorithm: Get W from the keyboard. X = W + W Y = X + X Z = Y + Y Print Z to screen. If interpreting, how many arithmetic operations occur? If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation? 4

Compiling a C Program Entire mechanism is usually called the compiler Preprocessor macro substitution conditional compilation source-level transformations output is still C Compiler generates object file machine instructions Linker combine object files (including libraries) into executable image Library Object Files Source Code Analysis Target Code Synthesis C Source and Header Files C Preprocessor Compiler Linker Executable Image Symbol Table 5

Compiler Source Code Analysis front end parses programs to identify its pieces variables, expressions, statements, functions, etc. depends on language (not on target machine) Code Generation back end generates machine code from analyzed source may optimize machine code to make it run more efficiently very dependent on target machine Symbol Table map between symbolic names and items like assembler, but more kinds of information 6

A Simple C Program #include <stdio.h> #define STOP 0 /* Function: main */ /* Description: counts down from user input to STOP */ main() { /* variable declarations */ int counter; /* an integer to hold count values */ int startpoint; /* starting point for countdown */ /* prompt user for input */ printf("enter a positive number: "); scanf("%d", &startpoint); /* read into startpoint */ /* count down and print count */ for (counter=startpoint; counter >= STOP; counter--) printf("%d\n", counter); } 7

Preprocessor Directives #include <stdio.h> Before compiling, copy contents of header file (stdio.h) into source code. Header files typically contain descriptions of functions and variables needed by the program. no restrictions -- could be any C source code #define STOP 0 Before compiling, replace all instances of the string "STOP" with the string "0" Called a macro Used for values that won't change during execution, but might change if the program is reused. (Must recompile.) 8

Comments Begins with /* and ends with */ Can span multiple lines Cannot have a comment within a comment Comments are not recognized within a string example: "my/*don't print this*/string" would be printed as: my/*don't print this*/string As before, use comments to help reader, not to confuse or to restate the obvious 9

main Function Every C program must have a function called main(). This is the code that is executed when the program is run. The code for the function lives within brackets: main() { /* code goes here */ } 10

Variable Declarations Variables are used as names for data items. Each variable has a type, which tells the compiler how the data is to be interpreted (and how much space it needs, etc.). int counter; int startpoint; int is a predefined integer type in C. 11

Input and Output Variety of I/O functions in C Standard Library. Must include <stdio.h> to use them. printf("%d\n", counter); String contains characters to print and formatting directions for variables. This call says to print the variable counter as a decimal integer, followed by a linefeed (\n). scanf("%d", &startpoint); String contains formatting directions for looking at input. This call says to read a decimal integer and assign it to the variable startpoint. (Don't worry about the & yet.) 12

More About Output Can print arbitrary expressions, not just variables printf("%d\n", startpoint - counter); Print multiple expressions with a single statement printf("%d %d\n", counter, startpoint - counter); Different formatting options: %d decimal integer %x hexadecimal integer %c ASCII character %f floating-point number 13

Examples This code: printf("%d is a prime number.\n", 43); printf("43 plus 59 in decimal is %d.\n", 43+59); printf("43 plus 59 in hex is %x.\n", 43+59); printf("43 plus 59 as a character is %c.\n", 43+59); produces this output: 43 is a prime number. 43 + 59 in decimal is 102. 43 + 59 in hex is 66. 43 + 59 as a character is f. 14

Examples of Input Many of the same formatting characters are available for user input. scanf("%c", &nextchar); reads a single character and stores it in nextchar scanf("%f", &radius); reads a floating point number and stores it in radius scanf("%d %d", &length, &width); reads two decimal integers (separated by whitespace), stores the first one in length and the second in width Must use ampersand (&) for variables being modified. (Explained in Chapter 16.) 15

Compiling and Linking Various compilers available cc, gcc, MS Visual Studio includes preprocessor, compiler, and linker Lots and lots of options! level of optimization, debugging preprocessor, linker options intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. 16

Variables Basic C Elements named, typed data items Operators predefined actions performed on data items combined with variables to form expressions, statements Rules and usage Implementation using LC-3 17

Data Types C has three basic data types int double char integer (at least 16 bits) floating point (at least 32 bits) character (at least 8 bits) Exact size can vary, depending on processor int is supposed to be "natural" integer size; for LC-3, that's 16 bits -- 32 bits for most modern processors 18

Variable Names Any combination of letters, numbers, and underscore (_) Case matters "sum" is different than "Sum" Cannot begin with a number usually, variables beginning with underscore are used only in special library routines Only first 31 characters are used 19

Examples Legal same identifier i wordspersecond words_per_second _green areally_longname_morethan31chars areally_longname_morethan31characters Illegal 10sdigit ten'sdigit done? double reserved keyword 20

Literals Integer 123 /* decimal */ -123 0x123 /* hexadecimal */ Floating point 6.023 Character 'c' 6.023e23 /* 6.023 x 10 23 */ 5E12 /* 5.0 x 10 12 */ '\n' /* newline */ '\xa' /* ASCII 10 (0xA) */ 21

Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region Compiler infers scope from where variable is declared programmer doesn't have to explicitly state Variable is local to the block in which it is declared block defined by open and closed braces { } can access variable declared in any "containing" block Global variable is declared outside all blocks 22

Example #include <stdio.h> int itsglobal = 0; main() { int itslocal = 1; /* local to main */ printf("global %d Local %d\n", itsglobal, itslocal); { int itslocal = 2; /* local to this block */ itsglobal = 4; /* change global variable */ printf("global %d Local %d\n", itsglobal, itslocal); } printf("global %d Local %d\n", itsglobal, itslocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1 23

Operators Programmers manipulate variables using the operators provided by the high-level language. Variables and operators combine to form expressions and statements which denote the work to be done by the program. Each operator may correspond to many machine instructions. Example: The multiply operator (*) typically requires multiple LC-3 ADD instructions. 24

Expression Any combination of variables, constants, operators, and function calls every expression has a type, derived from the types of its components (according to C typing rules) Examples: counter >= STOP x + sqrt(y) x & z + 3 9 - w-- % 6 25

Statement Expresses a complete unit of work executed in sequential order Simple statement ends with semicolon z = x * y;/* assign product to z */ y = y + 1;/* after multiplication */ ; /* null statement */ Compound statement groups simple statements using braces. syntactically equivalent to a simple statement { z = x * y; y = y + 1; } 26

Operators Three things to know about each operator (1) Function what does it do? (2) Precedence in which order are operators combined? Example: "a * b + c * d" is the same as "(a * b) + (c * d)" because multiply (*) has a higher precedence than addition (+) (3) Associativity in which order are operators of the same precedence combined? Example: "a-b-c" is the same as "(a-b)-c" because add/sub associate left-to-right 27

Assignment Operator Changes the value of a variable. x = x + 4; 1. Evaluate right-hand side. 2. Set value of left-hand side variable to result. 28

Assignment Operator All expressions evaluate to a value, even ones with the assignment operator. For assignment, the result is the value assigned. usually (but not always) the value of the right-hand side type conversion might make assigned value different than computed value Assignment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3. 29

Arithmetic Operators Symbol Operation Usage Precedence Assoc * multiply x * y 6 l-to-r / divide x / y 6 l-to-r % modulo x % y 6 l-to-r + addition x + y 7 l-to-r - subtraction x - y 7 l-to-r All associate left to right. * / % have higher precedence than + -. 30

Arithmetic Expressions If mixed types, smaller type is "promoted" to larger. x + 4.3 if x is int, converted to double and result is double Integer division -- fraction is dropped. x / 3 if x is int and x=5, result is 1 (not 1.666666...) Modulo -- result is remainder. x % 3 if x is int and x=5, result is 2. 31

Bitwise Operators Symbol Operation Usage Precedence Assoc ~ bitwise NOT ~x 4 r-to-l << left shift x << y 8 l-to-r >> right shift x >> y 8 l-to-r & bitwise AND x & y 11 l-to-r ^ bitwise XOR x ^ y 12 l-to-r bitwise OR x y 13 l-to-r Operate on variables bit-by-bit. Like LC-3 AND and NOT instructions. Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed. 32

Logical Operators Symbol Operation Usage Precedence Assoc! logical NOT!x 4 r-to-l && logical AND x && y 14 l-to-r logical OR x y 15 l-to-r Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE). 33

Relational Operators Symbol Operation Usage Precedence Assoc > greater than x > y 9 l-to-r >= greater than or equal x >= y 9 l-to-r < less than x < y 9 l-to-r <= less than or equal x <= y 9 l-to-r == equal x == y 10 l-to-r!= not equal x!= y 10 l-to-r Result is 1 (TRUE) or 0 (FALSE). Note: Don't confuse equality (==) with assignment (=). 34

Special Operators: ++ and -- Changes value of variable before (or after) its value is used in an expression. Symbol Operation Usage Precedence Assoc ++ postincrement x++ 2 r-to-l -- postdecrement x-- 2 r-to-l ++ preincrement ++x 3 r-to-l <= predecrement --x 3 r-to-l Pre: Increment/decrement variable before using its value. Post: Increment/decrement variable after using its value. 35

Using ++ and -- x = 4; y = x++; Results: x = 5, y = 4 (because x is incremented after assignment) x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before assignment) 36

Practice with Precedence Assume a=1, b=2, c=3, d=4. x = a * b + c * d / 2; /* x = 8 */ same as: x = (a * b) + ((c * d) / 2); For long or confusing expressions, use parentheses, because reader might not have memorized precedence table. Note: Assignment operator has lowest precedence, so all the arithmetic operations on the right-hand side are evaluated first. 37

Special Operators: +=, *=, etc. Arithmetic and bitwise operators can be combined with assignment operator. Statement Equivalent assignment x += y; x = x + y; x -= y; x = x - y; x *= y; x = x * y; x /= y; x = x / y; x %= y; x = x % y; x &= y; x = x & y; x = y; x = x y; x ^= y; x = x ^ y; x <<= y; x = x << y; x >>= y; x = x >> y; All have same precedence and associativity as = and associate right-to-left. 38

Special Operator: Conditional Symbol Operation Usage Precedence Assoc?: conditional x?y:z 16 l-to-r If x is TRUE (non-zero), result is y; else, result is z. Like a MUX, with x as the select signal. y z 1 0 x 39

Introduction to C Part 2 Control Loops and Functions (Ch13 + ch14) 40

Control Structures Conditional making a decision about which code to execute, based on evaluated expression if if-else switch Iteration executing code multiple times, ending based on evaluated expression while for do-while 41

if (condition) action; If condition T action F Condition is a C expression, which evaluates to TRUE (non-zero) or FALSE (zero). Action is a C statement, which may be simple or compound (a block). 42

Example If Statements if (x <= 10) y = x * x + 5; if (x <= 10) { y = x * x + 5; z = (2 * y) / 3; } compound statement; both executed if x <= 10 if (x <= 10) y = x * x + 5; z = (2 * y) / 3; only first statement is conditional; second statement is always executed 43

More If Examples if (0 <= age && age <= 11) kids += 1; if (month == 4 month == 6 month == 9 month == 11) printf( The month has 30 days.\n ); if (x = 2) y = 5; always true, so action is always executed! This is a common programming error (= instead of ==), not caught by compiler because it s syntactically correct. 44

If s Can Be Nested if (x == 3) if (y!= 6) { z = z + 1; w = w + 2; } is the same as... if ((x == 3) && (y!= 6)) { z = z + 1; w = w + 2; } 45

Generating Code for If Statement ; if (x == 2) y = 5; LDR R0, R5, #0 ; load x into R0 ADD R0, R0, #-2 ; subtract 2 BRnp NOT_TRUE ; if non-zero, x is not 2 AND R1, R1, #0 ; store 5 to y ADD R1, R1, #5 STR R1, R5, #-1 NOT_TRUE... ; next statement 46

If-else if (condition) action_if; else action_else; T F condition action_if action_else Else allows choice between two mutually exclusive actions without re-testing condition. 47

Generating Code for If-Else if (x) { y++; z--; } else { y--; z++; } LDR R0, R5, #0 BRz ELSE ; x is not zero LDR R1, R5, #-1 ; incr y ADD R1, R1, #1 STR R1, R5, #-1 LDR R1, R5, #-2 ; decr z ADD R1, R1, #1 STR R1, R5, #-2 JMP DONE ; skip else code ; x is zero ELSE LDR R1, R5, #-1 ; decr y ADD R1, R1, #-1 STR R1, R5, #-1 LDR R1, R5, #-2 ; incr z ADD R1, R1, #1 STR R1, R5, #-2 DONE... ; next statement 48

Matching Else with If if (x!= 10) if (y > 3) z = z / 2; else z = z * 2; is the same as... if (x!= 10) { if (y > 3) z = z / 2; else z = z * 2; } Else is always associated with closest unassociated if. is NOT the same as... if (x!= 10) { if (y > 3) z = z / 2; } else z = z * 2; 49

Chaining If s and Else s if (month == 4 month == 6 month == 9 month == 11) printf( Month has 30 days.\n ); else if (month == 1 month == 3 month == 5 month == 7 month == 8 month == 10 month == 12) printf( Month has 31 days.\n ); else if (month == 2) printf( Month has 28 or 29 days.\n ); else printf( Don t know that month.\n ); 50

while (test) loop_body; While test T loop_body F Executes loop body as long as test evaluates to TRUE (non-zero). Note: Test is evaluated before executing loop body. 51

Generating Code for While x = 0; while (x < 10) { printf( %d, x); x = x + 1; } AND R0, R0, #0 STR R0, R5, #0 ; x = 0 ; test LOOP LDR R0, R5, #0 ; load x ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load x... <printf>... ADD R0, R0, #1 ; incr x STR R0, R5, #0 JMP LOOP ; test again DONE ; next statement 52

Infinite Loops The following loop will never terminate: x = 0; while (x < 10) printf( %d, x); Loop body does not change condition, so test never fails. This is a common programming error that can be difficult to find. 53

For for (init; end-test; re-init) statement F Executes loop body as long as test evaluates to TRUE (non-zero). Initialization and re-initialization code includedin loop statement. init test T loop_body re-init Note: Test is evaluated before executing loop body. 54

Generating Code for For for (i = 0; i < 10; i++) printf( %d, i); This is the same as the while example! ; init AND R0, R0, #0 STR R0, R5, #0 ; i = 0 ; test LOOP LDR R0, R5, #0 ; load i ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load i... <printf>... ; re-init ADD R0, R0, #1 ; incr i STR R0, R5, #0 JMP LOOP ; test again DONE ; next statement 55

Example For Loops /* -- what is the output of this loop? -- */ for (i = 0; i <= 10; i ++) printf("%d ", i); /* -- what does this one output? -- */ letter = 'a'; for (c = 0; c < 26; c++) printf("%c ", letter+c); /* -- what does this loop do? -- */ numberofones = 0; for (bitnum = 0; bitnum < 16; bitnum++) { if (inputvalue & (1 << bitnum)) numberofones++; } 56

Nested Loops Loop body can (of course) be another loop. /* print a multiplication table */ for (mp1 = 0; mp1 < 10; mp1++) { for (mp2 = 0; mp2 < 10; mp2++) { printf( %d\t, mp1*mp2); } printf( \n ); } Braces aren t necessary, but they make the code easier to read. 57

Another Nested Loop The test for the inner loop depends on the counter variable of the outer loop. for (outer = 1; outer <= input; outer++) { for (inner = 0; inner < outer; inner++) { sum += inner; } } 58

For vs. While In general: For loop is preferred for counter-based loops. Explicit counter variable Easy to see how counter is modified each loop While loop is preferred for sentinel-based loops. Test checks for sentinel value. Either kind of loop can be expressed as the other, so it s really a matter of style and readability. 59

Do-While do loop_body; while (test); loop_body T test Executes loop body as long as test evaluates to TRUE (non-zero). F Note: Test is evaluated after executing loop body. 60

Switch evaluate expression switch (expression) { case const1: action1; break; case const2: action2; break; default: action3; } Alternative to long if-else chain. If break is not used, then case "falls through" to the next. = const1? F = const2? F action3 T T action1 action2 61

Switch Example /* same as month example for if-else */ switch (month) { case 4: case 6: case 9: case 11: printf( Month has 30 days.\n ); break; case 1: case 3: /* some cases omitted for brevity...*/ printf( Month has 31 days.\n ); break; case 2: printf( Month has 28 or 29 days.\n ); break; default: printf( Don t know that month.\n ); } 62

More About Switch Case expressions must be constant. case i: /* illegal if i is a variable */ If no break, then next case is also executed. switch (a) { } case 1: printf( A ); case 2: printf( B ); default: printf( C ); If a is 1, prints ABC. If a is 2, prints BC. Otherwise, prints C. 63

Function Smaller, simpler, subcomponent of program Provides abstraction hide low-level details give high-level structure to program, easier to understand overall program flow enables separable, independent development C functions zero or multiple arguments passed in single result returned (optional) return value is always a particular type In other languages, called procedures, subroutines,... 64

Example of High-Level Structure main() { SetupBoard(); /* place pieces on board */ DetermineSides(); /* choose black/white */ } /* Play game */ do { WhitesTurn(); BlacksTurn(); } while (NoOutcomeYet()); Structure of program is evident, even without knowing implementation. 65

Functions in C Declaration (also called prototype) int Factorial(int n); type of return value name of function types of all arguments Function call -- used in expression a = x + Factorial(f + g); 1. evaluate arguments 2. execute function 3. use return value in expression 66

Function Definition State type, name, types of arguments must match function declaration give name to each argument (doesn't have to match declaration) int Factorial(int n) { int i; int result = 1; for (i = 1; i <= n; i++) result *= i; return result; } gives control back to calling function and returns value 67

Why Declaration? Since function definition also includes return and argument types, why is declaration needed? Use might be seen before definition. Compiler needs to know return and arg types and number of arguments. Definition might be in a different file, written by a different programmer. include a "header" file with function declarations only compile separately, link together to make executable 68

Example double ValueInDollars(double amount, double rate); declaration main() {... dollars = ValueInDollars(francs, DOLLARS_PER_FRANC); printf("%f francs equals %f dollars.\n", francs, dollars);... } function call (invocation) definition double ValueInDollars(double amount, double rate) { return amount * rate; } 69

Example Function Call int Volta(int q, int r) { int k; int m;... return k; } int Watt(int a) { int w;... w = Volta(w,10);... return w; } 70

ANSI C Summary C is the basis for most modern languages: Java, C#, C++ Has a fairly close relationship to the hardware, not too much abstraction For the most part it is portable across platforms Use gcc or cc on UNIX machine 71