Sei sulla pagina 1di 15

Capital University of Science and Technology, Islamabad

Department of Computer Science,


Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-01)
Functions, Pointers, and Structure – Recap
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

Table of Contents
1. Introduction 3

2. Activity Time-boxing 3

3. Objective of the Experiment 3

4. Concept Map 4
4.1 Reusability/ Modularity of Code 4
4.2 Function Prototype and Function Definition 4
4.3 Function Arguments and Parameters 4
4.4 Returning a Value from a Function 5
4.5 Pass by Value and Pass by Reference 5
4.6 Pointers 6
4.7 Structures 7
4.7.1 How to define a structure in C++ programming? 8
4.7.2 How to define a structure variable? 8
4.7.3 How to access members of a structure? 8
4.7.4 Structure Example 9

5. Homework before Lab 10


5.1 Problem solution modeling 10
5.2 Practices from home 11
5.2.1 Task 1 11
5.2.2 Task 2 11

6. Procedure & Tools 11


6.1 Tools 11
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] 11
6.3 Walk-through Task [Expected time = 15 mins] 11
6.3.1 Writing Code 1
6.3.2 Compilation 1
6.3.3 Executing the Program 1

7. Practice Tasks 2
7.1 Practice Task 1 [Expected time = 10 mins] 2
7.2 Practice Task 2 [Expected time = 10 mins] 2
7.3 Practice Task 3 [Expected time = 10 mins] 2
7.4 Out comes 3
7.5 Testing 3

8. Evaluation Task (Unseen) [Expected time = 60 mins] 3

9. Evaluation Criteria 3

10. Further Readings 4


10.1 Books 4
10.2 Slides 4
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

Lab 1: Functions, Pointers, and Structure - Recap


1. Introduction
C++ programming that you studied in the previous semester is purely based on writing a set of
instructions in a particular sequence such that the output is based on the sequence of the written
statements. If this sequence of instructions is modified then it could have a large impact on the resulting
program. Often a situation arises where we intend to use a particular chunk of code again and again in a
single program. In this scenario using sequential programming the programmer is forced to copy-paste the
code in various locations of the source file.
Although this is a solution, it is not a practical one because it causes the code to become lengthy,
unmanaged, poorly structured and difficult to understand. In such a situation function handling offers
an attractive and easy to implement alternative that is widely accepted and promoted by programmers of all
languages.
This lab is a refresher course on the use of functions, pointers and building logic. The functions that are
designed will receive variables and arrays from the user. The function will perform some processing on the
provided data and return results back to the main program.
The importance of this lab can be highlighted through the fact that functions play a pivotal role in the
establishment of classes, objects and their manipulations. A large portion of object oriented programming is
based on manipulating variables using functions. In the later part of this lab the use of pointers has been
emphasized. Concepts relating to pointers, memory access, using arrays with pointers have been presented.

Relevant Lecture Readings

 Lectures: 1, 2
 Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Chapters: 5, 10

2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 15 mins 15 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Task 25 mins 25 mins
7 Practice tasks 15 + 15 + 20 + 35 (mins) 85 mins
8 Evaluation Task 40 min for two task 50 mins
Total Time 170 Mins

3. Objective of the Experiment


After completing this lab the student should be able to:
 Understand the purpose/ advantage of creating a function.
 Understand the difference between a function definition and prototype.
 Understand the difference between a parameter and an argument.
 Understand how a function is created and called.
 Understand how values are passed by value and by reference to a function. Returning the values
thereafter.
 Use pointers and manipulate variables using pointers.
 Use an array with pointers in a function
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

 Understanding of structure

4. Concept Map

4.1 Reusability/ Modularity of Code

Computer programmers have always devised mechanisms through which they can make their code more
understandable and then reusable. In this regard functions offer a very popular and easy mechanism of
introducing the above goals. Function handling operates on the concept of provision of service/
functionality. We can call the services of a function by providing the required data and in result getting the
promised service from the function.

Reusability of code means devising methods through which you can use code again and again without
having to copy-paste in the source file. Modularity of code means dividing the code into small, manageable
and easy to understand segments.

4.2 Function Prototype and Function Definition


The creation of a function is based on two similar yet distinct statements called a function definition and
function prototype.
A function prototype explains only how a function will be called and what data type it will return. A
function definition on the other hand matches the function prototype and also includes a function body.
For example the following is the function prototype of a function that finds the sum of two integers
passed to it:
void addtwo(int, int);
The following is the function definition of the above defined function:
void addtwo (int a, int b){
int c = a+b;
cout<<”Sum is…”<<c;
}

