0% found this document useful (0 votes)
8 views

PF And OOP Notes

The document provides an overview of programming fundamentals using C++ and Python, covering topics such as basic syntax, data types, control statements, loops, functions, arrays, strings, file handling, and error handling. It also explains the concepts of pointers, classes, and objects, including constructors and destructors. Key differences between C++ and Python are highlighted, emphasizing their respective compilation, typing, and syntax characteristics.

Uploaded by

kashaf zahra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PF And OOP Notes

The document provides an overview of programming fundamentals using C++ and Python, covering topics such as basic syntax, data types, control statements, loops, functions, arrays, strings, file handling, and error handling. It also explains the concepts of pointers, classes, and objects, including constructors and destructors. Key differences between C++ and Python are highlighted, emphasizing their respective compilation, typing, and syntax characteristics.

Uploaded by

kashaf zahra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Programming Fundamentals

Notebook
Juniors

A1_Alpha Kay Notes 😎


Basics
C++:

#include <iostream> // Includes library for input/output


using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}

#include <iostream> : Includes the standard library for input/output operations.

using namespace std; : Avoids prefixing std:: for standard functions like cout .

int main() : The main function, where program execution starts.

cout : Used for output.

return 0; : Ends the program and signals successful execution.

Python:

print("Hello, World!")

print() : A built-in function to display output to the console.

Data Types

Programming Fundamentals 1
C++:

int age = 25;


float price = 19.99;
char grade = 'A';
bool isStudent = true;

int : Stores integers.

float : Stores decimal numbers.

char : Stores a single character (enclosed in single quotes).

bool : Stores a boolean value ( true or false ).

Python:

age = 25 # Integer
price = 19.99 # Float
grade = 'A' # Single character (also treated as a str
ing)
is_student = True # Boolean (True/False)

Python automatically determines the data type based on the value assigned.

Control Statements
C++:

int age = 18;


if (age >= 18) {
cout << "You are an adult.";
} else {
cout << "You are a minor.";
}

if : Checks if the condition is true.

Programming Fundamentals 2
else : Executes if the condition is false.

Python:

age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")

Indentation is used instead of braces {} to define blocks.

Switch Statement in C++


The switch statement is a control structure that allows you to select one block of
code to execute from multiple options. It is particularly useful for handling discrete
values and makes the code more readable than multiple if-else statements.

Syntax

switch(expression) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
// More cases...
default:
// Code block for unmatched cases
}

Explanation of Syntax
switch(expression) : The expression is evaluated, and its result is compared with
each case value.

Programming Fundamentals 3
: Represents a possible match for the expression . If the
case value: expression

equals value , the code block under this case executes.

break; : Terminates the execution of the switch statement. Without break ,


execution continues into subsequent cases ("fall-through behavior").

default: : Optional block that executes if no case matches the expression .

Example 1: Basic Usage

#include <iostream>
using namespace std;

int main() {
int choice;
cout << "Enter a number (1-3): ";
cin >> choice;

switch(choice) {
case 1:
cout << "You selected option 1.\n";
break;
case 2:
cout << "You selected option 2.\n";
break;
case 3:
cout << "You selected option 3.\n";
break;
default:
cout << "Invalid choice.\n";
}

return 0;
}

Output

Programming Fundamentals 4
1. If choice = 1 :
Output:
You selected option 1.

2. If choice = 4 :
Output:
Invalid choice.

Key Points
1. Expression Type:

The expression must evaluate to an integral type (e.g., int , char ).

Floating-point ( float , double ) and string values are not allowed as switch

expressions.

2. Fall-through Behavior:

If break is omitted, execution continues into the subsequent case .

Example:

int x = 2;
switch(x) {
case 1:
cout << "One\n";
case 2:
cout << "Two\n";
case 3:
cout << "Three\n";
}
// Output: Two
// Three

Always use break unless fall-through behavior is intentional.

3. Default Case:

The default case is optional but ensures that all unmatched conditions are
handled.

Programming Fundamentals 5
It acts like the else block in an if-else structure.

Example 2: Using char as Case

#include <iostream>
using namespace std;

int main() {
char grade;
cout << "Enter your grade (A, B, C): ";
cin >> grade;

switch(grade) {
case 'A':
cout << "Excellent!\n";
break;
case 'B':
cout << "Good job!\n";
break;
case 'C':
cout << "You passed.\n";
break;
default:
cout << "Invalid grade.\n";
}

return 0;
}

Output
1. If grade = 'A' :
Output:
Excellent!

Programming Fundamentals 6
2. If grade = 'D' :
Output:
Invalid grade.

Advantages of Switch
Clear and concise for multiple discrete conditions.

Easier to read than nested if-else statements.

Improves performance in some cases due to compiler optimizations.

Limitations
Only works with integral or enumerated types.

Cannot handle ranges or complex conditions (use if-else for such scenarios).

Fall-through behavior can lead to bugs if break is forgotten.

Equivalent Logic in Python


Python does not have a switch statement, but similar functionality can be
achieved using if-elif statements or dictionaries.

Using if-elif :

choice = int(input("Enter a number (1-3): "))

if choice == 1:
print("You selected option 1.")
elif choice == 2:
print("You selected option 2.")
elif choice == 3:
print("You selected option 3.")
else:
print("Invalid choice.")

Using a Dictionary:

Programming Fundamentals 7
def option1():
return "You selected option 1."

def option2():
return "You selected option 2."

def option3():
return "You selected option 3."

choice = int(input("Enter a number (1-3): "))


options = {1: option1, 2: option2, 3: option3}

print(options.get(choice, lambda: "Invalid choice.")())

By mastering the switch statement in C++, you can efficiently handle multi-way
branching in programs, making them more structured and easier to debug.

Loops
C++:

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


cout << "Number: " << i << endl; // Outputs numbers 0
to 4
}

for : Repeats a block of code for a specified range.

i = 0 : Initialization.

i < 5 : Condition to check before each iteration.

i++ : Increment i after each iteration.

Python:

for i in range(5):

Programming Fundamentals 8
print("Number:", i) # Outputs numbers 0 to 4

range(5) : Generates numbers from 0 to 4.

Functions
C++:

#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

int main() {
cout << add(5, 3);
return 0;
}

int add(int a, int b) : Function declaration and definition.

return : Returns the result of the addition.

Python:

def add(a, b):


return a + b

print(add(5, 3))

def : Used to define a function.

return : Sends the result back to the caller.

Arrays and Lists

Programming Fundamentals 9
C++ Arrays:

int arr[3] = {1, 2, 3}; // Declares and initializes an array


cout << arr[0]; // Accesses the first element
arr[1] = 10; // Modifies the second element

int arr[3] : Declares an array of size 3.

arr[0] : Accesses the first element.

Python Lists:

arr = [1, 2, 3] # Declares and initializes a list


print(arr[0]) # Accesses the first element
arr[1] = 10 # Modifies the second element

Lists in Python are more flexible and can hold different data types.

Strings
C++:

#include <iostream>
#include <string>
using namespace std;

string name = "Alice";


cout << name.length(); // Outputs the length of the string
(5)

<string> : Library for string manipulation.

length() : Returns the length of the string.

Python:

Programming Fundamentals 10
name = "Alice" # Declares a string
print(len(name)) # Outputs the length of the string
(5)

Strings in Python are treated as objects, and many operations are built-in.

File Handling
C++:

#include <fstream>
using namespace std;

int main() {
ofstream file("example.txt"); // Opens a file for writing
file << "Hello, World!"; // Writes to the file
file.close(); // Closes the file
return 0;
}

Python:

with open("example.txt", "w") as file: # Opens a file for wr


iting
file.write("Hello, World!") # Writes to the file

with open() : Automatically closes the file after writing.

Error Handling
Error Handling in C++
C++ uses try , catch , and throw to handle exceptions.

Programming Fundamentals 11
Exceptions are events that disrupt the normal flow of the program (e.g.,
division by zero, invalid memory access).

Syntax

try {
// Code that might throw an error
throw exception; // Throw an error (exception)
} catch (type e) {
// Code to handle the error
}

Example

#include <iostream>
using namespace std;

int main() {
try {
int a = 5, b = 0;
if (b == 0)
throw "Division by zero error!"; // Throw an exc
eption
cout << a / b; // This line won't execute
} catch (const char* e) {
// Handle the exception
cout << "Error: " << e << endl;
}

return 0;
}

Explanation:

1. try Block: The code that might cause an error is placed here.

Programming Fundamentals 12
2. throw Statement: Used to raise (or "throw") an exception. In this case, it's a
string message.

3. catch Block: Handles the exception. Here, it catches the thrown string and
displays the error message.

Error Handling in Python


Python uses try , except , else , and finally to handle exceptions.

Exceptions are errors detected during runtime (e.g., ZeroDivisionError ,


FileNotFoundError ).

Syntax

try:
# Code that might raise an error
except ExceptionType:
# Code to handle the error
else:
# Code to execute if no error occurs
finally:
# Code that always executes

Example

try:
a = 5
b = 0
result = a / b # This line will raise an exception
except ZeroDivisionError as e:
# Handle the exception
print("Error:", e)
else:
# Executes if no exception occurs
print("Result:", result)
finally:

Programming Fundamentals 13
# Always executes
print("Execution complete.")

Explanation:

1. try Block: The risky code is placed here (e.g., division by zero).

2. exceptBlock: Catches specific exceptions ( ZeroDivisionError in this case) and


handles them.

3. else Block: Executes if no exception occurs (optional).

4. finallyBlock: Executes whether or not an exception occurred (useful for


cleanup tasks).

Best Practices for Error Handling


1. Handle Specific Exceptions: Avoid catching all exceptions unless necessary
(e.g., catch (...) in C++ or except: in Python).

2. Provide Meaningful Messages: Ensure error messages help diagnose the


problem.

3. Avoid Silent Failures: Always log or display exceptions instead of ignoring


them.

4. Use finally (or equivalent): Ensure resources like files or database


connections are properly closed.

5. Do Not Abuse Exceptions: Use exceptions for unexpected situations, not for
normal control flow.

Key Differences

Feature C++ Python

Compilation Compiled Interpreted

Typing Statically Typed Dynamically Typed

Syntax Strict (semicolons, braces) Flexible (indentation)

Performance Faster Slower

Programming Fundamentals 14
Pointers in Object-Oriented Programming
(OOP)
Definition:
Pointers are variables that store the memory address of another variable. They are
widely used in C++ for dynamic memory allocation, object management, and
implementing advanced OOP features like polymorphism.

Key Concepts of Pointers:


1. Declaration and Initialization:

int a = 10;
int* p = &a; // p stores the address of a

2. Accessing Values Using Pointers:

int a = 10;
int* p = &a;
cout << *p; // Outputs 10

3. Dynamic Memory Allocation:

int* p = new int(25); // Allocates memory dynamically


cout << *p; // Outputs 25
delete p; // Frees the allocated memory

4. Pointers and Arrays:

int arr[3] = {1, 2, 3};


int* p = arr; // Points to the first element of the array
cout << *(p + 1); // Outputs 2

5. Pointers to Objects:

Programming Fundamentals 15
class Sample {
public:
int x;
Sample(int val) : x(val) {}
};

Sample* obj = new Sample(42);


cout << obj->x; // Outputs 42
delete obj;

Classes and Objects


Definition:
A class is a blueprint for creating objects. It defines properties (attributes) and
behaviors (methods).

An object is an instance of a class.

Example in C++:

#include <iostream>
using namespace std;

class Car {
public:
string brand;
int year;

void displayDetails() {
cout << "Brand: " << brand << ", Year: " << year << e
ndl;
}
};

Programming Fundamentals 16
int main() {
Car car1;
car1.brand = "Toyota";
car1.year = 2020;

car1.displayDetails(); // Outputs: Brand: Toyota, Year: 2


020
return 0;
}

Example in Python:

class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year

def display_details(self):
print(f"Brand: {self.brand}, Year: {self.year}")

car1 = Car("Toyota", 2020)


car1.display_details() # Outputs: Brand: Toyota, Year: 2020

Constructors and Destructors


Definition:
Constructor: A special method called automatically when an object is created.

In C++, it shares the same name as the class.

In Python, it is __init__ .

Destructor: A special method called automatically when an object is


destroyed.

Programming Fundamentals 17
In C++, it is prefixed with ~ .

In Python, it is __del__ .

Example in C++:

#include <iostream>
using namespace std;

class Car {
public:
string brand;
int year;

// Constructor
Car(string b, int y) {
brand = b;
year = y;
cout << "Car object created!" << endl;
}

// Destructor
~Car() {
cout << "Car object destroyed!" << endl;
}

void displayDetails() {
cout << "Brand: " << brand << ", Year: " << year << e
ndl;
}
};

