Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
86 views

CSC213 Object Oriented Programming-Lab Manual-Sol

Here are a few examples of creating and using 2D arrays in C++: Example 1: Creating and initializing a 2D array int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; Example 2: Taking input in a 2D array int arr[3][4]; for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { cin >> arr[i][j]; } } Example 3: Accessing elements of a 2D array for(int
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

CSC213 Object Oriented Programming-Lab Manual-Sol

Here are a few examples of creating and using 2D arrays in C++: Example 1: Creating and initializing a 2D array int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; Example 2: Taking input in a 2D array int arr[3][4]; for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { cin >> arr[i][j]; } } Example 3: Accessing elements of a 2D array for(int
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Lab Manual

OBJECT ORIENTED
PROGRAMMING

CSC-213

SPRING 2020
OOPs Lab Manual

Lab Manual

OBJECT ORIENTED PROGRAMMING

Semester : Spring 2020


Program : BSCS
Course Title and Name : CSC 213
Credits : 0+1
Faculty : Mrs. Saadia Karim
Student Name :
Student ID :
Total Marks :
Obtained Marks :
Submitted Date :

2
OOPs Lab Manual

Table of Contents

Experiment
Experiment Title Date Signature
No.
The objective of this lab is to practice with input,
1. output and variables and to familiarize students with
IDE interface.
The objective of this lab is to practice with variables
2.
declaration, class components and compiling code.
To create a program with conditional IF-Statement and
3. IF-ELSE-IF Ladder and compare variables to display
the result.
To create a program with FOR loop for repeated
4.
processing of s statement.
To create a two dimensional array, insert values in the
5.
array and display the result.
To implement Switch statement and develop an
6.
arithmetic calculator.
To demonstrate the concept of class and declaration of
7.
objects with a class and display the output.
To develop a constructor, to initialize object and
8.
display output.
To implement inheritance concept using class and
9.
subclass and display the output.
To implement the concept of polymorphism (dynamic
10.
Binding or Late Binding) and display the output.
To implement exception handling using TRY-CATCH
11
statement and display the result.
To implement the concept of collection in java and run
12.
the program

13. To develop applet in java using HTML.

3
OOPs Lab Manual

LAB EXPERIMENT # 1

Objective: The objective of this lab is to practice with input, output and variables
and to familiarize students with IDE interface.

Example 1:
#include <iostream>  
using namespace std;  
int main( ) {  
   cout << " Welcome to C++ tutorial " << endl;  
}  
Output:

Example 2:
#include <iostream>  
using namespace std;  
int main( ) {  
  int age;  
   cout << "Enter your age: ";  
   cin >> age;  
   cout << "Your age is: " << age << endl;  
}  

Output:

4
OOPs Lab Manual

Task 1:
(Print a table) Write a program that displays the following table:

Task 2:
(Average speed in miles) Assume a runner runs 14 kilometers in 45 minutes
and 30 seconds. Write a program that displays the average speed in miles per
hour. (Note that 1 mile is 1.6 kilometers.)

Student Registration No: ________________________

Teacher Signature: ________________________

5
OOPs Lab Manual

LAB EXPERIMENT # 2

Objective: The objective of this lab is to practice with variables declaration, class
components and compiling code.

Example 1:
#include <iostream>  
using namespace std;  
int main( ) {  
   char ary[] = "Welcome to C++ tutorial";  
   cout << "Value of ary is: " << ary << endl;  
}  
Output:

Example 2:
#include <iostream>  
using namespace std;  
int main( ) {  
int x=5,b=10;  //declaring 2 variable of integer type    
float f=30.8;    
char c='A';
   cout << "Sum = " << x+b << endl;  
   cout << "Float = " << f << endl;  
cout << "Character = " << c << endl;  
}  
Output:

6
OOPs Lab Manual

Task 1:
Write a program that displays the following equation:  
-7 – 4a = -a + 8
Task 2:
Write a program that displays the following equation:
4c = 8 - 4c

Student Registration No: ________________________

Teacher Signature: ________________________

7
OOPs Lab Manual

LAB EXPERIMENT # 3

Objective: To create a program with conditional IF-Statement and IF-ELSE-IF


Ladder and compare variables to display the result.

Example 1: If Statement
// Program to print positive number entered by the user
// If user enters negative number, it is skipped

#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}

Output:

Example 2: If-Else Statement


// Program to check whether an integer is positive or negative
// This program considers 0 as positive number
#include <iostream>
using namespace std;
int main()
{
int number;

8
OOPs Lab Manual

cout << "Enter an integer: ";


cin >> number;
if ( number >= 0)
{
cout << "You entered a positive integer: " << number << endl;
}

else
{
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}

Output:

Example 3: Nested if...else


// Program to check whether an integer is positive, negative or zero
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}

9
OOPs Lab Manual

cout << "This line is always printed.";


return 0;
}
Output:

