0% found this document useful (0 votes)
11 views28 pages

Programming Fundamentals II Manual (1)

Uploaded by

nadia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views28 pages

Programming Fundamentals II Manual (1)

Uploaded by

nadia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 28

School of Information Technology

The University of Lahore, Islamabad Campus

Lab Manual

Programming Fundamentals II - CS02102


The University of Lahore, Islamabad Campus
School of Information Technology

LIST OF LAB PRACTICALS

Experiment 01:Introduction and implementation of 1-One Dimensional Arrays

Experiment 02: Introduction and implementation of 2- Multidimensional Arrays.

Experiment 03: Introduction and Implementation of Structures, Arrays of structures

Experiment 04: Introduction and Implementation of Array as a member of structure, Nested Structure

Experiment 05: Functions in C++ Language

Experiment 06: Functions in C++ Language

Experiment 07: Introduction and Implementations Built In Functions.

Experiment 08: Introduction and implementations of user defined functions.

Experiment 09: Introduction and implementations of user defined functions as an array.

Experiment 10: Introduction and implementation of pointers

Experiment 11: Introduction and implementation of pointers

Experiment 12: Introduction and implementation of pointers as an array

Experiment 13: Introduction and implementation of file handling.

Experiment 14: Introduction and implementing of string handling.


Practical # 01
Introduction and Implementation of 1-ONE Dimensional Arrays

Objective:
The objective of this lab session is to reinforce some programming concepts regarding to Arrays) in c
programming language.
1. Array declaration
2. Array initialization
3. Array traversing

Program to explain Arrays in C

1. Test the following program.

#include <stdio.h>

#include <conio.h>

int main(void)
{

constint NUM = 8;
void main( )
{
intnums[NUM];
int total = 0;
intctr;
for (ctr = 0; ctr< NUM; ctr++)
{
printf(“Please enter the next number...”);
scanf(“%d”, nums[ctr]);
total += nums[ctr];
}
printf(“The total of the numbers is %d“,total);
getch();
return 0;
}
2. Given the statement:
char teams[] = {‘E’,’a’,’g’,’l’,’e’,’s’,’\0', ’R’, ‘a’,’m’,’s’,’\0'};
which of the following statement is valid?
a) cout<< teams;
b) cout<< teams+7;
c) cout<< (teams+3);
d) cout<< teams[0];
e) cout<< (teams+0)[0];
f) cout<< (teams+5);

Tasks:

1. Write a C program that inputs an integer array and checks if all the elements in the array are
unique (i.e. we cannot find any pair of elements that are equal).
2. Write a function that reverses the elements of an array so that the last element becomes the
first, the second from the last becomes the second, and so forth.
3. We have two arrays A and B, each of 10 integers. Write a function that tests if every element
of array A is equal to its corresponding element in array B. In other words, the function must
check if A[0] is equal to B[0], A[1] is equal to B[1] and so forth. The function is to return true
(1) if al elements are equal and false if at least one element is not equal.

____________________________
(Concerned Teacher/Lab Engineer)
Practical # 02
Introduction and Implementation of 2-Dimensional Arrays

Objective:
The main objective of this lab session is to teach programming concepts related to 2 Dimensional
arrays and operations applied to them (Addition, Subtraction, and Multiplication).
Program to explain two dimensional Array in C
1. Given the array declaration:
int grades[3][5] = {80,90,96,73,65,67,90,68,92,84,70, 55,95,78,100};
Determine the value of the following subscripted variables:
a) grades[2][3]
b) grades[2][4]
c) grades[0][1]
2. Write a program that initializes two-dimensional array of 2 rows and 3 columns and then
displays its values.
#include <cstdlib>
#include <iostream>
using namespace std;
Output:
int main(intargc, char *argv[])
arr[0][0] =15 arr[0][1]=21 arr[0][2]=9
{ arr[1][0] =84 arr[1][1]=33 arr[1]
[2]=72
clrscr();
inti,j,arr[2][3]={15,21,9,84,33,72};
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
cout<<"arr["<<i<<"]["<<j"]="<<arr[i][j]<<"\t";
cout<<endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Tasks:

1. Write a C++ program, which takes row and column count from user and then take data
elements from user and display the array.
2. Write a C++ program which takes two 2-D arrays (input from user). Perform addition &
subtraction on the arrays and then store the result into resultant arrays.
3. Get a matrix from user and perform transpose operation on it.

____________________________
(Concerned Teacher/Lab Engineer)
Practical # 03
Functions in C Language-I
Objective:
Main objectives of this lab session are to reinforce programming concepts related to
 Function creation
 Functions with arguments
Tasks:

4. Write a C++ code which generate the following menu and perform the tasks according to the
menu. The whole task should be repeated till the user wants to exit.

Output:

***MENU***
Press:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

5. Write menu-oriented code, which allows user to perform addition of 2-numbers as well as 3-
numbers using functions.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------

---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 04
Functions in C Language-I

Objective:
Main objectives of this lab session is to reinforce programming concepts related to
 Function Return types
Tasks:

1. Write a C++ code which generate the following menu and perform the tasks according to the
menu. The whole task should be repeated till the user wants to exit.

Output:

***MENU***
Press:
6. Addition
7. Subtraction
8. Multiplication
9. Division

Perform the above-mentioned operations using the following function signatures

 int add(int a, int b );


 int sub(int a, int b);
 int mul(int a, int b);
 float div(int a, int b);

2. Write a menu-oriented program using functions that will allow the user to convert
temperatures i.e. from centigrade to Fahrenheit and Kelvin

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 05
Recursive Functions
Objective:
Main objectives of this lab session are to reinforce programming concepts related to function
recursion.
Software Tools:- Dev C++

Theory:

A recursive function (DEF) is a function which either calls itself or is in a potential cycle of function
calls. As the definition specifies, there are two types of recursive functions. Consider a function
which calls itself: we call this type of recursion immediate recursion.
A function that calls itself is known as recursive function. And, this technique is known as
recursion

How recursion works in C++?

void recurse()
{
recurse();
}

int main()
{
recurse();
}
The figure below shows how recursion works by calling itself repeatedly.
The recursion continues until some condition is met.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call and other doesn't.

Lab Task:

1. Write a C++ code to implement the Fibonacci series.


2. Write a program to find the GCD of two positive integers (entered by the user) using
recursion in C programming.

NOTE: Bring the task in hard copy and also attach the hand written dry run of the codes as well

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 06
Structures
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collection of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship number
and salary. You can easily create different variables name, citNo, salary to store these information
separately.
However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1, name2,
citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation between the
variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single name Person,
and use it for every person. Now, the code looks much cleaner, readable and efficient as well.
This collection of all related information under a single name Person is a structure.

Programs to explain structures:


1. Write a program that declares a structure to store day, month and year of birth date. It
inputs three values and displays date of birth in dd/mm/yy format.
#include <cstdlib>
#include <iostream>
struct birth
{
int day;
int month;
float year;
Output:
}; Enter day of birth: 26
int main(intargc, char *argv[]) Enter month of birth: 5
Enter year of birth: 94
{
clrscr(); Your date of birth is
26/5/94
birth b;
cout<<"Enter day of birth: ";
cin>>b.day;
cout<<"Enter month of birth: ";
cin>>b.month;
cout<<"Enter year of birth: ";
cin>>b.year;
cout<<"\nYour date of birth is "<<b.day<<"/"<<b.month<<"/"b.year;
system("PAUSE");
return EXIT_SUCCESS;
}
2. Write a program that uses a structure to store employee id and salary of an employee. It
defines and initializes a structure variable and displays it.
#include <cstdlib>
#include <iostream>
structemp
{
Output:
int id; Employee ID: 20
int salary; Salary: 18500

};
int main(intargc, char *argv[])
{
clrscr();
emp e={20,18500};
cout<<"Employee ID: "<<e.id<<endl;
cout<<"Salary: "<<e.salary<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Lab Task:

1. Write a C++ code to get record of 5 persons (name, age, salary) and display only those
records whose salary is 10,000 or more
2. Write a C++ code to implement the following structure
struct student
{
string name;
string reg_no;
int age;
int semester_no;
};

Display the record based on semester numbers. For example print all those students who are
in 1st semester then print who are in 2nd and so on.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 07
Nested Structures
Objective:
Main objectives of this lab session are to reinforce programming concepts related to nested
structures.
Software Tools:- Dev C++

Theory:

When a structure contains another structure, it is called nested structure. For example, we
have two structures named Address and Employee. To make Address nested to
Employee, we must define Address structure before and outside Employee structure and
create an object of Address structure inside Employee structure.

Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
struct structure1 obj;
};
Programs to Explain Nested of Structure:
1. Write a program in which data of student including his marks of 6 subjects are stored by
user and displayed on screen, using structures..
Example:
#include <iostream>
using namespace std;
struct Student
{
char name[50];
int age;
float marks[6];
};
int main()
{
Student s1;
cout << "Enter Full name: ";
cin.get(s1.name, 50);
cout << "Enter age: ";
cin >> s1.age;
cout <<"Enter marks of 6 Subjects below: \n ";
for (int i=1; i<=6; i++)
cin >> s1.marks[i];
cout << "\nDisplaying Information." << endl;
cout << "Name: "<< s1.name << endl;
cout <<"Age: "<< s1.age << endl;
cout <<"Marks: "<< endl;
for (int i=1; i<=6; i++)
cout << s1.marks[i];
return 0;
}
Lab Task:

1. Write a C++ code to get record 3 students in which student enter their name, age as well
university information (i.e., name and campus details). Provide a suitable menu-oriented
program which helps user to enter their details.
Also provide user the searching facility through the campus information.
2. Write a C++ code to implement the menu-oriented program using the following structures

struct Employee
struct Address
{
{
int Id;
string HouseNo;
string Name;
string City;
float Salary;
string PinCode;
Address Add;
};
};

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 08
Structures with Functions
Objective:
Main objectives of this lab session are to reinforce programming concepts related to
usage of structures in functions.
Software Tools:- Dev C++

Theory:
Structure variables can be passed to a function and returned in a similar way as normal arguments.

Passing structure to function in C++


A structure variable can be passed to a function in similar way as normal argument. Consider this
example:

Example 1: C++ Structure and Function


#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

void displayData(Person); // Function declaration

int main()
{
Person p;

cout << "Enter Full name: ";


cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;

// Function call with structure variable as an argument


displayData(p);

return 0;
}

void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}

