Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions. Alvin Valera

Similar documents
Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Lecture 2: C Programming Basic

Introduction. C provides two styles of flow control:

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Programming for Engineers Iteration

Model Viva Questions for Programming in C lab

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

The Design of C: A Rational Reconstruction: Part 2

C-LANGUAGE CURRICULAM

Flow Control. CSC215 Lecture

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Week 5 9 April 2018 NWEN 241 More on pointers. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

Continued from previous lecture

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Type Conversion. and. Statements

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Week 1 / Lecture 2 8 March 2017 NWEN 241 C Fundamentals. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington


Fundamental of Programming (C)

C Programming Language (Chapter 2 of K&R) Variables and Constants

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Computer System and programming in C

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

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

Lecture 02 C FUNDAMENTALS

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Unit 7. Functions. Need of User Defined Functions

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 6. Iulian Năstac

Programming for Electrical and Computer Engineers. Loops

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Course Outline Introduction to C-Programming

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Fundamentals of Programming

Operators and Expressions:

Review of the C Programming Language for Principles of Operating Systems

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Data Types. Data Types. Integer Types. Signed Integers

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

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

LESSON 6 FLOW OF CONTROL

Lecture 3. More About C

LESSON 4. The DATA TYPE char

Iteration. Side effects

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Data Types and Variables in C language

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

CS313D: ADVANCED PROGRAMMING LANGUAGE

UNIT- 3 Introduction to C++

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Control Flow, Functions and Basic Linkage

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Introduction to C++ with content from

Chapter 4. Flow of Control

THE FUNDAMENTAL DATA TYPES

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

3 The L oop Control Structure

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Variables and Operators 2/20/01 Lecture #

Informatica e Sistemi in Tempo Reale

BSM540 Basics of C Language

Lecture 10. Daily Puzzle

Fundamentals of Programming

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook

C++ Programming Lecture 1 Software Engineering Group

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

BİL200 TUTORIAL-EXERCISES Objective:

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

15 FUNCTIONS IN C 15.1 INTRODUCTION

Operators And Expressions

Functions. (transfer of parameters, returned values, recursion, function pointers).

Decision Making and Loops

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

CSE123. Program Design and Modular Programming Functions 1-1

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

Model Viva Questions for Programming in C lab

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Variables and literals

Programming Language A

from Appendix B: Some C Essentials

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

Review of the C Programming Language

Principles of C and Memory Management

Lecture 6. Statements

The Design of C: A Rational Reconstruction (cont.)

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Programming and Data Structures

Introduction to C Language (M3-R )

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

Introduction to C/C++ Lecture 3 - Program Flow Control

A Fast Review of C Essentials Part I

Transcription:

Week 2 / Lecture 2 15 March 2017 NWEN 241 Control constructs, Functions Alvin Valera School of Engineering and Computer Science Victoria University of Wellington

Admin stuff Tutorial #2 Expectations on programming assignment Development environment issues Data input/output with standard C library functions getchar putchar gets puts printf scanf General debugging tips 2

Recap Built-in operators Arithmetic Assignment Increment/decrement Relational Equality and logical Arithmetic, assignment, increment/decrement operators evaluate to some numeric value Relational, equality and logical operators evaluate to either 1 (true) or 0 (false) 3

Recap When evaluating expressions Operator precedence determines the sequence in which operators in an expression are evaluated Associativity determines execution for operators of equal precedence Precedence can be overridden by explicit grouping using ( and ) which has the highest precedence When expression involves operands of diferent types C automatically converts intermediate values to the proper type so that the expression can be evaluated without losing any significance 4

Clarification on conversion hierarchy Conversion hierarchy short int char unsigned long int long int double float long double Operands that are of type char, short and enum are always converted up to int if it is suficient, otherwise to unsigned int This is known as integral promotion 5

