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

Prince Assignment

Gggfddd

Uploaded by

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

Prince Assignment

Gggfddd

Uploaded by

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

UNIVERSITY OF PORT HARCOURT

FACULTY OF EDUCATION

DEPARTMENT OF SCIENCE EDUCATION

NAME: FRANK PRINCE JOSHUA

MAT NO: U2023/2593043

COURSE CODE: COS 102.2

ASSIGNMENT ON COS: PROBLEM SOLVING


1. Explain in details the various asymptotic notations used in algorithm
analysis
• Big O Notation (O)Big O notation is used to describe the upper bound of an
algorithm’s running time. It provides the worst-case scenario, ensuring that the
algorithm will not run slower than this time, no matter the input size. It’s used to give
an upper bound on the growth rate of the function.

• Omega Notation (Ω)Omega notation describes the lower bound of an algorithm’s


running time. It provides a guarantee that the algorithm will not run faster than this
time in the best-case scenario.
• Theta Notation (Θ)Theta notation provides a tight bound on the algorithm’s running
time, meaning it describes both the upper and lower bounds. It gives a more precise
description by stating that the algorithm’s running time grows exactly at this rate.
• HiLittle-o Notation (o)Little-o notation provides a strict upper bound on the
algorithm’s running time. It describes an upper bound that is not tight, meaning the
algorithm’s growth rate is less than this bound but cannot match it.

• Little-omega Notation (ω)Little-omega notation describes a strict lower bound on the


algorithm's running time. It states that the algorithm’s growth rate is greater than this
bound but cannot match it.
2. Is 3n2 + 5n + 6 = O(n3)?
• Yes, ( 3n^2 + 5n + 6 ) is ( O(n^3) ), but it’s a loose upper bound. A tighter bound would be (
O(n^2) ), which more accurately reflects the growth rate of the function as ( n )
increases.
3. Consider the algorithm that finds the existence of an element x in an
array of n elements.

Int search ( int a [ ], int n, int x )

{Int I ;

For ( I = 0; I < n – 1 ; I + + )

{If ( x = = a [ I ] )

Retur

n I ;}
Retur

n -1 ;}

If C(n) is the number of comparisons, describe and find C(n) for the worst case,
best case and average case complexity if the element is

i. Present in the array


ii. Not present in the array
• Worst Case (Element Present or Not Present): ( C(n) = n-1 )Best Case (Element
Present): ( C(n) = 1 )Best Case (Element Not Present): ( C(n) = n-1 )Average Case
(Element Present): ( C(n) = \frac{n}{2} )Average Case (Element Not Present): ( C(n) = n-1
).
4. It is important to study algorithms and complexity for the following
reasons
• Economic and Environmental Impact
• Algorithm Selection
• Understanding Trade-offs
• Scalability
• Problem Solving and Innovation

5. Discuss extensively on the Searching and Sorting Algorithms stating


their complexities, merit and demerit in each case.

Searching Algorithms: Searching algorithms are used to find an element within a


data structure, such as an array or a linked list. The efficiency of these algorithms is
measured by their time and space complexity.

. Linear Search
Description: Linear search checks each element of the array sequentially until the
desired element is found or the end of the array is reached.

Time Complexity:
Worst Case: \(O(n)\) (Element is not present or is at the last
position) Best Case:\(O(1)\) (Element is at the first position)
Average Case:/(O(n)\)
Space Complexity: \(O(1)\) (constant space)
Merits
- Simple to implement.
- No requirement for the data to be sorted.
- Works well with small datasets.

Demerits
- Inefficient for large datasets due to its linear time complexity.
- On average, it requires \(n/2\) comparisons, which is not optimal for large \(n\)
. Binary Search
Description :Binary search is a more efficient algorithm that works by repeatedly
dividing
the sorted array in half and comparing the middle element with the target value. The
search continues in the half where the element could be.

Time complexity:

Worst Case:\(O(\log n)\)


Best case: \(O(1)\) (Element is the middle
element) Average case : \(O(\log n)\)
Space complexity: \(O(1)\) for iterative version, \(O(\log n)\) for recursive
version due to the stack space.
Merits:
- Much more efficient than linear search, especially for large datasets.
- Logarithmic time complexity ensures that it scales well with large datasets.
Demerits:
- Requires the array to be sorted, which adds preprocessing time if the array is
unsorted.
- More complex to implement than linear search.

. Hash Table Search


