Quiz 2.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Principles of Programming Chapter 6: Function & Recursion  In this chapter, you will learn about  Introduction to function  User define function  Function.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Principles of Programming Chapter 11: Recursive Function  In this chapter, you will learn about  Recursion function 1 NI S1 2009/10.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
© 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.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Principles of Programming - NI Chapter 6: Function In this chapter, you will learn about Introduction to function User define function Function prototype.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Functions.
User-Written Functions
Chapter 6 - Functions modular programming general function format
Functions and an Introduction to Recursion
C Functions -Continue…-.
Lesson #6 Modular Programming and Functions.
INC 161 , CPE 100 Computer Programming
Lesson #6 Modular Programming and Functions.
C Functions Pepper.
Functions, Part 2 of 2 Topics Functions That Return a Value
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC113: Computer Programming (Theory = 03, Lab = 01)
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
Lesson #6 Modular Programming and Functions.
Functions Declarations CSCI 230
Chapter 6 - Functions Outline 5.1 Introduction
Functions and Modular Programming
Assignment Operators Topics Increment and Decrement Operators
Function In this lesson, you will learn about Introduction to Function
Chapter 9: Value-Returning Functions
Lesson #6 Modular Programming and Functions.
Function.
In C Programming Language
Function.
CPS125.
Functions that return a value
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Quiz 2

1 2 3

Lecture 9 Function

Outline What is Function Function Definition Standard (Predefined) Functions User-Defined Functions Flow of Execution

Functions - Mathematical View X Function Returned value

Function Input and Output

Example

Call power Call power power Call power

Function Syntax Function define syntax: <return type> <function name> (param …) { <statements> } param …  <data type> <variable name> , …

Example

Why we use function Provides a layer of ‘abstraction’ Reduce code line Use one block of code several time. Building Programs from Existing Programs Standard library For example : stdio, math, rand … Provides a layer of ‘abstraction’ Helps manage complexity Smaller blocks of code Easier to read

Why we use function Divide and conquer Construct a program from smaller pieces or components Smaller pieces sometimes called function Each piece more manageable than the original program Divide and Conquer

Functions Every C program starts with main() function Functions could be Pre-defined library functions e.g., printf, sin, tan Programmer-defined functions e.g., my_printf, area

Pre-defined library functions <math.h> Defines common mathematical functions e.g. sin, cos. sqrt, pow <stdio.h> Defines core input and output functions e.g. printf, scanf <time.h> Defines date and time handling functions e.g. time, clock <stdlib.h> Defines pseudo-random numbers generation functions e.g. rand, srand

C mathematical functions double      pow( double base, double exp); Computes the value of base raised to the power exp double      sin( double arg ); Computes sine of arg (representing angle in radians) double      cos( double arg ); Computes cosine of arg (representing angle in radians) double      tan( double arg ); Computes tangent of arg (representing angle in radians) ...

An example

An example

Random numbers generation functions int rand(); Returns a uniformly distributed pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included) RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent. #define RAND_MAX 32767 /*implementation defined*/ srand() should be called before any calls to rand() to initialize the random number generator void srand( unsigned seed ); Initializes the built-in random number generator used to generate values for rand() with the seed value seed

An Example #include <stdio.h> #include <stdlib.h> int main(void) { unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

An Example #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

Random Numbers in [a b] Generate a random number [0 .. 7] x = rand() % 8; Generate a random number [10 ..17] x = 10 + rand() % 8; rand() % (b-a+1) + a;

User- defined function

Functions in C Queries: Return a value sin(), fabs() Commands: do some tasks, do not return any value or we don’t use the value printf(...) scanf(...)

Functions in C Three steps to use functions in C Function declaration Introduce the function to compiler Function definition What the function does Function call Use the function

Function Definitions Function definition format return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result void – indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter No input: empty parameter list () or void

Functions - Definition Structure Function 'header' Return data type (if any) Name Descriptive Arguments (or parameter list) Notice: data type and name Statements Variable declaration Operations Return value (if any) type function_name (type arg1, type arg2 ) { statements; } A function that calculates the product of two numbers double product(double x, double y) { double result; result = x * y; return result; } The function definition declares the return data type, its name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Contrast this with the function prototype.

Function Definitions Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } Declarations and statements: function body (block) Variables can be declared inside blocks Functions can not be defined inside other functions

Producing output Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } Query functions Produce output To produce an output Declare output type Generate the output by return

