INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from
|
|
- Jonas Sullivan
- 5 years ago
- Views:
Transcription
1 INTRODUCTION TO C++ FUNCTIONS Original slides are from Dept. of Electronic Engineering, NCHU
2 Outline 2 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Header files Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion
3 What is a function? 3 Top-down design: Divide and conquer Partition a problem into several small sub-problems Each sub-problem can be solved by a function (module) Function A module with a specific function name Given a set of inputs, return an output Two types of functions User-defined functions ANSI C standard library functions, such as print(), scanf(), pow()
4 Function call 4 Invoke functions Provide function name and arguments (inputs) Return results (output) Format: output = function_name(input1, input2, ) Example printf( There are 50 students\n ); Function name: printf Inputs: There are 50 students\n pow(5.0, 3.0) Function name: pow Inputs: 5.0, 3.0 Output: 125 (5 3 )
5 Advantages of functions 5 Reusability Readability Ease of maintenance Avoid code repetition Use ANCI C standard library to improve portability
6 Function Definition 6 return-data-type function-name (data-type arg1, data-type arg2, ) { declarations; statements; return output; Function-name Any valid identifier (follow the same rule with variables) Parameter list A set of inputs separated by comma (,) Specify a data type for each input argument
7 Function Definition 7 Return-data-type Data type of the result void: Indicate that the function returns nothing Need to return an output with the specified data type If return-data-type is void return; If something returned return output; // output needs to be the specified type Function body Declarations and statements Declarations: variables used inside the function block, which can not be used outside the function Functions can not be defined inside a function
8 Function Definition: example 8 double compute_avg(int a, int b, int c) { Starting point return (double) (a + b + c)/3; int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; Function definition: Name: compute_avg Inputs: a, b, c (integer) Output: return a double value // call function A function needs to be defined before function call
9 Function Prototype 9 Declare function prototypes before function call if the function is defined after function call Put semicolon (;) at the end of function prototype Argument names can be omitted in function prototypes double compute_avg(int, int, int); // function prototype int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; double compute_avg(int a, int b, int c) { return (double) (a + b + c)/3; // call function // function definition
10 Function Prototype 10 Parameter names are sometimes included in function prototypes for documentation purposes. The compiler ignores these names. double compute_avg(int a, int b, int c); int main() { double avg; int a, b, c; scanf( %d %d %d, &a, &b, &c); avg = compute_avg(a, b, c); return 1; double compute_avg(int a, int b, int c) { return (double) (a + b + c)/3; // function prototype // call function // function definition
11 Programming error 11 Variable name can not be the same with argument names void foo(int tmp) { /* tmp is the argument name, so it can not be used as a variable name */ int tmp = 1; return; int main() { foo(1); return 1; // call function
12 Programming error 12 Must return a result in any condition int foo(int tmp) { /* no returned value when tmp <= 0 */ if (tmp > 0) return tmp + 1; int main() { foo(-1); return 1; // call function
13 Programming error 13 The returned value can only be assigned to another variable with the same type double foo(int a, int b) { return (double) (a+b)/2; int main() { /* the returned data type of foo() is double, but the type of avg is int */ int avg; avg = foo(2, 3); // call function return 1; Can force it to transform the data type by avg = (int) foo(2, 3)
14 Programming error 14 A variable declared in the function can not be used outside the function double foo(int a, int b) { int sum = a + b; return (double) sum/2 int main() { /* assign the results of foo() to avg */ double avg = foo(2, 3); // call function /* sum is declared in foo(), so can not be used here */ printf( sum is %d, avg is %f\n, sum, avg); return 1;
15 Available usage 15 Function call A() can be the argument of another function call B() if the return type of A() is not void int max(int a, int b) { if (a > b) return a; else return b; int main() { int i, j; scanf( %d %d, &i, &j); /* print the output of max(i,j) use %d because max() returns an integer value */ printf( max is %d\n, max(i, j)); return 1;
16 Available usage 16 The output of function call can be used as a logical control /* return 1 if a > b; otherwise, 0 */ int test_larger (int a, int b) { if (a > b) return 1; else return 0; int main() { int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { if (test_larger(i, j)) printf( (%d,%d)\n, i, j); // print if i > j return 1; (2,1) (3,1) (3,2) (4,1) (4,2) (4,3) (5,1) (5,2) (5,3) (5,4) output
17 Available usage 17 Call another function in a function int square (int); int square_sum(int); int square (int num) { return num * num; int square_sum(int num) { int sum = 0; for(int i = 1; i <= num; i++) sum += square(i); return sum; Function definition of square () must be placed before that of square_sum() Otherwise, declare function prototypes in the beginning of the program int main() { printf( square sum = %d\n, square_sum(10)); return 1;
18 Math Library Functions 18 Math library functions perform common mathematical calculations #include <math.h> Reference Function Function definition Description Example cos() double cos(double x) cosine of an angle of x sin(0.0)=0.0 sin() double sin(double x) sine of an angle of x cos(0.0)=1.0 tan() double tan(double x) tangent of an angle of x tan(0.0)=0.0 acos() double acos(double x) arc cosine of x asin() double asin(double x) arc sine of x atan() double atan(double x) arc tangent of x
19 Math Library Functions 19 Function Function definition Description Example sqrt() double sqrt(double x) square root of x sqrt(9.0)=3.0 exp() double exp(double x) exponential function e x exp(1.0)= log() double log(double x) natural logarithm of x (base e) log10() double log10(double x) natural logarithm of x (base e) log( )=1.0 log10(100.0)=2.0 fabs() double fabs(double x) Absolute value of x abs(-2.3)=2.3 ceil() double ceil(double x) round x to the smallest integer not less than x floor() double floor(double x) round x to the largest integer not greater than x pow() double pow(double x, double y) x raised by power y (x y ) ceil(2.3)=3.0 ceil(-9.8)=-9.0 floor(2.7)=2.0 floor(-9.8)=-10 pow(2.0,3)=8.0 pow(4.0,0.5)=2.0
20 Outline 20 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Headers Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion
21 Headers 21 Standard library header files Contain function prototypes for library functions <stdlib.h>, <math.h>, etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Advantage: Reusability
22 Standard library header files 22 <assert.h> <ctype.h> Convert lowercase letters to uppercase letters and vice versa <errno.h> <float.h> <limits.h> <locale.h> <math.h> Math library functions <setjmp.h>
23 Standard library header files 23 <signal.h> <stdarg.h> <stddef.h> <stdio.h> Standard input/output library functions <stdlib.h> Convert number to text and text to number, memory allocation, random number, and other utility functions <string.h> String-processing functions <time.h> Time and date
24 Custom header files 24.c file #include myheader.h int main() { statements; void function1() { statements; return; myheader.h file #include <stdio.h> #include <stdlib.h> void function1(); int function2(int, int); int function2(int a, int b) { statements; return output;
25 Outline 25 Functions: Program modules in C Function Definitions Function Prototypes Math Library Functions Headers Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion
26 Calling Functions 26 Call by value Passes copy of argument to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference (or call by address) Passes original argument Changes in function effect original Only used with trusted functions
27 Example: Call by value 27 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = * radius * radius; return a; Copy 2.5 to another memory block main() r 2.5 compute_area(r); foo() radius 2.5
28 Outline 28 Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion
29 Scope Rules 29 Types of variables Local variable Can only be referenced inside a function body Global variable Identifier defined outside function, known in all functions Global variables, function definitions, function prototypes
30 Example: local variable 30 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = * radius * radius; return a; Scope of area and r Scope of a and radius
31 Example: local variable 31 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f\n, area); return 0; double foo (double radius) { double a; a = * radius * radius; return a; main() area r compute_area(r); Copy Copy 2.5 foo() a radius
32 Example: local variable 32 double foo (double); int main () { double area, r = 2.5; area = foo(r); printf( area: %f r: %f\n, area, r); return 0; area: 7.07 r: 2.5 double foo (double r) { double area; r = 1.5; area = * r * r; return area; r in main() and foo() are two different variables occupying two memory blocks with the same name!! area 7.07 main() r 2.5 compute_area(r); Copy 7.07 area foo() r Copy 2.5 Modifying the value of r in foo() does not affect the value of r in main()
33 Example: global variable 33 double foo (); double r; int main () { r = 2.5; double area; area = foo(); printf( area: %f\n, area); printf( r:%f\n,r_; return 0; double foo () { double area; r = 1.5; area = * r * r; return area; Scope of area in main() Scope of r Scope of area in foo()
34 Example: global variable 34 double foo (); double r; int main () { r = 2.5; double area; area = foo(); printf( area: %f\n, area); printf( r: %f\n, r); return 0; area: 7.07 r: 1.5 double foo () { double area; r = 1.5; area = * r * r; return area; r main() area 7.07 compute_area(); Copy 7.07 foo() area 7.07
35 Example: global variable 35 double foo (); double r; int main () { r = 1; double area; area = foo(); printf( area: %f, r: %f\n, area, r); area = foo(); printf( area: %f, r: %f\n, area, r); return 0; double foo () { double area; area = * r * r; r++; return area; Copy 3.14 r 12 main() area 3.14 compute_area(); foo() area 3.14
36 Example: global variable 36 double foo (); double r; int main () { r = 1; double area; area = foo(); printf( area: %f, r: %f\n, area, r); area = foo(); printf( area: %f, r: %f\n, area, r); return 0; area: 3.14, r: 2 area: 12.57, r: 3 double foo () { double area; area = * r * r; r++; return area; r 32 main() area compute_area(); Copy foo() area 12.57
37 Calling Functions 37 Call by value Passes copy of argument to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference Passes original argument Changes in function effect original Only used with trusted functions
38 Call by reference 38 The address of an argument is passed to a function Function definition function_name(data_type* arg_name) symbol *: pointer for getting the value stored in the specified address Calling function function_name(&variable_name); symbol &: get the address of a variable
39 Pointer 39 Address: *b 10 int a; b *b int *b; b = &a (assign the address of a to b) int main () { int a = 10; int * b = &a; printf( a: %d\n, a); printf( address of a: %d\n, b); printf( data pointed by b: %d\n, *b); return 0; output a: 10 address of a: data pointed by b: 10 *b (data pointed by b)
40 Example: Call by reference 40 double foo (double *); int main () { double area, r = 2.5; area = foo(&r); printf( area: %f r: %f\n, area, r); return 0; area main() r 2.5 compute_area(&r); Address Pass the address of r (&r = 21220) double foo (double * pr) { double area; *pr = 1.5; area = * (*pr) * (*pr); return area; area foo() pr 22110
41 Example: Call by reference 41 double foo (double); main() *pr r in main() is set to 1.5 int main () { double area, r = 2.5; area = foo(&r); printf( area: %f r: %f\n, area, r); return 0; area: 7.07 r: 1.5 double foo (double * pr) { double area; *pr = 1.5; area = * (*pr) * (*pr); return area; area 7.07 r compute_area(&r); Assign 1.5 to *pr (=r) area foo() pr * (*pr) * (*pr) = 3.14 * 1.5 * 1.5 Address 21220
42 Sample-05-4: swap 42 Write a function to swap the values of two variables Why the following code does not work? void swap (int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf( swap: a = %d; b = %d\n, a, b); int main() { int a = 10, b = 5; printf( main; a = %d; b = %d\n, a, b); swap (a, b); printf( main; a = %d; b = %d\n, a, b); return 0; Local variables in swap() a b 10 5 tmp 1 a b a b 5 10 output main: a = 10; b = 5 swap: a = 5; b = 10 main: a = 10; b = 5
43 Sample-05-4: swap 43 *pa main() *pb void swap(int *, int *); int main() { int a = 10, b = 5; printf( main; a = %d; b = %d\n, a, b); swap (&a, &b); printf( main; a = %d; b = %d\n, a, b); return 0; void swap (int * pa, int * pb) { int tmp; tmp = *pa; *pa = *pb; *pb = tmp; a b swap(&a, &b) *pa *pb pa pb tmp 10 swap()
44 Outline 44 Calling Functions: Call-by-value and Call-byreference Scope Rules Recursion
45 Recursion 45 Functions that call themselves Example void foo () { foo(); Termination condition is required to ensure that the function will eventually end and return
46 Example: factorials 46 void fac (int num) { //if (num <= 1) // return 1; //else Must have a termination condition return (num * fac(number - 1)); int main() { int a, result; scanf( %d, &a); result = fac(a); printf( %d!=%d\n, a, result); return 0; Recursive Call
47 Example: factorials 47 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4! = 4 * 3 * 2 * 1 = 4 * 3! = 3 * 2 * 1 = 3 * 2! 5! = 120 = 5 * 24 = 24 = 4 * 6 = 6 = 3 * 2 return factorial(5) =120 return factorial(4) =24 return factorial(3) =6 return factorial(2) =2 void factorial (int num) { if (num <= 1) return 1; else return (num * fac(num - 1)); = 2 * 1 = 2 * 1! 1 = 2 = 2 * 1 1 return factorial(1) =1
48 Sample-05-5: Fibonacci series 48 0, 1, 1, 2, 3, 5, 8... Each number is the sum of the previous two fib( n ) = fib( n - 1 ) + fib( n 2 ) Terminate when n = 0 or n = 1 if(n == 0 n == 1) return n; + + fib(n) 0 n= n=1 n=2 n=3 n=4 n=5 n=6
49 Sample-05-5: Fibonacci series 49 fib(3) return fib(2) + fib(1) return fib(1) + fib(0) return 1 return 1 return 0
Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 4
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions
More informationFunctions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries
More informationFunctions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction
Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that
More informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
More informationECET 264 C Programming Language with Applications
ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10
More informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationC Programs: Simple Statements and Expressions
.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following
More informationFunctions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5
More informationFunctions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa
Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined
More informationProgramming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.
Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results
More informationFunction. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers
Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out
More informationC Functions Pearson Education, Inc. All rights reserved.
1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville
More information6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x
(Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)
More informationLecture 2:- Functions. Introduction
Lecture 2:- Functions Introduction A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. The most important reason
More informationProgramming in C Quick Start! Biostatistics 615 Lecture 4
Programming in C Quick Start! Biostatistics 615 Lecture 4 Last Lecture Analysis of Algorithms Empirical Analysis Mathematical Analysis Big-Oh notation Today Basics of programming in C Syntax of C programs
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationCS110: PROGRAMMING LANGUAGE I
CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters
More informationTo define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,
1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationLecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch
Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationFunction Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design
What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationIntroduction to Programming
Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More informationIntroduction to C Language
Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,
More informationCOP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of
More informationPreview from Notesale.co.uk Page 2 of 79
COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the
More informationChapter 5 Methods / Functions
Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a
More informationUsing Free Functions
Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Evaluate some mathematical and trigonometric functions Use arguments in function
More informationTutorial 5. PDS Lab Section 16 Autumn Functions The C language is termed as function-oriented programming
PDS Lab Section 16 Autumn-2018 Tutorial 5 Functions The C language is termed as function-oriented programming Every C program consists of one or more functions. The concept is based on the divide-and conquer
More informationC++, How to Program. Spring 2016 CISC1600 Yanjun Li 1
Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationChapter 4 Functions By C.K. Liang
1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information
More informationWriting an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and
Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and #include The Use of printf() and scanf() The Use of printf()
More informationCS101 Introduction to computing Function, Scope Rules and Storage class
CS101 Introduction to computing Function, Scope Rules and Storage class A. Sahu and S. V.Rao Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Outline Functions Modular d l Program Inbuilt
More informationBenefits of Methods. Chapter 5 Methods
Chapter 5 Methods Benefits of Methods Write a method once and reuse it anywhere. Information hiding: hide the implementation from the user Reduce complexity 1 4 Motivating Example Often we need to find
More informationComputer Programming
Computer Programming Make everything as simple as possible, but not simpler. Albert Einstein T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 1 Outline Functions Structure of a function
More informationChapter 6 Methods. Dr. Hikmat Jaber
Chapter 6 Methods Dr. Hikmat Jaber 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationChapter 5 C Functions
Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(
More informationLecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi
Lecture 5 Functions II Functions with Arguments CptS 121 Summer 2016 Armen Abnousi Remember Functions break problems into smaller pieces Easier to read, test and maintain Functions allow to avoid repetition
More informationJAVA Programming Concepts
JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa Find the sum of integers from 1 to 10,
More informationChapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }
Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,
More informationChapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk
Chapter 5 Methods Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Introducing Methods A method is a collection of statements that
More informationComputer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries
Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,
More informationC Functions. CS 2060 Week 4. Prof. Jonathan Ventura
CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference
More informationFunctions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.
1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare
More informationDUBLIN CITY UNIVERSITY
DUBLIN CITY UNIVERSITY SEMESTER ONE EXAMINATIONS 2007 MODULE: Object Oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering B.Eng. in Information Telecommunications Engineering B.Eng.
More informationMethods (Deitel chapter 6)
Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
More informationDUBLIN CITY UNIVERSITY
DUBLIN CITY UNIVERSITY REPEAT EXAMINATIONS 2008 MODULE: Object-oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering (Year 2 & 3) B.Eng. in Information Telecomms Engineering (Year 2 &
More informationMethods (Deitel chapter 6)
1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
More information1001ICT Introduction To Programming Lecture Notes
1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming
More informationC++ PROGRAMMING SKILLS Part 3 User-Defined Functions
C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions
More informationSlide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary
Slide Set 3 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2016 ENCM 339 Fall 2016 Slide Set 3 slide 2/46
More informationLanguage Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science
Language Design COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Language Design Issues Syntax: how programs look Names and reserved words Instruction
More informationIntroduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer
Introduction to Computers II Lecture 4 Dr Ali Ziya Alkar Dr Mehmet Demirer 1 Contents: Utilizing the existing information Top-down design Start with the broadest statement of the problem Works down to
More information12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
12. Numbers Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Numeric Type Conversions Math Class References Numeric Type Conversions Numeric Data Types (Review) Numeric Type Conversions Consider
More informationCalling Prewritten Functions in C
Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow
More informationAssoc. Prof. Dr. Tansu FİLİK
Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming
More informationComputer Programming 6th Week Functions (Function definition, function calls),
Computer Programming 6th Week Functions (Function definition, function calls), Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 loops (do-while, for), Arrays, array operations,
More informationMethods: A Deeper Look
1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number
More informationfrom Appendix B: Some C Essentials
from Appendix B: Some C Essentials tw rev. 22.9.16 If you use or reference these slides or the associated textbook, please cite the original authors work as follows: Toulson, R. & Wilmshurst, T. (2016).
More informationCT 229 Java Syntax Continued
CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment
More informationExpressions and operators
Mathematical operators and expressions The five basic binary mathematical operators are Operator Operation Example + Addition a = b + c - Subtraction a = b c * Multiplication a = b * c / Division a = b
More informationChapter 6 - Notes User-Defined Functions I
Chapter 6 - Notes User-Defined Functions I I. Standard (Predefined) Functions A. A sub-program that performs a special or specific task and is made available by pre-written libraries in header files. B.
More informationHoltek C and ANSI C Feature Comparison User s Guide
Holtek C and ANSI C Feature Comparison User s Guide July 2009 Copyright 2009 by HOLTEK SEMICONDUCTOR INC. All rights reserved. Printed in Taiwan. No part of this publication may be reproduced, stored in
More informationC Functions. Object created and destroyed within its block auto: default for local variables
1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program
More informationVisual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.
Tips and Tricks Topics Visual Studio Handling Output to the Screen Handling Input from the Keyboard Simple Text Menus When to use a For Loop When to use a While Loop Reviewing a Function Visual Studio
More informationCS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Teacher: Sourangshu Bha@acharya sourangshu@gmail.com h@p://cse.iitkgp.ac.in/~sourangshu/ Department of Computer Science and Engineering
More information(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University
(2-2) Functions I H&K Chapter 3 Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University Problem Solving Example (1) Problem Statement: Write a program that computes your
More informationC++ Programming Lecture 11 Functions Part I
C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationFunctions and Recursion
Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game
More informationcs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).
cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion
More informationThe Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class
The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined
More informationPrimitive Data Types: Intro
Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types
More informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More informationCS115 Principles of Computer Science
CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops)
More informationSlide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng
Slide Set 3 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2017 ENCM 339 Fall 2017 Section 01
More informationUNIT III (PART-II) & UNIT IV(PART-I)
UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System
More informationFunction I/O. Function Input and Output. Input through actual parameters. Output through return value. Input/Output through side effects
Function Input and Output Input through actual parameters Output through return value Only one value can be returned Input/Output through side effects printf scanf 2 tj Function Input and Output int main(void){
More informationLAB 7 FUNCTION PART 2
LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1 OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To
More informationFunction I/O. Last Updated 10/30/18
Last Updated 10/30/18 Program Structure Includes Function Declarations void main(void){ foo = fun1(a, b); fun2(2, c); if(fun1(c, d)) { } } Function 1 Definition Function 2 Definition 2 tj Function Input
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building
More informationCSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU
CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition
More informationProgramming in C. Part 1: Introduction
Programming in C Part 1: Introduction Resources: 1. Stanford CS Education Library URL: http://cslibrary.stanford.edu/101/ 2. Programming in ANSI C, E Balaguruswamy, Tata McGraw-Hill PROGRAMMING IN C A
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationBBM 101 Introduc/on to Programming I Fall 2013, Lecture 6-7
BBM 101 Introduc/on to Programming I Fall 2013, Lecture 6-7 Instructors: Aykut Erdem, Erkut Erdem, Fuat Akal TAs: Yasin Sahin, Ahmet Selman Bozkir, Gultekin Isik, Oguzhan Guclu 1 Today Func/ons Defini@ons
More informationFaculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions
Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with
More informationLesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University
Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only
More informationOther C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.
1 The previous lecture Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations Pointer basics 1 Common library functions [Appendix of K+R]
More informationALGORITHM 2-1 Solution for Exercise 4
Chapter 2 Recursion Exercises 1. a. 3 * 4 = 12 b. (2 * (2 * fun1(0) + 7) + 7) = (2 * (2 * (3 * 0) + 7) + 7) = 21 c. (2 * (2 * fun1(2) + 7) + 7) = (2 * (2 * (3 * 2) + 7) + 7) = 45 2. a. 3 b. (fun2(2, 6)
More informationECE 2400 Computer Systems Programming Fall 2017 Topic 12: Transition from C to C++
ECE 2400 Computer Systems Programming Fall 2017 Topic 12: Transition from C to C++ School of Electrical and Computer Engineering Cornell University revision: 2017-10-23-01-13 1 C++ Namespaces 2 2 C++ Functions
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data
More information