Task 1:
Write a program that a student will not be allowed to sit in exam if his/her
attendance is less than 75%.
 Take following input from user
o Number of classes held
o Number of classes attended.
 And print percentage of class attended
 In addition, print student is allowed to sit in exam or not.

Task 2:
Write a program and display the answer of the expressions:
If
x=2
y=5
z=0
Then find values of the following expressions:
 x == 2
 x != 5
 x != 5 && y >= 5
 z != 0 || x == 2
 !(y < 10)

Task 3:
Write a program to check whether a entered character is lowercase (a to z ) or
uppercase ( A to Z ).
Task 4:
Write a program to create grade book using IF Statement.

Student Registration No: ________________________

Teacher Signature: ________________________

10
OOPs Lab Manual

LAB EXPERIMENT # 4

Objective: To create a program with FOR loop for repeated processing of s


statement.

Example: For Loop


// C++ Program to find factorial of a number
// Factorial on n = 1*2*3*...*n

#include <iostream>
using namespace std;

int main()
{
int i, n, factorial = 1;

cout << "Enter a positive integer: ";


cin >> n;

for (i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}

Output:

Task 1:
Write a C++ program to print all odd number between 1 to 100.

Task 2:
Write a C++ program to enter any number and check whether it is Prime
number or not.

11
OOPs Lab Manual

Task 3:
Write a C++ program to enter any number and calculate sum of all natural
numbers between 1 to n.

Student Registration No: ________________________

Teacher Signature: ________________________

12
OOPs Lab Manual

LAB EXPERIMENT # 5

Objective: To create a two dimensional array, insert values in the array and
display the result.

Example: two-dimensional array


#include <iostream>
using namespace std;

int main()
{
int test[3][2] =
{
{2, -5},
{4, 0},
{9, 1}
};

// Accessing two dimensional array using


// nested for loops
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}
Output:

Task 1:
Write a C++ Program to Store value entered by user in three-dimensional
array and display it

13
OOPs Lab Manual

Task 2:
Write a C++ Program to store temperature of two different cities for a week
and display it.

Task 3:
Write a C++ program to find the largest element of a given array of integers.

Student Registration No: ________________________

Teacher Signature: ________________________

14
OOPs Lab Manual

LAB EXPERIMENT # 6

Objective: To implement Switch statement and develop an arithmetic calculator.

Example : Switch Statement


// Program to built a simple calculator using switch Statement

#include <iostream>
using namespace std;

int main()
{
char o;
float num1, num2;

cout << "Enter an operator (+, -, *, /): ";


cin >> o;

cout << "Enter two operands: ";


cin >> num1 >> num2;

switch (o)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1/num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! operator is not correct";
break;
}

return 0;
}

15
OOPs Lab Manual

Output:

Task 1:
Write a C++ program that have some grades of students and you need to
display, like following,
Grade A = YOU VERY GOOD
Grade B = EXCELLENT
Grade C = EXCELLENT
Grade F = WORST
(**if user enter any other letter programme should display “ERROR” message!**)

Task 2:
Write a C++ program to develop an arithmetic calculator.

Student Registration No: ________________________

Teacher Signature: ________________________

16
OOPs Lab Manual

LAB EXPERIMENT # 7

Objective: To demonstrate the concept of class and declaration of objects with a


class and display the output.

Example:
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

Output:

17
OOPs Lab Manual

Task 1:
Write a C++ program to print the area and perimeter of a triangle having
sides of 3, 4 and 5 units by creating a class named 'Triangle' with a function to
print the area and perimeter.

Task 2:
Create a class named 'Student' with a string variable 'name' and an integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as
"John" by creating an object of the class Student.

Task 3:
Write a C++ program to print the average of three numbers entered by the
user by creating a class named 'Average' having a function to calculate and
print the average without creating any object of the Average class.

Student Registration No: ________________________

Teacher Signature: ________________________

18
OOPs Lab Manual

LAB EXPERIMENT # 8

Objective: To develop a constructor, to initialize object and display output.

Example:
#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}
Output:

19
OOPs Lab Manual

To develop a constructor, to initialize the object and display output.


