CSC113: Computer Programming (Theory = 03, Lab = 01)

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 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.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
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.
1 Lecture 3 Part 1 Functions with math and randomness.
© 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.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
C++ Programming Lecture 10 Functions – Part II
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
© 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.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Functions.
Dr. Shady Yehia Elmashad
CISC181 Introduction to Computer Science Dr
IS Program Design and Software Tools Introduction to C++ Programming
Functions and an Introduction to Recursion
C Functions -Continue…-.
Chapter 3 - Functions Outline 3.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
FUNCTIONS IN C++.
Deitel- C:How to Program (5ed)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Dr. Shady Yehia Elmashad
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Functions Najah Alsubaie Kingdom of Saudi Arabia
Chapter 5 - Functions Outline 5.1 Introduction
Dr. Shady Yehia Elmashad
Scope, Parameter Passing, Storage Specifiers
Functions Declarations CSCI 230
توابع در C++ قسمت اول اصول كامپيوتر 1.
Chapter 6 - Functions Outline 5.1 Introduction
6 Functions.
Chapter 3 - Functions Outline 3.1 Introduction
Presentation transcript:

CSC113: Computer Programming (Theory = 03, Lab = 01) Momina Moetesum Computer Science Department Bahria University, Islamabad

Introduction to functions Week # 7

Modular Programming Divide and conquer Modules in C++ Construct a program from smaller pieces or components Each piece more manageable than the original program Modules in C++ Functions Classes

Program Components in C++ Programs written by combining new functions with “prepackaged” functions in the C++ standard library. The standard library provides a rich collection of functions.

Library functions Avoid reinventing the wheel Facilitates portability e.g. pow( ), sqrt( ), cin, cout etc

Library Files ANSI C Library Usually have the extension .lib Contain the actual machine-executable code for library functions Linker links the objects in the library files to create an executable file.

Header files Contains the declaration of any library function Contain function prototypes for library functions E.g. cin/cout are declared in iostream.h E.g. pow( )/sqrt( ) are declared in math.h Usually have extension .h Must include the respective headerfile in the program to use these library functions. #include preprocessor includes the headerfiles. Two ways to include: #include<math.h> #include “math.h”

Custom header files Defined by the programmer Save as filename.h Loaded into program using #include "filename.h"

Library files vs. headerfiles Standard Library Functions are divided into different header files. A library file contains the code of the library function which is automatically linked to the program by the linker. A header file contains the declaration of that function and must be included in the source file using a #include preprocessor.

Program Components in C++ Functions call A function call specifies the function name and provides information (as arguments) that the called function needs Boss to worker analogy: A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e., report back) the results when the task is done. Function definitions Only written once These statements are hidden from other functions. The boss does not know how the worker gets the job done; he just wants it done

Examples of header files

Math Library Functions Allow the programmer to perform common mathematical calculations Are used by including the header file <cmath> Functions called by writing functionName (argument) Example cout << sqrt( 900.0 ); Calls the sqrt (square root) function. The preceding statement would print 30 The sqrt function takes an argument of type double and returns a result of type double, as do all functions in the math library

Math Library Functions Function arguments can be Constants sqrt( 4 ); Variables sqrt( x ); Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );

Example: Math header file

Example: random number generation rand function i = rand(); Load <stdlib> Generates a pseudorandom number between 0 and RAND_MAX (usually 32767) A pseudorandom number is a preset sequence of "random" numbers The same sequence is generated upon every program execution srand function Jumps to a seeded location in a "random" sequence srand( seed ); srand( time( 0 ) ); //must include <ctime> time( 0 ) The time at which the program was compiled Changes the seed every time the program is compiled, thereby allowing rand to generate random numbers

Example: random number generation Scaling Reduces random number to a certain range Modulus ( % ) operator Reduces number between 0 and RAND_MAX to a number between 0 and the scaling factor Example i = rand() % 6 + 1; Generates a number between 1 and 6

1. Define loop Output random number Program Output 1 // Fig. 3.7: fig03_07.cpp 2 // Shifted, scaled integers produced by 1 + rand() % 6 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 #include <cstdlib> 13 14 int main() 15 { 16 for ( int i = 1; i <= 20; i++ ) { 17 cout << setw( 10 ) << ( 1 + rand() % 6 ); 18 19 if ( i % 5 == 0 ) 20 cout << endl; 21 } 22 23 return 0; 24 } 1. Define loop Output random number Program Output Notice rand() % 6 . This returns a number between 0 and 5 (scaling). Add 1 to get a number between 1 and 6. Executing the program again gives the same "random" dice rolls. 5 5 3 5 5 2 4 2 5 5 5 3 2 2 1 5 1 4 6 4

Functions Functions Local variables Parameters Allow the programmer to modularize a program Local variables Known only in the function in which they are defined All variables declared in function definitions are local variables Parameters Local variables passed when the function is called that provide the function with outside information

identifiers Attributes of Identifiers Other Attributes Name Type Size Value Other Attributes Storage class: Determines the period during which an object exists in memory. (briefly, created/destroyed, entire program) Scope: Where object is referenced in program Linkage: Where an identifier is known

Storage Class Specifiers Automatic storage Object created and destroyed within its block auto Default for local variables. Example: auto float x, y; register Tries to put variables into high-speed registers Can only be used with local variables and parameters Static storage Variables exist for entire program execution static Local variables defined in functions Keep value after function ends Only known in their own function Extern Default for global variables and functions. Known in any function

Identifier Scope Rules File scope Defined outside a function, known in all functions Examples include, global variables, function definitions and functions prototypes Function scope Can only be referenced inside a function body Only labels (start:, case:, etc.) Block scope Declared inside a block. Begins at declaration, ends at } Variables, function parameters (local variables of function) Outer blocks “hidden” from inner blocks if same variable name Function prototype scope Identifiers in parameter list Names in function prototype optional, and can be used anywhere

Scope of the Variables

User defined functions Function definitions Function prototypes Function calls

Create customized functions to Function Definitions Create customized functions to Take in data Perform operations Return the result Format for function definition: return-value-type function-name( parameter-list ) { declarations and statements } Example: int square( int y) { return y * y; }

Function Prototypes Function prototype Example: Function name Parameters Information the function takes in Return type Type of information the function passes back to caller (default int) void signifies the function returns nothing Only needed if function definition comes after the function call in the program Example: int maximum( int, int, int ); Takes in 3 ints Returns an int

Example of user defined functions int square ( int y ) { return y*y; }

Self practice Create a function to: Add two variables of type int Add three variables of type float Multiply two variables of type double

examples int add ( int x, int y ) { return x+y; } ************************ float add (float x, float y, float z ) return x+y+z; double multiply ( double x, double y ) return x*y;

Test drivers Whenever you create your own function, you should immediately test it with a simple program. Such programs are called “test drivers”. Temporary or adhoc programs without comments or prompts etc. “Quick and dirty”

1. Function prototype 2. Loop Function definition Function call 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int square( int ); 9 10 int main() 11 { 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; 14 15 cout << endl; 16 return 0; 17 } 18 19 20 int square( int y ) 21 { 22 return y * y; 23 } 1. Function prototype 2. Loop Function definition Function call Program Output 1 4 9 16 25 36 49 64 81 100

Self practice Create test drivers for the programs created previously i.e.: int add (int , int); float add (float, float, float); double multiply (double, double);