Programming Fundamentals Updated April 2019
Programming Fundamentals Updated April 2019
Programming Fundamentals Updated April 2019
LAB MANUAL
Last Updated by: Mr. Umar Bashir and Mr. Hamza Yousuf
Page | 2
Lab Manual of Programming Fundamentals
Table of Contents
Sr. No. Description Page No.
1 List of Equipment 04
8 Experiment No. 07, Separate Compilation, Friend Function and Friend Classes 30
Page | 3
Lab Manual of Programming Fundamentals
List of Equipment
Sr. No. Description
1 Workstations (PCs)
Page | 4
Lab Manual of Programming Fundamentals
Experiment No. 01
Static Arrays and File Streaming
OBJECTIVE:
Things that will be covered in today’s lab:
Introduction to Compiler
Revision of Static Arrays
File Streaming:
We have been dealing with input and output streams the whole time (cin and cout). The
input/output stream is used with <iostream> library.
In C++ and any other programming language, you can read and write from a text file (.txt
extension). We have to include a library in the same way as we include a library for cin and cout.
Page | 5
Lab Manual of Programming Fundamentals
inDATA.open(“Infile.txt”);
3. Open input output files outDATA.open(“Outfile.txt”);
Example:
Unsorted list 23 78 45 08 32 56
First Pass 08 78 45 23 32 56
Second Pass 08 23 45 78 32 56
Third Pass 08 23 32 78 45 56
Fourth Pass 08 23 32 45 78 56
Fifth Pass 08 23 32 45 56 78
Sorted List 08 23 32 45 56 78
Page | 6
Lab Manual of Programming Fundamentals
Student data is stored in a “student.txt” file and are arrange in following order.
Suppose that we have data of 20 students in a file. Your program must contain at least the
following functions:
Your program must output each student’s name in this form: last name followed by a comma,
followed by a space, followed by the first name; the name must be left justified. Moreover, other
than declaring the variables and opening the input and output files, the function main should only
be a collection of function calls.
Page | 7
Lab Manual of Programming Fundamentals
Example:
5 12 7 6 45 10 11 56 45 12
Average= (5+12+7+6+45)/5 = 15
15
5 12 7 6 45 10 11 56 45 12
Average= (12+7+6+45+10)/5 = 16
15 16
5 12 7 6 45 10 11 56 45 12
5 12 7 6 45 10 11 56 45 12
Page | 8
Lab Manual of Programming Fundamentals
Experiment No. 02
Pointers and Dynamic Arrays
OBJECTIVE:
Things that will be covered in today’s lab:
Pointers
Dynamic Arrays
THEORY:
Pointer variable: A variable whose content is an address (i.e., a memory address) In C++, you
declare a pointer variable by using the asterisk symbol (*) between the datatype and the variable
name. The general syntax to declare a pointer variable is as follows:
datatype * identifier;
In C++, the ampersand (&), address of the operator, is a unary operator that returns the address
of its operand. Similarly, “*” is a dereferencing operator, refers to the object to which its operand
(pointer) points. For example, given the statements:
int x;
int *p;
p = &x; // assigns address of x to p
cout << *p << endl; // pointer p points to x
The arrays discussed in last lab are called static arrays because their size was fixed at compile
time. One of the limitations of a static array is that every time you execute the program, the size
of the array is fixed. One way to handle this limitation is to declare an array that is large enough
to process a variety of data sets. However, if the array is very big and the data set is small, such a
declaration would result in memory waste. On the other hand, it would be helpful if, during
program execution, you could prompt the user to enter the size of the array and then create an
array of the appropriate size.
Dynamic Array: An array created during the execution of a program. To create a dynamic
array, we use new operator.
int size;
int *p;
p = newint [size];
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory previously allocated by new operator.
delete [] p;
Page | 9
Lab Manual of Programming Fundamentals
Exercise 1: (5 points)
Write the output of the following C++ codes without running the code in Visual Studio.
a)
int x;
int y;
int *p=&x;
int *q=&y;
x=35;
y=46;
p=q;
*p=78;
cout<<x<<“ ”<<y<<“ ”;
cout<<*p<<“ ”<<*q;
b)
int x[3]={0,4,6};
int *p,t1,t2;
p=x;
(*p)++;
cout<<*p;
cout<<*(p+1);
c)
int x,*p,*q;
int arr[3]={0};
p=arr;
q=p;
*p=4;
for (int j=0;j<2;j++)
{
x=*p;
p++;
*p=(x+j);
}
for (int k=0;k<3;k++)
{
cout<<*q;
q++;
}
Page | 10
Lab Manual of Programming Fundamentals
Example:
Case 1: (new_size > size)
new_size=7, size=5
Before calling resize function:
Array => 2 32 4 34 51
Case 2: (new_size<size)
new_size=3, size=5
Before calling resize function:
Array => 2 32 4 34 51
Example:
Array 1=> 1 2 3 4
Array 2=> 3 4 5 6 7
Array 3=> 1 2 3 4 5 6 7
Page | 11
Lab Manual of Programming Fundamentals
void main()
{
char input[100];
cin.getline(input,100);
//For example, user enters National University.
char *q=input;
ReverseSentence(q);
cout<<input<<endl;
Write the implementation of the function void ReverseSentence(char*). Assume that each
sentence ends with a full stop. You should use the following function ReverseWord() to reverse
each word of the whole sentence. You are not allowed to use any static array. You are only
allowed to use simple character pointers.
“p” is a pointer pointing to the first location of char array and length is the number of characters
in the array. For example, if p is pointing to “HELLO” then the length is 5. After calling this
function, p is pointing to “OLLEH”.
Page | 12
Lab Manual of Programming Fundamentals
Experiment No. 03
Double Pointers and 2-D Dynamic Arrays
OBJECTIVE:
Things that will be covered in today’s lab:
Double Pointers
Dynamic Two Dimensional Arrays
THEORY:
Double Pointer: A double pointer is a pointer to pointer. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer contains the address
of the second pointer, which points to the location that contains the actual value as shown in
Figure 3.1:
In C++, you declare a double pointer variable by using two asterisks (**) between the data type
and the variable name. The general syntax to declare a pointer variable is as follows:
datatype ** identifier;
int var=3000;
int *ptr;
int **pptr;
Page | 13
Lab Manual of Programming Fundamentals
Dynamic 2-D Array: First, we will allocate memory for an array which contains a set of
pointers. Next, we will allocate memory for each array which is pointed by pointers. The de-
allocation of memory is done in the reverse order of memory allocation.
int **Array = 0;
Array = newint *[ROWS]; //memory allocated for elements of
// row.
for(int i=0; i<ROWS; i++)//memory allocated for each col.
Array[i] = newint[COLUMNS];
int **T2D
*
*
*
*
Figure 3.2
Page | 14
Lab Manual of Programming Fundamentals
This function takes a single pointer by reference and dynamically allocates memory to it.
You will call this function in main to allocate number of columns to each row turn by turn.
int main( ){
int **p;
p=newint *[rows];
for(int i=0; i<rows; i++)
//call function...
}
This function simply takes a pointer as an argument and takes input in it from the user.
The second argument is the size of 1D array pointed by pointer.
Page | 15
Lab Manual of Programming Fundamentals
Figure 3.3
Here, * indicates that the seat is available; X indicates that the seat is occupied. Make this a
menu-driven program; show the user’s choices and allow the user to make the appropriate
choices.
Page | 16
Lab Manual of Programming Fundamentals
1 2 3
[4 5 6]
7 8 9
Transpose:
1 4 7
[2 5 8]
3 6 9
2. Given Matrix
1 2
[3 4]
5 6
Transpose:
1 3 5
[ ]
2 4 6
A matrix is represented by a 2D array. Use a double pointer to declare this 2D array dynamically.
The number of rows and columns should be taken as input from the user. Your code should be
generic, i.e., it should work for any number of rows and columns.
You will have to create a new matrix of reversed size. For example, if the input matrix is of size
(2x3), the new matrix should be of a size (3x2). Create the new matrix dynamically.
Page | 17
Lab Manual of Programming Fundamentals
Experiment No. 04
Structure
OBJECTIVE:
Things that will be covered in today’s lab:
File Input and Output Streams
Structures
THEORY:
Structs:
We have already discussed array which is a structured data type having all elements of the same
type. Another structured data type is a struct (or record) which allows you to group related
values that are of different types.
A struct is a collection of fixed number of components, members, in which the members are
accessed by name. The members may be different data types.
Defining a Structure:
A struct is a user defined data type that requires the keyword struct followed by the name chosen
for the struct. The data members that define struct are contained between a set of curly brackets.
Struct definition must be ended with a semicolon.
struct struct_name
{
//
// Member variables
//
};
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the struct keyword to define variables of
structure type.
Page | 18
Lab Manual of Programming Fundamentals
struct uni_t {
char * title ;
int year;
};
int main (){
uni_t uni;
For example,
If the phone number is 042-5610, the output should be 0425610.
Show the customer different breakfast items offered by the restaurant. Assume that the restaurant
offers the following breakfast items (the price of each item is shown to the right of the item):
Bacon and Egg $2.45
French Toast $1.99
Fruit Basket $2.49
Cereal $0.69
Coffee $0.50
Peanut butter: $0.80
Page | 19
Lab Manual of Programming Fundamentals
Allow the customer to select more than one item from the menu. Calculate and print the bill.
Your program must contain at least the following functions:
1. getdata: This function loads the data into the array menuList and number of items may
vary.
2. showMenu: This function shows the different items offered by the restaurant and tells
the user how to select the items.
3. printCheck: This function calculates and prints the check.
(Note that the billing amount should include a 5% tax.) The customer can select multiple items
of a particular type. A sample output in this case is:
Tax $0.25
Amount Due $5.18
Page | 20
Lab Manual of Programming Fundamentals
Experiment No. 05
Nested Structure and Pointer to Structure
OBJECTIVE:
Things that will be covered in today’s lab:
Nested Structures (A struct within a struct)
Pointer to Structure
THEORY:
A nested structure in C++ is nothing but a structure within a structure. One structure can be
declared inside the other structure as we declare structure members inside a structure. A structure
variable can be a normal structure variable or a pointer variable to access the data.
Pointer to structure
You can define pointers to structures in a very similar way as you define a pointer to any other
variable. Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place “&” operator before the name of the
structure.
Page | 21
Lab Manual of Programming Fundamentals
Here variable is an object of structure type struct_name and p_var is a pointer to point to objects
of structure type variable. Therefore, the following code would also be valid:
struct_name * p_var;
struct_name variable;
p_var = & variable;
p_var->struct_members;
The value of the pointer p_var would be assigned the address of the object variable. The arrow
operator (->) is a dereference operator that is used exclusively with pointers to objects that have
members. This operator serves to access the member of an object directly from its address as can
be seen from Table 5.1.
movies_t * pmovie;
pmovie = & amovie;
pmovie->title= "MATRIX";
pmovie->year = 1999;
cout << pmovie->title;
+ cout <<" ("<< pmovie->year <<")\n";
}
Page | 22
Lab Manual of Programming Fundamentals
ID number (int)
First Name (string)
Last Name (string)
Designation (string) e.g. Assistant professor, Lecturer etc.
4. Implement your main function. Declare a variable of FacultyMember type. Assign values to
it using NewRecord function. Print its values using PrintDetails function.
5. Now, declare a FacultyMember type array of size 3 in main( ). Fill the values using
newRecord function. (Note that your newRecord can assign value to a single FacultyMember
type variable and you cannot change the prototype).
6. Print the values of the above array using PrintDetails Function without changing the
prototype.
// Point 5
facultyMember f1[3];
for( int i=0; i<3; i++)
newrecord(f1[i]);
for( int j=0; j<3; j++)
printdetails(f1[j]);
// Point 7
sortid(f1,3);
for( int k=0; k<3; k++)
printdetails(f1[k]);
Page | 23
Lab Manual of Programming Fundamentals
In main ( ), declare a variable myUni of theUniversity type. Set any values to name and address
of myUni. Copy the values of the array you declared in step5 into the FacultyMember type array
of myUni.
Print the details of the myUni. You should use the PrintDetails function for printing the details of
Facultymember list of myUni.
university uni;
uni.name="National University";
uni.adress="Block-B,Faisal Town";
for( int b=0; b<3; b++) {
// Assign value university faculty member
}
for( int a=0; a<3; a++) {
cout<<uni.name<<" "<<uni.adress<<" ";
printdetails(uni.FM[a]);
}
Author’s ID
Author’s Name
Book List
o Book Code
o Book name
o Subject
o Book Price
o Edition
The record of each author should contain details of three books.
Page | 24
Lab Manual of Programming Fundamentals
Experiment No. 06
Classes
OBJECTIVE:
Things that will be covered in today’s lab:
Classes
C++ Structs
THEORY:
Classes are an expanded concept of data structures: like data structures, they can contain data
members, but classes can also contain functions as members.
Classes have the same format as plain structures, except that they can also include functions and
have these new things called access specifiers. An access specifier is one of the following three
keywords: private, public or protected. These specifiers modify the access rights for the
members that follow them:
Private members of a class are accessible only from within other members of the same
class (or from their"friends").
Protected members are accessible from other members of the same class (or from
their "friends"), but also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its
members. Therefore, any member that is declared before any other access specifier has private
access automatically.
Class Definition: Classes are defined using either keyword class, with the following syntax:
class class_name
{
access_specifier:
//data member;
//member functions;
access_specifier:
//data member;
//member functions;
};
Page | 25
Lab Manual of Programming Fundamentals
C++ structs are almost similar to classes and have the same syntax for definition. The only
difference is that the reserve word struct is used and all functions and data member within a class
are pubic by default instead of private as in classes.
Exercise 1: (5 points)
Copy and paste the following code in a text editor and check output. What is the difference
between C++ Structs and Classes?
public: public:
voidrec(int value); voidrec(int value);
void printdetails(); void printdetails();
}; };
Page | 26
Lab Manual of Programming Fundamentals
class dateType
{
private:
int day, month, year;
string mon; //Month name
public:
//define functions here with appropriate parameters and //return
type.
}
Sample main function:
void main()
{
dateType D;
dateType C;
int d,y,m;
cout<<"Enter date"<<endl;
cin>>d>>m>>y;
cout<<endl;
D.setdate(d,m,y);
D.printdate();
cout<<endl;
cout<<"********************"<<endl;
d=31,
m=9;
y=1995;
Page | 27
Lab Manual of Programming Fundamentals
cout<<"Set date:"<<d<<"-"<<m<<"-"<<y<<endl;
D.setdate(d,m,y);
cout<<endl;
D.printdate();
cout<<endl;
cout<<"********************"<<endl;
cout<<"If "<<endl;
D.setdate(30,11,2007);
D.printdate();
cout<<endl;
cout<<"AFTER INCREMENTING BY 1 MONTH"<<endl;
D.incmonth();
D.printdate();
cout<<endl;
cout<<"********************"<<endl;
cout<<"AFTER INCREMENTING BY 1 YEAR"<<endl;
D.incyear();
D.printdate();
cout<<endl;
cout<<"********************"<<endl;
C.setdate(12,3,1999);
cout<<"New object created:"<<endl;
cout<<"DATE1:"<<endl;
C.printdate();
cout<<"DATE2:"<<endl;
D.printdate();
cout<<endl;
D.equal(C);
cout<<"********************************"<<endl;
cout<<"If ";
D.printdate();
cout<<endl;
cout<<"Date after 9 days will be"<<endl;
D.incbyday(9);
D.printdate();
}
Page | 28
Lab Manual of Programming Fundamentals
Use an integer variable to represent the Private data of the class-- the numerator and the
denominator. Provide a constructor that enables an object of this class to be initialized when it is
declared. The constructor should contain default values in case no initializes are provided and
should store the fraction in reduced form. For example, the fraction 2/4 should be stored in object
as 1 in the numerator and 2 in the denominator. Provide public member functions that perform
each of the following tasks:
1. Add two Rational numbers. The result should be stored in reduced form.
Two rational numbers a/b and c/d can be added as follows:
(a/b) + (c/d) = (a*d + c*b) / (b*d)
2. Multiply two Rational numbers. The result should be stored in reduced form.
The product of two rational numbers a/b and c/d can be found as follows:
(a/b) * (c/d) = (a*c) / (b*d)
3. Divide two Rational numbers. The result should be stored in reduced form.
Two rational numbers a/b and c/d can be divided as follows:
(a/b) ÷ (c/d) = (a*d) / (b*c)
4. Print Rational numbers in the form a/b where ais the numerator and b is the
denominator.
Page | 29
Lab Manual of Programming Fundamentals
Experiment No. 07
Separate Compilation, Friend Function and Friend Classes
OBJECTIVE:
Things that will be covered in today’s lab:
Separate Compilation
Friend Function and Friend Classes:
THEORY:
You might be wondering why you need header files and why you would want to have multiple
.cpp files for a program. The reasons for this are simple:
In C++, the contents of a module consist of structure type (struct) declarations, class
declarations, global variables, and functions. The functions themselves are normally defined in a
source file (a “.cpp” file). Except for the main module, each source (.cpp) file has a header file (a
“.h” file) associated with it that provides the declarations needed by other modules to make use
of this module.
The idea is that other modules can access the functionality in module X simply by #including the
“X.h” header file and the linker will do the rest. The code in X.cpp needs to be compiled only the
first time or if it is changed; the rest of the time, the linker will link X’s code into the final
executable without needing to recompile it, which enables IDEs to work very efficiently.
Header files contain mostly declarations that are used in the rest of the program. The skeleton of
a class is usually provided in a header file. Header files are not compiled, but rather provided to
other parts of the program through the use of #include.
A typical header file looks like the following:
// Inside sample.h
#ifndef SAMPLE_H
#define SAMPLE_H
// Contents of the header file.
//…
#endif/* SAMPLE_H */
Source File:An implementation file includes the specific details, that is the definitions, for what
is done by the program
Page | 30
Lab Manual of Programming Fundamentals
#include"sample.h"
//Definition of function
Friend functions: A non-member function can access the private and protected members of a
class if it is declared a friend of that class. That is done by including a declaration of this external
function within the class, and preceding it with the keyword friend. The general form is
A friend function is preceded by the keyword friend. Properties of friend functions are given
below:
Friend function is not in the scope of the class to which it has been declared as a friend.
Hence it cannot be called using the object of that class.
Usually it has objects as arguments.
It can be declared either in the public or the private part of a class. It cannot access member
names directly. It has to use an object name and dot membership operator with each member
name. (e.g., A . x )
Let’s take an example:
class Box{
double width;
public:
friend void printWidth( Box box );
void setWidth(double w) { width=w; }
};
void printWidth( Box box ){
cout << box.width <<endl;
}
void main( ){
Box box;
box.setWidth(10.0);
printWidth( box );
}
Page | 31
Lab Manual of Programming Fundamentals
Friend classes: Similar to friend functions, a friend class is a class whose members have access
to the private or protected members of another class. A class can be made a friend of another
class using keyword friend.
class A{
friend class B; // class B is a friend class
...
}
class B{
...
}
When a class is made a friend class, all the member functions of that class becomes friend
functions. In this program, all member functions of class B will be friend functions of class A.
Thus, any member function of class B can access the private and protected data of class A.
If B is declared afriend class of A then, all member functions of class B can access private data
and protected data of class A but, member functions of class A cannot private and protected data
of class B. Remember, friendship relation in C++ is granted not taken.
Page | 32
Lab Manual of Programming Fundamentals
Include a constructor that takes values of theName, Rollno and Marks from user as input. Also
include the following methods:
CalculatePercentage: that adds all elements of array Marks and calculate percentage and stores
the result in the member variable Percentage.
Grade: that calls CalculatePercentage method and displays the grade accordingly
Write a driver program to test your class.
Write a program that can read values for the class objects and add one object of DM with another
object of DB. Use a friend function to carry out the addition operation. The object that stores the
results maybe a DM object or DB object, depending on the units in which the results are
required. The display should be in the format of feed and inches or meters and centimeters
depending on the object on display.
Page | 33
Lab Manual of Programming Fundamentals
Experiment No. 08
Composition
OBJECTIVE:
Things that will be covered in today’s lab:
Composition
THEORY:
Composition (aggregation) is another way to relate two classes. In composition (aggregation),
one or more members of a class are objects of another class type. Composition is a “has a”
relation; for example “every person has a date of birth”.
class DOB
{
// member variables/ functions
};
class person
{
DOB date; // Declare object of date of birth
// member variable/ functions
}student;
Now, let us discuss how the constructors of the objects of date are invoked.Recall that a class
constructor is automatically executed when a class object enters itsscope. Suppose that we have
the following statement:
person student;
When the object “student” enters its scope, the objects “date”, which is themember of the
student, also enters their scope. As a result, one of their constructors is executed. We, therefore,
need to know how to pass arguments to the constructors of the member objects “date”, which
occurs when we give the definitions of the constructors of the class. Recall that constructors do
not have a type and so cannot be called like other functions. The arguments to the constructor of
a member object are specified in the heading part of the definition of the constructor of the class.
Page | 34
Lab Manual of Programming Fundamentals
Furthermore, member objects of a class are constructed (that is, initialized) in the order they are
declared (not in the order they are listed in the constructor’s member initialization list) and
before the containing class objects are constructed. Thus, in our case, the object “date” is
initialized first and then “student”.
.
The following statements illustrate how to pass arguments to the constructors of the member
objects DOB:
person::person(string f_n, string l_n, int m, int d, int y)
:date(m, d, y)
{
// Definition of Constructor person
}
class Birthday
{
public:
Birthday(int cmonth, int cday, int cyear){
month = cmonth;
day = cday;
year = cyear;
}
void printDate(){ cout<<month<<"/"<<day <<"/"<<year;}
private:
int month;
int day;
int year;
};
class People
{
public:
People(string cname, Birthday cdateOfBirth)
:name(cname),dateOfBirth(cdateOfBirth){}
void printInfo(){
cout<<name <<" was born on: ";
dateOfBirth.printDate();
}
private:
string name;
Birthday dateOfBirth;
};
int main()
{
Birthday birthObject(7,9,97);
People infoObject("Lenny the Cowboy", birthObject);
infoObject.printInfo();
}
Page | 35
Lab Manual of Programming Fundamentals
Provide constructors that enable objects of these classes to be initialized when they are declared.
The constructors should contain default values in case no initializes are provided.
The definition of class CircleType and class PointType is as under: (you may define additional
functions if you require any).
class PointType
{
int x;
int y;
public:
//default constructor
//constructor so that objects are initialized
//print the x and y- coordinates
//determine the quadrant in which the point lies
//getter and setter functions
};
class CircleType
{
double radius;
char * color;
PointType center;
public:
//default constructor
//constructor so that objects are initialized
//print the radius, center, color
//calculate area
//calculate circumference
//getter and setter functions
//destructor
};
Page | 36
Lab Manual of Programming Fundamentals
PointType P(-20,3);
int p=P.checkquad();
P.print();
switch (p)
{
case 0:
cout<<"Point lies at center"<<endl;
break;
case 1:
cout<<"Point lies in I quadrant"<<endl;
break;
case 2:
cout<<"Point lies in II quadrant"<<endl;
break;
case 3:
cout<<"Point lies in III quadrant"<<endl;
break;
case 4:
cout<<"Point lies in IV quadrant"<<endl;
break;
default:
cout<<"INVALID";
break;
}
int x;
inty;
double r;
char col[9];
CircleType circ(2,5,4.89,"purple");
cout<<"\n\n***********************\n\n";
circ.print();
circ.setparam(x,y,r,col);
cout<<"\n\n***********************\n\n";
circ.print();
cout<<"\n\n***********************\n\n";
}
Page | 37
Lab Manual of Programming Fundamentals
class section
{
int secNumber;
course c;//composition
public:
void setSection (int,int,int);
};
Page | 38
Lab Manual of Programming Fundamentals
Experiment No. 09
Inheritance
OBJECTIVE:
Things that will be covered in today’s lab:
Inheritance
THEORY:
Inheritance: The process by which a class incorporates the attributes and behaviors of a
previously defined class.The new classes that we create from the existing classes are
calledderived classes and the existing classes are called base classes. Derived classes inherit the
properties of base classes. Therefore, rather than creating completely new classes from scratch,
we can take advantage of inheritance and reduce software complexity.Each derived class, in turn,
becomes a base class for a future derived class. Inheritance can be either single inheritance or
multiple inheritances. In single inheritance, the derived class is derived from a single base class;
in multiple inheritances, the derived class is derived from more than one base class.
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
When deriving a class from a base class, the base class may be inherited through public,
protected orprivate inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While
using different type of inheritance, following rules are applied:
Public Inheritance: When deriving a class from a public base class, public members of the base
class become public members of the derived class and protectedmembersof the
base class become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but
can be accessed through calls to the public and protected members of the base
class
Protected Inheritance: When deriving from a protected base class, public and protectedmembersof the
base class become protected members of the derived class.
Page | 39
Lab Manual of Programming Fundamentals
Private Inheritance: When deriving from a private base class, public and protectedmembersof the
base class become private members of the derived class.
Multiple Inheritances:
C++ class can inherit members from more than one class and here is the extended syntax:
Where access is one of public, protected, or private and would be given for every base class
and they will be separated by comma as shown above. Let us try the following example:
class Shape
{
public:
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h;}
private:
int width;
int height;
};
class Rectangle: public Shape
{
public:
int getArea() { return (width * height); }
};
int main()
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
Page | 40
Lab Manual of Programming Fundamentals
Product
Book Electronics
TV MP3Player
Figure 9.1
For each product, system needs to store its regular price and discount. The system should provide
a functionality to set or get a price for each product. For the products that are categorized as
electronics, the name of the manufacturer should be stored. For MP3Players, system should store
the color and capacity (in Giga Bytes). The system stores the size of each television. For each
book, the following information is needed: Name of the book and Author’s name. For each
product, the system should calculate its discounted price.
Apply object oriented programming concepts and implement this system in C++. Implement
setter and getter functions for each class and all other required functions. Use the following
main().
void main(){
int choice1=0,choice2=0,capacity,size;
double price,discount;
string manufacturer,color,author,name;
Page | 41
Lab Manual of Programming Fundamentals
cout<<"\nSet Attributes\n";
cout<<"Price: ";
cin>>price;
cout<<"\nDiscount in %: ";
cin>>discount;
cout<<"\nManufacturer: ";
cin>>manufacturer;
cout<<"\nColor: ";
cin>>color;
cout<<"\nCapacity in GB: ";
cin>>capacity;
MP3player m1(price,discount,manufacturer,color,capacity);
if (m1.getCapacity()==1)
m1.setDiscount(10);
else
m1.setDiscount(50);
cout<<m1.SalePrice();
}
elseif (choice2==2) {
cout<<"\nSet Attributes\n";
cout<<"Price: ";
cin>>price;
cout<<"\nDiscount in %: ";
cin>>discount;
cout<<"\nManufacturer: ";
cin>>manufacturer;
cout<<"\nSize: ";
cin>>size;
TV t1(price,discount,manufacturer,size);
cout<<t1.SalePrice();
}
else
cout<<"\nInvalid value... try again later";
}
elseif (choice1==2){
cout<<"\nSet Attributes\n";
cout<<"Price: ";
cin>>price;
cout<<"\nDiscount in %: ";
cin>>discount;
cout<<"\nAuthor: ";
cin>>author;
cout<<"\nName: ";
cin>>name;
Book b1(price, discount, author,name);
cout<<b1.SalePrice();
}
else
cout<<"\nInvalid value... try again later";
}
Page | 42
Lab Manual of Programming Fundamentals
b. Every circle has a center and a radius. Given the radius, we can determine the circle’s
area and circumference. Given the center, we can determine its position in the x-y
plane. The center of the circle is a point in the x-y plane. Design a class, “circleType”,
which can store the radius and center of the circle. Because the center is a point in the
x-y plane and you designed the class to capture the properties of a point in Part a), you
must derive the class “circleType” from the class “pointType”. You should be able to
perform the usual operations on the circle, such as setting the radius, printing the
radius, calculating and printing the area and circumference, and carrying out the usual
operations on the center. Also, write a program to test various operations on a circle.
c. Every cylinder has a base and height, wherein the base is a circle. Design a class,
“cylinderType” that can capture the properties of a cylinder and perform the usual
operations on the cylinder. Derive this class from the class “circleType” designed in
Part b). Some of the operations that can be performed on a cylinder are as follows:
calculate and print the volume, calculate and print the surface area, set the height, set
the radius of the base, and set the center of the base. Also, write a program to test
various operations on a cylinder.
Page | 43
Lab Manual of Programming Fundamentals
Experiment No. 10
Polymorphism
OBJECTIVE:
Things that will be covered in today’s lab:
Polymorphism
THEORY:
Polymorphism is the term used to describe the process by which different implementations of a
function can be accessed via the same name. For this reason, polymorphism is sometimes
characterized by the phrase “one interface, multiple methods”.
In C++ polymorphism is supported both run time, and at compile time. Operator and function
overloading are examples of compile-time polymorphism. Run-time polymorphism is
accomplished by using inheritance and virtual functions.
One of the key features of class inheritance is that a pointer to a derived class is type-compatible
with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but
powerful and versatile feature.
class XYZ {
public:
void print() { cout<<"Parent class print:"<<endl; }
};
class ABC: public XYZ{
public:
void print() { cout<<"child class print:"<<endl; }
};
void main( )
{
XYZ *xyz;
ABC abc;
xyz = &abc; // store the address of abc
xyz->print(); // call abc print .
}
When the above code is compiled and executed, it produces the following result:
The reason for the incorrect output is that the call of the function print() is being set once by the
compiler as the version defined in the base class. This is called static resolution of the function
call, or static linkage - the function call is fixed before the program is executed. This is also
sometimes called early binding because the print () function is set during the compilation of the
program.
Page | 44
Lab Manual of Programming Fundamentals
But now, let's make a slight modification in our program and precede the declaration of print ()
in the “abc” class with the keyword virtual. After this slight modification, when the previous
example code is compiled and executed, it produces the following result:
This time, the compiler looks at the contents of the pointer instead of its type. Hence, since
address of object of “abc” class is stored in *xyz the respective print() function is called.As you
can see, each of the child classes has a separate implementation for the function print(). This is
how polymorphism is generally used. You have different classes with a function of the same
name, and even the same parameters, but with different implementations.
Virtual Function:
A virtual function is a function in a base class that is declared using the keyword virtual.
Defining in a base class a virtual function, with another version in a derived class, signals to the
compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to
be based on the kind of object for which it is called. This sort of operation is referred to
as dynamic linkage, or late binding.
Page | 45
Lab Manual of Programming Fundamentals
Figure 10.1
Every employee has an employee ID and a basic salary. The Commissioned employee has a sales
amount and rate. Hourly employee is paid on the basis of number of working hours. A regular
employee may have a bonus.
You have to implement all the above classes. Write constructor for all classes. The main
functionality is to calculate salary for each employee which is calculated as follows:
Page | 46
Lab Manual of Programming Fundamentals
int main()
{
CommissionedEmployee E1(25, 5000, 1000, 10);
CommissionedEmployee * ptr;
ptr = &E1;
cout<<" Commissioned Employee salary:"<<ptr->calculateSalary();
cout<<endl;
Employee * eptr;
eptr = &E1;
cout<<" Commissioned Employee salary:"<<eptr->calculateSalary();
cout<<endl;
return 0;
}
Page | 47
Lab Manual of Programming Fundamentals
Now derive two classes from Shape; Circle having attribute radius and Rectangle
havingattributes Length and Breadth. Include following in each class.
A constructor that takes values of member variables as argument.
A method Display() that overrides Display() method of Shape class.
A method Calculate_Area() that calculates the area as follows:
int main()
{
Shape *p;
Circle C1(5);
Rectangle R1(4,6);
p=&C1;
p->Calculate_Area();
p->Display();
p=&R1;
p->Calculate_Area();
p->Display();
return 0;
}
Page | 48
Lab Manual of Programming Fundamentals
Experiment No. 11
Operator Overloading
OBJECTIVE:
Things that will be covered in today’s lab:
Operator Overloading
THEORY:
Operator Overloading provides the ability to use the same operator to perform different actions
In C++ the statement c = a + b will compile successfully if a, b and c are of “int” and “float”
types and if we attempt to compile the statement when a,b and c are the objects of user-defined
classes, the compiler will generate error message but with operator overloading, this can happen.
Operator overloading is done with the help of a special function, called operator function, which
defines the operation that the overloaded operator will perform relative to the class upon which it
will work. An operator function is created using the keyword operator.
return_typeoperator op(arglist)
Function definition:
You can also overload an operator for a class by using a non-member function, which is usually
a friend of the class. Since a friend function is not a member of the class, it does not have a this
pointer. Therefore, an overloaded friend operator function is passed the operands explicitly. This
means that a friend function that overloads a binary operator has two parameters, and a friend
function that overloads a unary operator has one parameter. When overloading a binary operator
using a friend function, the left operand is passed in the first parameter and the right operand is
passed in the second parameter. Insertion and extraction operators, Operator function must be a
nonmember function of the class. Here is the syntax.
Page | 49
Lab Manual of Programming Fundamentals
Function definition:
ostream& operator<<( ostream& out, const class_name& obj )
{
// ...
return out;
}
Istream& operator>>( istream& in,class_name& obj )
{
// ...
return in;
}
We can overload the entire C++ operator except following.
1. Class member access operator (. )
2. Scope resolution operator (::)
3. Size operator (sizeof)
4. Conditional operator (? :)
class Distance
{
private:
int feet, inches;
public:
Distance(int f, int i) { feet = f; inches = i; }
void operator=(const Distance &D )
{
feet = D.feet;
inches = D.inches;
}
void displayDistance() {
cout <<"F: "<< feet <<" I:"<< inches << endl;
}
};
void main()
{
Distance D1(11, 10), D2(5, 11);
D1 = D2;
cout <<"First Distance :";
D1.displayDistance();
}
Page | 50
Lab Manual of Programming Fundamentals
1. *(Multiplication)
2. +(Addition)
3. –(Subtraction)
4. /(Division)
5. =(Assignment)
6. == (Equality Comparator)
class comp
{
double real;
double imag;
public:
// default constructor
// function that set real and imag part of complex no
// function that print complex number
// Opertator “+” for addition
// Opertator “-” for Subtraction
// Opertator “*” for Multiplication
// Opertator “/” for Division
// Opertator “==” for check both complex are equal or not
// Opertator “=” for assignment
};
n1.setpara(2,3);
n2.setpara(1,4);
n3=n1;
n3.show();
(n1+n2).show();
n3=n1*n2;
n3.show();
n3=n1-n2;
Page | 51
Lab Manual of Programming Fundamentals
n3.show();
n3=n1/n2;
n3.show();
if(n1==n2)
cout<<"Both no have same real and imag part "<<endl;
else
cout<<"Unequal !!!"<<endl;
Write a class implementation for a class named PhoneNumber giving the specification
below:
Functions:
Declare an object of type “PhoneNumber”, read in its values, and then print it
(using operator<<, operator>>).
Declare an array of three objects of type “PhoneNumber”, read in their values
and then print their values (using operator<<, operator>>).
Page | 52
Lab Manual of Programming Fundamentals
Write a class Rationalwhich represents a numerical value by two double values Numerator and
Denominator. Include the following public member functions:
Page | 53
Lab Manual of Programming Fundamentals
Experiment No. 12
Templates
OBJECTIVE:
Things that will be covered in today’s lab:
Templates
THEORY:
Templates are a very powerful feature of C++. They allow you to write a single code segment for
a set of related functions, called a function template, and for a set of related classes, called a class
template. The syntax we use for templates is:
template<class Type>
declaration;
Function templates: A function template behaves like a function except that the template can
have arguments of many different types In other words; a function template represents a family
of functions. The general format of a function template is as follows:
template<class T>
return_type functionname(argument T )
{
// body of function with Type T
};
Class templates: A class template provides a specification for generating classes based on
parameters. Class templates are generally used to implement containers.
template <class type>
class class_name
{
//(Body of the class)
};
Let’s take an example, just declare an “integer” generic class. This class contains two member
variables which are of Type T, and a member function “greater” to return greater number.
template<class T>
class number
{
T no_1, no_2;
public:
number (T n1, T n2) { no_1=n1; no_2=n2; }
T greater();
};
Page | 54
Lab Manual of Programming Fundamentals
The class that we have just defined serves to store two elements of any valid type. For example,
if we wanted to declare an object of this class to store two integer values of type “int” with the
values 115 and 36 we would write:
number<int> myobject1(1,2);
This same class could also be used to create an object to store any other type, such as:
number<double> myobject2(1.2,2.2);
If a member function is defined outside the definition of the class template, it shall be preceded
with the template <...> prefix:
Notice the syntax of the definition of a member function “greater” is:
template<class T>
T number<T>::greater()
{
// body of greater definition
}
template<class T>
class number
{
T no_1, no_2;
public:
number (T n1, T n2) { no_1=n1; no_2=n2; }
T greater();
};
template<class T>
T number<T>::greater()
{
if(no_1>no_2)
return no_1;
else
return no_2;
}
void main()
{
number<int> myobject1(1,2);
cout<<myobject1.greater()<<endl;
number<double> myobject2(1.2,2.2);
cout<<myobject2.greater()<<endl;
}
Page | 55
Lab Manual of Programming Fundamentals
//Make a template out of this function. Don't forget the return type.
int myMax(int one, int two)
{
int bigger;
if (one < two)
bigger = two;
else
bigger = one;
return bigger;
}
int main()
{
int i_one = 3, i_two = 5;
cout <<"The max of "<< i_one <<" and "<< i_two <<" is "
<< myMax(i_one, i_two) << endl;
//Test your template on float and string types
return 0;
}
Exercise 2: (10 points)
Write a C++ generic bubblesort function using templates that takes as parameters an array and its
size. You may assume that the compared objects have a < operator already defined. Test your
template function with a built-in type and a user-defined type.
Page | 56
Lab Manual of Programming Fundamentals
}
point::point(double a, double b){
x = a; y = b;
}
void point::print() const{
cout<<x<<""<<y<< endl;
}
double point::get_x() const{
return x;
}
double point::get_y() const{
return y;
}
void point::move(double dx, double dy){
x = x+dx;
y = y+dy;
}
Generalize the class Point into a template and test your code using following main function.
int main()
{
point<int> A = point<int>(1, 2);
A.print();
A.move(4, -5);
A.print();
point<float>B(3.2, 4.9);
cout << B.get_x() <<""<< B.get_y() << endl ;
point<string> C("day", "young");
C.print();
C.move("s","ster");
C.print();
return 0;
}
Page | 57
Lab Manual of Programming Fundamentals
Experiment No. 13
Design Experiment
Objective
To gain experience with inheritance, virtual functions, application of polymorphism and
templates. Also, to gain further practice with file I/O and dynamic memory allocation.
Lab Task
You will design a set of classes for storing student information, along with a class that will
manage a list of students. Data can be imported from files for storage in the list, and summary
reports with computed final grades will be printed to output files.
1. Design a set of classes that stores student grade information. Students can be classified
into three categories: English students, History students, and Math students.
2. Each class should have a function that will compute and return the student's final
average, based on the stored grades. All grades are based on a 100-point scale. Here are
the grades that need storing for each subject, along with the breakdown for computing
each final grade:
English -- Attendance = 10%, Project = 30%, Midterm = 30%, Final Exam = 30%
History -- Term Paper = 25%, Midterm = 35%, Final Exam = 40%
Math -- There are 3 quizzes (each out of 100), to be averaged into one Quiz Average
(which will be a decimal number). Final grade computed as follows:
* Quiz Average = 10%, Test 1 = 25%, Test 2 = 25%, Final Exam = 40%
3. The datatype of marks in above courses (English, History and Math) can vary. It could be
float, double, integer, long or any other user defined datatype. If the input file contains
double marks instead of integer, your program should run for it. Use class templates and
function templates in classes.
4. Identify all the classes and their relation and find which functions need to be virtual.
Make a UML Diagram and define all the classes according to UML Diagram.
Page | 58
Lab Manual of Programming Fundamentals
Experiment No. 14
Design Experiment
Objective
To gain experience with inheritance, virtual functions, application of polymorphism and
templates. Also, to gain further practice with file I/O and dynamic memory allocation
Lab Task
5. Write a class called StudentList, which will be used to store the list of
various students, using a single array of pointers but with flexible size. Note that this
array will act as a heterogeneous list, and it will need to be dynamically managed. Each
item in the array should be a Base Class pointer, which should point to the appropriate
type of object. Your list should only be big enough to store the students currently in it.
Your StudentList class needs to have these public functions available:
a StudentList() -- default constructor. Sets up an empty list
b ~StudentList() -- destructor. Needs to clean up all dynamically managed
data being managed inside a StudentList object, before it is deallocated
c bool ImportFile(const char* filename)
i This function should add all data from the given file (the parameter) into
the internally managed list of students. The file format is specified below in
this writeup. (Note that if there is already data in the list from a previous
import, this call should add MORE data to the list). Records should be added
to the end of the given list in the same order they appear in the input file.
If the file does not exist or cannot be opened, return false for failure.
Otherwise, after importing the file, return true for success.
d bool CreateReportFile(const char* filename)
i This function should create a grade report and write it to an output file
(filename given by the parameter). Grade report file format is described below
in this writeup.
If the output file cannot be opened, return false for failure. Otherwise, after
writing the report file, return true for success.
e void ShowList() const
i This function should print to the screen the current list of students, one
student per line. The only information needed in this printout is last name,
first name, and course name. Format this output so that it lines up in columns
Note that while this class will need to do dynamic memory management, you do not need
to create a copy constructor or assignment operator overload (for deep copy) for this
class. (Ideally we would, but in this case, we will not be using a StudentList object in a
Page | 59
Lab Manual of Programming Fundamentals
class StudentList
{
public:
StudentList(); // starts out empty
~StudentList(); // cleanup (destructor)
private:
};
6. Write a program that creates a single StudentList object and then implements a menu
interface to allow interaction with the object. Your main program should implement the
following menu loop (any single letter options should work on both lower and upper case
inputs):
*** Student List menu ***
7. The import and export options should start by asking the user for input of a filename (you
may assume it will be 30 chars or less, no spaces. If the import/export fails due to bad
file, print a message in the main() indicating that the job was not successfully
completed).
The "Show student list" option should print the brief student list to screen. Make sure
that no data member of class changes in this function.
The “Show this Menu” option should re-display the menu.
Quit should end the menu program.
8. File formats
Input File -- The first line of the input file will contain the number of students listed in the
file. This will tell you how many student records are being imported from this file. After
the first lines, every set of two lines constitutes a student entry. The first line of a student
entry is the name, in the format lastName, firstName. Note that a name could include
spaces -- the comma will delineate last name from first name. The second line will
contain the subject ("English", "History", or "Math"), followed by a list of grades (all
Page | 60
Lab Manual of Programming Fundamentals
integers), all separated by spaces. There will be no extra spaces at the ends of lines in the
file. The order of the grades for each class type is as follows:
English -- Attendance, Project, Midterm, Final Exam
History -- Term Paper, Midterm, Final Exam
Math -- Quiz 1, Quiz 2, Quiz 3, Test 1, Test 2, Final Exam
1. Output File -- The output file that you print should list each student's name
(firstName lastName- no extra punctuation between), Final Exam grade,
final average (printed to 2 decimal places), and letter grade (based on 10 point
scale, i.e. 90100 A, 80-89 B, etc). Output should be separated by subject, with an
appropriate heading before each section, and each student's information listed on a
separate line, in an organized fashion. (See example below). The order of the
students within any given category should be the same as they appear in the
student list. Data must line up appropriately in columns when multiple lines are
printed in the file. At the bottom of the output file, print a grade distribution of
ALL students -- how many As, Bs, Cs, etc.
8. General Requirements
• No global variables, other than constants!
• All member data of your classes must be private or protected
• You may use any of the standard I/O libraries that have been discussed in class
(iostream, iomanip, fstream, as well as C libraries, like cstring,
cctype, etc). You may also use the string class library
• You may not use any of the other STL (Standard Template Libraries) besides
string
4
Bunny, Bugs
Math 90.1 86.2 80.3 99.5 96.7 93.2
Schmuckatelli, Joe
History 88 75 90
Dipwart, Marvin
English 95 76 72 88
Crack Corn, Jimmy
Math 44 58 23 59 77 68
test2.txt
2 Kirk,
James T.
English 40 100 68 88
Lewinsky, Monica
Page | 61
Lab Manual of Programming Fundamentals
Sample run
Screen input and output: (keyboard input is underlined here to differentiate output from input)
*** Student List menu ***
I Import students from a file
S Show student list (brief)
E Export a grade report (to file)
M Show this Menu
Q Quit Program
>i
Enter filename: test1.txt
>s
First Last Course
>i
Enter filename: test2.txt
>s
First Last Course
>e
Enter filename: outfile1.txt
>q
Good
bye!
Page | 62
Lab Manual of Programming Fundamentals
HISTORY CLASS
MATH CLASS
A: 1
B: 3
C: 1
D: 1
F: 0
Page | 63
Lab Manual of Programming Fundamentals
Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of
copying may entail ZERO in that experiment. Second instance of copying may be reported to
DC. This may result in awarding FAIL in the lab course.
Page | 64
Lab Manual of Programming Fundamentals
Remember that the voltage of the electricity and the available electrical current in EE labs
has enough power to cause death/injury by electrocution. It is around 50V/10 mA that the
“cannot let go” level is reached. “The key to survival is to decrease our exposure to
energized circuits.”
If a person touches an energized bare wire or faulty equipment while grounded,
electricity will instantly pass through the body to the ground, causing a harmful,
potentially fatal, shock.
Each circuit must be protected by a fuse or circuit breaker that will blow or “trip” when
its safe carrying capacity is surpassed. If a fuse blows or circuit breaker trips repeatedly
while in normal use (not overloaded), check for shorts and other faults in the line or
devices. Do not resume use until the trouble is fixed.
It is hazardous to overload electrical circuits by using extension cords and multi-plug
outlets. Use extension cords only when necessary and make sure they are heavy enough
for the job. Avoid creating an “octopus” by inserting several plugs into a multi-plug
outlet connected to a single wall outlet. Extension cords should ONLY be used on a
temporary basis in situations where fixed wiring is not feasible.
Dimmed lights, reduced output from heaters and poor monitor pictures are all symptoms
of an overloaded circuit. Keep the total load at any one time safely below maximum
capacity.
If wires are exposed, they may cause a shock to a person who comes into contact with
them. Cords should not be hung on nails, run over or wrapped around objects, knotted or
twisted. This may break the wire or insulation. Short circuits are usually caused by bare
wires touching due to breakdown of insulation. Electrical tape or any other kind of tape is
not adequate for insulation!
Electrical cords should be examined visually before use for external defects such as:
Fraying (worn out) and exposed wiring, loose parts, deformed or missing parts, damage
to outer jacket or insulation, evidence of internal damage such as pinched or crushed
outer jacket. If any defects are found the electric cords should be removed from service
immediately.
Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
Plug your heavy current consuming or any other large appliances into an outlet that is not
shared with other appliances. Do not tamper with fuses as this is a potential fire hazard.
Do not overload circuits as this may cause the wires to heat and ignite insulation or other
combustibles.
Keep lab equipment properly cleaned and maintained.
Ensure lamps are free from contact with flammable material. Always use lights bulbs
with the recommended wattage for your lamp and equipment.
Be aware of the odor of burning plastic or wire.
Page | 65
Lab Manual of Programming Fundamentals
ALWAYS follow the manufacturer recommendations when using or installing new lab
equipment. Wiring installations should always be made by a licensed electrician or other
qualified person. All electrical lab equipment should have the label of a testing
laboratory.
Be aware of missing ground prong and outlet cover, pinched wires, damaged casings on
electrical outlets.
Inform Lab engineer / Lab assistant of any failure of safety preventive measures and safe
practices as soon you notice it. Be alert and proceed with caution at all times in the
laboratory.
Conduct yourself in a responsible manner at all times in the EE Labs.
Follow all written and verbal instructions carefully. If you do not understand a direction
or part of a procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT BEFORE
PROCEEDING WITH THE ACTIVITY.
Never work alone in the laboratory. No student may work in EE Labs without the
presence of the Lab engineer / Lab assistant.
Perform only those experiments authorized by your teacher. Carefully follow all
instructions, both written and oral. Unauthorized experiments are not allowed.
Be prepared for your work in the EE Labs. Read all procedures thoroughly before
entering the laboratory. Never fool around in the laboratory. Horseplay, practical jokes,
and pranks are dangerous and prohibited.
Always work in a well-ventilated area.
Observe good housekeeping practices. Work areas should be kept clean and tidy at all
times.
Experiments must be personally monitored at all times. Do not wander around the room,
distract other students, startle other students or interfere with the laboratory experiments
of others.
Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or
baggy clothing are a hazard in the laboratory. Long hair must be tied back, and dangling
jewelry and baggy clothing must be secured. Shoes must completely cover the foot.
Know the locations and operating procedures of all safety equipment including fire
extinguisher. Know what to do if there is a fire during a lab period; “Turn off equipment,
if possible and exit EE lab immediately.”
Page | 66
Lab Manual of Programming Fundamentals
For programming streams, the format of the report will be as given below:
1. Introduction: Introduce the new constructs/ commands being used, and their
significance.
2. Objective: What are the learning goals of the experiment?
3. Design: If applicable, draw the flow chart for the program. How do the new constructs
facilitate achievement of the objectives; if possible, a comparison in terms of efficacy and
computational tractability with the alternate constructs?
4. Issues: The bugs encountered and the way they were removed.
5. Conclusions: What conclusions can be drawn from experiment?
6. Application: Suggest a real world application where this exercise may apply.
7. Answers to post lab questions (if any).
Introduction
The ability to control the flow of the program, letting it make decisions on what code to execute,
is important to the programmer. The if-else statement allows the programmer to control if a
program enters a section of code or not based on whether a given condition is true or false. If-
else statements control conditional branching.
if ( expression )
statement1
else
statement2
If the value of expression is nonzero, statement1 is executed. If the optional else is present,
statement2 is executed if the value of expression is zero. In this lab, we use this construct to
select an action based upon the user's input, or a predefined parameter.
Page | 67
Lab Manual of Programming Fundamentals
Objective:
Design:
#include<iostream>
usingnamespace std;
int main()
{
int i,temp,d,revrs=0;
}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";
}
}
Page | 68
Lab Manual of Programming Fundamentals
Screen shots of the output for various inputs are shown in Figure 1:
The conditional statement made this implementation possible; without conditional branching, it
is not possible to achieve this objective.
Issues:
Encountered bugs and issues; how were they identified and resolved.
Conclusions:
Applications:
Page | 69