Lecture 5 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Review of Chapter 3--- Flow of Control  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound.
CS 201 Functions Debzani Deb.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections & Chapter 6.
Function (L16) * Mathematical Library Functions * Program Components in C++ * Motivations for Functionalizing a Program * Function Prototype * Function.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Functions. COMP104 Lecture 13 / Slide 2 Review of Array: Bubble Sort for (j=0; j List[j+1]) swap(List[j], List[j+1]); }
Introduction to Java Programming, 4E Y. Daniel Liang.
CS 201 Functions Debzani Deb.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Chapter 6: User-Defined Functions I
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Topic 2A – Library Functions and Casting. CISC 105 – Topic 2A Functions A function is a piece of code which performs a specific task. When a function.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Lecture 4 Introduction to Programming in C Prof. Dr. Arne Kutzner Hanyang University / Seoul Korea.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Fundamentals of C and C++ Programming Control Structures and Functions.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter 5 Methods F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters F Pass by Value F Overloading Methods F Method Abstraction.
Lecture 12: Dividing Up Work. Why Using Functions Divide-and-conquer making large program development more manageable. Software reusability Use existing.
Chapter 4 – C Program Control
CS1001 Programing Fundamental Lecture 5 Top-Down Design with Functions
Chapter 6: User-Defined Functions I
Lecture 7: Repeating a Known Number of Times
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Lec8.
Chapter 5 Methods.
1-6 Midterm Review.
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Lecture 5 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea

Further loop structures: for structures, do-while statements

Introduction to CL3.3 for structure Syntax: For-loops have three loop control statements: –Initialization of the loop control variable. –Test of the loop repetition condition –Update of the loop variable for( initialization; loop_repetition_condition; update ) statement;

Introduction to CL3.4 for structure with compound Syntax: for( initialization; loop_repetition_condition; update ) {statement_1; statement_2; … statement_n; }

Introduction to CL3.5 for structure (cont.) Any for-loop may be represented as while- loop as follows: for (stat1; expr2; stat3) { statement; } stat1; while (expr2) { statement; stat3; }

Introduction to CL3.6 Example while versus for i = 0; while (i < N) { printf("*"); i = i + 1; } initialization update loop repetition condition for (i = 0; i < N; i = i + 1) printf("*"); initialization loop repetition condition update statement

Introduction to CL3.7 Caution: common error The following loop does not sum up the values from 0 to n. (only up to n – 1) for (i=0; i<n; i = i + 1) sum = sum + i;

Introduction to CL3.8 Caution (weird C) Adding a semicolon at the end of the for clause before the loop body is a common mistake: int i; for (i = 0; i < 10; i = i + 1); { printf("i is %d", i); } Wrong

Introduction to CL3.9 do-while Statement Syntax The for and while statements both evaluate the loop repetition condition before the execution of the loop body The do-while loop checks the repetition condition at the end of the loop body do { statement_1; statement_2; … statement_n; } while (loop_repetition_condition);

Introduction to CL3.10 while versus do-while do { printf("Enter a letter from A to Z>"); scanf("%c", &letter_choice); } while (letter_choice => 'A' && letter_choice <= 'Z'); printf("Enter a letter from A to Z>"); scanf("%c", &letter_choice); while (letter_choice => 'A' && letter_choice <= 'Z') { printf("Enter a letter from A to Z>"); scanf("%c", &letter_choice); };

