Unit 1 of 1 · M.Sc IT Sem 2

Unit 1: C++ programming exercises

Object Oriented Programming using C++ Laboratory notes · PTU syllabus (PGCA1915)

6 min read12 topics10 exam questions
On this page
  1. Unit summary
  2. Formatted I/O and number programs
  3. Nested if, switch, factorial and largest of three
  4. Pointers, references and palindromes
  5. Strings and arrays: sorting and copying
  6. Class with arithmetic and pointer member access
  7. Inline, static and friend functions
  8. Constructors, destructors and copy constructors
  9. Function overloading: area of a triangle
  10. Abstract classes and virtual functions
  11. Single and multilevel inheritance
  12. Operator overloading, virtual functions and file streams
  13. File programs: case conversion and copying
  14. Key terms
  15. Quick revision
  16. Important questions

Unit summary

This lab practises C++ from basic I/O to object-oriented features: formatted output, number programs, Fibonacci, results with nested if, factorial by iteration and recursion, switch, largest and smallest, pointers and references, palindromes, string sorting and copying, array sorting, classes with pointer access, friend functions, copy constructors, overloading, abstract classes and virtual functions, inheritance, operator overloading and file case conversion and copying.

After this unit you can

  • Write programs with formatted I/O, control structures and recursion
  • Use pointers, references, strings and arrays
  • Implement classes, constructors, friends, overloading and virtual functions
  • Implement inheritance, operator overloading and file programs

PTU syllabus topics

  • Formatted I/O
  • prime/even/odd number display
  • Fibonacci series
  • result computation with nested if
  • factorial via iteration and recursion
  • switch-based weekday display
  • largest/smallest of three
  • pointer address and content display
  • reference-based value swap
  • palindrome checking
  • string sorting and copying
  • array sorting
  • class-based arithmetic and pointer member access
  • friend functions
  • copy constructors
  • function overloading
  • abstract classes
  • virtual functions
  • single and multilevel inheritance
  • unary and binary operator overloading
  • function overloading for triangle area
  • file case conversion and file copying
ComparisonVirtual functions and abstract classes
Declared as
Effect

Virtual function

virtual void show();

Derived class version called through a base pointer

Pure virtual function

virtual void show() = 0;

Must be overridden

Abstract class

Has at least one pure virtual function

Cannot be instantiated

1

Topic 1

Formatted I/O and number programs

cpp#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << left << setw(10) << "Item" << right << setw(8) << "Price" << '\n';
    cout << left << setw(10) << "Pen" << right << setw(8) << fixed << setprecision(2) << 12.5 << '\n';

    int n; cout << "Upto: "; cin >> n;
    for (int i = 2; i <= n; i++) {                         // primes
        bool p = true;
        for (int d = 2; d * d <= i; d++) if (i % d == 0) { p = false; break; }
        if (p) cout << i << ' ';
    }
    cout << "\nEven: "; for (int i = 2; i <= n; i += 2) cout << i << ' ';
    cout << "\nFibonacci: ";
    long a = 0, b = 1; for (int i = 0; i < n; i++) { cout << a << ' '; long t = a + b; a = b; b = t; }
}
2

Topic 2

Nested if, switch, factorial and largest of three

cppint marks; cin >> marks;
if (marks >= 40) {
    if (marks >= 75) cout << "Distinction";
    else if (marks >= 60) cout << "First division";
    else cout << "Pass";
} else cout << "Fail";

int day; cin >> day;
switch (day) {
    case 1: cout << "Monday"; break;   case 2: cout << "Tuesday"; break;
    case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break;
    case 5: cout << "Friday"; break;   case 6: cout << "Saturday"; break;
    case 7: cout << "Sunday"; break;   default: cout << "Invalid day";
}

long factIter(int n) { long f = 1; for (int i = 2; i <= n; i++) f *= i; return f; }
long factRec(int n)  { return n <= 1 ? 1 : n * factRec(n - 1); }

int a, b, c; cin >> a >> b >> c;
cout << "Largest " << max({a, b, c}) << " Smallest " << min({a, b, c});   // needs <algorithm>
3

Topic 3

Pointers, references and palindromes

cppint x = 25; int *p = &x;
cout << "Address " << p << " Content " << *p << '\n';

void swapRef(int &a, int &b) { int t = a; a = b; b = t; }   // call by reference
int m = 3, n = 7; swapRef(m, n);                             // m = 7, n = 3

bool isPalindrome(const string &s) {
    int i = 0, j = s.size() - 1;
    while (i < j) if (s[i++] != s[j--]) return false;
    return true;
}
4

Topic 4

Strings and arrays: sorting and copying

cpp#include <cstring>
#include <algorithm>
char src[] = "Ludhiana", dest[20];
strcpy(dest, src);                                // copy C-string
string names[] = {"Riya", "Aman", "Kabir", "Simran"};
sort(names, names + 4);                           // alphabetical
int arr[] = {45, 12, 78, 3, 56};
for (int i = 0; i < 4; i++)                       // bubble sort
    for (int j = 0; j < 4 - i; j++)
        if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]);
5

Topic 5

Class with arithmetic and pointer member access

