KNEC July 2019 DICT module 2 past paper Object oriented programming exam questions & answers

Object oriented programming exam questions & answers

1a) Define object and variable in object oriented programming(4 Marks)

In object-oriented programming, an object is an instance of a class that encapsulates data (known as attributes) and behavior (known as methods). Objects are the building blocks of object-oriented programs, and they represent real-world entities, concepts, or abstract ideas.

A variable in object-oriented programming refers to a named memory location that stores a value. In the context of objects, a variable can refer to an object itself or to an attribute of an object. When a variable is used to refer to an object, it is known as a reference variable or object reference. This variable contains the memory address of the object in memory, which allows the program to access and manipulate the object’s data and behavior.

b)Differentiate between Token and identifiers as used in object oriented programming(4 Marks)

In object-oriented programming, tokens and identifiers are both used to represent elements of a program, but they have different meanings and uses.

A token is a basic unit of a program that the compiler or interpreter can recognize and process. Tokens can be divided into different types, such as keywords, operators, punctuation marks, and literals. Examples of tokens in object-oriented programming include the “+” operator, the “class” keyword, and the string “Hello, World!”.

An identifier, on the other hand, is a name given to a programming element such as a variable, function, class, or object. Identifiers are used to refer to these elements in the program and to distinguish them from each other. Identifiers must follow certain rules, such as starting with a letter or underscore, and they should be descriptive and meaningful. Examples of identifiers in object-oriented programming include variable names such as “count” or “balance”, function names such as “calculateTotal”, and class names such as “Rectangle” or “Customer”.

In summary, while tokens are basic units of a program that represent syntax elements, identifiers are names given to program elements for reference and differentiation.

c) Determine the output of the following C++ statements (2Marks)

char c = 'A';
short m = 26;
int n = c + m;
std::cout << "n: " << n;

declares a variable c of type char and initializes it with the ASCII code for the character ‘A’ (which is 65). It also declares a variable m of type short and initializes it with the value 26.

The expression c + m adds the values of c and m, which are both promoted to int before the addition. Since the ASCII code for the character ‘A’ is 65, and m is 26, the result of the addition is 91.

The cout statement then prints the value of n to the console, which is 91. Therefore, the output of the program will be:

di) With the aid of C++ syntax code explain instance and variable(4 marks)

In C++, an instance is a specific occurrence of a class, which is created using the new keyword. It is a unique object with its own set of properties and methods.

Here is an example of how to create an instance of a class named MyClass in C++:

MyClass* myObject = new MyClass();

A variable in C++ is a named storage location in memory that holds a value of a particular type. The type of the variable determines the size and format of the data stored in the variable.

Here is an example of how to declare and initialize a variable of type int in C++:

int myVariable = 42;

Variables can be used to store values of many different types, including integers, floating point numbers, characters, and more complex data structures like arrays and structs. They can also be used to store pointers to instances of classes, as shown in the example of creating an instance above.

ii) Johan designed an object oriented program, the program failed to compile due to incorrect identifier declarations. Explain 3 rules he should have followed(6 marks)

When designing an object-oriented program in C++, it’s important to follow certain rules and best practices to avoid errors and ensure that the program is correct and easy to maintain. Here are three rules that Johan should have followed when declaring identifiers in his program:

  1. Use unique and descriptive names: Each identifier (such as class names, variable names, and function names) should have a unique name that accurately describes its purpose in the program. This makes the code easier to read and understand, and helps to avoid naming conflicts. For example, if Johan has two variables that store the current temperature of a room, he should use names like temperature1 and temperature2, rather than just temperature.
  2. Follow naming conventions: C++ has certain naming conventions that help to make the code more readable and consistent. For example, class names should start with a capital letter, while variable and function names should start with a lowercase letter. Johan should follow these conventions to make his code more consistent and easier to read.
  3. Declare identifiers in the correct scope: Each identifier has a scope, which is the part of the program where it is visible and can be used. Variables, for example, should be declared in the smallest possible scope where they are needed. This helps to avoid naming conflicts and makes the code easier to read and understand. Johan should ensure that each identifier is declared in the correct scope to avoid errors and ensure that the program is correct.

3ai) Identify the type of error that will be generated in each of the following cases; (3 Marks)

i)Division by a variable that contains a value of zero

ii)Multiplication operator used for division

iii)Missing semicolon

i) Division by a variable that contains a value of zero will generate a runtime error called “division by zero”. This is because division by zero is undefined and cannot be computed. The program will typically terminate with an error message.

ii) Multiplication operator used for division will not generate a syntax error, but it will produce an incorrect result. This is a logical error because the program will not behave as intended. For example, if the code is supposed to divide two numbers but instead uses the multiplication operator, the result will be the product of the two numbers, not their quotient.

iii) Missing semicolon will generate a syntax error because the C++ compiler expects each line of code to end with a semicolon. The error message will typically indicate the location of the missing semicolon and the type of error. If the error is not fixed, the program will not compile and will not be able to run.

