A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

1 ICS103 Programming in C Lecture 5: Introduction to Functions.
An Introduction to Programming with C++ Fifth Edition
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Top-Down Design with Functions 4 What do programmer’s (not programs!) use as input to the design of a program? –Documentation Problem definition Requirements.
Data types and variables
Chapter 6: User-Defined Functions I
Chapter 2 Data Types, Declarations, and Displays
Topic 2A – Library Functions and Casting. CISC 105 – Topic 2A Functions A function is a piece of code which performs a specific task. When a function.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Objectives You should be able to describe: Data Types
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
1 Lecture 3 Part 1 Functions with math and randomness.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 Chapter 9 Scope, Lifetime, and More on Functions.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Why we use functions C library functions Creating our own functions.
STANDARD FUNCTIONS Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Week 1 Algorithmization and Programming Languages.
CSE1222: Lecture 2The Ohio State University1. mathExample2.cpp // math example #include using namespace std; int main() { cout
CMSC 1041 Functions II Functions that return a value.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Chapter 9 Scope, Lifetime, and More on Functions.
USING & CREATING FUNCTIONS. MODULAR PROGRAMMING  Why Modular Programming?  Improves Readability & Understandability  Improve Maintainability  Allows.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Simple C Programs.
Chapter 9: Value-Returning Functions
Chapter 6: User-Defined Functions I
BIL 104E Introduction to Scientific and Engineering Computing
TMF1414 Introduction to Programming
Functions, Part 2 of 2 Topics Functions That Return a Value
The Selection Structure
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Chapter 6: User-Defined Functions I
Chapter 2: Introduction to C++.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Assignment Operators Topics Increment and Decrement Operators
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses: int main(void). Ideally, your main( ) function should be very short and should consist primarily of function calls Built-in functions Build-in functions are part of the compiler package, such as exit(1);

A function definition consists of two parts: interface and body. The interface of a function (also called its prototype) specifies how it may be used. It consists of three entities: The function name. This is simply a unique identifier. The function parameters (also called its signature). This is a set of zero or more typed identifiers used for passing values to and from the function. The function return type. This specifies the type of value the function returns. A function which returns nothing should have the return type void.

The body of a function contains the computational steps (statements) that comprise the function. Using a function involves ‘calling’ it. A function call consists of the function name followed by the call operator brackets ‘()’, inside which zero or more comma-separated arguments appear

int Power (int base, unsigned int exponent) { intresult = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; } Function body Note: A function should be declared before its is used

User-defined functions User-defined functions are created by you, the programmer.

Declare the function. The declaration, called the function prototype, tells the computer the name, return type, and parameters of the function. This statement is placed after #include (and other headers) and before int main(void).

FORMAT NOTE: Please have all of your functions end with return.

2. Define the function. The function definition tells the compiler what task the function will be performing. A function definition cannot be called unless the function is declared. The function prototype and the function definition must agree EXACTLY on the return type, the name, and the parameters. The only difference between the function prototype and the function header is a semicolon (see diagram below). The function definition is placed AFTER the end of the int main(void) function. The function definition consists of the function header and its body. The header is EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon

Local Variable..a variable that is restricted to use within a function of a program. Our first style of function will simply perform an independent task. It will not send or receive any parameters and it will not return any values. The word void appears as the return type and the parameters.

#include int Power (int base, unsigned int exponent ); // function declaration main (void) { cout << "2 ^ 8 = " << Power(2,8) << '\n'; } int Power (int base, unsigned int exponent) { intresult = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; }

C++ supports two styles of parameters: value and reference. A value parameter receives a copy of the value of the argument passed to it A reference parameter, on the other hand, receives the argument passed to it and works on it directly

#include void Foo (int num) { num = 0; cout << "num = " << num << '\n'; } int main (void) { int x = 10; Foo(x); cout << "x = " << x << '\n'; return 0; }

variables generally denote memory locations where variable values are stored The storage class specifier register may be used to indicate to the compiler that the variable should be stored in a register if possible. For example: for (register int i = 0; i < n; ++i) sum += i;

