Lab Activity 5c
Lab Activity 5c
Lab Activity 5c
Duration: 2 Hours
Learning Outcomes
This lab activity encompasses activities 5C(i), 5C(ii), 5C(iii) and 5C(iv).
Hardware/Software: C++ software (Dev C++, Microsoft Visual Studio, Turbo C++ 5.0/6.0)
Activity 5C (i)
Activity Outcome: Write and compile a program in user-defined function.
Duration: 30 minutes
The following example illustrates how to write program to describe the concept of recursion.
Procedure:
#include<iostream>
using namespace std;
//function prototype/declaration
int fibonacci(int);
int main()
{
for(int c = 0; c<=10; c++)
{
cout<<"fibonacci("<<c<<")="<<fibonacci(c)<<endl; //call function
}
}
DFC 20113 PROGRAMMING FUNDAMENTALS
//function definition
int fibonacci(int number)
{
if((0==number)||(1==number))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
Activity 5C(ii)
The following example illustrates how to write program using user-defined function.
Procedure:
1|Page
DFC 20113 PROGRAMMING FUNDAMENTALS
#include<iostream>
using namespace std;
int main()
{
int height,width;
int height2,base;
//call function
cout<<"\nTHE AREA OF RECTANGLE IS:"<<RECTANGLEAREA(height,width);
cout<<endl<<endl;
//call function
cout<<"\nTHE AREA OF TRIANGLE IS:"<<TRIANGLEAREA(height2,base);
cout<<endl<<endl;
return 0;
}
//function definition
int RECTANGLEAREA(int height, int width)
{
int area=height*width;
return area;
}
//function definition
int TRIANGLEAREA(int height2, int base)
{
double area3=0.5*height2*base;
return area3;
}
Step 2: Compile the program.
Step 3: Write the output.
Step 4: Save the program as _______________
2|Page
DFC 20113 PROGRAMMING FUNDAMENTALS
Activity 5C(iii)
Procedure:
3|Page
DFC 20113 PROGRAMMING FUNDAMENTALS
Activity 5C (iv)
Activity Outcome: Write and compile a program using C++ using recursive function
Duration: 30 minutes
Procedure:
#include <iostream>
using namespace std;
void numberFunction(int i)
{
cout << "The number is: " << i << endl;
i++;
if(i<10)
{
numberFunction(i);
}
}
int main()
{
int i = 0;
numberFunction(i);
return 0;
}
4|Page
DFC 20113 PROGRAMMING FUNDAMENTALS
#include <iostream>
Step 5:namespace
using Compile thestd;
program.
Step 6: Write the output.
void numberFunction(int i)
{
cout << "The number is: " << i << endl;
}
int main()
{
return 0;
}
5|Page