Clarification on relational operator example Suppose: double x = 7e+33, y = 0.001; Expression Equivalent expression Value x < x + y x < (x + y) Expression is evaluated as (x - (x + y)) < 0.0 Because is x extremely large and y is small, there is loss in accuracy in evaluating x + y That is, x and x + y becomes equal The expression simplifies to 0.0 < 0.0 which is false (0) 0 6

This lecture Control blocks Ternary operator Functions Function-like macros 7

Recallf compound statement Compound statement Begins with { and ends with } Consists of 0 or more declarations and 0 or more statements Main use is to group statements into an executable unit Also known as block { int i, j=1; } i = 2*j + 1; printf("%d", i); 8

When to declare variables Prior to C99 Variables can only be declared at the beginning of a block With C99 and afer Variables can be declared anywhere in block, before usage { int i, j; { int i; scanf("%d", &i); } scanf("%d", &i); scanf("%d", &j); } int j; scanf("%d", &j); 9

Control constructs in C Control flow If-else Else-if Switch Loop While-loop For-loop Do-while-loop 10

Control flowf if-else statement if (expression) statement 1 else statement 2 The else part is optional If expression evaluates to true*, statement 1 is executed Else, statement 2 is executed if the else part is present *Recall: true non-zero; false zero statement 1 and statement 2 can be single or compound statements 11

Examplesf if-else statement if (y!= 0.0) x /= y; if (c == ' ') { ++blank_cnt; printf("found another blank\n"); } if (a > b) max = a; else max = b; if (n > 0) if (a > b) z = a; else z = b; To which if does this else belong to? 12

Conditional expression (ternary operator) expr 1? expr 2 : expr 3 expr 1 is evaluated first If expr 1 evaluates to true, then expression expr 2 is evaluated and that is used as the value of the expression Otherwise, expr 3 is evaluated and that is used as the value of the expression Example: z = (a > b)? a : b; /* z = max(a, b) */ 13

Control flowf else-if statement if (expression 1 ) statement 1 else if (expression 2 ) statement 2... else if (expression N ) else statement N statement The else part is optional expression 1 to expression N are evaluated in sequence If expression k (where k is 1,2,...,N) evaluates to true, statement k is executed The rest of else if and else are not evaluated any further If none of expression 1 to expression N is true, then the else statement is executed (if present) The statements can be single or compound statements 14

Examplef else-if statement if (temp <= 0) printf("it's freezing out there.\n"); else if (temp <= 10) { too_cold++; printf("it's too cold for me.\n"); } else if (temp <= 20) printf("it's still cold.\n"); else printf("awesome!\n"); 15

Control flowf switch statement switch (expression) { case const_expr 1 : } statements 1 case const_expr 2 : statements 2... case const_expr N : statements N default: statements The default part is optional const_expr 1 to const_expr N must be integer constants or constant expressions If expression matches const_expr k, execution starts at that case default is executed if none of the cases match The statements can consist of single or multiple statements statements, or compound statements 16

Examplef switch statement char c = getchar(); switch(c) { case 'Y': case 'y': printf("you answered yes.\n"); break; case 'N': case 'n': printf("you answered no.\n"); break; default: printf("what was that?\n"); break; Is this necessary? } 17

Loopf while-loop statement while (expression) statement If expression evaluates to true: statement is executed expression is re-evaluated again Cycle continues until expression evaluates to false statement can be single or compound statement 18

Loopf for-loop statement for (expr 1 ; expr 2 ; expr 3 ) statement expr 1 ; while (expr 2 ) { } statement expr 3 ; The expressions are optional expr 1 and expr 3 are usually assignments or function calls expr 2 is usually a relational expression If expr 2 is missing, it is taken as permanently true 19

Loopf do-while-loop statement do statement while (expression); statement is executed, then expression is evaluated If expression evaluates to true, statement is executed again Loop terminates when expression evaluates to false 20

Examplef loop statements Infinite loops: while(1); for (;;); do {} while(1); int i = 10; while(i > 0) { printf("%d\n", i); i--; } for(int i = 10; i > 0; i--) { printf("%d\n", i); } Are these necessary? do { printf("do you agree with the contract?\n"); ans = getchar(); } while (ans!= 'Y' ans!= 'y'); 21