4.3 Function Arguments and Parameters


There are two types of variables a function is related with; namely function arguments and function parameters.
Function arguments are those variables that are provided to a function. These variables are passed whenever a
function is called.
Function parameters are those variables that are created and initialized when parameters are passed to a function.
The scope of a function parameter is always within the body of the function. It should be pointed out here that any
variable that is created in a function body has a local scope and cannot be accessed outside the function body. The data
type of arguments must match the parameters of a function. In the following example, variables a and b are parameters
of the function addtwo( ).
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

void addtwo(int a, int b){


int c = a+b;
cout<< c;
}

Now suppose we are calling the same function from within the main().
void main (){
int x=3, y=4;
addTow(x, y);
}

4.4 Returning a Value from a Function


To increase the practical use of functions, a programmer may want the result of a function to be given back after
processing. This process is called returning a value from a function. It is important to reme mber that functions can
only return a single value (of any data type). If a function will not return a value then it is necessary to write void
before the function name in the prototype and the definition. It is not necessary for a function to return a val ue.

For example the following function does not return a value hence the void keyword is used
void addtwo (int a, int b);{
int c=a+b;
cout<<c;
}

The following function returns an integer value hence the keyword int is used.

int addtwo (int a, int b);{


int c=a+b;
return (c);
}

The value being returned can be displayed by using the following statement from where the function is being c
cout<< addrow(x, y);

4.5 Pass by Value and Pass by Reference


All the functions we have discussed until now are pass by value. Pass by value is an argument passing technique in
which the function receives a parameter and works with a copy of the value being provided. This means if a change
is made to the parameter value then still no change will not be reflected in the argument.
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

On the other hand pass by reference is an argument passing technique in which the function works with the exact
variable that is being passed as an argument. This means that even the smallest change in a parameter will be exactly
reflected in the arguments. This further implies that the arguments and the parameters are tightly coupled.

4.6 Pointers
Pointers are special kind of variables that are allowed to hold the address of another variable. Because of their pointing
ability pointers are considered very powerful in C++. Pointers can hold the address of another variable and this is
called referencing the memory location. When we attempt to extract values from a memory location then this is called
dereferencing a pointer
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

Figure 1: The working of a pointer (image courtesy of Wikipedia)


In the figure provided above there is a pointer variable called “a”. This variable is pointing to the memory address of
variable b. The memory address of variable b is 1008. In this diagram you will also note that the pointer “a” has its
own memory address. This is a very important fact because pointers themselves also require a space in memory.
When we write a code on our compilers remember that every computer has its own memory and the availability of
memory space. Our compilers take the help of a memory manager and allocate space in a memory slot that is
available to the system. This means every time we run the code we may get a different memory allocation.
Consider the code provided below:

Figure 2: The various operations that can be performed with a pointer. Output is also provided. Memory addresses
may be different depending on the hardware environment

In the code above first a simple integer variable is created. Then an integer pointer is created because we intend to
point to an integer variable. The pointer is then given the address of variable x by using the address operator. Then
we use the dereference operator (*) that directs us to the memory location where the pointer is pointing to.

4.7 Structures
Structure is the collection of variables of different types under a single name for better visualization of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure can
hold data of one or more types.
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

4.7.1 How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier (name of the structure). Then inside
the curly braces, you can declare one or more members (declare variables inside curly braces) of that
structure. For example:

Here a structure person is defined which has three members: name, age and salary.

4.7.2 How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as:

person bill;

Here, a structure variable bill is defined which is of type structure person .

4.7.3 How to access members of a structure?

The members of structure variable is accessed using dot operator. Suppose, you want to access ageof
structure variable bill and assign it 50 to it. You can perform this task by using following code below:

bill.age = 50;
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

4.7.4 Structure Example

Output:
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

5. Homework before Lab

5.1 Problem solution modeling


Write the pseudo-code of the following task. You are required to bring this code with you and submit to your
lab instructor.

Write pseudo-code for a program that will find the factorial of a number. Your task is to also perform checks on the
number entered by the user because the factorial can only be found of an integer and a positive number. Incorporate
these two conditions in you pseudo-code
Capital University of Science and Technology, Islamabad
Department of Computer Science,
Faculty of Computing

