0% found this document useful (0 votes)
3 views11 pages

Assignment 1 4

Uploaded by

Joe Blrs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Assignment 1 4

Uploaded by

Joe Blrs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

# Assignment 1

## Question 1: Features of Object-Oriented Programming

### 1. Polymorphism (3)

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It


enables methods to do different things based on the object it is acting upon, even when they share the
same name. There are two types of polymorphism:

- **Compile-time polymorphism** (method overloading): Resolving method calls at compile time.

- **Run-time polymorphism** (method overriding): Resolving method calls at run time through virtual
functions.

### 2. Inheritance (3)

Inheritance is a mechanism where a new class (derived class) can inherit attributes and methods from an
existing class (base class). This promotes code reusability and establishes a natural hierarchy between
classes.

- **Types of Inheritance**:

- Single inheritance

- Multiple inheritance

- Multilevel inheritance

- Hierarchical inheritance

### 3. Encapsulation (2)

Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data
within a single unit or class. It restricts direct access to some of the object's components, which is a
means of preventing unintended interference and misuse of the methods and data. Access specifiers
(public, private, protected) are used to enforce encapsulation.
### 4. Abstraction (2)

Abstraction is the concept of hiding the complex reality while exposing only the necessary parts of an
object. It helps in reducing programming complexity and increases efficiency by allowing the
programmer to focus on interactions at a higher level. In C++, abstraction can be achieved through
abstract classes and interfaces.

---

## Question 2: Components of a C++ Program

### 1. Single Line Comment (2)

A single line comment in C++ is used to annotate code and is ignored by the compiler. It is initiated with
two forward slashes (`//`).

```cpp

// This is a single line comment

```

### 2. Pre-processor Directive (2)

Pre-processor directives are commands that are processed before actual compilation begins. They
typically start with a `#` symbol. For example, `#include` is used to include libraries.

```cpp

#include <iostream>

```

### 3. Global Declaration (2)


Global declarations refer to variables or functions defined outside of all functions and classes. These are
accessible from any function within the same file.

```cpp

int globalVariable = 10; // Global variable

```

### 4. C++ Statement (2)

A C++ statement is an instruction that the compiler can execute. It can be a declaration, assignment, or
control flow statement.

```cpp

int a = 5; // C++ statement

```

### 5. Local Variable (2)

A local variable is declared within a function and can only be accessed within that function. It is created
when the function is called and destroyed when the function exits.

```cpp

void exampleFunction() {

int localVariable = 20; // Local variable

}ASSIGNMENT 2
```Here's a simple Arduino program to control three LEDs representing traffic lights: GREEN, YELLOW,
and RED. Each LED will be turned on for 5 seconds in the specified sequence.

```cpp
// Define pin numbers for the LEDs

const int greenLED = 7;

const int yellowLED = 6;

const int redLED = 4;

void setup() {

// Initialize the LED pins as outputs

pinMode(greenLED, OUTPUT);

pinMode(yellowLED, OUTPUT);

pinMode(redLED, OUTPUT);

void loop() {

// Turn on the GREEN LED

digitalWrite(greenLED, HIGH);

digitalWrite(yellowLED, LOW);

digitalWrite(redLED, LOW);

delay(5000); // Keep GREEN LED on for 5 seconds

// Turn on the YELLOW LED

digitalWrite(greenLED, LOW);

digitalWrite(yellowLED, HIGH);

digitalWrite(redLED, LOW);

delay(5000); // Keep YELLOW LED on for 5 seconds


// Turn on the RED LED

digitalWrite(greenLED, LOW);

digitalWrite(yellowLED, LOW);

digitalWrite(redLED, HIGH);

delay(5000); // Keep RED LED on for 5 seconds

```

## Explanation:

- **Pin Definitions**: The LEDs are assigned to digital pins 7, 6, and 4.

- **Setup Function**: Initializes the LED pins as outputs.

- **Loop Function**:

- Turns on each LED in sequence, with a delay of 5 seconds for each LED.

- Only one LED is on at a time, simulating a traffic light system.

Upload this code to your Arduino, and it will control the LEDs as specified!#

ASSIGNMENT 3
Question 1: Programming Tools

### 1. Flow Chart (2)

A flow chart is a visual representation of a process or algorithm. It uses shapes such as rectangles,
diamonds, and arrows to illustrate the steps involved and the flow of control. Flow charts help in
understanding the logic of a program and can be useful for debugging and communication.

### 2. Algorithms (2)


An algorithm is a finite set of well-defined instructions or steps designed to perform a specific task or
solve a problem. It is a systematic approach that outlines the sequence of operations required, typically
expressed in natural language or pseudocode. Algorithms are fundamental to programming and
computer science.

### 3. Pseudocode (2)

Pseudocode is a high-level description of an algorithm that uses a mix of natural language and
programming constructs. It is not meant to be executed but serves as an intermediary step between an
algorithm and actual code, allowing programmers to focus on logic without getting bogged down by
syntax specifics.

### 4. Editor (2)

An editor is a software application used for writing and modifying code. Text editors can range from
simple ones like Notepad to advanced Integrated Development Environments (IDEs) that offer features
like syntax highlighting, code completion, and debugging tools. Editors help programmers write, test,
and maintain their code efficiently.