bi) Explain two types of class access specifiers in C++ (4 Marks)

  1. Public Access Specifier: Members that are declared as public can be accessed from anywhere in the program, including from outside the class. This means that any code that has access to an instance of the class can access its public members. Public members are typically used to provide an interface to the class, allowing external code to interact with it in a controlled way. For example, if a class represents a car, its public members might include methods for starting and stopping the engine, adjusting the speed, and opening and closing the doors.
  2. Private Access Specifier: Members that are declared as private can only be accessed from within the class. This means that external code cannot access or modify private members of the class. Private members are typically used to store data and implement the internal workings of the class. For example, if a class represents a car, its private members might include variables for the current speed and fuel level, as well as methods for calculating fuel consumption and adjusting the speed. Private members help to ensure that the internal state of the class is protected and can only be modified in a controlled way.

ii) write a C++ expression for the following mathematical equations (z=x3+y3-xy / z)(3Marks)

z = (pow(x, 3) + pow(y, 3) - x*y) / z;

In this expression, pow(x, 3) and pow(y, 3) are used to calculate the cube of x and y respectively, and x*y is used to calculate the product of x and y. The expression (pow(x, 3) + pow(y, 3) – x*y) represents the numerator of the equation. The expression is then divided by the variable z to get the final value of z. The result of this expression will be assigned to the variable z.

c)Distinguish between Boolean and character literals as used in programming (4marks)

  1. Boolean literals: Boolean literals are used to represent the values of true and false in a program. In C++, the keyword true represents the Boolean value of true, and the keyword false represents the Boolean value of false. These values are typically used in conditional statements and expressions to control the flow of a program. Boolean literals have a type of bool in C++.
  2. Character literals: Character literals are used to represent individual characters, such as letters, numbers, and punctuation marks, in a program. In C++, character literals are enclosed in single quotes (‘). For example, the character literal ‘a’ represents the character a. Character literals are often used to represent individual characters in strings, which are sequences of characters. Character literals have a type of char in C++.

In summary, Boolean literals are used to represent true and false values and have a type of bool, while character literals are used to represent individual characters and have a type of char.

d) Explain 3 error handling techniques used in C++ (6 Marks)

In C++, error handling is the process of detecting and responding to errors that may occur during the execution of a program. Here are three common error handling techniques used in C++:

  1. Exception handling: Exception handling is a powerful technique for dealing with errors in C++. It involves throwing an exception when an error occurs and catching the exception in a try-catch block. The try block contains the code that may generate an exception, and the catch block contains the code that handles the exception. Exception handling can be used to handle errors that occur at runtime, such as division by zero, out-of-bounds array access, and file input/output errors.
  2. Return values: Return values are commonly used to indicate errors in C++. A function can return a value to indicate success or failure, with a specific value indicating an error condition. For example, a function that reads data from a file might return a value of 0 if the read operation was successful, and a value of -1 if an error occurred. The calling code can check the return value and take appropriate action based on the result.
  3. Assertions: Assertions are used to check that certain conditions are true during program execution. An assertion is a statement that evaluates a Boolean expression and terminates the program if the expression is false. Assertions are typically used to catch errors that should never occur, such as out-of-bounds array access or invalid input parameters. Assertions are often used during testing and debugging to catch errors early in the development process.

3a) explain 2 advantages of using functions in object oriented programming (2 Marks)

  1. Encapsulation: One of the key principles of object-oriented programming is encapsulation, which means that the internal details of an object should be hidden from the outside world. Functions can be used to implement encapsulation by providing a public interface to an object’s behavior, while keeping the implementation details private. By using functions to encapsulate an object’s behavior, we can ensure that the object is used correctly and that its internal state is not corrupted by external code.
  2. Reusability: Functions are also a powerful tool for code reuse. By implementing a function that performs a specific task, we can reuse that function in multiple parts of our code, without having to duplicate the code. In object-oriented programming, functions can be reused across different objects and classes, making it easier to build complex systems with a large number of components. Additionally, functions can be overridden in subclasses to provide specialized behavior, allowing us to reuse the core functionality while customizing the behavior for specific use cases.

b) State two differences between static and non-static data members (4Marks)

  1. Memory allocation: Non-static data members are allocated memory separately for each object of the class, whereas static data members are shared by all objects of the class. This means that there is only one copy of a static data member, regardless of how many objects of the class are created.
  2. Accessing data members: Non-static data members can be accessed using the object of the class, whereas static data members can be accessed using the class name itself, without the need for an object. This is because static data members are shared by all objects of the class and are not tied to any specific instance of the class.

c) The following is a C++ programs segment Use it to answer the questions that follow(6 Marks)

String. x=”information”;

String. y=”communication”.

Questions are Determine the out generated by each of the following functions:

1. Cout<< "x+y)": 
2 Cout« "(x length())": 
3. Cout "(x.equals (y))'·; 
string x = "information";
string y = "communication";
  1. cout << “x+y”: This will output the concatenation of x and y as a string literal, i.e., “x+y”.
  2. cout << “(x.length())”: This will output the length of the string x, which is 11. The function length() returns the number of characters in the string.
  3. cout << “(x.equals(y))”: This will output the result of comparing the strings x and y. The function equals() returns true if the strings are equal and false otherwise. In this case, the output will be false since the strings are not equal.