Description: Hashing is a technique used to map data of arbitrary size to fixed-size
values (hash codes). In hash table search, elements are stored in a table based on
their hash values, allowing for quick retrieval.

Time complexity:

Average case:\(O(1)\) (constant time for insertion, deletion, and search)

Worst Case:\(O(n)\) (in case of many collisions)

Space Complexity: \(O(n)\) (for storing the hash table)

Merits:

- Extremely fast average-case performance.


Efficient for dynamic datasets where frequent insertions and deletions are required.
Demerits:
- Performance degrades with many collisions.
- Requires extra space for the hash table.
- The choice of hash function is critical to avoid collisions.

Sorting Algorithms
Sorting algorithms are used to arrange the elements of a dataset in a particular
order (usually ascending or descending). Sorting is a fundamental operation
that is often required before performing other tasks like searching.

Bubble sort:

Description: Bubble sort repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the wrong order. This process is repeated
until the list is sorted.

Time complexity:

Worst Case:\(O(n^2)\) (the list is in reverse order)

Best Case: \(O(n)\) (the list is already sorted, with an optimized version that checks if
swaps were made)

Average Case:\(O(n^2)\)

Space complexity:\(O(1)\) (in-place sorting)

Merits:

- Simple to implement and understand.


- Works well on small datasets or nearly sorted datasets.

Demerits:

- Highly inefficient on large datasets due to its quadratic time complexity.


- Not suitable for large lists or datasets.

. Insertion Sort:

Description: Insertion sort builds the final sorted array one element at a time. It picks
elements and inserts them into their correct position by comparing them with elements
in the sorted portion of the array.

Time Complexity

Worst case:\(O(n^2)\) (the list is in reverse


order) Best case:\(O(n)\) (the list is already

sorted) Average case:: \(O(n^2)\)

Space Complexity: \(O(1)\) (in-place

sorting) Merits:

- Efficient for small datasets or nearly sorted data.


- Simple and adaptive; performs well on small, partially sorted lists.
- Stable sort, meaning it preserves the relative order of equal elements.
Demerits:
- Inefficient for large datasets due to its quadratic time complexity.
- Not suitable for large datasets.
. Merge Sort

Description: Merge sort is a divide-and-conquer algorithm that divides the array into
two halves, recursively sorts them, and then merges the two sorted halves.

Time complexity:

Worst case:\(O(n \log

n)\) Best case:\(O(n \log

n)\) Average case:\(O(n

\log n)\)

Space Complexity: \(O(n)\) (requires additional space for merging)

Merits:

- Consistent \(O(n \log n)\) time complexity.


- Stable sort, meaning it maintains the relative order of equal elements.
- Efficient for large datasets and linked lists.

Demerits:

- Requires additional space for merging, making it less space-efficient than in-
place sorts.
- More complex to implement than simple algorithms like bubble sort or insertion
sort.
s
Ǫuick sort:

Description: Ǫuick sort is another divide-and-conquer algorithm that picks a pivot


element and partitions the array around the pivot. The subarrays are then sorted
recursively.

Time complexity

Worst case*: \(O(n^2)\) (when the smallest or largest element is always chosen as
the pivot)

Best case:\(O(n \log n)\)

Average case:\(O(n \log

n)\)

Space complexity: \(O(\log n)\) for the stack space in recursive calls

- Merits**:
- Very efficient on average for large datasets.
- Works well with in-place partitioning.
- Has a small overhead, so it’s faster in practice than merge sort in many cases.
- **Demerits**:
- Worst-case performance can be quadratic if poor pivot choices are made.
- Not a stable sort.
- Recursive, which could lead to stack overffow on very large arrays.

#### **5. Heap Sort**

- **Description**: Heap sort builds a binary heap from the array and
repeatedly extracts the maximum (or minimum) element from the
heap, rebuilding the heap as necessary until the array is sorted.

- **Time Complexity**:
- **Worst Case**: \(O(n \log n)\)
- **Best Case**: \(O(n \log n)\)
- **Average Case**: \(O(n \log n)\)
- **Space Complexity**: \(O(1)\) (in-place sorting)
- **Merits**:
- Guarantees \(O(n \log n)\) time complexity regardless of input.
- In-place sorting algorithm with no need for additional memory.
- Efficient for large datasets.
- **Demerits**:
- Not a stable sort.

- Slightly slower than quick sort on average due to the overhead of maintaining the
heap structure.
- More complex to implement compared to simpler sorting algorithms.

c. What do you understand by divide and conquer


algorithm, show how any of the divide and conquer
algorithm can be used to sort the given data set 8, 2,
3, 7, 1, 5, 4.
Divide and Conquer Algorithm A Divide and Conquer algorithm is a method of
solving a problem by breaking it down into smaller sub problems, solving each sub
problem recursively, and then combining the solutions to solve the original problem.
This approach is often used in algorithms where the problem can naturally be
divided into smaller,
manageable parts. The three main steps in a divide and conquer algorithm are

Divide: Split the problem into smaller sub problems. Conquer: Solve the sub
problems recursively. If the sub problems are small enough, solve them directly.
Combine: Combine the solutions of the sub problems to form the solution to the
original problem.

The Merge Sort algorithm divides the dataset into smaller parts, recursively sorts each
part, and then merges the sorted parts to form the final sorted dataset. The dataset
8, 2, S, 7, 1, 5, 4 is sorted into 1, 2, 4, 5, 7, 8, S using the divide and conquer strategy
of the Merge Sort algorithm.

7. Miss. Shakira is having Rice in container A and


Beans in Container C while Container C is empty.
She intends to swap the content of B and A. write an
algorithm and the corresponding ffowchart to achieve
this task.
.Input: Containers A and B (represented as arrays or vectors).
.Initialize a temporary variable temp.
.Swap the contents of A and B:
.Set temp equal to the contents of A.
.Copy the contents of B into A.
.Set the contents of B equal to temp.
.Output: Updated contents of containers A and B.
St=>start: Start
Op1=>operation: Initialize
temp Op2=>operation:
Swap A and B E=>end:
End

St->op1->op2->e
8. Write an algorithm and the corresponding flowchart to
compute the root of a quadratic equation

The standard form of a quadratic equation is: [ ax^2 + bx + c = 0 ] where


(a), (b), and (c) are coefficients, and (x) is the variable
.Algorithm:Start.
.Input the coefficients (a), (b), and(c).
.Calculate the discriminant ( \Delta = b^2 – 4ac ).If ( \Delta > 0 ):
.The equation has two real and distinct roots.
.Calculate the roots using: [ x_1 = \frac{-b + \sqrt{\Delta}}{2a} ] [ x_2 =
\frac{-b
- \sqrt{\Delta}}{2a} ]
.Output (x_1) and (x_2).Else if ( \Delta = 0 ):
.The equation has one real and repeated root.
.Calculate the root using: [ x_1 = \frac{-b}{2a} ]
.Output (x_1).Else ( \Delta < 0 ):The equation has two complex roots.
.Calculate the real part and imaginary part using: [ \text{Real part} =
\frac{- b}{2a} ] [ \text{Imaginary part} = \frac{\sqrt{|\Delta|}}{2a} ]Output
the complex roots as: [ x_1 = \frac{-b}{2a} + i\frac{\sqrt{|\Delta|}}{2a} ] [
x_2 = \frac{-b}{2a} – i\frac{\sqrt{|\Delta|}}{2a} ]End.Flowchart to
Compute the Roots of a Ǫuadratic Equation Below is the description
of the ffowchart steps:
Start. Input the coefficients (a), (b), and (c)
.Calculate the discriminant ( \Delta = b^2 – 4ac )
.Decision: Is ( \Delta > 0 )?Yes: Calculate the two real and distinct roots (
x_1
) and ( x_2 ). .Output the roots.No: Move to the next
decision. Decision: Is ( \Delta = 0 )?
Yes: Calculate the single real root ( x_1 ). Output the root.
.No: The discriminant must be less than zero. Else: Calculate the real
and imaginary parts. Output the complex roots. End.

3.Develop an algorithm and flowchart to compute the


square of N numbers.
Algorithm:
.Start
.Input: Number of elements N
.Initialize: An empty list or array to store the numbers.
.Loop:
For I = 1 to N, do the following :Input the number
.Compute the square of the number
.Store the squared value in a list or array.
. Output: Display the list or array of squared
numbers. End.

10.Develop an algorithm and the corresponding ffowchart to compute the


grade of students in the Department of Computer Science Faculty of Computing University Port
Harcourt River State.

.A: 70
– 100
B: c0
– cS
C: 50
– 5S
D: 45
– 4S
E: 40
– 44
F: 0 – 3S
Algorithm:
.Start
. Input: Number of students N.
.Loop: For I = 1 to N, do the following:
.Input the student’s name and marks obtained.
.Determine the grade based on the marks:
If marks >= 70 then grade = ‘A’
Else If marks >= c0 then grade
= ‘B’ Else If marks >= 50 then
grade = ‘C’ Else If marks >= 45
then grade = ‘D’ Else If marks
>= 40 then grade = ‘E’ Else
grade = ‘F’
Store the student's name, marks, and grade.
.Output: Display the list of students with their corresponding marks and
grades.
End.
11. Write a comprehensive note on how the various symbols of the ffowchart are
used in modeling developed systems in question 7, 8 3 and 10.

.
.Oval (Terminator) – Start/End:Usage: The oval symbol is used to
indicate the beginning and the end of the process.
. Application:Ǫuestion 7 (Summing and Averaging Numbers): The process
starts with initializing the sum and ends after calculating the average and
displaying the result.
. Ǫuestion 8 (Finding Maximum and Minimum of N Numbers): The process
starts with input and ends after displaying the maximum and minimum
values.

. Ǫuestion S (Computing the Square of N Numbers): The process begins with


inputting the total number of elements and ends after outputting the list of
squared numbers.
. Ǫuestion 10 (Computing Student Grades): The ffowchart starts by taking the
number of students as input and ends after displaying the list of students with
their grades.
. Parallelogram – Input/Output:
Usage: This symbol represents the input of data and the output of results.
. Application:
.Ǫuestion 7: Used to input the numbers and output the sum and average.
. Ǫuestion 8: Used to input each number and output the maximum and
minimum.
. Ǫuestion S: Used to input each number and output the list of squared numbers.
. Ǫuestion 10: Used to input student details (name, marks) and output the
grades.
Rectangle – Process/Operation:
.Usage: The rectangle represents an action or operation that is performed, such
as calculations or variable assignments.
. Application:
. Ǫuestion 7: Summing the numbers and calculating the average are represented
by process symbols.
. Ǫuestion 8: Comparing each number to find the maximum and minimum
involves processes.
. Ǫuestion S: Calculating the square of each number is represented by this
symbol.
. Ǫuestion 10: Used extensively to determine the grade based on the
student’s marks (e.g., whether marks are greater than or equal to 70 for a
grade 'A').
. Arrow (Flow line):
. Usage: The arrows indicate the direction of the process ffow, guiding the
reader from one step to the next.
. Application: Ǫuestions 7-10: Arrows connect all the symbols and guide the
ffow from input to output, ensuring the logical sequence of steps is clear.
. Circle (Connector):
Usage: The circle is used to connect different parts of the flowchart when it
spans multiple pages or to connect intersecting flow lines.

. Application: This symbol may not be necessary for simpler flowcharts like the
ones in questions 7-10 but is crucial for more complex systems where the
flowchart might be broken up.

. Application in Specific Questions:

Question 7 (Summing and Averaging Numbers): The flowchart starts with an oval
for “Start,” uses parallelograms for inputs and outputs, rectangles for summing
and averaging processes, and ends with an oval.

. Question 8 (Finding Maximum and Minimum): The flowchart begins with an


oval, uses a parallelogram for input, diamonds for decisions about the
maximum and minimum, rectangles for updating values, and ends with an
oval.

. Question 9 (Computing Squares): The flowchart uses ovals for start and end,
parallelograms for inputting numbers and outputting results, and rectangles for the
process of squaring each number.

. Question 10 (Computing Student Grades): The flowchart uses a combination


of ovals, parallelograms, rectangles, and diamonds to process student data,
make decisions on grades, and output the results.

SECOND ASSIGNMENT ANSWERS


1. Described the type of error known to you in computer
programs
ANSWER:

Syntax Errors
• Description: These errors occur when the code violates the grammatical rules of the
programming language. For example, missing a semicolon in languages like C++ or
Java, or incorrect indentation in Python.

Logic Errors

• Description: These errors occur when the program runs without crashing but
produces incorrect results. Logic errors happen due to mistakes in the algorithm or
incorrect assumptions in the code.

1. Describe three interpretation of the upper bound in problem


solving in python
ANSWER:

a. . Time Complexity Upper Bound

• Description: Time complexity is the upper bound on the time an algorithm takes to
run as the size of the input grows. This is usually expressed using Big-O notation
(e.g., O(n), O(n²), O(log n), etc.). It represents the worst-case scenario for how long
an algorithm will take to complete.

b. Space Complexity Upper Bound

• Description: Space complexity refers to the upper bound on the memory usage of an
algorithm. It describes how much additional memory the algorithm requires in
relation to the size of the input.

2. Explain the asymptotic notations known to you


ANSWER:

i. Big-O Notation (O)

• Definition: Big-O notation describes the upper bound of an algorithm's runtime. It


provides the worst-case scenario of how an algorithm will perform as the input size
grows. It tells us how the algorithm scales as the input size approaches infinity.
• Interpretation: The function will not take longer than the time represented by the
Big-O notation, even in the worst case.

ii. Big-Omega Notation (Ω)

• Definition: Big-Omega notation provides a lower bound for an algorithm's runtime.


It describes the best-case scenario, or the minimum amount of time an algorithm will
take as the input size grows.
• Interpretation: The function will take at least this amount of time to complete, no
matter how favorable the input is.

3. What are the methods of passing parameter to a function?

ANSWER:
a. Pass by Value
• Description: In this method, a copy of the actual parameter's value is passed to the
function. Changes made to the parameter inside the function do not affect the original
variable outside the function.
• Behavior: The function receives a copy of the argument, so any modifications to the
parameter inside the function are local to that function.

b. Pass by Reference

• Description: In this method, the reference (or address) of the actual parameter is
passed to the function. Changes made to the parameter inside the function affect the
original variable because both the original variable and the parameter point to the
same memory location.
• Behavior: The function modifies the original object or variable directly.

4. Write python code to print 3 by 3 matrix

# Define the matrix

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

# Print the matrix

for row in matrix:

print(row)

OUTPUT;

1 [1, 2, 3]

2 [4, 5, 6]

3 [7, 8, 9]
5. With the aid of python program differentiate between a
function and recursion
ANSWER:

Differentiating between a Function and Recursion in Python

A function and recursion are two fundamental concepts in programming, and they
are often confused with each other. In this response, I'll explain the difference
between a function and recursion in Python, with examples to illustrate each
concept.

A Function in Python

A function in Python is a block of code that can be executed multiple times from
different parts of a program. It is a self-contained piece of code that takes in
arguments, performs some operations, and returns a value. A function has a name,
and it can be called multiple times in a program.

Here is an example of a simple function in Python:

def greet(name):

print("Hello, " + name + "!")

greet("Confidence") # Output: Hello, Anyawata!

greet("Confidence`") # Output: Hello, Anyawata!

6. In a tabular form list the methods in a function?

METHOD DESCRIPTION BEHAVIOUR EXAMPLE

Pass by Value Passes a copy of the Modifications modify_value(x)


variable’s value. inside the function (with integers, floats,
Changes do not do not change the etc.)
affect the original. original variable
outside the
function.
Pass by Passes the reference Changes inside the modify_list(lst)
Reference (address) of the function affect the (with lists, dictionaries,
variable original variable etc.)
(for mutable
objects).
Pass by Object Python's method. Mutable objects modify_list(lst)
Reference Passes reference for (lists, dicts) are or
mutable, value for modified in the modify_string(s)

immutable objects. function;


immutable objects
(int, str) are not.
Keyword Arguments are Allows passing greet(greeting="Hi",
Arguments passed by explicitly arguments in any name="Alice")
naming them in the order by name.
function call.
Default Assigns default If no argument is greet(name,
Arguments values to function provided, the greeting="Hello")
parameters if no default value is
argument is passed. used.
Variable-length Allows functions to args for positional sum_numbers(args)
Arguments accept a variable arguments, kwargs or
number of for keyword print_info(kwargs)

arguments (args or arguments.


kwargs).

7. With the aid of python program demonstrate various how


various types of variable are used?

ANSWER:
In Python, variables can be classified into different types based on their data type (like
integers, floats, strings, lists, dictionaries, etc.), scope (local vs. global), and mutability
(mutable vs. immutable). Here's how you can demonstrate the usage of different types of
variables in a Python program:

a. Global and Local Variables

• Global variables are declared outside of functions and can be accessed inside any function.
• Local variables are declared inside functions and are only accessible within that function.

b. Mutable and Immutable Variables

• Mutable variables (like lists and dictionaries) can be modified after their creation.
• Immutable variables (like integers, strings, and tuples) cannot be modified once created.

c. Different Data Types

• Variables can store data of different types, such as integers, floats, strings, lists, tuples,
dictionaries, and sets.
# Global Variable
global_var = 100
# Function demonstrating Local vs. Global variables
def show_local_global():
local_var = 50 # Local Variable
print("Inside function (local_var):", local_var)
print("Inside function (global_var):", global_var) # Accessing global variable inside
function
# Mutable Variable (List)
mutable_list = [1, 2, 3]
# Function demonstrating mutable variable behavior
def modify_mutable():
mutable_list.append(4) # Modifying the global mutable list
print("Inside function (modified mutable_list):", mutable_list)
# Immutable Variable (Integer)
immutable_var = 10