int main() {
Car car1("Toyota", 2020);
car1.displayDetails();

Programming Fundamentals 18
return 0;
}

Example in Python:

class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
print("Car object created!")

def __del__(self):
print("Car object destroyed!")

def display_details(self):
print(f"Brand: {self.brand}, Year: {self.year}")

car1 = Car("Toyota", 2020)


car1.display_details()
del car1 # Forces destruction

Friend Functions
Definition:
A friend function in C++ can access the private and protected members of a
class even though it is not a member of that class.

Not applicable in Python since it uses dynamic attribute access, and there is
no strict privacy enforcement.

Example in C++:

#include <iostream>
using namespace std;

Programming Fundamentals 19
class Box {
private:
int width;

public:
Box(int w) : width(w) {}

// Declare friend function


friend void displayWidth(Box b);
};

// Friend function definition


void displayWidth(Box b) {
cout << "Width: " << b.width << endl;
}

int main() {
Box b1(50);
displayWidth(b1); // Outputs: Width: 50
return 0;
}

Operator Overloading
Definition:
Operator overloading allows operators to be redefined for user-defined types.

Example in C++:

#include <iostream>
using namespace std;

class Complex {

Programming Fundamentals 20
private:
int real, imag;

public:
Complex(int r, int i) : real(r), imag(i) {}

// Overload '+' operator


Complex operator+(const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Using overloaded '+' operator
c3.display(); // Outputs: 4 + 6i
return 0;
}

Example in Python:

class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag

# Overload '+' operator


def __add__(self, other):
return Complex(self.real + other.real, self.imag + ot
her.imag)

Programming Fundamentals 21
def __str__(self):
return f"{self.real} + {self.imag}i"

c1 = Complex(3, 4)
c2 = Complex(1, 2)
c3 = c1 + c2 # Using overloaded '+' operator
print(c3) # Outputs: 4 + 6i

Summary of Python Compatibility


Feature C++ Python

Classes and Objects Supported Supported

Constructors & Destructors Supported Supported ( __init__ , __del__ )

Friend Functions Supported Not applicable

Operator Overloading Supported Supported (magic methods)

1. Encapsulation
Encapsulation is the bundling of data (variables) and methods (functions) that
operate on the data into a single unit, typically a class. It ensures that the internal
details of the class are hidden from the outside world.

Example:

cpp
Copy code
class BankAccount {
private:
double balance;

public:
BankAccount(double initialBalance) : balance(initialBalan
ce) {}

Programming Fundamentals 22
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

double getBalance() const {


return balance;
}
};

int main() {
BankAccount account(100.0);
account.deposit(50.0);
cout << "Balance: $" << account.getBalance() << endl;
return 0;
}

2. Inheritance
Inheritance allows one class (derived class) to inherit properties and methods
from another class (base class). It promotes code reusability.

Example:

cpp
Copy code
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};

Programming Fundamentals 23
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};

int main() {
Dog myDog;
myDog.eat();
myDog.bark();
return 0;
}

3. Polymorphism
Polymorphism allows objects to take many forms. It enables a single interface to
control access to a variety of types.

Example:
Compile-Time Polymorphism (Function Overloading):

cpp
Copy code
class Calculator {
public:
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
};

Programming Fundamentals 24
int main() {
Calculator calc;
cout << calc.add(2, 3) << endl; // Outputs 5
cout << calc.add(2.5, 3.5) << endl; // Outputs 6.0
return 0;
}

Run-Time Polymorphism (Virtual Functions):

cpp
Copy code
class Animal {
public:
virtual void sound() {
cout << "This is an animal sound." << endl;
}
};

class Dog : public Animal {


public:
void sound() override {
cout << "The dog barks." << endl;
}
};

int main() {
Animal* animal = new Dog();
animal->sound(); // Outputs "The dog barks."
delete animal;
return 0;
}

Programming Fundamentals 25
4. Abstraction
Abstraction hides implementation details and shows only essential features. In
C++, it can be implemented using abstract classes or interfaces.

Example:

cpp
Copy code
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing a Circle." << endl;
}
};

int main() {
Shape* shape = new Circle();
shape->draw(); // Outputs "Drawing a Circle."
delete shape;
return 0;
}

Programming Fundamentals 26

You might also like