di) Define an impure function (2 Marks)

In programming, an impure function is a function that has side effects or does not always return the same result when called with the same inputs. In other words, an impure function can modify some state or have an unpredictable behavior.

ii) with the aid of syntax code explain how the member functions can be accessed using pointers (6 Marks)

In C++, member functions can be accessed using pointers through the arrow (->) operator or the dot (.) operator, depending on the type of the pointer.

Here’s an example code snippet that demonstrates how to access a member function using a pointer:

#include <iostream>
using namespace std;

class MyClass {
public:
    void myFunction() {
        cout << "Hello, world!" << endl;
    }
};

int main() {
    MyClass obj;
    MyClass* ptr = &obj;  // pointer to obj

    // access myFunction using the arrow operator
    ptr->myFunction();

    // access myFunction using the dot operator
    (*ptr).myFunction();

    return 0;
}

4a) explain local variable as used in object oriented programming(2 Marks)

In object-oriented programming (OOP), a local variable is a variable that is declared and used within the scope of a function or a code block. In other words, local variables are variables that are only accessible within the function or code block in which they are declared.

b) Distinguish between encapsulation and abstraction as used in C++ (4 Marks)

Encapsulation is the practice of grouping related data and behavior into a single unit, such as a class, and restricting access to that unit from outside. In C++, encapsulation is achieved through access modifiers, such as public, private, and protected. These access modifiers specify which data members and member functions of a class are accessible from outside the class, and which are not.

Abstraction, on the other hand, is the practice of focusing on the essential features of an object and ignoring the non-essential details. In C++, abstraction is achieved through interfaces, which are abstract classes or class templates that define a set of pure virtual functions that must be implemented by derived classes. Interfaces allow different classes to provide different implementations of the same functionality, while ensuring that they conform to a common set of rules and expectations.

c) With an aid of a syntax code explain inline function (4 Marks)

In C++, an inline function is a function that is expanded inline by the compiler, instead of being called like a regular function.

inline int add(int a, int b) {
    return a + b;
}

di) Define the term enumerated datatype (2 Marks)

In C++, an enumerated datatype (or enum for short) is a user-defined type that consists of a set of named values, known as enumerators. An enumerator is a constant with a specific integer value that can be assigned to variables of the enum type

ii) Write a program in C++ that will initialize the values (20 50 40 10 30) into an array. The program then displays the sum, maximum and minimum of the values. (8 Marks)

#include <iostream>
using namespace std;

int main() {
    int arr[] = {20, 50, 40, 10, 30};
    int n = sizeof(arr) / sizeof(arr[0]);

    int sum = 0, max = arr[0], min = arr[0];

    // Compute the sum, maximum, and minimum of the array
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
    }

    // Display the sum, maximum, and minimum of the array
    cout << "Sum: " << sum << endl;
    cout << "Maximum: " << max << endl;
    cout << "Minimum: " << min << endl;

    return 0;
}

5a) Outline four characteristics of constructors as used in object oriented programming (4 Marks)

  1. Same name as the class: Constructors have the same name as the class they belong to, and are distinguished from other member functions by not having a return type (not even void). When an object is created, the constructor is called automatically to initialize its data members.
  2. No explicit return type: Constructors do not have an explicit return type, not even void. This is because the constructor is called automatically when the object is created, and its job is to initialize the data members, not to return a value.
  3. Can be overloaded: Like other member functions, constructors can be overloaded, meaning that a class can have multiple constructors with different parameters. This allows objects to be initialized in different ways depending on the arguments passed to the constructor.
  4. Can be used to allocate memory: Constructors can be used to allocate memory dynamically using the new operator, which is often used to create objects that need to be created at runtime. This is particularly useful when the size of the object is not known at compile time, or when the object needs to be created on the heap rather than the stack.

b) With the aid of a syntax code explain copy constructor (4Marks)

In C++, a copy constructor is a special constructor that is used to create a new object as a copy of an existing object. The syntax for a copy constructor is as follows:

class MyClass {
public:
  MyClass(const MyClass& other) {
    // Copy constructor code goes here
  }
  // Other class member functions go here
};

c) A C++ class has the name student with the following attributes: 

Roll number: 5

Total marks: 430

Age: 16

Write a C++ program to declare the class(6 Marks)

#include <iostream>
using namespace std;

class Student {
public:
  int rollNumber;
  int totalMarks;
  int age;
};

int main() {
  // Create a new student object
  Student student;

  // Set the attributes
  student.rollNumber = 5;
  student.totalMarks = 430;
  student.age = 16;

  // Print the attributes
  cout << "Roll number: " << student.rollNumber << endl;
  cout << "Total marks: " << student.totalMarks << endl;
  cout << "Age: " << student.age << endl;

  return 0;
}

 

(Visited 6 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *