0% found this document useful (0 votes)
16 views18 pages

List of Programs

Uploaded by

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

List of Programs

Uploaded by

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

Program 1: Familiarity with Classes Representing Entities that Interact

with the User

Objectives:Understand how to design and implement classes that


represent real-world entities.
Requirements:Python or C++ environment,Basic knowledge of
object-oriented programming concepts such as classes, objects, methods,
and attributes.
Familiarity with handling user input through command-line interfaces.

Task Breakdown:

Task 1: Implementing the Person Class

1. Objective:
○ Create a class Person that models a person with attributes
such as name and age.

Python Implementation:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

def update_info(self, new_name, new_age):


self.name = new_name
self.age = new_age

# Main program
person = Person("John Doe", 25)
person.display_info()

new_name = input("Enter a new name: ")


new_age = int(input("Enter a new age: "))
person.update_info(new_name, new_age)
person.display_info()

C++ program:
#include <iostream>
using namespace std;

class Person {
private:
string name;
int age;

public:
Person(string n, int a) : name(n), age(a) {}

void display_info() {
cout << "Name: " << name << ", Age: " << age << endl;
}

void update_info(string new_name, int new_age) {


name = new_name;
age = new_age;
}
};

int main() {
Person person("John Doe", 25);
person.display_info();

string new_name;
int new_age;
cout << "Enter a new name: ";
cin >> new_name;
cout << "Enter a new age: ";
cin >> new_age;

person.update_info(new_name, new_age);
person.display_info();

return 0;
}

Task 2: Designing a BankAccount Class


Objective:mplement a BankAccount class that represents a user’s bank
account.

Define attributes for account_number, account_holder, and balance.


Python Implementation:
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance

def deposit(self, amount):


self.balance += amount
print(f"{amount} deposited. New balance: {self.balance}")

def withdraw(self, amount):


if amount > self.balance:
print("Insufficient funds!")
else:
self.balance -= amount
print(f"{amount} withdrawn. Remaining balance:
{self.balance}")

def display_info(self):
print(f"Account holder: {self.account_holder}, Balance:
{self.balance}")

# Main program
account = BankAccount("Alice")
account.display_info()

deposit_amount = float(input("Enter amount to deposit: "))


account.deposit(deposit_amount)

withdrawal_amount = float(input("Enter amount to withdraw: "))


account.withdraw(withdrawal_amount)

account.display_info()
C++ Code: #include <iostream>
using namespace std;

class BankAccount {
private:
string account_holder;
double balance;

public:
BankAccount(string holder, double bal = 0) :
account_holder(holder), balance(bal) {}

void deposit(double amount) {


balance += amount;
cout << amount << " deposited. New balance: " << balance <<
endl;
}

void withdraw(double amount) {


if (amount > balance) {
cout << "Insufficient funds!" << endl;
} else {
balance -= amount;
cout << amount << " withdrawn. Remaining balance: " <<
balance << endl;
}
}

void display_info() {
cout << "Account holder: " << account_holder << ", Balance: "
<< balance << endl;
}
};

int main() {
BankAccount account("Alice");
account.display_info();

double deposit_amount;
cout << "Enter amount to deposit: ";
cin >> deposit_amount;
account.deposit(deposit_amount);

double withdrawal_amount;
cout << "Enter amount to withdraw: ";
cin >> withdrawal_amount;
account.withdraw(withdrawal_amount);

account.display_info();

return 0;
}

Task 3: Creating a Vehicle Class with Inheritance

Objective:

● Implement a base Vehicle class and a derived class Car that


inherits from Vehicle.
● The Car class should add unique attributes (e.g., fuel_type) and
methods specific to cars.

Instructions:
Create a base class Vehicle with attributes like make, model, and year.

Python Implementation:

class Vehicle:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

def display_info(self):

print(f"Vehicle: {self.make} {self.model}, Year: {self.year}")

class Car(Vehicle):

def __init__(self, make, model, year, fuel_type):

super().__init__(make, model, year)

self.fuel_type = fuel_type

def display_info(self):

super().display_info()

print(f"Fuel Type: {self.fuel_type}")


# Main program

my_car = Car("Toyota", "Corolla", 2020, "Gasoline")

my_car.display_info()

Program 2. Writing Simple Programs Involving If Statements

Objective:

● To learn how to use conditional statements (if, else if, else) to


control the flow of a program.

If-Else Structure:

1. If Statement: The if statement evaluates a condition (expression). If


the condition is true, the block of code inside the if statement is
executed

if condition:

# Code block to execute if condition is true

If-Else Statement: If the if condition is false, the else block is


executed.
if condition:

# Code block to execute if condition is true

else:

# Code block to execute if condition is false

Else-If Ladder (Optional): If there are multiple conditions, you can use
an else if or elif (in Python) to test additional conditions.

Syntax:

if condition1:

# Code block if condition1 is true

elif condition2:

# Code block if condition2 is true

else:

# Code block if none of the above conditions are true

Simple If Statement

Problem:

Write a program that checks if a number entered by the user is positive.

Steps:

1. Prompt the user to enter a number.


2. Check if the number is greater than zero using the if statement.
3. If the number is positive, display a message saying "The number is
positive."

Python code: # Program to check if a number is positive

num = int(input("Enter a number: "))

if num > 0:

print("The number is positive.")

Lab Exercise 2: If-Else Statement

Write a program that checks if a number entered by the user is positive


or negative.

# Program to check if a number is positive or negative

num = int(input("Enter a number: "))

if num > 0:

print("Positive number.")

else:

print("Negative number.")
Program 3: Understanding and Practicing Boolean Operators (&&
and ||)

Objective:

The aim of this lab is to gain hands-on experience with Boolean


operators, specifically the logical AND (&&) and OR (||) operators, and
understand their usage in conditional expressions.

Logical AND (&&):

This operator returns true if both operands are true. If any operand is
false, the entire expression evaluates to false.

if (a > 5 && b < 10) {

// Executes if both conditions are true.

Logical OR (||):

This operator returns true if at least one operand is true. It only returns
false if both operands are false.

if (a > 5 || b < 10) {

// Executes if either one of the conditions is true.

}
Experiment 1: Use of the and Operator

Problem Statement:

Write a Python program that checks whether a number is within the


range of 10 to 20 and whether it is even.

# Function to check if a number is within range and even


def check_number(num):
if num >= 10 and num <= 20 and num % 2 == 0:
print(f"The number {num} is within the range 10-20 and is even.")
else:
print(f"The number {num} does not meet the criteria.")

# Test cases
check_number(12) # Should meet both conditions
check_number(25) # Out of range
check_number(15) # In range but odd

Output:

\The number 12 is within the range 10-20 and is even.


The number 25 does not meet the criteria.
The number 15 does not meet the criteria.

Experiment 2: Use of the or Operator

Problem Statement:
Write a Python program that checks whether a number is either negative
or greater than 50.

# Function to check if a number is negative or greater than 50


def check_number(num):
if num < 0 or num > 50:
print(f"The number {num} is either negative or greater than 50.")
else:
print(f"The number {num} is neither negative nor greater than 50.")

# Test cases
check_number(-5) # Negative
check_number(55) # Greater than 50
check_number(25) # Neither condition met

O/p: The number -5 is either negative or greater than 50.


The number 55 is either negative or greater than 50.
The number 25 is neither negative nor greater than 50.

Practice Exercises:

1. Exercise 1:
Write a Python program that checks whether a number is divisible
by both 3 and 5.
2. Exercise 2:
Write a Python program that checks whether a string starts with
"A" or ends with "Z".
Program 4: Write a Program to Implement 4 Types of Pyramid Patterns
in Python

Left-aligned Pyramid:

This pyramid aligns its stars (*) to the left, increasing the number of
stars per row.

# Left-aligned Pyramid
def left_aligned_pyramid(rows):
for i in range(1, rows + 1):
print('* ' * i)

# Test the function


rows = 5
left_aligned_pyramid(rows)

O/P
*
**
***
****
*****

Right-aligned Pyramid:

This pyramid aligns its stars to the right by adding leading spaces.

# Right-aligned Pyramid

def right_aligned_pyramid(rows):
for i in range(1, rows + 1):

print(' ' * (rows - i) + '* ' * i)

# Test the function

rows = 5

right_aligned_pyramid(rows)

**

***

****

*****

Centered Pyramid:

This pyramid is centered, with stars symmetrically placed and expanding


outward.

# Centered Pyramid

def centered_pyramid(rows):

for i in range(1, rows + 1):

print(' ' * (rows - i) + '* ' * i)


# Test the function

rows = 5

centered_pyramid(rows)

O/P:

**

***

****

*****

Inverted Pyramid:

This pyramid starts with the maximum number of stars and decreases
with each row.

# Inverted Pyramid

def inverted_pyramid(rows):

for i in range(rows, 0, -1):

print('* ' * i)

# Test the function

rows = 5
inverted_pyramid(rows)

O/P:

*****

****

***

**

Program 5: Identifying Whether a Number is Positive, Negative, or Zero

# Program Name: Options.py

# Purpose: To determine if the entered integer is positive, negative, or


zero.

# Step 1: Get user input

number = int(input("Please enter an integer: "))

# Step 2: Use conditional statements to check the number

if number > 0:
print("The number is positive.")

elif number < 0:

print("The number is negative.")

else:

print("The number is zero.")

You might also like