Oop Lab 1
Oop Lab 1
Summary
Items Description
Duration 3 Hours
Objectives
You have already seen C++ functions in your first course on Programming. This lab activity is
intended to provide an overview/recap of:
1|Page
Scope of Variables
int main ()
{
int x=5, y=3, z; z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) <<
'\n';
cout << "The third result is " << subtraction (x,y) <<
'\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n'; return 0;
2|Page
Example 1.3 Practice
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}
Example 1.4
3|Page
// passing parameters by reference
#include <iostream>
using namespace std;
Example 1.5
6
5
4|Page
// default values in functions #include
<iostream>
using namespace std;
int main ()
{
cout << divide (12); cout
<< endl;
Overloaded Functions
5|Page
int main ()
{
int x=5,y=2; float
n=5.0,m=2.0; cout <<
operate (x,y); cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}
Example 1.8
int main ()
{
long number;
cout << "Please type a number: "; cin >>
number;
cout << number << "! = " << factorial (number);
return 0;
}
6|Page
Inline Functions
Example 1.9
// TestInlineFunction.cpp
#include <iostream> using
namespace std;
LAB TASKS
Task 1 :
Give answers to the following.
7|Page
1. Write the prototype of a function named fnct() which accepts an int by value, a float by
reference and returns a char.
a. void function();
b. void function(void);
c. void function(int);
d. function(int);
e. int function();
function(int) : This declaration is not valid because it has not the return type. A return
type is necessary for all functions in C++.
4. A function needs to compute the average as well as the sum of three integers passed to it
and return the answers in the main(). Suggest the prototype for this function.
void computeAverage And Sum(int a, int b, int c, float &average, int &sum);
Inline functions in C++ are like shortcuts. Instead of going through the process of
calling a function, the code inside the function is copied right where it's needed. It's like
8|Page
writing the same thing over and over again instead of making a phone call. This can
make things faster because it skips the extra steps of making that call.
Task 2 :
for(int i=0;i<10;i+=3)
cout << cube(i) << endl;
return 0;
}
int cube(int a)
{
return a*a*a;
}
Output:
0
27
216
729
9|Page
Output:
10
Output:
10
9
8
Task # 03
COMPILE a program with a function isPrime() which takes an integer as an argument and returns
true if the argument is a prime number.
10 | P a g e
Task # 04
Write a program with a function volume() which accepts three sides of a cube and returns its volume.
Provide a default value of 1 for all the three sides of a cube.
Call this function with zero, one, two and three arguments and display the volume returned in the
main().
1 . Functions
11 | P a g e
2
12 | P a g e
5
7 8
13 | P a g e
9 10
14 | P a g e