Professional Documents
Culture Documents
Pointers & Functions
Pointers & Functions
WEEK # 16
LECTURE 1
Error Address of Array are fixed and cant be changed like Pointer
Functions of Factorial
#include <iostream.h> int factorial(int num); void main() { int x; int factorial(int num) { int product=1; for(int i=1;i<=num;i++) { product=product*i; } return product; }
Call-by-Value
#include<iostream.h> double reciprocal(double x); void main() { double t=10; cout<<"Reciprocol of 10 is "<<reciprocal(t)<<endl; cout<<"Value of t is "<<t<<endl; } The only thing modified is the local variable x. The local double reciprocal(double x) variable t used as an argument { will still have the value 10 and x=1/x; is unaffected by the operations return x; inside the function. }
Call-by-Value
#include<iostream.h> double reciprocal(double x); void main() { double x=10; cout<<"Reciprocol of 10 is "<<reciprocal(x)<<endl; cout<<"Value of x is "<<x<<endl; } double reciprocal(double x) { x=1/x; return x; }
Call-by-Reference
It is possible to manually create a call-by-reference by passing the address of an argument (that is, a pointer) to a function. Pointers are passed to functions just like any other values. Of course, it is necessary to declare the parameters as pointer types.
Call-by-Reference
#include<iostream.h> void fun(int *j); void main() { int i; int *p; p=&i; fun(p); cout<<i<<endl; void fun(int *j) { *j=100; } }
Call-by-Reference
#include<iostream.h> void fun(int *j); void main() { int i=10; int *p; p=&i; cout<<i<<endl; fun(p); cout<<i<<endl; void fun(int *j) { *j=100; } }
Call-by-Reference
#include<iostream.h> void fun(int *j); void main() { int i=10; cout<<i<<endl; fun(&i); cout<<i<<endl; void fun(int *j) { *j=100; } }
Call-by-Reference
#include<iostream.h> void fun(int *j); void main() { int i=10; cout<<i<<endl; fun(&i); cout<<i<<endl; void fun(int *i) { *i=100; } }
Call-by-Value
#include<iostream.h> double reciprocal(double x); void main() { double t=10; cout<<"Reciprocol of 10 is "<<reciprocal(t)<<endl; cout<<"Value of t is "<<t<<endl; } The only thing modified is the local variable x. The local double reciprocal(double x) variable t used as an argument { will still have the value 10 and x=1/x; is unaffected by the operations return x; inside the function. }
Call-by-Reference
#include<iostream.h> void reciprocal(double *x); void main() { double t=10; reciprocal(&t); cout<<"Value of t is "<<t<<endl; } void reciprocal(double *x) { *x=1/(*x); }
Factorial (Call-by-Value)
#include <iostream.h> int factorial(int num); void main() { int x; int factorial(int num) { int product=1; for(int i=1;i<=num;i++) { product=product*i; } return product; }
Factorial (Call-by-Reference)
#include <iostream.h> void factorial(int *num); void main() { int x; cout<<"Enter number to find Factorial : "; cin>>x; } factorial(&x); cout<<"Answer is "<<x; cout<<endl<<endl; } void factorial(int *num) { int product=1; for(int i=1;i<=(*num);i++) { product=product*i; } *num=product;