The return command To generate a result by a function return <value>; return <expression>; Only one value can be returned If noting returned return; Or until reaches right brace

The return command return finishes running the function Function can have multiple return Only one of them runs each time The type of the returned value = the result type Otherwise, cast

Functions that do not return a value Use the return type of void void functionName( DataType arg_1,…) void functionName() void functionName( void)

Function call Command function Query function <function name> (inputs); Query function <variable> = <function name>(inputs); Inputs should match by function definition Functions are called by another function Function call comes inside in a function

Example void my_info(void){ printf("My name is Ahmad Ahmadi\n"); printf("My student number: 95222222\n"); } int main(void){ my_info(); printf("--------------\n"); my_info(); return 0;

Function Call – An Example If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored int GetUserInput (void); /* function prototype*/ int main(void) { int input; input = GetUserInput( ); return(0); /* return 0; */ } However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value We can also call a function inside another function printf("User input is: %d", GetUserInput( ));

N = f(pi*pow(r,2), b+c) + d; Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used, N = f(pi*pow(r,2), b+c) + d;

Using Functions (continued) This is a parameter Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used , N = f(pi*pow(r,2), b+c) + d; This is an argument This is also an argument

Quick review Define a function: <return type> <function name>(<param> …) { <Statement> … } <param>  <data type> <value name> , …

Quick review If in function execute return, function will be terminate. Function data type and return type must be same. If function type be void, can be use return; to terminate function.

Quick review In order to call a function: <function name>(<param> …);

Example

Example Enter a number: 5 Enter a number: 4 Sum is 9 Press any key to continue

Example

Example

Example

Example

Example

Example

Definitions Parameter:– a declaration of an identifier within the '()' of a function declaration Used within the body of the function as a variable of that function Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter

Scope of variables

Scope of Variables Until now, Variables Scope of variable Are declared in the start of functions Are used any where in the function after declaration Can we used them outside of function? Can we used them in other functions? Scope of variable A range of code that the variable can be used  Variable cannot be used outside of its scope Compile error

Scopes vs. Blocks Scopes are determined by Blocks Variables Start with { and finished by } Example: statements of a function, statement of a if or while, … Variables Can be declared in a block Can be used in the declared block Cannot be used outside the declared block The Declared block is the scope of the variable

Example

Nested Scopes/Blocks Scopes can be nested Example: Nested if, nested for, …

Variables in Nested Blocks All variables from outer block can be used inner blocks Scope of outer block contains the inner block Variables in inner block cannot be used in outer block Scope of the inner block does not contains the outer block

Example

Same Variables in Nested Block If a variable in inner block has the same identifier of a variable in outer block The inner variable hides the outer variable Changing inner variables does not change outer variable

Local Variables All defined variables in a function are the local variable of the function Can ONLY be used in the function, not other functions

Global Variables Global variables are defined outside of all functions Global variables are initialized to zero Global variables are available to all subsequent functions

Example

Example

Argument Passing

Argument Passing In C language we study two type of argument passing. Pass by value Pass by reference

Call by value In call by value mechanism The values are copied to the function Only the copy of variable’s value (copy of actual parameter’s value) is passed to the function. If we change values in the function The copied version is changed The original value does not affected Any modification to the passed value inside the function will not affect the actual value

Example Enter two numbers to calculate its sum: 4 9 4 + 9 = 13 Press any key to continue #include <stdio.h> int calSum(int,int); /*function protototype*/ int main(void) { int sum, num1, num2; printf("Enter two numbers to calculate its sum:\n"); scanf("%d%d",&num1,&num2); sum = calSum(num1,num2); /* function call */ printf("\n %d + %d = %d", num1, num2, sum); return(0); } int calSum(int val1, int val2) /*function definition*/ int sum; sum = val1 + val2; val2 = 100; return sum; 4 num2 9 num1 13 sum 4 num2 9 num1 ? sum ? num2 num1 sum 100 val2 9 val1 13 sum 4 val2 9 val1 13 sum 4 val2 9 val1 ? sum

Call by reference Call by reference In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value

Call by reference 10 b a 5 b 1 a b a main -5 b a main 5 b 1 a CalByVal #include <stdio.h> void CalByVal(a, b) { a = 0; b = 10; } void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) *a = 0; *b = -5; int main(void) int a = 1, b = 5; printf("Before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("After cal CalByVal: a = %d, b = %d\n", a, b); printf("Before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("After cal CalByRef: a = %d, b = %d\n", a, b); return 0; /* Exit program. */ CalByVal 10 b a CalByVal 5 b 1 a CalByRef b a main -5 b a main 5 b 1 a

Recursive function

Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type A recursive function is a function invoking itself, either directly or indirectly Recursion: A → B → C → D → A Concept of recursive function (generally): A recursive function is called to solve a problem The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer if (stopping case) solve it else reduce the problem using recursion

Recursion Recursive Algorithm An algorithm uses itself to solve the problem There is a basic problem with known solution Recursive Algorithms are implemented by recursive functions Recursive function A function which calls itself There is a condition that it does not call itself

Recursion Any problem that can be solved recursively can also be solved iteratively (using loop) Recursive functions are slow and takes a lot of memory space compared to iterative functions So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug Iterative solution might not be apparent

An Example: xy In this example, we want to calculate x to the power of y i.e. xy If we analyze the formula for xy, we could see that xy could be written as (x being multiplied to itself, y times) An example is 24, which can be written as 24 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4) 24 could also be rewritten as 24 = 21 x 23 where 21 = 2 (i.e the number itself) Therefore, we could divide the problem into two stage: Simplest case: when y = 1, the answer is x Recursive case, we need to solve for x * x(y-1)