# Function demonstrating immutable variable behavior


def modify_immutable():
global immutable_var
immutable_var += 5 # Attempting to modify the global immutable variable
print("Inside function (modified immutable_var):", immutable_var)
# Data Types Demonstration
def data_types():
integer_var = 42 # Integer
float_var = 3.1415 # Float
string_var = "Hello, World!" # String
tuple_var = (1, 2, 3) # Tuple (Immutable)
dict_var = {"name": "Alice", "age": 25} # Dictionary (Mutable)
print("\nDifferent Data Types:")
print("Integer Variable:", integer_var)
print("Float Variable:", float_var)
print("String Variable:", string_var)
print("Tuple Variable (immutable):", tuple_var)
print("Dictionary Variable (mutable):", dict_var)

# Main Code Execution


print("Global Variable (global_var):", global_var)
show_local_global()

print("\nMutable Variable (Before modification):", mutable_list)


modify_mutable()
print("Mutable Variable (After modification):", mutable_list)

print("\nImmutable Variable (Before modification):", immutable_var)


modify_immutable()
print("Immutable Variable (After modification):", immutable_var)

data_types()

OUTPUT:
Global Variable (global_var): 100
Inside function (local_var): 50
Inside function (global_var): 100

Mutable Variable (Before modification): [1, 2, 3]


Inside function (modified mutable_list): [1, 2, 3, 4]
Mutable Variable (After modification): [1, 2, 3, 4]

Immutable Variable (Before modification): 10


Inside function (modified immutable_var): 15
Immutable Variable (After modification): 15

Different Data Types:


Integer Variable: 42
Float Variable: 3.1415
String Variable: Hello, World!
Tuple Variable (immutable): (1, 2, 3)
Dictionary Variable (mutable): {'name': 'Alice', 'age': 25}

8. Write a python code to accept and print out the average of


three numbers.
ANSWER:
# Function to calculate the average of three numbers
def calculate_average(num1, num2, num3):
average = (num1 + num2 + num3) / 3
return average

# Accepting input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Calculating the average


average = calculate_average(num1, num2, num3)

# Printing the result


print(f"The average of {num1}, {num2}, and {num3} is: {average}")

OUTPUT:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
The average of 10.0, 20.0, and 30.0 is: 20.0

9. Write a python code to print days in the week?

ANSWER:
# Function to print the days of the week
def print_days_of_week():
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
for day in days_of_week:
print(day)

# Calling the function to print the days


print_days_of_week()

OUTPUT:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
10. Write an extensive notes on various control structure
in python support with python code
ANSWER:
a. . Conditional Statements

Conditional statements allow you to execute certain code blocks based on conditions.

a. if Statement

• Description: Executes a block of code if its condition evaluates to True

b. if-else Statement

• Description: Executes one block of code if its condition evaluates to True, otherwise
executes another block of code.

if-elif-else Statement

• Description: Executes one of multiple code blocks based on several conditions.

2. Loops

Loops allow you to execute a block of code repeatedly.

a. for Loop

• Description: Iterates over a sequence (such as a list, tuple, or string) and executes a
block of code for each item in the sequence.
b. while Loop

• Description: Repeats a block of code as long as its condition evaluates to True.

c. break Statement

• Description: Exits the nearest enclosing loop prematurely.

d. continue Statement

• Description: Skips the remaining code inside the nearest enclosing loop for the
current iteration and proceeds to the next iteration.

e.else Clause with Loops

• Description: Executes a block of code after the loop completes, but not if the loop
was terminated by a break statement.

3. Exception Handling

Exception handling allows you to manage errors gracefully during program execution.

a. try-except Block

• Description: Catches and handles exceptions that occur in the try block.

b. try-except-else Block

• Description: Executes an additional block of code if no exceptions were raised in the


try block.

c.try-except-finally Block

• Description: Executes a block of code regardless of whether an exception was raised


or not, often used for cleanup actions.

11.Using the if else statement in python compute the grade of students in


the department of computer science?
ANSWER:
# Function to determine the grade based on the score
def compute_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

# Accepting the student's score from the user


score = float(input("Enter the student's score: "))

# Computing the grade


grade = compute_grade(score)

# Printing the result


print(f"The grade for a score of {score} is: {grade}")

You might also like