View
228
Download
0
Category
Preview:
DESCRIPTION
“Hello World” program 3 #include using namespace std; int main () { cout
Citation preview
CSC1201: Programming Language 2
1
Functions
2
Function declaration:return_type FuncName(Type arg1, Type arg2,….. Type argN)
{ function body }• A program can contain one or many functions• Must always have a function called “main”.• The main function is the starting point of all C++ programs• The compiler will not compile the code unless it finds a function called
“main” within the program.
A Function is a group of statements that together perform a task.It can be used anywhere in the program. Why we need function? – Organize code in program– Code are easier to maintain?
“Hello World” program
3
#include <iostream>using namespace std;int main (){cout << “Hello World\n”;Return 0;}
Function
4
When we need function?– When you need to repeat the same process over and over in a program.– The function can be called many times but appears in the code once.
1- Predefined functions
5
Predefined functions are functions that are built into C++ Language to perform some standard operations.
The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings
the definitions have been written and it is ready to be used.
User needs to include pre-defined header file (i.e. math.h, time.h)
2- User defined functions
6
Function that been created by the user.
This functions need to be declared and defined by the
user
functions
7
Value returning functions: functions that have a return type. These functions return a value of a specific data type using
the return statement.
Void functions: functions that do not have a return type. These functions do not use a return statement to return a
value.
Value returning functions
8
The syntax is:
FuncType FuncName(formal parameter list ){
statements}
Void functions
9
The syntax is:Void FuncName ( formal parameter list ){
statements}
Examples:
10
1. Write a Function larger, which returns the larger of the two given doubles.
2. Write a Function Square, which returns the square of the given integer.
3. Write a function number_type. The function should output the number and message saying whether the number is positive, negative, or zero.
Example: With return value
11
#include<iostream>using namespace std;
Double larger ( double x , double y ){
double max;
if ( x >= y )max = x;
elsemax = y;
return max;}int main ( ){cout << “The larger of 5 and 6 is “ << larger(5 , 6) << endl; //Function Callreturn 0;}
Example: With return value
12
#include<iostream>using std::cin;using std::cout;using std::endl;
int square (int x){
return x*x;}
int main ( ){
int number;cout<<"Enter any number to Calculate the square of this number ";cin>>number;cout<<endl;cout<<"the square of "<<number<<" is " <<square(number)<<endl; //Function Callreturn 0;
}
Example: Without return value
13
#include<iostream>using namespace std;
void number_type ( int x){
if ( x > 0 )cout << x << “ is positive.” << endl;
else if ( x < 0 )cout << x << “ is negative.” << endl;
elsecout<< x << “is a zero.”<<endl;
}int main ( ){number_type( 5 ); //Function Callreturn 0;}
Function
The function are reusablereusable. Functions may be called ProceduresProcedures or RoutinesRoutines and in
object oriented programming called MethodsMethods . Save programmers’ time.
14
Prototype VS. Declaration Prototype : normally placed before the start of main()
but must be before the function definition.
General form :function_return_type function_name (type
parameter1, type parameter2,…, type parameterN) ;
EX: void Factorial (int x); // prototype -- x is a parameter
15
Prototype VS. Declaration
Prototype :void foo(int x); // prototype -- x is a parameter
Declaration void foo(int x) // declaration -- x is a parameter{Statements...}
16
EX:#include<iostream>using namespace std;
int square (int x){ return x*x; }
void main ( ){
int number;cout<<"Enter any number to Calculate the square of this number ";cin>>number;cout<<endl;cout<<"the square of "<<number<<" is "
<<square(number)<<endl;
}17
EX:
#include<iostream>using namespace std;
int square (int x) ;Void main ( ){
int number;cout<<"Enter any number to Calculate the square of this number ";cin>>number;cout<<endl;cout<<"the square of "<<number<<" is "
<<square(number)<<endl;
}int square (int x){ return x*x; }18
Finding Errors in Function Codeint sum(int x, int y){int result;result = x+y;
}
this function must return an integer value as indicated in the header definition (return result;) should be added
19
Finding Errors in Function Codeint sum (int n){ if (n==0)
return 0;else
n+(n-1);}
the result of n+(n-1) is not returned; sum returns an improper result, the else
part should be written as -:else return n+(n-1);
20
Finding Errors in Function Codevoid f(float a);{float a;cout<<a<<endl;
}; found after function definition header. redefining the parameter a in the function
void f(float a){
float a2 = a + 8.9;cout <<a2<<endl;
}21
Finding Errors in Function Codevoid product(void){ int a, b, c, result;cout << “enter three integers:”;cin >> a >> b >> c;result = a*b*c;cout << “Result is” << result;return result;
}According to the definition it should not return a value , but in the block (body) it did & this is WRONG. Remove return Result;
22
Scope of variables
C++ Variables A variable is a place in memory that has
A name or identifier (e.g. income, taxes, etc.) A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can
use it) Global variables – all functions can see it and using it Local variables – only the function that declare local
variables see and use these variables A life time (the duration of its existence)
Global variables can live as long as the program is executed
Local variables are lived only when the functions that define these variables are executed
24
25
Global VS Local variablesGlobal VS Local variables
local variable Variables that declared inside a function
Declared inside any block of code
Global variablesOpposite of local the known throughout the entire program
26
Global VS Local variablesGlobal VS Local variables
#include < iostream>Using namespace std;
27
Global VS Local variablesGlobal VS Local variables
#include < iostream>Using namespace std;
void main() { int i=4; int j=10; i++; if (j > 0)cout<<“ I is “<<i<<endl; if (j > 0) { int i=100; /* 'i' is defined and so local to * this block */cout << “I is” << i;} //end if
cout<<“I is “<<i;} //end main
I is 5I is 100I is 5
28
Scope of Local Variables, cont.
void function1() { int x = 1; int y = 1;
for (int i = 1; i < 10; i++) {
x += i; }
for (int i = 1; i < 10; i++) {
y += i; } }
It is fine to declare i in two non-nesting blocks
void function2() { int i = 1; int sum = 0;
for (int i = 1; i < 10; i++) { sum += i; } cout << i << endl; cout << sum << endl;
}
It is not good practice to declare i in two nesting blocks
29
Variable Scope
In fact, you can reuse names in a scope which is nested inside another 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}void doSomething(int i){ cout<<++i;}// OK, this is new i
30
Variable Scope Local variables of same name can be nested inside
global variables
int total = 5;
int main ( ) { int total = 4; // OK, this is nested scope ….}int sub1 ( ) { int i = total; // OK, i set to 5}
#include<iostream>using namespace std;int i = 10;int main ( ) { cout<<i<<endl;//10 for (int j = 0; j < 10; j++ ) {
int i = 20; cout<<i<<endl;//20
}cout<<i<<endl;//10 int i = 30;cout<<i<<endl;//30cout<<i<<endl;//30return 0;}
31
I. Using Global Variables#include <iostream>using namespace std;
int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }void main(){ f2(); cout << x << endl;}
32
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x 0
33
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x 0
void main()void main(){ { f2();f2(); cout << x << endl ;cout << x << endl ;}}
1
34
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x 0
void main()void main(){ { f2();f2(); cout << x << endl ;cout << x << endl ;}}
1
void f2()void f2(){ { x += 4;x += 4; f1();f1();}}
2
4
35
45
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x
void main()void main(){ { f2();f2(); cout << x << endl ;cout << x << endl ;}}
1
void f2()void f2(){ { x += 4;x += 4; f1();f1();}}
3
void f1()void f1(){ { x++;x++;}}
4
36
45
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x
void main()void main(){ { f2();f2(); cout << x << endl;cout << x << endl;}}
1
void f2()void f2(){ { x += 4;x += 4; f1();f1();}}
3
void f1()void f1(){ { x++;x++;}}5
37
45
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x
void main()void main(){ { f2();f2(); cout << x << endl;cout << x << endl;}}
1
void f2()void f2(){ { x += 4;x += 4; f1();f1();}}6
38
45
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x
void main()void main(){ { f2();f2(); cout << x << endl;cout << x << endl;}}
7
39
45
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
x
void main()void main(){ { f2();f2(); cout << x << endl;cout << x << endl;}}8
40
I. Using Global Variables#include <iostream>using namespace std;int x = 0;void f1() { x++; }void f2() { x+=4;
f1(); }void main(){ f2(); cout << x << endl;}
41
What is Bad About UsingGlobal Vairables?
Not safe! If two or more programmers are working
together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value!
Against The Principle of Information Hiding! Exposing the global variables to all functions is
against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!)
42
Local Variables Local variables are declared inside the
function body and exist as long as the function is running and destroyed when the function exit
You have to initialize the local variable before using it
If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable
43
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function // function
prototypeprototypevoid main(){ x = 4; fun(); cout << x << endl;} void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
44
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;}
void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 0
Global variables are automatically initialized to 0
45
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;} void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 0
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
1
46
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;} void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
2
void fun()void fun()
{ { int x = 10;int x = 10; cout << x << endl;cout << x << endl;}}
x ????
3
47
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;} void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
2
void fun()void fun()
{ { int x = 10;int x = 10; cout << x << endl;cout << x << endl;}}
x 10
3
48
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;}
void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
2
void fun()void fun()
{ { int x = 10;int x = 10; cout << x << endl;cout << x << endl;}}
x 10
4
49
Example of Defining and Using Global and Local Variables
#include <iostream>using namespace std;
int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){ x = 4; fun(); cout << x << endl;}
void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
2
void fun()void fun()
{ { int x = 10;int x = 10; cout << x << endl;cout << x << endl;}}
x 10
5
50
Example of Defining and Using Global and Local Variables#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;}
void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}
651
Example of Defining and Using Global and Local Variables#include <iostream>using namespace std;int x; // Global variable// Global variableVoid fun(); // function prototype// function prototype
void main(){ x = 4; fun(); cout << x << endl;}
void fun(){ int x = 10; // Local variable// Local variable cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl;}}752
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 0
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}
1
53
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}
2
void fun(int x )void fun(int x ){ { cout << x << endl;cout << x << endl; x=x+5;x=x+5;}}
3
3
54
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}
2
void fun(int x )void fun(int x ){ { cout << x << endl;cout << x << endl; x=x+5;x=x+5;}}
3
4
8
55
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}
2
void fun(int x )void fun(int x ){ { cout << x << endl;cout << x << endl; x=x+5;x=x+5;}}
38
5
56
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}
657
Example of Using Value Parameters and Global Variables#include <iostream>using namespace std;int x; // Global variable// Global variablevoid fun(int x){ cout << x << endl;
x=x+5;}void main(){ x = 4; fun(x/2+1); cout << x << endl;}
x 4
void main()void main(){ { x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl;}}758
Methods of Passing
Methods of Passing There are 2 primary methods of passing
arguments to functions: pass by value, pass by reference,
60
Absolute value#include <iostream>using namespace std;int absolute (int);// function prototype for absolute()int main(){ int num, answer; cout << "Enter an integer (0 to stop): "; cin >> num;
while (num!=0){ answer = absolute(num); cout << "The absolute value of " << num << " is: " << answer << endl; cin >> num; }
return 0; } // Define a function to take absolute value of an integer int absolute(int x){ if (x >= 0) return x; else return -x; }
61
Methods of Passing There are 2 primary methods of passing
arguments to functions: pass by value, pass by reference,
62
Passing arguments by reference When passing arguments by value, the only way to return
a value back to the caller is via the function’s return value.
While this is suitable in many cases, there are a few cases where better options are available.
63
Passing arguments by reference
In pass by reference, we declare the function parameters as references rather than normal variables:
1234
void AddOne(int &y) // y is a reference variable{ y = y + 1;}
• When the function is called, y will become a reference to the argument.
• The reference to a variable is treated exactly the same as the variable itself.
• any changes made to the reference are passed through to the argument!
64
Passing arguments by reference
Sometimes we need a function to return multiple values.
However, functions can only have one return value. One way to return multiple values is using reference
parameters
65
Cont. Example
void foo(int &y) // y is now a reference{ cout << "y = " << y << endl; y = 6; cout << "y = " << y << endl;} // y is destroyed here int main(){ int x = 5; cout << "x = " << x << endl; foo(x); cout << "x = " << x << endl; return 0;}
This program is the same as the one we used for the pass by value example, except foo’s parameter is now a reference instead of a normal variable.
When we call foo(x), y becomes a reference to x.
Note that the value of x was changed by the function!
66
Passing arguments by reference
Example 2void AddOne(int &y){ y++;} int main(){ int x = 1; cout << "x = " << x << endl; AddOne(x); cout << "x = " << x << endl; return 0;}
67
Passing arguments by reference
Example 3#include <iostream>Using namespace std ;Void duplicate (int& a, int& b, int & c); Void main (){ Int x=1,y=3,z=7;
Duplicate (x,y,z);Cout << “x=“<<x<<“, y=“<<y<<“,z=“<<z;
}
Void duplicate (int& a, int& b, int & c){ a*=2;
b*=2;c*=2;
}
68
Passing arguments by reference
Example 4#include <iostream>Using namespace std ;void swap(float &x, float &y); int main() {
float a, b; cout << "Enter 2 numbers: " << endl; cin >> a >> b;
if(a>b) swap(a,b); cout << "Sorted numbers: "; cout << a <<
" " << b << endl; return 0; } void swap(float &x, float &y) { float temp; temp = x; x = y; y = temp; }
69
Passing arguments by reference
1
#include <iostream>#include <math.h> // for sin() and cos()Using namespace std; void GetSinCos(double dX, double &dSin, double &dCos){ dSin = sin(dX); dCos = cos(dX);} int main(){ double dSin = 0.0; double dCos = 0.0; GetSinCos(30.0, dSin, dCos); cout << "The sin is " << dSin << endl; cout << "The cos is " << dCos << endl; return 0;}
70
Advantages of passing by reference It allows us to have the function change the value of the
argument, which is sometimes useful. Because a copy of the argument is not made, it is fast, even
when used with large structus or classes. We can pass by CONST reference to avoid unintentional
changes. We can return multiple values from a function.
71
Function Overloading
73
Function Overloading Two or more functions can have the same
name but different parameters Example:
int max(int a, int b) {if (a>= b)
return a;else
return b;}
float max(float a, float b) {if (a>= b)
return a;else
return b;}
Function Overloading In a C++ program, several functions can have
the same name This is called function overloading or
overloading a function name
74
Function Overloading (continued) Two functions are said to have different
formal parameter lists if both functions have: A different number of formal parameters, or If the number of formal parameters is the same,
then the data type of the formal parameters, in the order you list them, must differ in at least one position
75
The functions functionSix and functionSeven both have three formal parameters and the data type of the corresponding parameters is the same; therefore, these functions have the same formal parameter list
76
• Function overloading: creating several functions with the same name
• The signature of a function consists of the function name and its formal parameter list
• Two functions have different signatures if they have either different names or different formal parameter lists
• Note that the signature of a function does not include the return type of the function
Function Overloading (continued)
77
These function headings correctly overload the function functionXYZ:
• Both of these function headings have the same name and same formal parameter list
• Therefore, these function headings to overload the function functionABC are incorrect
• In this case, the compiler will generate a syntax error
• Note that the return types of these function headings are different
78
Functions with Default Parameters When a function is called
The number of actual and formal parameters must be the same
C++ relaxes this condition for functions with default parameters
You specify the value of a default parameter when the function name appears for the first time, such as in the prototype
79
Functions with Default Parameters (continued)
If you do not specify the value of a default parameter The default value is used
All of the default parameters must be the rightmost parameters of the function
In a function call where the function has more than one default parameter and a value to a default parameter is not specified You must omit all of the arguments to its right
80
Functions with Default Parameters (continued)
Default values can be constants, global variables, or function calls
The caller has the option of specifying a value other than the default for any default parameter
You cannot assign a constant value as a default value to a reference parameter
81
82
83
Function Overloading Function overloading
Functions with same name and different parameters or return data type
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; }
A call-time c++ complier selects the proper function by examining the number, type and order of the parameters
84
Function overloadingExample
85
#include <iostream>using namespace std;
void FtoC(int temp);void FtoC(float temp);void FtoC(double temp);
int main(){ int inttemp, level; float floattemp; double doubletemp;cout << "CONVERTING FAHRENHEIT TO CELSIUS\n"; cout << "Select required level of precision\n"; cout << "Integer (1) - Float (2) - Double (3)\n"; cin >> level;
cout << "Enter Fahrenheit temperature: ";switch (level) { case 1 : cin >> inttemp;
FtoC(inttemp); break;
case 2 : cin >> floattemp; FtoC(floattemp); break;
case 3 : cin >> doubletemp; FtoC(doubletemp);break;
default : cout << "Invalid selection\n"; } return 0;}
Function overloading
Cont .
86
void FtoC( int itemp)} int temp = (itemp - 32) * 5 / 9; cout << "Integer precision" :; cout << itemp << "F is " << temp << "C\n";{
void FtoC( float ftemp)} float temp = (ftemp - 32) * 5.0 / 9.0; cout << "Float precision" :; cout << ftemp << "F is " << temp << "C\n";;{
void FtoC( double dtemp)
}
double temp = (dtemp - 32) * 5.0 / 9.0;
cout << "Double precision" : ;
cout << dtemp << "F is " << temp << "C\n";;
{
By: Nouf Almunyif
Recursion
Recursion and Recursive Functions Main calls another function…..normal A function calls another function2….normal A function calls itself ?! Possible??
YESA recursive function is one that call itself.
88
General form void recurse(){ recurse(); //Function calls itself}
89
Finding Factorial 5! = 5*4*3*2*1
5!
5*4!
4*3!
3*2!
2*1!
1
5!
5*4!
4*3!
3*2!
2*1!
1
Final value=120
1
2!=2*1=2 returned
3!=3*2=6 returned
4!=4*6=24 returned
5!=5*24=120 returned
90
Finding Factorial #incloud <iostream>; Using nampespace std; Void main() { int n,factorial,i; cout << "Enter a positive integer: "; cin >> n; for (i = 1; i <= n; i++)
{ if (i == 1) factorial = 1; Else factorial = factorial * i; }
cout << "The factorial of " << n << " is " << factorial << endl;
}91
Finding Factorial Recursively//Recursive factorial Function#include<iostream>
Int factorial(int N);Void main(){ int num;
cout<<“Enter a positive integer:”;cin>>num;cout<<“factorial=“<<factorial(num);
}Int factorial( int N){
if ( N <= 1) //the base casereturn 1;
elsereturn N * factorial (N - 1);
}
N=4Retrun 4
*factorial(3)N=3
Retrun 3 *factorial(2)
N=2Retrun 2
*factorial(1)
N=1Retrun 1
Enter a positive integer : 4
12*1 = 2
23*2 =6
64*6=24
Factorial = 24
92
Example printing number counting down
#include <iostream>using namespace std; void myMethod( int counter){if(counter == 0) return; // no value returning just for EXIT
the functionelse { cout<<counter<<endl; myMethod(--counter); return; // no value returning just for EXIT
the function }}
void main(){
int input;cout<<"enter positive number ";cin>>input;myMethod(input);
}
93
Recommended