Introduction Factorial GCD n! = n x n-1 x … x 2 x 1 GCD(a, b) = Euclidean Algorithm GCD(a, b) = GCD(b, a mod b) There is a simple (basic) problem which we can solve it directly (without recursion) Factorial: 1! = 1 GCD: b == 0

Fibonacci solution

Fibonacci x = 5; temp = 1; temp = 1 + Fib(1); return temp; temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = 1 + 1; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 1; temp = 1; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 5; temp = 1; temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = 1 + 1; return temp; int Fib (int x) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */ temp = Fib(x-1) + Fib(x-2); return temp; } x = 4; temp = 1; temp = 2 + 1; return temp; x = 4; temp = 1; temp = 2 + Fib(2); return temp; x = 4; temp = 1; temp = Fib(3) + Fib(2); return temp; x = 5; temp = 1; temp = 3 + 2; return temp; x = 5; temp = 1; temp = Fib(4) + Fib(3); return temp; x = 5; temp = 1; temp = 3 + Fib(3); return temp;

Fibonacci 5 fib(5) fib(3) fib(4) fib(3) fib(2) fib(2) fib(1) fib(2) int Fib (int n) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */ temp = Fib(n-1) + Fib(n-2); return temp; } fib(5) 3 2 fib(3) fib(4) 1 1 2 1 fib(3) fib(2) fib(2) fib(1) 1 1 fib(2) fib(1)

Print Right to Left Example

Print Left to Right Example

Recursion solution of xy

Factorial solution

GCD solution

Indirect recursion What we have seen are direct recursion A function calls itself directly Indirect recursion A function calls itself using another function Example: Function A calls function B Function B calls function A

Example

Storage Class

Storage Classes Storage class(Refers to the lifetime of a variable) How memory is allocated for the variable Until when the variable exists How it is initialized Storage classes in C  Automatic External  Static Register

Storage Classes Refers to the lifetime of a variable Local variables only exist within a function by default. When calling a function repeatedly, we might want to Start from scratch – reinitialize the variables The storage class is ‘auto’ Continue where we left off – remember the last value The storage class is ‘static’ Another two storage classes (seldomly used) register (ask to use hardware registers if available) extern (global variables are external)

Syntax storage_classes variable_type variable_name Example: int auto float double char auto register static extern Example:

Storage Classes: Automatic Automatic storage class Variable created when program enters its block Variable destroyed when program leaves block Only local variables of functions can be automatic Automatic by default keyword auto explicitly declares automatic

Example Auto example: 1 Press any key to continue

Storage Classes: External All global variables are external by default Are generated when program starts Are destroyed when program finishes Usage of keyword “extern” To use global variables in other files To emphasize that variable is global This usage is optional

Storage Classes: Static Keyword “static” comes before them For local variables: 1) Generated in the first run of the block 2) Destroyed when program finishes 3) Initialized If no value  initialized by 0 Only initialized in the first run of the block

Static storage class However the static keyword can be applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds

Example Static example: 1 3 5 Press any key to continue

Storage Classes: Register Keyword “register” comes before them Can be used for local variables Compiler tries to allocated the variable in registers of CPU But does not guaranteed Registers are very fast and small memories Improve performance