Introduction to CL3.11 Caution (weird C) The problem with while, do-while and the semicolon. int i=0; while (i<10); { printf("i is %d", i); i = i + 1; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { printf("i is %d“, i); i = i + 1; } while (i<10); Wrong Correct

break, continue and goto

Introduction to CL3.13 break and continue Statements A break statement causes the innermost enclosing loop to be exited immediately. continue causes the next iteration of the enclosing for, while, or do-while loop to begin. When continue statement is used in while and do-while loops, then this means that the condition part is executed immediately; in the for loop, control passes to loop variable update step.

Introduction to CL3.14 Flowchart continue statement (for while loop) false true Statement(s) Next Statement Continue condition? Statement(s) continue;

Introduction to CL3.15 Flowchart break statement (for while loop) false true Statement(s) Next Statement Continue condition? Statement(s) break;

Introduction to CL3.16 Example continue In the above program the sum of all odd numbers from 1 to 99 is calculated. int sum = 0; int n = 1; while (n <= 100) { if ((n % 2) == 0) { n = n + 1; continue; } sum = sum + n; n = n + 1; }

Introduction to CL3.17 The goto statement General Syntax: goto label; … label: … The goto statement is only for very special situations and almost never used. If the program flow reaches the goto statement it continues at the position marked with label:

Introduction to CL3.18 The goto statement (cont.) Example: for (…) for (…) { … if (disaster) goto error; } … error: error related code

switch Structures

Introduction to CL3.20 switch structure Syntax switch (expression) { case const-expr : statements; break; case const-expr : statements; break; … default : statements; }

Introduction to CL3.21 switch structure To select one of several alternatives. Selection is based on the value of an expression. Expression can be a single value. The type of expression can be either int or char, but not double.

Introduction to CL3.22 switch structure / Flow diagram case A case A actions true false break case B case B actions true false break case N case N actions true false break default actions

Introduction to CL3.23 switch structure (Example) switch (class) { case 'B': case 'b': printf ("Battleship\n"); break; case 'C': case 'c': printf ("Cruiser\n"); break; case 'D': case 'd': printf ("Destroyer\n"); break; case 'F': case 'f': printf ("Frigate\n"); break; default: printf ("Unknown ship class%c\n", class); }

Conditional Operator, decrement and increment Operators, Shortcut assignments

Introduction to CL3.25 Conditional Operator General form: (booleanExp) ? exp1 : exp2 Example: if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; Ternary operator

Introduction to CL3.26 Increment and Decrement Operators

Introduction to CL3.27 Increment and Decrement Operators, cont. int i=10; int newNum = 10*(i++); int newNum = 10*i; i = i + 1; Equivalent to int i=10; int newNum = 10*(++i); i = i + 1; int newNum = 10*i; Equivalent to

Introduction to CL3.28 Shortcut Assignment Operators OperatorExampleEquivalent +=i+=8i = i+8 -=f-=8.0f = f-8.0 *=i*=8i = i*8 /=i/=8i = i/8 %=i%=8i = i%8

Functions

Introduction to CL3.30 Functions: Introduction Functions are program modules written to –avoid the repetition of identical code parts –solve “a bigger problem” by decomposing it into “smaller problems” Example: A Function max that delivers the maximum of two values. Functions 1.take one or several arguments, 2.compute some statements and 3.return a single value

Introduction to CL3.31 Function Definition in C Syntax data_type identifier (arg_1, arg_2,…) { local variable declarations executable statements } Function name (identifier) Formal Arguments Data type of the returned value

Introduction to CL3.32 Function Arguments / Local Variables Syntax of a single formal argument: data_type identifier Local variables are variables that are known inside a function only –Different functions may have local variables with identical names

Introduction to CL3.33 Scope of Local Variables Scope of a variable: The part of the program where a variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the function that contains the variable.

Introduction to CL3.34 The return statement Functions return a single value using the return statement. Syntax: return expression ;

Introduction to CL3.35 Example: max function int max (int i, int j) { int m; if (i > j) m = i; else m = j; return m; } Local variable definition

Introduction to CL3.36 Function Calls Syntax: function_name(arg1, arg2, …); –Actual arguments may be constants, variables, or expressions. –Example of function call max(a, b) –Example of function call plus assignment x = max(a, b); actual arguments

Introduction to CL3.37 Example Function Call pass i pass j int max (int i, int j) { int m; if (i > j) m = i; else m = j; return m; } void main() { int a, b, x; a = 5; b = 2; x = max (a, b); printf("%d", x); }

Introduction to CL3.38 Example Function Call, cont. The main method a: b: x: The max method i: j: m: pass pass 2 parameters return value The values of a and b are copied to i and j.Graphically:

Introduction to CL3.39 Call by Value Semantic Because the arguments are copied in C we talk of a call by value semantic

Introduction to CL3.40 Function without Returned Value Syntax void fname (arg1, arg2, …) { local variable declarations executable statements } The keyword void indicates that the function does not return any value

Introduction to CL3.41 Iterative Programming The factorial function can be programmed by a for loop as follows: int factorial(int x) { int prod, i; prod = 1; for (i = 1; i <= x; i = i + 1) prod = prod * i; return prod; } Such a loop-based solution is called a “iterative programming”

Introduction to CL3.42 Recursion A function can call itself inside its body. Example factorial function: int factorial(int x) { if (x > 1) return x * factorial(x - 1); else return 1; } This programming technique is called Recursion Recursive call of factorial

Introduction to CL3.43 Computing Factorial, cont. Main function: factorial (4) factorial (4) = 4*factorial(3) factorial (3) = 3*factorial(2) factorial (2) = 2*factorial(1) factorial (1) = 1*factorial(0) factorial (0) = 1 factorial(4) is called in the main Step 5: factorial(0) returns 1 Step 1: factorial(4) calls factorial(3) Step 2: factorial(3) calls factorial(2) Step 3: factorial(2) calls factorial(1) Step 4: factorial(1) calls factorial(0) Step 6: factorial(1) returns 1 (1*1) Step 7: factorial(2) returns 2 (2*1) Step 8: factorial(3) returns 6 (3*2) Step 9: factorial(4) returns 24 (4*6)

Introduction to CL3.44 Function Declarations Function declaration format return-value-type function-name (arguments'-type); return-value-type: data type of the result (default int) –void indicates that the function returns nothing function-name: any valid identifier Arguments' type: comma separated list of arguments' type

Introduction to CL3.45 Example: Function declaration and definition in a program A function named example that takes 2 arguments of type double and returns no data, would look like: double example(double, int); int main() { … } double example (double a, int b); { … }

Introduction to CL3.46 Predefined Library Functions Functions that are implemented as a part of C toolkit. Example: printf If a library function is used, then the corresponding header file should be included at the top of the program using an appropriate preprocessor directive. Example: #include for printf function.

Introduction to CL3.47 Some Mathematical Library Functions Defined in math.h FunctionPurpose double ceil(double x) returns the smallest integer greater than x double exp(double x) returns double fabs(double x) returns the absolute value of x double floor(double x) returns the largest integer less than x double log(double x) returns the natural logarithm of x double log10(double x) returns the base 10 logarithm of x double sqrt(double x) returns the square root of x

Introduction to CL3.48 Some Mathematical Library Functions Defined in math.h FunctionPurpose double sin(double x) returns the sine of x double cos(double x) returns the cosine of x double tan(double x) returns the tangent of x double pow(double x, double y) returns int abs(int x) returns the absolute value of x Defined in stdlib.h

Introduction to CL3.49 Programming Technique: Top-Down Design A problem-solving method in which a given problem is first broken into its major subproblems. Then the subproblems are solved to get some solution for the original problem Subproblems are typically solved by use of functions.

Introduction to CL3.50 Example Top-Down Design: Structure Chart for drawing a Stick figure ** /\ /\ ** /\ /\

Introduction to CL3.51 Program for drawing a stick figure #include /* function declarations (prototypes) */ void draw_circle(void); void draw_intersect(void); void draw_base(void); void draw_triangle(void); int main() { /* draw a circle */ draw_circle(); /* draw a triangle */ draw_triangle(); /* draw intersection lines */ draw_intersect(); }

Introduction to CL3.52 Function Definitions used for Drawing a Stick Figure /* Draw a circle */ void draw_circle(void) { printf(" **\n"); } /* Draw a intersection lines */ void draw_intersect(void) { printf(" /\\\n"); } /* Draw a base line */ void draw_base(void) { printf ("------\n"); } /* Draw a triangle */ void draw_triangle(void) { draw_intersect(); draw_base(); }