Introduction to OOPs using C++ SEM 2 Uint-1 Question Bank Solution

  FY.Bsc.Cs Sem-2 Based on Mumbai Unversity 

Introduction to OOPs using C++ (Uint-1) Question Bank Answer:-



1.What are the principles of OOP?

Solution:-

The principles of Object-Oriented Programming (OOP) include:

1. Encapsulation: Bundling data and methods that operate on the data into a single unit, known as a class, to control access and protect the integrity of the data.

2. Inheritance: Creating new classes by inheriting properties and behaviors from existing classes, promoting code reusability and establishing a hierarchy.

3. Polymorphism: Allowing objects of different types to be treated as objects of a common base type, enabling flexibility and extensibility in code.

4. Abstraction: Simplifying complex systems by modeling classes based on their essential features and ignoring unnecessary details.



2.Enlist any four concepts of OOP?

Solution:-
 
  1. Classes and Objects: The fundamental building blocks in OOP, where classes define the blueprint for objects, and objects are instances of classes.

  2. Inheritance: The mechanism by which a class can inherit properties and behaviors from another class, promoting code reuse and establishing a hierarchy.

  3. Encapsulation: The bundling of data and methods that operate on the data within a single unit (class), controlling access and protecting the integrity of the data.

  4. Polymorphism: The ability of objects to take on multiple forms, allowing objects of different types to be treated as objects of a common base type, enhancing flexibility and extensibility.


3.Write any four features of object oriented programming.
  1. Encapsulation: Bundling data and methods into a single unit (class), hiding the internal details of an object and protecting its state.

  2. Abstraction: Simplifying complex systems by modeling classes based on their essential features, and ignoring unnecessary details, providing a high-level view.

  3. Inheritance: Allowing a class to inherit properties and behaviors from another class, promoting code reuse, and establishing a hierarchical relationship between classes.

  4. Polymorphism: Allowing objects of different types to be treated as objects of a common base type, enabling flexibility and extensibility in code through method overriding and interfaces.

4
4.Explain arrays in C++ with an example.

In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. Each element is accessed using an index, starting from 0. Here's an example of an array in C++:

#include <iostream>

int main() {
    // Declare an array of integers with size 5
    int myArray[5];

    // Initializing array elements
    myArray[0] = 10;
    myArray[1] = 20;
    myArray[2] = 30;
    myArray[3] = 40;
    myArray[4] = 50;

    // Accessing and printing array elements
    std::cout << "Elements of the array: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << myArray[i] << " ";
    }

    return 0;
}

In this example, an integer array myArray is declared with a size of 5. Elements are then assigned values, and a loop is used to print the elements. The output would be: Elements of the array: 10 20 30 40 50.


5.Explain String in C++ with an example.

In C++, a string is a sequence of characters represented by the std::string class. Here's an example demonstrating the use of strings:

#include <iostream> #include <string> int main() { // Declare and initialize a string std::string myString = "Hello, World!"; // Accessing and printing the string std::cout << "String: " << myString << std::endl; // Modifying the string myString += " Welcome to C++"; // Printing the modified string std::cout << "Modified String: " << myString << std::endl; // Finding the length of the string std::cout << "Length of the String: " << myString.length() << std::endl; return 0; }

In this example, a string variable myString is declared and initialized with the value "Hello, World!". The string is then modified, and its length is displayed. The output would be:

String: Hello, World! Modified String: Hello, World! Welcome to C++ Length of the String: 32

6.What is a token and explain different types of tokens in C++?

In C++, a token is the smallest unit in a program, representing a fundamental component of the source code. There are several types of tokens in C++, including:

  1. Keywords: Reserved words with special meaning in the language, such as int, if, else, etc.

  2. Identifiers: User-defined names for variables, functions, classes, etc. For example, main, myVariable, or calculateSum.

  3. Literals: Constant values used in the program, like numeric literals (42, 3.14), character literals ('a', 'b'), and string literals ("Hello").

  4. Operators: Symbols representing operations, such as arithmetic operators (+, -), relational operators (==, !=), and logical operators (&&, ||).

  5. Punctuators: Special symbols used for punctuation and separation, like semicolons (;), commas (,), and parentheses (()).

  6. Comments: Text ignored by the compiler, providing explanations or annotations. C++ supports both single-line (//) and multi-line (/* */) comments.

#include <iostream> int main() { // Identifiers: main, myVariable int myVariable = 10; // Keywords: int, if, else if (myVariable > 5) { // Operators: =, >, + myVariable = myVariable + 5; // Literals: 5, 'a', "Hello" char myChar = 'a'; std::string greeting = "Hello"; // Punctuators: ;, { std::cout << greeting << std::endl; } return 0; }

In this example, various tokens like identifiers, keywords, operators, literals, and punctuators are used within a simple C++ program.

7.Explain the structure of C++ program with suitable example.

A C++ program has a basic structure that includes several components. Here's a simple explanation with an example:

// Preprocessor Directives #include <iostream> // Function Declaration int main() { // Statements std::cout << "Hello, World!" << std::endl; // Return Statement return 0; }

  1. Preprocessor Directives: These are lines in your code that start with #. They are processed by the preprocessor before actual compilation. In the example, #include <iostream> is a directive that tells the compiler to include the input/output stream library.

  2. Function Declaration (main function): Every C++ program must have a main function, and the execution of the program begins from here. The int before main() indicates that the function returns an integer. The { and } define the scope of the main function.

  3. Statements: Inside the main function, you have statements that perform actions. In the example, std::cout << "Hello, World!" << std::endl; is a statement that outputs "Hello, World!" to the console.

  4. Return Statement: The return 0; statement is used to exit the program. The 0 indicates a successful execution, and other values can be used to indicate different exit statuses.

8.Explain any two operators used in C++.


explanations for two operators commonly used in C++:

  1. Arithmetic Operators:

    • Examples: +, -, *, /, % (addition, subtraction, multiplication, division, modulus)
    • Explanation: Arithmetic operators perform basic mathematical operations on numeric values. For instance, a + b adds the values of a and b, a - b subtracts b from a, a * b multiplies a and b, a / b divides a by b, and a % b gives the remainder when a is divided by b.
  2. Logical Operators:

    • Examples: && (logical AND), || (logical OR), ! (logical NOT)
    • Explanation: Logical operators are used to perform logical operations on boolean values. && returns true if both operands are true, || returns true if at least one operand is true, and ! returns the opposite boolean value of the operand. For example, x && y is true only if both x and y are true.

Understanding and using these operators is fundamental for performing calculations and making logical decisions in C++ programs.

9.Explain manipulators in C++

In C++, manipulators are special functions or objects provided by the iostream library to modify the behavior of the input and output streams. They are used to control the formatting of data when it is read from or written to the console. Manipulators are often chained together to achieve a specific output format.

#include <iostream> #include <iomanip> // Required for manipulators int main() { int number = 42; double pi = 3.14159; // Using setw() manipulator to set the width of the output std::cout << "Number: " << std::setw(5) << number << std::endl; // Using setprecision() manipulator to set the precision of floating-point output std::cout << "Pi: " << std::setprecision(3) << pi << std::endl; // Using fixed and showpoint manipulators to display trailing zeros in floating-point output std::cout << std::fixed << std::showpoint << "Pi: " << pi << std::endl; return 0; }

In this example:

  • setw(5) sets the width of the output field for the number to 5 characters.
  • setprecision(3) sets the precision of the floating-point output to 3 decimal places.
  • fixed and showpoint together ensure that trailing zeros are displayed in the floating-point output.
10.Explain Access specifiers and give an example?

Access specifiers in C++ determine the visibility and accessibility of class members. There are three main access specifiers: public, private, and protected.

  1. Public Access Specifier:
    • Members declared as public are accessible from outside the class and its subclasses.
    • Example:
  2. #include <iostream> class MyClass { public: int publicVar; void publicFunction() { std::cout << "Public function called." << std::endl; } }; int main() { MyClass obj; obj.publicVar = 42; obj.publicFunction(); return 0; }

  3. Private Access Specifier:
    • Members declared as private are only accessible within the class. They are not accessible from outside the class or its subclasses.
    • Example:
    • #include <iostream> class MyClass { private: int privateVar; void privateFunction() { std::cout << "Private function called." << std::endl; } public: void setPrivateVar(int value) { privateVar = value; } void callPrivateFunction() { privateFunction(); } }; int main() { MyClass obj; // The following lines would result in a compilation error // obj.privateVar = 42; // obj.privateFunction(); obj.setPrivateVar(42); obj.callPrivateFunction(); return 0; }
  4. Protected Access Specifier:
    • Similar to private, but members declared as protected are accessible in subclasses (derived classes).
    • Example:
    • #include <iostream> class BaseClass { protected: int protectedVar; void protectedFunction() { std::cout << "Protected function called." << std::endl; } }; class DerivedClass : public BaseClass { public: void accessProtectedMember() { protectedVar = 42; // Accessing protected member from the base class protectedFunction(); // Accessing protected function from the base class } }; int main() { DerivedClass obj; obj.accessProtectedMember(); return 0; }
    • These access specifiers provide a way to control the encapsulation and visibility of class members in C++.

  5. 11. Explain any four applications of OOP?

Object-Oriented Programming (OOP) is widely used in various applications due to its advantages in organizing code, promoting reuse, and enhancing modularity. Here are four applications of OOP:

  1. Software Development:

    • OOP is extensively used in software development to model real-world entities and their interactions. It promotes the creation of modular and maintainable code, making it easier to design, implement, and modify complex systems. Popular programming languages like Java, C++, and Python are heavily based on OOP principles.
  2. Graphical User Interface (GUI) Development:

    • GUI frameworks often leverage OOP concepts to create user interfaces. Widgets, buttons, windows, and other graphical elements are represented as objects. OOP allows for easy customization, event handling, and the creation of reusable UI components.
  3. Simulation and Modeling:

    • OOP is employed in simulation and modeling applications to represent and simulate complex systems. Objects can be created to model entities, and their interactions can be simulated through methods and properties. This is particularly useful in fields such as physics, engineering, and finance.
  4. Database Systems:

    • OOP principles are applied in the development of database systems. Objects are used to represent data entities, and their relationships are modeled through classes and associations. Object-Relational Mapping (ORM) frameworks, which map database entities to objects in programming languages, are based on OOP concepts.

These applications demonstrate the versatility of OOP in solving diverse problems across various domains, providing a scalable and efficient approach to software development.

12. Explain data type casting in C++ with examples.


In C++, data type casting refers to the conversion of a variable from one data type to another. There are two main types of casting: implicit (automatic) casting and explicit (manual) casting.

  1. Implicit Casting:
    • Occurs automatically when the compiler converts one data type to another without the need for explicit instructions from the programmer.
    • Example:
    • #include <iostream> int main() { int intValue = 42; double doubleValue = intValue; // Implicit casting from int to double std::cout << "Integer Value: " << intValue << std::endl; std::cout << "Double Value: " << doubleValue << std::endl; return 0; }
    • Explicit Casting:
      • Requires manual intervention from the programmer to specify the desired conversion.
      • Example:
      • #include <iostream> int main() { double doubleValue = 3.14; int intValue = static_cast<int>(doubleValue); // Explicit casting from double to int std::cout << "Double Value: " << doubleValue << std::endl; std::cout << "Integer Value: " << intValue << std::endl; return 0; }
      • In the explicit casting example, static_cast is used to convert the doubleValue from double to int. This type of casting is useful when the programmer wants to control the conversion process explicitly.

        It's important to note that explicit casting may result in loss of data or precision, especially when converting from a larger data type to a smaller one. Care should be taken to ensure that the conversion does not lead to unexpected behavior or loss of information.

13.Explain any two control statements with examples?


Control statements in C++ are used to alter the flow of program execution based on certain conditions or loops. Here are explanations for two types of control statements along with examples:

  1. if-else Statement:
    • The if-else statement is used to make decisions in a program. It executes a block of code if a specified condition is true; otherwise, it executes a different block of code.
    • Example:
    • #include <iostream> int main() { int number; std::cout << "Enter a number: "; std::cin >> number; // if-else statement to check if the number is positive or negative if (number > 0) { std::cout << "The number is positive." << std::endl; } else if (number < 0) { std::cout << "The number is negative." << std::endl; } else { std::cout << "The number is zero." << std::endl; } return 0; }
    • In this example, the program prompts the user to enter a number, and then the if-else statement checks whether the number is positive, negative, or zero.

      1. for Loop:
        • The for loop is used for iterating a block of code a specified number of times.
        • Example:
        • #include <iostream> int main() { // for loop to print numbers from 1 to 5 for (int i = 1; i <= 5; ++i) { std::cout << i << " "; } std::cout << std::endl; return 0; }
        • In this example, the for loop iterates from 1 to 5, and at each iteration, it
      14.Explain break and continue statements with examples ?
  2. The break and continue statements are control flow statements in C++ that are used within loops to alter the normal execution flow.

    1. break Statement:
      • The break statement is used to exit a loop prematurely, stopping further execution of the loop even if the loop condition is still true.
      • Example:
      • #include <iostream> int main() { // Break out of a loop when a specific condition is met for (int i = 1; i <= 10; ++i) { std::cout << i << " "; if (i == 5) { std::cout << "\nBreaking out of the loop."; break; // Exit the loop when i equals 5 } } return 0; }
      • In this example, the program uses a for loop to print numbers from 1 to 10. However, when i reaches 5, the break statement is encountered, and the loop is exited prematurely.

        1. continue Statement:
          • The continue statement is used to skip the rest of the code within a loop for the current iteration and proceed to the next iteration.
          • Example:
          • #include <iostream> int main() { // Use continue to skip printing even numbers for (int i = 1; i <= 5; ++i) { if (i % 2 == 0) { continue; // Skip the rest of the loop for even numbers } std::cout << i << " "; } return 0; }
          • In this example, the for loop is used to print numbers from 1 to 5. The continue statement is encountered when i is an even number, skipping the std::cout statement and moving to the next iteration of the loop. As a result, only odd numbers are printed.

        2. 15. Define class and object with its syntax.?
        In C++, a class is a user-defined data type that serves as a blueprint for creating objects. An object, on the other hand, is an instance of a class, and it represents a real-world entity with properties (attributes) and behaviors (methods). Here's the syntax for defining a class and creating objects:

      • // Class declaration class ClassName { // Member variables (attributes) datatype memberVariable1; datatype memberVariable2; public: // Member functions (methods) void memberFunction1(datatype parameter1); void memberFunction2(datatype parameter2); }; // Class implementation void ClassName::memberFunction1(datatype parameter1) { // Implementation of the first member function } void ClassName::memberFunction2(datatype parameter2) { // Implementation of the second member function } int main() { // Object creation ClassName object1; ClassName object2; // Accessing members of objects object1.memberFunction1(value1); object2.memberFunction2(value2); return 0; }
      • Explanation:

        • The class ClassName declares a class named ClassName.
        • Inside the class, you can define member variables (attributes) and member functions (methods).
        • The public: section specifies the access level for the members. Members declared after public: are accessible from outside the class.
        • Member functions are defined outside the class using the ClassName:: syntax.
        • In the main function, objects (object1 and object2) of the class are created.
        • Members of the objects are accessed using the dot (.) notation.

        This syntax provides a template for creating reusable and organized code using the principles of Object-Oriented Programming (OOP).


Short Answer:-

  1. 1.State any four applications of OOP? 

  1. Software Development: OOP is widely used for developing software applications, providing a modular and organized approach to design. Classes and objects help in encapsulating data and behavior, leading to more maintainable and scalable code.

  2. User Interface Design: OOP principles are often applied in creating graphical user interfaces (GUIs). GUI components can be represented as objects with associated behaviors, facilitating interaction and providing a seamless user experience.

  3. Game Development: OOP is extensively used in game development. Game entities, such as characters, items, and environments, can be modeled as objects with specific attributes and behaviors. This approach allows for easy extension and modification of game features.

  4. Database Systems: OOP is employed in database design to model and represent real-world entities as objects. Object-Relational Mapping (ORM) frameworks facilitate the interaction between database systems and programming languages, enabling a more natural representation of data.


  5. 2.Explain keywords with examples? 

  1. keywords are reserved words with specific meanings and functionalities. These words cannot be used as identifiers (such as variable names or function names) because they serve predefined purposes in the language. Here are explanations and examples of some C++ keywords:

  2. int:

    • Used to declare integer variables.

    • Example: int number = 42;

    • double:

      • Used to declare double-precision floating-point variables.

      • Example: double pi = 3.14159;

      • if, else:

        • Used for conditional statements.

        • Example: int x = 10;

          if (x > 5) { // Code to execute if x is greater than 5 } else { // Code to execute if x is not greater than 5 }
        • for:

          • Used for loop control.

          • Example: for (int i = 0; i < 5; ++i) {

            // Code to repeat five times }
          • while:

            • Used for a loop with a conditional test.

            • Example:

            • int count = 0; while (count < 3) { // Code to execute as long as count is less than 3 ++count; }

            • class:

              • Used to declare a class.

              • Example:

              • class Car { // Class definition };

              • public, private:

                • Used in class definitions to specify access control for class members.

                • Example:

                • class Example { public: int publicMember; private: int privateMember; };

                • new, delete:

                  • Used for dynamic memory allocation and deallocation.

                  • Example:

                  • int* dynamicInt = new int; // Code using dynamicInt delete dynamicInt;


                  • 3.Explain type modifier. 

                  • type modifiers are keywords used to modify the properties of basic data types. They provide additional information about the range or storage of a particular data type. Here are some common type modifiers:

                  • const:

                    • Used to declare constant variables. Once assigned a value, a const variable cannot be modified.

                    • Example:

                    • const int MAX_SIZE = 100;

                    • volatile:

                      • Indicates that a variable's value may be changed by external factors not known to the compiler. It prevents the compiler from optimizing out certain operations involving the variable.

                      • Example:

                      • volatile int sensorValue;

                      • signed, unsigned:

                        • Used with integer types (char, int, long, etc.) to specify whether the type can represent both positive and negative values (signed) or only non-negative values (unsigned).

                        • Example:

                        • signed int temperature; // Can represent both positive and negative values unsigned int count; // Can only represent non-negative values

                        • short, long:

                          • Used with integer types to indicate a smaller or larger storage size, respectively.

                          • Example:

                        • short int smallNumber; // Smaller storage size than a regular int long int largeNumber; // Larger storage size than a regular int
                        • long long:

                          • Used with integer types to specify an even larger storage size than long.

                      • Example:

                        long long:

                        • Used with integer types to specify an even larger storage size than long.

                        • Example: long long int veryLargeNumber; // Larger storage size than a regular long int


  1. 4.Explain logical operator in c++ with example 

  2. Logical operators in C++ are used to perform logical operations on boolean values (true or false). These operators allow you to combine or manipulate boolean expressions to make decisions in your program. The logical operators in C++ are && (logical AND), || (logical OR), and ! (logical NOT).

    1. Logical AND (&&):

      • Returns true if both operands are true; otherwise, it returns false.

      • Example: #include <iostream> int main() { int x = 5; int y = 10; // Logical AND if (x > 0 && y > 0) { std::cout << "Both x and y are positive." << std::endl; } else { std::cout << "At least one of x or y is not positive." << std::endl; } return 0; }

      • Logical OR (||):

        • Returns true if at least one of the operands is true; otherwise, it returns false.

        • Example:

        • #include <iostream> int main() { int x = 5; int y = -3; // Logical OR if (x > 0 || y > 0) { std::cout << "At least one of x or y is positive." << std::endl; } else { std::cout << "Neither x nor y is positive." << std::endl; } return 0; }

        • Logical NOT (!):

          • Returns true if the operand is false, and false if the operand is true.

          • Example:

          • #include <iostream> int main() { bool isSunny = true; // Logical NOT if (!isSunny) { std::cout << "It's not sunny today." << std::endl; } else { std::cout << "It's sunny today." << std::endl; } return 0; }

          • ogical operators can be used to create conditional expressions based on boolean values. Logical operators are commonly used in control structures like if statements to make decisions in a program based on multiple conditions.



  1. 5.Explain Relational Operators in C++ with examples. 

  2. Relational operators in C++ are used to compare values and determine the relationship between them. These operators return a boolean result (true or false) based on the comparison. The common relational operators in C++ are:

    1. Equal to (==):

      • Checks if the values on both sides of the operator are equal.

      • Example:

      • #include <iostream> int main() { int x = 5; int y = 5; // Equal to if (x == y) { std::cout << "x is equal to y." << std::endl; } else { std::cout << "x is not equal to y." << std::endl; } return 0; }

      • Not equal to (!=):

        • Checks if the values on both sides of the operator are not equal.

        • Example:

        • #include <iostream> int main() { int x = 5; int y = 10; // Not equal to if (x != y) { std::cout << "x is not equal to y." << std::endl; } else { std::cout<<"x is equal to y ."<<endl;



  1. 6.Explain insertion and extraction operator. 

  2. insertion and extraction operators (<< and >>) are used for formatted input and output operations, especially with streams. These operators are commonly associated with the standard input (cin) and output (cout) streams.

    1. Insertion Operator (<<):

      • Used to send data to an output stream, typically to display it on the console (cout).

      • Example:

      • #include <iostream> int main() { int age = 25; double height = 5.9; // Insertion operator (<<) to display values on the console std::cout << "Age: " << age << ", Height: " << height << " feet" << std::endl; return 0; }

      • Output:

      • Age: 25, Height: 5.9 feet

      • Extraction Operator (>>):

        • Used to read data from an input stream, typically to obtain values from the user (cin).

        • Example:

        • #include <iostream> int main() { int userInput; double userHeight; // Extraction operator (>>) to get values from the user std::cout << "Enter your age: "; std::cin >> userInput; std::cout << "Enter your height in feet: "; std::cin >> userHeight; // Displaying the user-input values std::cout << "You entered: Age - " << userInput << ", Height - " << userHeight << " feet" << std::endl; return 0; }

        • output


        • Enter your age: 25 Enter your height in feet: 5.9 You entered: Age - 25, Height - 5.9 feet




Next (unit-2)

Comments