Output

Enter Full name: Bill Jobs


Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4

Lab Task:

1. Write a C++ code to get record 3 Persons in which student enter their name and age.
Implement functions to get and display the record of the persons. Provide a suitable menu-
oriented program which helps user to enter their details.
2. Write a C++ code to implement the to add and subtract two complex numbers. Write a proper
menu-oriented program.
Hint: program should have the following structure

Struct complex {
int real;
int imag;
};

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 09
Structures Revision
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collecion of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship number
and salary. You can easily create different a name, a, salary to store these information separately.
However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1, name2,
citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation between the
variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single name Person,
and use it for every person. Now, the code looks much cleaner, readable and efficient as well.
This collection of all related information under a single name Person is a structure.
How to declare 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:

struct Person
{
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and salary.

Example: C++ Structure


C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}
Lab Task:

1. Calculate the final salary of employee including the basic pay in addition with the overtime
money using enumeration. You can write the enumeration and follows:
Enum (one-hour=10000, two-hours=15000, three-hours=20000, four-hours=25000);
Use the above enumeration in the program to calculate the salary of employee.

2. Write a predictor program to predict the day of the week using enumeration.
Hint: the program also need to get the ist day of the month as well

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)

Practical # 10
Pointers
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:

What are Pointers?


A pointer is a variable whose value is the address of another variable. Like any variable or constant,
you must declare a pointer before you can work with it. The general form of a pointer variable
declaration is −

type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the
pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Following are the valid pointer declaration −

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the
same, a long hexadecimal number that represents a memory address. The only difference between
pointers of different data types is the data type of the variable or constant that the pointer points to.

Using Pointers in C++


There are few important operations, which we will do with the pointers very frequently. (a) We
define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the
value at the address available in the pointer variable. This is done by using unary operator * that
returns the value of the variable located at the address specified by its operand. Following example
makes use of these operations −

