Function.

Slides:



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

Modular Programming With Functions
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.
Functions and InterfacesCS-2303, C-Term Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming.
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.
Introduction to FunctionsCS-2301 D-term Introduction to Functions CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Introduction to FunctionsCS-2301 B-term Introduction to Functions CS-2301, System Programming for Non-majors (Slides include materials from The.
 2007 Pearson Education, Inc. All rights reserved C Functions.
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.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
1 Storage Classes, Scope, and Recursion Lecture 6.
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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Chapter 6: User-Defined Functions
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
CPS120: Introduction to Computer Science Functions.
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.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Lecture 13: Working with Multiple Programmers. Headers Header files: Each standard library has a corresponding header. The function prototype for all.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Lecture 2 Friday 11 July Chapter 3, Functions l built-in functions l function prototype, function definition and use l storage class and scope.
Introduction to FunctionsCIS 1057 Fall Introduction to Functions CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Variable Scope. When you declare a variable, that name and value is only “alive” for some parts of the program  We must declare variables before we use.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions Course conducted by: Md.Raihan ul Masood
IS Program Design and Software Tools Introduction to C++ Programming
Functions and an Introduction to Recursion
C Functions -Continue…-.
Lesson #6 Modular Programming and Functions.
C++.
Lesson #6 Modular Programming and Functions.
Programming Fundamentals Lecture #7 Functions
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Programming Fundamentals Lecture #7 Functions
Deitel- C:How to Program (5ed)
CS1061 C Prgramming Lecture 11: Functions
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
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
Scope, Parameter Passing, Storage Specifiers
Functions Declarations CSCI 230
Chapter 6 - Functions Outline 5.1 Introduction
6 Chapter Functions.
Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
1-6 Midterm Review.
Programming Languages and Paradigms
CS1201: Programming Language 2
Function.
CPS125.
Presentation transcript:

Function

Variable Scope LOCAL GLOBAL

Variable Scope (local scope) The scope of a variable starts when it is declared in a block {} and, it only stays alive until the end of the block. Example If the block defines: A function body, the variable is alive from where it is declared until the end of the function. a loop body or if-statement body, the variable only lives till the end of loop/if You can add a block anywhere you want in the code, and it will define the scope for any variables declared within it.

Example scopes int main ( ) { int i; i for (i=0; i < 10; i++ ) { int total = i; } int j = total; // error! total out of scope { int k; // use k int m = j; … i total j k m

Variable Scope int main ( ) { int i = 5, j = 0; for (j = 0; j < 10; j++) { int i = j; // OK, this is new i int k = 5; doSomething (i); } int sum = k; // compile error, no k in scope j = i; // sets j to 5 for (j = 0; j < 100; j++ ) { int i = j; // yet another new i int i = 0; // compile error –redefined variable You can reuse names, as long as they are not in overlapping scopes. In fact, you can reuse names in a scope which is nested inside another scope

Static variables Local variables declared with the keyword static are still known only in the function static local variables retain their value when the function is exited. declares local variable count to be static and initializes it to 1. static int count = 1; All numeric variables of static storage duration are initialized to zero by default if you do not explicitly initialize them.

Variable Scope (global scope) int total = 5; int main ( ) { int total = 4; // OK, this is nested scope …. } int sub1 ( ) { int i = total; // OK, i set to 5 This is for variables defined outside of functions Global variables have scope from the point they are defined throughout the rest of file Local variables of same name can be nested inside global variables

Exercise int i = 10; int main ( ) { i ? for (j = 0; j < 10; j++ ) { int i = 20; i? } int i = 30;

Style rules Only use global variables if you really, really have to !!! 2 different approaches for local variables inside a function Declare all variables at the top of the function This is the way you used to have to do it in C Helps the reader to know where to look for the variable declaration Declare variables as they are needed Minimizes scope Allows you to set the value only once, rather then once at declaration and then again at first use Either approach is OK – probably the most common in industry is to declare as needed Don’t re-use names heavily, except for maybe i, j, k

Function

Introduction to Functions Definition – Function A fragment of code that accepts zero or more argument values, produces a result value, and has zero or more side effects. A method of encapsulating a subset of a program or a system To hide details To be invoked from multiple places To share with others CS-2301, B-Term 2009 Introduction to Functions 11

Functions Predefined functions: available in C / C++ standard library such as stdio.h, math.h, string.h etc. User-defined functions: functions that programmers create for specialized tasks.

Introduction to Functions Predefined Functions #include <math.h> sin(x) // radians cos(x) // radians tan(x) // radians atan(x) atan2(y,x) exp(x) // ex log(x) // loge x log10(x) // log10 x sqrt(x) // x  0 pow(x, y) // xy ... #include <stdio.h> printf() fprintf() scanf() sscanf() ... #include <string.h> strcpy() strcat() strcmp() strlen() Functions called by writing functionName (argument) CS-2301, B-Term 2009 Introduction to Functions 13

Predefined Functions (continued) See also things like <pthread.h> // concurrent execution <socket.h> // network communications ... // many, many other facilities Fundamental Rule: if there is a chance that someone else had same problem as you, … … there is probably a package of functions to solve it! CS-2301, B-Term 2009 Introduction to Functions 14

User-defined Functions resultType functionName(type1 param1, type2 param2, …) { … body } If no result, resultType should be void Warning if not! If there is a result, use return keyword to return a value. The return value must match the return data type. A function can contain multiple return statements. If no parameters, use void between () CS-2301, B-Term 2009 Introduction to Functions 15

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 in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; CS-2301, B-Term 2009 Introduction to Functions

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 in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; This is an argument This is also an argument CS-2301, B-Term 2009 Introduction to Functions

Introduction to Functions Function Prototypes There are many, many situations in which a function must be used separate from where it is defined – before its definition in the same C program In one or more completely separate C programs This is actually the normal case! Therefore, we need some way to declare a function separate from defining its body. Called a Function Prototype CS-2301, B-Term 2009 Introduction to Functions 19

Function Prototypes (continued) Definition:– a Function Prototype in C is a language construct of the form:– return-type function-name (parameter declarations) ; I.e., exactly like a function definition, except with a ';' instead of a body in curly brackets CS-2301, B-Term 2009 Introduction to Functions 20

Header Files Header files Custom header files Contain function prototypes for library functions <cstdlib> , <cmath>, etc. Load with #include <filename> Example: #include <cmath.h> Custom header files Defined by the programmer Save as filename.h Loaded into program using #include "filename.h"

Passing Arguments By Value and By Reference When arguments are passed by value, a copy of the argument’s value is made and passed to the called function. Changes to the copy do not affect an original variable’s value in the caller. void f(int x) When an argument is passed by reference, the caller allows the called function to modify the original variable’s value. void f(int& x)

Recursion Recursive functions Example: factorial Are functions that calls themselves Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 Recursive relationship ( n! = n * ( n – 1 )! ) 5! = 5 * 4! 4! = 4 * 3!… Base case (1! = 0! = 1)

The Fibonacci Series Fibonacci series: 0, 1, 1, 2, 3, 5, 8... return 1 return 0 return + Fibonacci series: 0, 1, 1, 2, 3, 5, 8... Each number sum of two previous ones Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2) C code for fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) // base case return n; else if ( n < 0 ) return –1; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); }  

Recursion vs. Iteration Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)