An enumeration of symbolic constants is introduced by an enum declaration. This is useful for declaring a set of closely-related constants. For example, enum {north, south, east, west}; introduces four enumerators which have integral values starting from 0 (i.e., north is 0, south is 1, etc.) enum {north = 10, south, east = 0, west}; Here, south is 11 and west is 1.

However, instead of replicating this expression in many places in the program, it is better to define it as a function: int Abs (int n) { return n > 0 ? n : -n; }

//Screen display shown at the right //Prototyping, defining and calling a function #include #include void astericks(void); //function prototype int main(void) { system("CLS"); cout<<"Heads up, function!\n"; astericks( ); //function call cout<<"Again, function!\n"; astericks( ); //function call cout<<"Job well done!\n"; return 0; //main( ) is over - ALL STOP!! } //function definition void astericks(void) { int count; // declaring LOCAL variable for(count = 1; count<=10; count++) cout<<"*"; cout<<endl; return; //return value is VOID, no return } SCREEN DISPLAY Heads up, function! ********** Again, function! ********** Job well done!

Our second style of function will take arguments (parameters) but will not return a value. The argument list in the parentheses specifies the types and number of arguments that are passed to the function. void sum(int x, int y, int z); //function prototype Acceptable Prototypes voi d add(int x, int y); void add(int, int); While both of these prototypes are acceptable, we will be using the first style.

//Example program //Screen display shown at the right //Passing arguments to a function #include #include void greeting(int x); //function prototype int main(void) { system("CLS"); greeting(5); //function call- argument 5 int number; do { cout >number; } while ((number 10)); greeting(number); //argument is a variable return 0; } //function definition void greeting(int x) // formal argument is x { int i; // declaring LOCAL variable for(i = 0; i < x; i++) { cout<<"Hi "; } cout<<endl; return; //return value is VOID, no return } Screen Display Hi Hi Hi Hi Hi Please enter value(1-10): 4 Hi Hi Hi Hi

Our third style of function takes no arguments, but will return a value. Up until now, we have been communicating information TO a called function. Now we will be returning information FROM the function by using the function return value. The return value can be a constant, a variable, or an expression. The only requirement is that the return value be of the type specified in the function prototype. return_type functionName(void) //function header { statements; return (value); //value is of type return_type }

C++ compilers include built-in functions to make programming easier. The number and type of functions available to you depends upon the compiler you are using. These functions that come with the compiler are called "built-in" library functions.

Library functions are just like the functions that you, as the programmer, create and are used in a similar manner. The only difference is that the source code (definition) for library functions does NOT appear in your program. The prototype for the library function is provided to your program using the #include compiler directive. The most common library functions. Character classification and conversion Math functions Data conversion Time functions

Required header: #include C++ uses the American Standard Code for Information Interchange (ASCII) character set. The CTYPE library includes character classification functions. A character is passed to the functions and the functions return values that can be stored or printed.

CategoryASCII Characters Uppercase letters 'A' through 'Z' Lowercase letters 'a' through 'z' Digits (0 through 9) '0' through '9' Whitespace Space, tab, line feed(newline), and carriage return Punctuation !"#$%&'()*+,-./:; Blank spaceThe blank space character Basic ASCII Categories

1. isalnum( ) returns a TRUE (nonzero) if the argument is digit 0-9, or an alphabetic character (alphnumeric). Otherwise returns FALSE. 2. isalpha( ) returns TRUE if the argument is an upper or lower case letter. 3. isascii( ) returns TRUE if the integer argument is in the ASCII range Treats as non-ASCII. 4. isdigit( )returns TRUE if the argument is a digit isgraph( ) returns TRUE if the argument is any printable character from ASCII 32 to 127, except the space. 6. islower( )returns TRUE if the argument is a lowercase letter. 7. isupper( )returns TRUE if the argument is an uppercase leter. 8. ispunct( ) returns TRUE if the argument is any punctuation character (see chart above). 9. isspace( )returns TRUE if the argument is a whitespace (see chart above).