Lab Task:

1. Write a program in C to find the maximum number between two numbers using a pointer. Use
call by reference methods to implement.
2. Learn the usage of array through pointers. Write a program in C to store n elements in an
array and print the elements using pointer. Hint: https://www.geeksforgeeks.org/c-
language-2-gq/pointers-gq/

3. Show the output of the following code

#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

Change the code to double pointer.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)

Practical # 11
Enumeration in C++

Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
An enumeration is a user-defined data type that consists of integral constants. To define an
enumeration, keyword enum is used.
enum season { spring, summer, autumn, winter };
Here, the name of the enumeration is season.
And, spring, summer and winter are values of type season.
By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element
during declaration (if necessary).
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};

Enumerated Type Declaration


When you create an enumerated type, only blueprint for the variable is created. Here's how you can
create variables of enum type.
enum boolean { false, true };

// inside function
enum boolean check;
Here, a variable check of type enum boolean is created.

Here is another way to declare same check variable using different syntax.
enum boolean
{
false, true
} check;

Lab Task:
1. Calculate the final salary of employee including the basic pay in addition with the overtime
money using enumeration. You can write the enumeration and follows:
Enum (one-hour=10000, two-hours=15000, three-hours=20000, four-hours=25000);
Use the above enumeration in the program to calculate the salary of employee.

2. Write a predictor program to predict the day of the week using enumeration.
Hint: the program also need to get the ist day of the month as well

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)

Practical # 12
Classes in C++
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called
members of the class.

C++ Class Definitions


When you define a class, you define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist of
and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list
of declarations. For example, we defined the Box data type using the keyword class as follows −

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A
public member can be accessed from outside the class anywhere within the scope of the class object.
You can also specify the members of a class as private or protected which we will discuss in a sub-
section.

Define C++ Objects


A class provides the blueprints for objects, so basically an object is created from a class. We declare
objects of a class with exactly the same sort of declaration that we declare variables of basic types.
Following statements declare two objects of class Box −

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Lab Task:
1. Write a C++ code for the following class.

BOX
Double length;
Double breadth;
Double height;

+get_info()
+display_info()
+ cal_volume()

2. Write a class with the name “circle”, which has “radius” as a data member. Create a function
that calculates circumference of circle (circumference of circle= 2πr).
In the main instantiate two circles and compare their circumference to show which circle has
greater value for circumference.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)

Practical # 13
Classes in C++ -II
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called
members of the class.

Lab Task:

1. Write a class with the name “circle”, which has “radius” as a data member. Create a function
that calculates circumference of circle (circumference of circle= 2πr).
In the main instantiate two circles and compare their circumference to show which circle has
greater value for circumference.
2. Create a base class of name ‘shape’ and a derive class with the name ‘triangle’.

Base class consists of a get function which assign the 3sides of the triangle (entered from user). This
class also contain a print() which when invoked displays the values of the three sides..

Derive class It consists of a function which calculates the area of the triangle using the following
formulas:

S= a+b+c/2 and area= square root(s*(s-a)*(s-b)*(s-c))

This class should have printarea() method which on calling displays the area of triangle.

Create a main class which will provide menu based implementation of the above mentioned classes.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)
Practical # 14
File Handling in C++
Objective:
Main objective of this lab is to let students know about structures and make them work on it.
Software Tools:- Dev C++

Theory:
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream
headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);

Modes :
MEMBER STANDS

CONSTANT FOR ACCESS

File open for reading: the internal stream buffer supports


in * input input operations.

File open for writing: the internal stream buffer supports


out output output operations.

binary binary Operations are performed in binary mode rather than text.

ate at end The output position starts at the end of the file.

app append All output operations happen at the end of the file,
appending to its existing contents.

Any contents that existed in the file before it is open are


trunc truncate discarded.

Default Open Modes :


ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Lab Task:

1. Write a program to store data into file and display the contents of the file.

2. Write a program to store the student data (i.e. name, registration #, department, university)
entered by the user. Store this content into the file and display.

Conclusion

--------------------------------------------------------------------------------------------------------------------------
-------------------------------------
---------------------------------------------
(Concerned Teacher/Lab Engineer)

You might also like