Statements that can alter control flow & loop break, return, continue and goto break: jumps out of the loop or switch return: jumps out of the loop or switch (the loop or switch must be inside a function) continue: stops current loop iteration and starts next iteration goto jumps to a labelled statement 22

Functions in C programs Every C program has at least one function: main() No C program needs to have more than one function in it Everything can be put in main(): not a good idea Any C program with only a main function is almost certainly for training purposes What are functions good for? structuring our thoughts (structured programming) allowing us to re-use code, reducing work and reducing errors A C program can be modularised by functions A big program can be broken down into a number of smaller ones 23

Creating a simple function Suppose we frequently wanted to compare two integers and then use the larger. We might have code like this repeatedly written in our program: int p, q, l;... /* p, q initialised */ if (p > q) l = p; else l = q;... /* l gets used */ 24

Creating a simple function How about making it a stand-alone function? What we need to do: l = larger(p, q); Pick a name for the function: larger() Specify what type of variables that larger() is going to compare: larger(int, int) Specify what type of value that larger (int, int) is going to return: int larger(int, int) int larger(int, int): this is called function prototype / declaration Code it: function definition/implementation 25

Creating a simple function Function definition: int larger(int x, int y) { if (x > y) return x; else return y; } x and y are called formal parameters, whose scope is the body of the function. 26

Invoking a function... int main(void) {... l = larger(p, q); /* p and q are called actual */... /* parameters. Their values are */ } /* going to be copied to x and y. */ int larger(int x, int y) { /* x and y (NOT p and q) are */ if (x > y) /* going to be compared here. */ return x; /* the larger value is going to be */ else return y; /* returned to larger(p, q). */ } 27

Role of function prototype Function prototype is used by compiler to check whether your program is passing the right parameters For functions that do not return a value, the compiler ensures that the function is not part of an expression Hence, a function prototype must be declared prior to its use For functions in standard library (and other provided libraries), include the appropriate header files For user-defined functions, you have to declare the prototypes before the main function 28

Role of function prototype int main(void) {... l = larger(p, q); /* larger() not declared yet */... } int larger(int x, int y) {... } Problem: function prototype not declared before being used int larger(int, int); int main(void) {...} int larger(int x, int y) {...} 29

Passing arguments to a function Function call: l = larger(p, q); Pass by value The values of actual parameters (p, q) are copied to formal parameters (x, y) actual parameters and formal parameters are separate entities What happens thereafer to formal parameters has nothing to do with actual parameters Any changes on x, y will not be transferred back to p, q There is another way of passing arguments to functions 30

Function-like macros Recall: C preprocess can used to define constants #define PI 3.14 Can also define macros that can be invoked like functions Append () in the macro name #define READ_CHAR() getchar() 31

Function-like macros Just like functions, function-like macros can take arguments Insert comma-separated parameter names between ( and ) Parameter names must be valid C identifiers #define max(x, Y) ((X) > (Y)? (X) : (Y)) Invoke just like normal functions z = max(1, 3); z = ((1)>(3)?(1):(3)); This expression evaluates to 3 32

Problems with function-like macros Suppose: #define SQ(X) X * X Then: (int)sq(r); (int)r * r; SQ(r1 + r2); r1 + r2 * r1 + r2; Solution: enclose individual variables with (), including the whole replacement text #define SQ(X) ((X) * (X)) 33

Problems with function-like macros Suppose: #define SQ(X) ((X) * (X)) Then: (int)sq(r); (int)((r) * (r)); SQ(r1 + r2); ((r1 + r2) * (r1 + r2)); 34

Problems with function-like macros Suppose: #define SQ(X) ((X) * (X)) How about these? SQ(++r); ((++r) * (++r)); r incremented twice SQ(f()); ((f()) * (f())); f() invoked twice Be careful when defining and calling function-like macros! 35

Next week Arrays 36