5.2 Practices from home

5.2.1 Task 1
In The field of Physics you are aware of the concept of force and acceleration. Your task is to write a program to
find the force if the mass and the acceleration of a body is given. Write a function to perform the calculation. Your
task is to provide the mass and acceleration as arguments to the function and then display the force without returning a
value.

5.2.2 Task 2
Write a program that creates a function to find the area of a cylinder if the radius and height of the cylinder is provided.
The function should return the value of area. The area of a cylinder is 𝜋 𝑟2ℎ. Consider the figure below for further
clarification.

6. Procedure & Tools

6.1 Tools
Visual Studio 2008.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “FindAverage”.

6.3 Walk-through Task [Expected time = 15 mins]


Write a C++ program that creates (in main function) an array of type int having 6 elements. Now write a function
called arr_avg( ) that will find the average of all the elements of the array. This function should return the average
back to the main( ) function. Also write another function called arr_display() that will display all the elements of the
array.
Lab 1: Formatting using Escape Sequences

6.3.1 Writing Code


In the source file created in the project “FindAverage” write following C++ code:

Figure 3: Function for finding average of values in an array

In the code above note that the two functions use different mechanisms for passing/ using an array. You can
choose the method that suits your code/ situation. The size is passed in both functions because without the size
the functions can easily cross the array bounds. Hence passing the array size is a good practice.

6.3.2 Compilation
Write a program to find the power of a number if the base and exponent is provided in the main function. Use pass
by value mechanism to compute the power and return the results back to the main function then display the result in
main function.

6.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Capital University of Science and Technology, Islamabad P age |1


Department of Computer Science (2017)
Lab 1: Formatting using Escape Sequences

Figure 2: Final output of FindAverage


program.

7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to finish
the tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab01.

7.1 Practice Task 1 [Expected time = 10 mins]


Write a program to find the power of a number if the base and exponent is provided in the main function. Use pass
by value mechanism to compute the power and return the results back to the main function then display the result in
main function.

7.2 Practice Task 2 [Expected time = 10 mins]


Modify the program 7.1 by adding another function to find power of a number if the base and exponent is provided
in the main function. In this function use pass by reference mechanism to compute the power then display the result
in main function.
Note: Your function should not return a value.

7.3 Practice Task 3 [Expected time = 10 mins]


Create a structure student with some attributes i.e regNo, name, age etc.. Then Implement following 5 functions
(Known as CRUDS operations which means CREATE, READ, UPDATE, DELETE, SEARCH operations):
1. addAStudent
2. updateAStudent
3. deleteAStudent
4. searchAndDisplayAStudent
5. displayAllstudents

After that create array of 5 Students in main function. Create a menu in main function to enable user to select and
perform the operations we created above. Program must not exit until and unless user wants to do so.

Capital University of Science and Technology, Islamabad P age |2


Department of Computer Science (2017)
Lab 1: Formatting using Escape Sequences

Sample Menu:
Main Menu
---------------

Press 1 to add a Student


Press 2 to update a Student
Press 3 to delete a Student
Press 4 to search and display a Student
Press 5 to display all students
Press e to exit the program

7.4 Out comes


After completing this lab, students will be able to use functions and also understand the concept of parameters,
Arguments and returning of values. Students should also be comfortable with pointers and their use in functions.

7.5 Testing
Test Cases for Practice Task-1 and Task-2

Sample Inputs Sample Outputs


Base: 4 Result = 4194304
Exponent: 11
Check that the function works with pass by reference

Table 2: Confirmation of practice tasks T1, T2, T3, T4

Practice Tasks Confirmation Comments


T1
T2
T3
T4

8. Evaluation Task (Unseen) [Expected time = 60 mins]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. Task No Description Marks
No.
1 4.1 Problem Modelling 20
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with Testing 10
4 7.2 Practice task 2 with Testing 10

Capital University of Science and Technology, Islamabad P age |3


Department of Computer Science (2017)
Lab 1: Formatting using Escape Sequences

5 7.3 Practice task 3 with Testing 10


6 7.4 Practice task 4 with Testing 15
7 8 Evaluation Tasks (Unseen) 20
8 Good Programming 10
Practices
Total Marks 100

10. Further Readings

10.1 Books
Text Book:
Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

Capital University of Science and Technology, Islamabad P age |4


Department of Computer Science (2017)

Potrebbero piacerti anche