### 5. Argument (2)

An argument is a value or reference passed to a function or method when it is called. Arguments provide
the necessary inputs that the function uses to perform its task. They can be of various data types,
including integers, strings, or objects, depending on the function's requirements.

---

# Question 2: Identifiers and Arrays

### 1. Define an Identifier (2)

An identifier is a name used to identify a variable, function, class, or any other user-defined item in a
program. Identifiers are essential for referencing these elements in the code, and they must be unique
within their scope.
### 2. Outline the Rules for Naming Identifiers (5)

1. **Character Set**: Identifiers can only contain letters (uppercase and lowercase), digits (0-9), and
underscores (_). They cannot begin with a digit.

2. **Case Sensitivity**: Identifiers are case-sensitive; for example, `variable` and `Variable` are
considered different identifiers.

3. **Length**: There is generally no fixed limit on the length of identifiers, but it's best to keep them
reasonable for readability.

4. **Reserved Keywords**: Identifiers cannot be the same as reserved keywords or built-in function
names in the programming language.

5. **Descriptive Names**: While not a strict rule, it's good practice to use meaningful and descriptive
names that reflect the purpose of the identifier.

### 3. Syntax for Declaring an Array

The syntax for declaring an array in most programming languages (e.g., C++, Java) typically looks like
this:

```cpp

dataType arrayName[arraySize];

```

**Example**:

```cpp

int numbers[10]; // Declares an array of integers with size 10

```# Question 1: Distinguishing Between Loops

## For Loop

- **Definition**: The `for` loop is used when the number of iterations is known beforehand. It consists
of three parts: initialization, condition, and increment/decrement.
- **Syntax**:

```cpp

for (initialization; condition; increment) {

// Code to execute

```

- **Use Case**: Ideal for iterating over arrays or when the exact number of iterations is predetermined.

## While Loop

- **Definition**: The `while` loop continues to execute as long as its condition is true. The condition is
checked before each iteration.

- **Syntax**:

```cpp

while (condition) {

// Code to execute

```

- **Use Case**: Best used when the number of iterations is not known in advance, and the loop should
continue until a certain condition is met.

## Do-While Loop

- **Definition**: The `do-while` loop is similar to the `while` loop, but it guarantees at least one
execution of the loop body since the condition is checked after the loop's body is executed.

- **Syntax**:

```cpp

do {

// Code to execute
} while (condition);

```

- **Use Case**: Useful when the loop body must run at least once, such as when prompting for user
input.

### Key Differences

1. **Execution Guarantee**:

- **For Loop**: Executes based on the condition before each iteration.

- **While Loop**: Executes based on the condition before each iteration.

- **Do-While Loop**: Executes the body at least once, checking the condition afterward.

2. **Use Cases**:

- **For Loop**: Best for a known number of iterations.

- **While Loop**: Best for unknown iterations with a condition.

- **Do-While Loop**: Best when at least one execution is required.

3. **Initialization and Increment**:

- **For Loop**: Combines initialization, condition, and increment in a single line.

- **While Loop**: Initialization and increment must be managed separately.

- **Do-While Loop**: Similar to the while loop regarding initialization and increment.

4. **Readability**:

- **For Loop**: Often more concise and easier to read for fixed iterations.

- **While Loop**: More flexible but can be less clear for complex conditions.

- **Do-While Loop**: Clear for cases needing guaranteed execution.


---

# Question 2: Data Types and Importance of Constructors and Destructors

## Four Data Types in C++ (4)

1. **int**: Represents integer numbers (e.g., `int age = 30;`).

2. **float**: Represents floating-point numbers (e.g., `float weight = 65.5;`).

3. **char**: Represents a single character (e.g., `char grade = 'A';`).

4. **bool**: Represents a boolean value (true or false) (e.g., `bool isPassed = true;`).

## Importance of Constructors and Destructors in C++ Classes (6)

### Constructors

- **Definition**: A constructor is a special member function that is automatically called when an object
of a class is created. It has the same name as the class and no return type.

- **Purpose**:

- **Initialization**: Constructors initialize object attributes, ensuring they start with valid values.

- **Overloading**: Multiple constructors can be defined with different parameters, allowing for
flexible object creation.

- **Resource Management**: They can allocate resources (like memory) needed for the object.

### Destructors

- **Definition**: A destructor is a special member function that is automatically called when an object
goes out of scope or is deleted. It has the same name as the class but is prefixed with a tilde (~) and has
no return type or parameters.

- **Purpose**:
- **Cleanup**: Destructors release resources that were acquired during the object's lifetime, such as
memory or file handles, to prevent memory leaks.

- **Finalization**: They can perform any cleanup operations before the object is destroyed, ensuring
that all operations are properly concluded.

### Overall Importance

Both constructors and destructors are crucial for managing the lifecycle of objects in C++. They ensure
that resources are properly allocated and deallocated, which is essential for writing efficient and reliable
code. Proper use of these features helps maintain the integrity of resource management, avoids
memory leaks, and facilitates easier debugging and maintenance.

You might also like