Beruflich Dokumente
Kultur Dokumente
2
Modules: functions and classes
Programs use new and “prepackaged”
modules
◦ New: programmer-defined functions, classes
◦ Prepackaged: from the standard library
Functions invoked by function call
◦ Function name and information (arguments) it
needs
Function definitions
◦ Only written once
◦ Hidden from other functions
3
Perform common mathematical calculations
◦ Include the header file <cmath>
Functions called by writing
◦ functionName (argument);
or
◦ functionName(argument1, argument2, …);
Example
cout << sqrt( 900.0 );
◦ sqrt (square root) function The preceding statement
would print 30
◦ All functions in math library return a double
4
Function arguments can be
◦ Constants
sqrt( 4 );
◦ Variables
sqrt( x );
◦ Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
5
Method Description Example
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
6
Functions
◦ Modularize a program
◦ Software reusability
Call function multiple times
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 to function when called
◦ Provide outside information
7
Function prototype
◦ Tells compiler argument type and return type of
function
◦ int square( int );
Function takes an int and returns an int
Calling/invoking a function
◦ square(x);
◦ Parentheses an operator used to call function
Pass argument x
Function gets its own copy of arguments
◦ After finished, passes back result
8
Format for function definition
return-value-type function-name( parameter-list
)
{
declarations and statements
}
◦ Parameter list
Comma separated list of arguments
Data type needed for each argument
If no arguments, use void or leave blank
◦ Return-value-type
Data type of result returned (use void if nothing
returned)
9
Example function
int square( int y )
{
return y * y;
}
return keyword
◦ Returns data, and control goes to function’s caller
If no data to return, use return;
◦ Function ends when reaches right brace
Control goes to caller
Functions cannot be defined inside other
functions
Next: program examples
10
#include <iostream> Function prototype: specifies data types of
arguments and return values. square expects and
int square( int ); int, and returns an int.
void main()
{
// loop 10 times and calculate and output() cause
Parentheses
// square of x each time function to be called. When
for ( int x = 1; x <= 10; x++ ) done, it returns the result.
cout << square( x ) << " "; // function call
} // end main
11
// square function definition returns square of an integer
int square( int x ) // y is a copy of argument to function
{
return x * x; // returns square of y as an int
12
#include <iostream>
double maximum( double, double); // function prototype
void main()
{ Function maximum takes 2
double number1; arguments (all double) and
double number2; returns a double.
13
} // end main Comma separated list for
multiple parameters.
// function maximum definition;
// x, y and z are parameters
double maximum( double x, double y)
{
if ( x > y) // if y is larger,
return x; // assign y to max
14
Function prototype contains
◦ Function name
◦ Parameters (number and data type)
◦ Return type (void if returns nothing)
◦ Only needed if function definition after function call
Prototype must match function definition
◦ Function prototype
double maximum( double, double, double );
◦ Definition
double maximum( double x, double y, double z )
{
…
}
15
Function signature
◦ Part of prototype with name and parameters
double maximum( double, double, double );
Function signature
Argument Coercion
◦ Force arguments to be of proper type
Converting int (4) to double (4.0)
cout << sqrt(4)
◦ Conversion rules
Arguments usually converted automatically
Changing from double to int can truncate data
3.4 to 3
16
Header files contain
◦ Function prototypes
◦ Definitions of data types and constants
Header files ending with .h
◦ Programmer-defined header files
#include “myheader.h”
Library header files
#include <cmath>
17
Empty parameter lists
◦ void or leave parameter list empty
◦ Indicates function takes no arguments
◦ Function print takes no arguments and returns no
value
void print();
void print( void );
18
// Functions that take no arguments.
#include <iostream>
void function1(); // function prototype
void function2( void ); // function prototype
void main()
{
function1(); // call function1 with no arguments
function2(); // call function2 with no arguments
} // end main
19
void function1()
{
cout << "function1 takes no arguments" << endl;
} // end function1
} // end function2
20
Inline functions
◦ Keyword inline before function
◦ Asks the compiler to copy code into program
instead of making function call
Reduce function-call overhead
Compiler can ignore inline
◦ Good for small, often-used functions
Example
inline double cube( const double s )
{ return s * s * s; }
21
// Using an inline function to calculate the
volume of a cube.
#include <iostream>
inline double cube( const double side )
{
return side * side * side; // calculate cube
22
void main()
{
cout << "Enter the side length of your cube: ";
double sideValue;
23
Call by value
◦ Copy of data passed to function
◦ Changes to copy do not change original
◦ Prevent unwanted side effects
Call by reference
◦ Function can directly access data
◦ Changes affect original
24
Reference parameter
◦ Alias for argument in function call
Passes parameter by reference
◦ Use & after data type in prototype
void myFunction( int& data )
Read “data is a reference to an int”
◦ Function call format the same
However, original can now be changed
25
// Comparing pass-by-value and pass-by-reference with
references. Notice the & operator,
#include <iostream> indicating pass-by-reference.
int squareByValue( int ); // function prototype
void squareByReference( int & ); // function prototype
void main()
{
int x = 2;
int z = 4;
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: “
<< squareByValue( x ) ;
cout << "x = " << x << " after squareByValue\n" << endl;
26
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;
} // end main Changes number, but
original parameter (x) is not
// squareByValue multiplies number by itself,modified.
stores the
// result in number and returns the new value of number
int squareByValue( int number )
{
return number *= number; // caller's argument not modified
Changes numberRef, an
} // end function squareByValue
alias for the original
parameter. Thus, z is
// squareByReference multiplies numberRef by itself and
changed.
// stores the result in the variable to which numberRef
// refers in function main
void squareByReference( int &numberRef )
{
numberRef *= numberRef; // caller's argument modified
27
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
z = 4 before squareByReference
z = 16 after squareByReference
28
#include <iostream>
void swap(int &x, int &y);
int main ()
{
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
getch();
}
29
void swap(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
}
30
Function call with omitted parameters
◦ If not enough parameters, rightmost go to their
defaults
◦ Default values
Can be constants, global variables, or function calls
Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
◦ myFunction(3)
x = 3, y and z get defaults (rightmost)
◦ myFunction(3, 5)
x = 3, y = 5 and z gets default
31
In call by value, a copy of actual arguments is
passed to formal arguments of the called
function and any change made to the formal
arguments in the called function have no
effect on the values of actual arguments in
the calling function.
32
In call by reference, the location (address) of
actual arguments is passed to formal arguments
of the called function. This means by accessing
the addresses of actual arguments we can alter
them within from the called function.
33
Function overloading
◦ Functions with same name and different parameters
◦ Should perform similar tasks
I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
Overloaded functions distinguished by signature
◦ Based on name and parameter types (order matters)
◦ Name mangling
Encodes function identifier with parameters
◦ Type-safe linkage
Ensures proper overloaded function called
34
// Using overloaded functions.
#include <iostream> Overloaded functions have
// function square for int values
the same name, but the
int square( int x ) different parameters
distinguish them.
{
cout << "Called square with int argument: " << x << endl;
return x * x;
35
void main()
{
int intResult = square( 7 ); // calls int version
double doubleResult = square( 7.5 ); // calls double version
36
If we inherit a class into the derived class and
provide a definition for one of the base
class's function again inside the derived class,
then that function is said to be overridden,
and this mechanism is called Function
Overriding.
37
class Base
{
public:
void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
38
void main()
{
Base b; //Base class object
Derived d; //Derived class object
b.show();
d.show();
}
39
Use goto statement to print numbers from 1
to 50.
Create a program that prints 1 to 100
numbers in descending order.
Write a program to generate the cubes of first
10 numbers.
Write a program that outputs quotient and
remainder until the user enters the character
“n”.
40
setw() is library function in C++.
setw() is declared inside #include<iomanip>
setw() will set field width.
setw() sets the number of characters to be
used as the field width for the next insertion
operation.
41
#include <iostream>
#include <iomanip>
int main ()
{
cout << setw (10);
cout << “Hello" << endl;
return 0;
}
42
Now Length of String Hello is 5
We have set field width 10 so it will utilizes 5
fields
Remaining 5 fields are kept blank.
Default Justification : Left
43