Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Algorithms and Programming COMP151

Similar presentations


Presentation on theme: "Introduction to Algorithms and Programming COMP151"— Presentation transcript:

1 Introduction to Algorithms and Programming COMP151
LAB 9 FUNCTIONS Introduction to Algorithms and Programming COMP151

2

3 User Defined Functions
Example program for Simple Function (no arguments) #include<iostream> using namespace std; void starline(); //Function Declaration (or) Prototype int main() { cout<<"Program for Function \n"; starline(); //Call to Function starline cout<<"This is the simple Program\n "; cout<<"Printing Star line to decorate the output\n"; return(0); } void starline() //Function definition int j; for(j=0;j<45;j++) cout<<"*"; cout<<endl;

4 Passing Parameters (or) Arguments to Functions
When a function is called, the program may send values into the function. Values that are passed into a function are called actual arguments (or) actual parameter. Two ways to pass arguments to functions Pass-by-Value 2. Pass-by-Reference

5 Pass-by-Value

6 Example: swapping-pass by value
#include<iostream> using namespace std; void swap(int,int); int main() { int a,b; cout<<"Enter the value for a"<<endl; cin>>a; cout<<"Enter the value for b"<<endl; cin>>b; swap(a,b); return(0); } void swap(int c,int d) int temp; temp=c; c=d; d=temp; cout<<"Value of c after swapping"<<c<<endl; cout<<"Value of d after swapping"<<d<<endl;

7 2. Pass-by-Reference A reference variable that used as a formal argument allows access to the original values of actual arguments. A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias. Reference variables are declared like regular variables, except you have to place an ampersand (&) symbol in front of the name.

8 Example: swapping-pass by reference
#include<iostream> using namespace std; void swap(int&,int&); int main() { int a,b; cout<<"Enter the value for a"<<endl; cin>>a; cout<<"Enter the value for b"<<endl; cin>>b; swap(a,b); cout<<"Value of a after swapping"<<a<<endl; cout<<"Value of b after swapping"<<b<<endl; return(0); } void swap(int &c,int &d) int temp; temp=c; c=d; d=temp;

9 Library Functions (or) Predefined Functions

10 Exercise 1 Write C++ program to find x to the power y using the predefined function pow

11 Exercise 2 Write C++ program to find the square root of a given number using the predefined function sqrt


Download ppt "Introduction to Algorithms and Programming COMP151"

Similar presentations


Ads by Google