Watch this video: https://www.coursera.org/lecture/cs-fundamentals-1/3-1-class-constructors-
lYErY

Book link for Task 2 & 3, read and solve them.


Solution: https://github.com/djkovrik/EckelCpp/tree/master/Volume%202
Constructors in C++
Constructor is a special member function of a class that initializes the object of the class. Constructor
name is same as class name and it doesn’t have a return type. Lets take a simple example to understand
the working of constructor.

Simple Example: How to use constructor in C++


Read the comments in the following program to understand each part of the program.

#include <iostream>

using namespace std;

class constructorDemo{

public:

int num;

char ch;

/* This is a default constructor of the

* class, do note that it's name is same as

* class name and it doesn't have return type.

*/

constructorDemo() {

num = 100; ch = 'A';

};

int main(){

/* This is how we create the object of class,

* I have given the object name as obj, you can

* give any name, just remember the syntax:

* class_name object_name;

20
OOPs Lab Manual

*/

constructorDemo obj;

/* This is how we access data members using object

* we are just checking that the value we have

* initialized in constructor are reflecting or not.

*/

cout<<"num: "<<obj.num<<endl;

cout<<"ch: "<<obj.ch;

return 0;

}
Output:

num: 100

ch: A
Program TASK 1: Solution - You have to do up to n = 15
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    for(int i = 1; i<10; i++)
  {
        int N, zeroth=3, first=2, second;
        cout << "Enter in an integer N: " << flush;
        cin >> N;
        if(N==0)
            cout << "u(" << N << ") = " << zeroth << endl << endl;
        else if (N==1)
            cout << "u(" << N << ") = " << first << endl << endl;
        else if (N>1)
    {
            for(int x = 2; x<=N; x++)

21
OOPs Lab Manual

      {
                second = x*first + (x+1)*zeroth + x;
                zeroth = first;
                first = second;
      }
            cout << "u(" << N << ") = " << second <<  endl << endl;
    }
  }
  cin.get();
}
    Output:
 Enter in an integer N: 1 
 u(1) = 2 
 Enter in an integer N: 2
 u(2) = 15
 Enter in an integer N: 3
 u(3) = 56
 Enter in an integer N: 4
 u(4) = 303
 

Task 2: 
Create a base class X with a single constructor that takes an int argument and a member function
f( ), which takes no arguments and returns void. Now derive Y and Z from X, creating
constructors for each of them that take a single int argument. Next, derive A from Y and Z.
Create an object of class A, and call f( ) for that object. Fix the problem with explicit
disambiguation.
Solution:
 #include <iostream>
         class X {
          public:
                   X(int xxx) : x(xxx) {}
                   void f() { std::cout << "X::f()\n"; }
          private:
                   int x;

22
OOPs Lab Manual

          };
          class Y : public X {
          public:
                   Y(int yyy) : X(yyy), y(yyy) {}
                   void f() { std::cout << "Y::f()\n"; }
          private:
                   int y;
          };
       class Z : public X {
          public:
                   Z(int zzz) : X(zzz), z(zzz) {}
                   void f() { std::cout << "Z::f()\n"; }
          private:
                   int z;
          };
         class A : public Y, public Z {
          public:
                   using Z::f;
                   A(int aaa) : Y(aaa), Z(aaa), a(aaa) {}
          private:
                   int a;
          };
       int main() {
                   A a(1);
                   a.f();
                 return 0;
          }
 Task 3: 
Starting with the results of Exercise 1, create a pointer to an X called px and assign to it the
address of the object of type A you created before. Fix the problem using a virtual base class.
Now fix X so you no longer have to call the constructor for X inside A.

23
OOPs Lab Manual

 Solution:
 #include <iostream>
          class X {
          public:
                   X(int xxx = 0) : x(xxx) {}
                   void f() { std::cout << "X::f()\n"; }
          private:
                   int x;
          };
         
          class Y : virtual public X {
          public:
                   Y(int yyy) : X(yyy), y(yyy) {}
          private:
                   int y;
          };
         
          class Z : virtual public X {
          public:
                   Z(int zzz) : X(zzz), z(zzz) {}
          private:
                   int z;
          };
         
          class A : public Y, public Z {
          public:
                   A(int aaa) : Y(aaa), Z(aaa), a(aaa) {}
          private:
                   int a;
          };

24
OOPs Lab Manual

         
          int main() {
         
                   A a(1);
         
                   X* px = &a;
                   px->f();
         
         
          return 0;
          }
 

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 9

25
OOPs Lab Manual