cppclass Arith {
    double a, b;
public:
    Arith(double x, double y) : a(x), b(y) {}
    double add() { return a + b; }   double sub() { return a - b; }
    double mul() { return a * b; }   double div() { return b ? a / b : 0; }
};
Arith obj(12, 4);
Arith *ptr = &obj;
cout << ptr->add() << ' ' << ptr->mul() << ' ' << (*ptr).div();   // arrow and dot access
6

Topic 6

Inline, static and friend functions

cppclass Student {
    static int count;
    int marks;
public:
    Student(int m) : marks(m) { ++count; }
    inline int getMarks() const { return marks; }
    static int total() { return count; }
    friend void compare(const Student &a, const Student &b);
};
int Student::count = 0;
void compare(const Student &a, const Student &b) {
    cout << (a.marks > b.marks ? "First" : "Second") << " is higher\n";
}
7

Topic 7

Constructors, destructors and copy constructors

cppclass Box {
    int l, b;
public:
    Box() : l(1), b(1) { cout << "Default\n"; }
    Box(int x, int y) : l(x), b(y) { cout << "Parameterised\n"; }
    Box(const Box &o) : l(o.l), b(o.b) { cout << "Copy\n"; }
    ~Box() { cout << "Destructor\n"; }
    int area() { return l * b; }
};
int main() { Box a; Box b(3, 4); Box c = b; cout << c.area() << endl; }
  • Viva: constructors have the class name and no return type; destructors run in reverse order of creation.
8

Topic 8

Function overloading: area of a triangle

Overload area() for (base, height) using ½ × b × h and for three sides using Heron's formula, s = (a + b + c)/2 and area = √[s(s − a)(s − b)(s − c)].

9

Topic 9

Abstract classes and virtual functions

cppclass Shape {                                    // abstract class
public:
    virtual double area() const = 0;             // pure virtual function
    virtual ~Shape() {}
};
class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
};
class Rect : public Shape {
    double l, b;
public:
    Rect(double l, double b) : l(l), b(b) {}
    double area() const override { return l * b; }
};
Shape *s[] = { new Circle(2), new Rect(3, 4) };
for (Shape *x : s) { cout << x->area() << '\n'; delete x; }   // run-time polymorphism
10

Topic 10

Single and multilevel inheritance

ClassificationPublication hierarchy
Publication|title, price
  • Book

    adds page count

  • Tape

    adds playing time in minutes

  • Publication → Book and Tape (hierarchical): the base stores title and price; each derived class adds its own data and a display function.
  • Student → Exam → Result (multilevel): Student stores roll number, Exam stores marks and Result calculates and displays the total.
11

Topic 11

Operator overloading, virtual functions and file streams

  • Unary operator: overload - to negate the coordinates of a point: void operator-() { x = -x; y = -y; }
  • Binary operator: overload + to add two complex numbers or two distances.
  • Virtual function: a base Shape with virtual void area(); derived Circle and Rectangle override it; call through Shape *.
  • Abstract class: make area() pure virtual (= 0) and show that Shape objects cannot be created.
  • Files: write student records with ofstream, read them with ifstream, and copy a file with get() and put().

Exam tip

In the viva, expect: "Why use a reference instead of a pointer?", "What happens if a virtual keyword is removed?" and "Why can't we create an object of an abstract class?"

12

Topic 12

File programs: case conversion and copying

cpp#include <fstream>
#include <cctype>
int main() {
    ifstream in("input.txt");
    ofstream up("upper.txt"), cp("copy.txt");
    if (!in) { cerr << "Cannot open input.txt\n"; return 1; }
    char ch;
    while (in.get(ch)) {
        up.put(toupper(static_cast<unsigned char>(ch)));    // case conversion
        cp.put(ch);                                         // copy unchanged
    }
    cout << "Done\n";
}

Key terms

Manipulator
Stream function such as setw or setprecision
Reference
Alias for an existing variable
Friend function
Non-member with access to private data
Abstract class
Class with at least one pure virtual function
ifstream and ofstream
File input and output stream classes

Quick revision

  • setw, setprecision, fixed, left, right.
  • Primes, even numbers, Fibonacci, nested if, switch, factorial both ways.
  • Pointers (&, *), references, palindrome, strcpy, sort.
  • Classes with pointer access (->), friend, copy constructor, overloading, abstract class, virtual functions.
  • Single and multilevel inheritance; unary and binary operator overloading; file get, put.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.What does setprecision(2) do?
  2. Q2.Distinguish call by value and call by reference.
  3. Q3.How are members accessed through a pointer to an object?
  4. Q4.When is a copy constructor invoked?
  5. Q5.What makes a class abstract?
  6. Q6.How do you read a file character by character?

Long-answer questions

  1. Q1.Write a program to compute factorial iteratively and recursively.
  2. Q2.Write a program demonstrating friend functions and copy constructors.
  3. Q3.Write a program demonstrating abstract classes and virtual functions.
  4. Q4.Write programs for unary and binary operator overloading and file copying.

Stuck on this unit?

Message SBS on WhatsApp for help with Object Oriented Programming using C++ Laboratory, or to ask about studying M.Sc IT at Synetic.

WhatsApp us