toascii( ) converts the argument (an arbitrary integer) to a valid ASCII character number c = toascii(500); //c gets number 116 // (modulus 500%128) c = toascii('d'); //c gets number 100 tolower( ) converts the argument (an uppercase ASCII character) to lowercase. c = tolower('Q'); // c becomes 'q' toupper( ) converts the argument (a lowercase ASCII character) to uppercase. c = toupper('q'); //c becomes 'Q' **Note: tolower( ) and toupper( ) will actually check to see if the argument is the appropriate uppercase or lowercase before making the conversion.

Required headers: #include #include Computers can be used to simulate the generation of random numbers with the use of the rand( ) function. This random generation is referred to as a pseudo- random generation. These created values are not truly "random" because a mathematical formula is used to generate the values.

rand( ) returns a random positive integer in the range from 0 to 32,767. This function can be thought of as rolling a die with 32,767 faces. The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers. Since the same sequence is generated each time the seed remains the same, the rand( ) function generates a pseudo- random sequence. To prevent the same sequence from being generated each time, use srand(x) to change the seed value

srand(x) used to set the starting value (seed) for generating a sequence of pseudo-random integer values. The srand(x) function sets the seed of the random number generator algorithm used by the function rand( ). A seed value of 1 is the default setting yielding the same sequence of values as if srand(x) were not used. Any other value for the seed produces a different sequence.

In order to produce random integer numbers within a specified range, you need to manipulate the rand( ) function. The formula is: int number = a + rand( ) % n; a = the first number in your range n = the number of terms in your range (range computed by largest value - smallest value + 1)

Sample program: /*generate 10 random numbers between 10 and 55 inclusive, without repetition of the sequence between program runs*/ #include #include #include int main(void) { // to prevent sequence repetition between runs srand(time(NULL)); for(int i = 1; i <=10; i++) // looping to print 10 numbers { cout<< 10 + rand( ) % 46; // formula for numbers } return 0; } Example: /*random integers between 35 and 42 inclusive*/ int num =35+rand( )% 8;

Math Functions Function Prototype Purpose abs(x) int abs(int x); returns the absolute value of an integer. fabs(x) double fabs(double x); returns the absolute value of a floating point number ceil(x) double ceil(double x); rounds up to a whole number cout<<ceil(11.2); (prints 12) (not normal rounding) floor(x) double floor(double x); rounds down to a whole number cout<<floor(11.5); (prints 11) (not normal rounding) hypot(a,b) double hypot(double a, double b); calculates the hypotenuse (c) of a right triangle where a and b are the legs. pow(x,y) double pow(double x, double y); calculates x to the power of y. If x is negative, y must be an integer. If x is zero, y must be a positive integer. pow10(x) double pow10(int x); calculates 10 to the power of x. sqrt(x) double sqrt(double x); calculates the positive square root of x. (x is >=0) fmod(x,y) double fmod(double x, double y); returns floating point remainder of x/y with same sign as x. Y cannot be zero. Because the modulus operator(%) works only with integers, this function is used to find the remainder of floating point number division.

cos(x) cosine of x sin(x) sine of x tan(x) tangent of x acos(x) arc cosine x asin(x) arc sine of x atan(x) arc tangent x cosh(x) hyperbolic cosine of x sinh(x) hyperbolic sine of x tanh(x) hyperbolic tangent of x exp(x) exponential function log(x) natural logarithm log10(x) base 10 logarithm NOTE: The trigonometric functions work with angles in radians rather than degrees. All of the trigonometric functions take double arguments and have double return types.

You can exchange simple if-else code for a single operator – the conditional operator. The conditional operator is the only C++ ternary operator (working on three values). Other operators you have seen are called binary operators (working on two values). FORMAT: conditional Expression ? expression1 : expression2;

** if the conditional Expression is true, expression1 executes, otherwise if the conditional Expression is false, expression 2 executes. If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time: (a>b) ? (c=25) : (c=45); can be written as: c = (a>b) ? 25 : 45;

if (a>b) { c=25; } else { c=45; } can be replaced with (a>b) ? (c=25) : (c=45); The question mark helps the statement read as follows: "Is a greater than b? If so, put 25 in c. Otherwise, put 45 in c."