Objective: To implement inheritance concept using class and subclass and display
the output.

Example 1:
#include <iostream>
using namespace std;

class stud {
protected:
int roll, m1, m2;

public:
void get()
{
cout << "Enter the Roll No.: "; cin >> roll;
cout << "Enter the two highest marks: "; cin >> m1 >> m2;
}
};
class extracurriculam {
protected:
int xm;

public:
void getsm()
{
cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm;
}
};
class output : public stud, public extracurriculam {
int tot, avg;

public:
void display()
{
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << roll << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
int main()
{
output O;
O.get();
O.getsm();

26
OOPs Lab Manual

O.display();
}
Output:

Example 2:
#include <iostream>
using namespace std;

class Person
{
public:
string profession;
int age;

Person(): profession("unemployed"), age(16) { }


void display()
{
cout << "My profession is: " << profession << endl;
cout << "My age is: " << age << endl;
walk();
talk();
}
void walk() { cout << "I can walk." << endl; }
void talk() { cout << "I can talk." << endl; }
};

// MathsTeacher class is derived from base class Person.


class MathsTeacher : public Person
{
public:
void teachMaths() { cout << "I can teach Maths." << endl; }
};

// Footballer class is derived from base class Person.


class Footballer : public Person
{
public:

27
OOPs Lab Manual

void playFootball() { cout << "I can play Football." << endl; }
};

int main()
{
MathsTeacher teacher;
teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();

Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();

return 0;
}
Output:

Task 1:
Write a C++ program to make a class named Fruit with a data member to calculate
the number of fruits in a basket. Create two other class named Apples and Mangoes
to calculate the number of apples and mangoes in the basket. Print the number of
fruits of each type and the total number of fruits in the basket.

Task 2:
Write a C++ program to calculate the total marks of each student of a class in
Physics, Chemistry and Mathematics and the average marks of the class. The user
enters the number of students in the class. Create a class named Marks with data
members for roll number, name and marks. Create three other classes inheriting
the Marks class, namely Physics, Chemistry and Mathematics, which are used to
define marks in individual subject of each student. Roll number of each student will
be generated automatically.

28
OOPs Lab Manual

Task 3:
Write a program with a mother class and an inherited daughter class. Both of them
should have a method void display() that prints a message (different for mother and
daughter).In the main define a daughter and call the display() method on it.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 10

29
OOPs Lab Manual

Objective: To implement the concept of polymorphism (dynamic Binding or Late


Binding) and display the output

Example 1:
#include<iostream>
using namespace std;
   
class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}
       
    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};
   
int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

Output:

Example 2:
// pointers to base class
#include <iostream>
using namespace std;

class Polygon {
protected:
int width, height;
public:

30
OOPs Lab Manual

void set_values (int a, int b)


{ width=a; height=b; }
};

class Rectangle: public Polygon {


public:
int area()
{ return width*height; }
};

class Triangle: public Polygon {


public:
int area()
{ return width*height/2; }
};

int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << '\n';
cout << trgl.area() << '\n';
return 0;
}

Output:

Task 1:
Create one example of your own.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 11

31
OOPs Lab Manual

Objective: To implement exception handling using TRY-CATCH statement and


display the result.

Example 1:
// exceptions
#include <iostream>
using namespace std;

int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}

Output:

Task 1:
Write a C++ program to create a class with its own operator new. This
operator should allocate ten objects, and on the eleventh object run out of
memory and throw an exception. Also add a static member function that
reclaims this memory. Now create a main( ) with a try block and
a catch clause that calls the memory-restoration routine. Put these inside
a while loop, to demonstrate recovering from an exception and continuing
execution.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 12

32
OOPs Lab Manual

Objective: To implement the concept of collection in java and run the program

Example:
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}

Call this file AccountBalance.java and put it in a directory called MyPack.


Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory. Then, try executing the AccountBalance class, using the following command
line:
java MyPack.AccountBalance

Output:

Student Registration No: ________________________

Teacher Signature: ________________________

33
OOPs Lab Manual

LAB EXPERIMENT # 13

34
OOPs Lab Manual

Objective: To develop applet in java using HTML

The "Hello World" Applet

Create a Java Source File:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {


public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}

Create an HTML File that Includes the Applet:

Using a text editor, create a file named Hello.html in the same directory that
contains HelloWorld.class. This HTML file should contain the following text:

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>

Here is the output of my program:


<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

Once you've successfully completed these steps, you should see


something like this in the browser window:

Output:

35
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

36

You might also like