0% found this document useful (0 votes)
12 views9 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

Unit-3

1. What is the purpose of conditional statements in programming? Provide an example of a


simple if-else statement.

Conditional statements in programming are used to control the flow of a program based on specified
conditions. They allow the program to make decisions and execute different blocks of code
depending on whether a particular condition or set of conditions is true or false.

Here's an example of a simple "if-else" statement in Python:

# Simple if-else statement to determine if a number is positive or


negative

# Input from the user


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

# Check if the number is positive or negative


if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

2. Explain the difference between the "if" statement and the "switch" statement. When would
you use each?

The "if" statement and the "switch" statement are both control structures used in programming to
make decisions and control the flow of code based on specific conditions. However, they have
distinct differences in terms of syntax, use cases, and readability.
The "if" statement is used when there are multiple conditions to evaluate sequentially or when
conditions are more complex. On the other hand, a "switch" statement is used when a single variable
or expression may have many possible values and you want to make your code more readable and
efficient. Note that not all programming languages support the "switch" statement. The "switch"
statement is typically used in languages like C, C++, and Java. In such cases, "if" statements are the
more versatile choice.

Syntax of "if" statement in Python:

if condition:
# Code to execute if the condition is true
elif another_condition:
# Code to execute if another_condition is true
else:
# Code to execute if none of the above conditions are true

Syntax of "switch" statement in Java:

switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Code to execute if no match is found
}

3. Define a loop in programming. Differentiate between "for" and "while" loops with suitable
examples.

A loop in programming is a control structure that allows you to execute a block of code repeatedly
based on a specified condition.
The "for" loops are used for definite iteration, where the number of iterations is known in advance,
while "while" loops are used for indefinite iteration, where you iterate until a certain condition
becomes false.

Example of For loop in Python:

A "for" loop to print numbers from 1 to 5.

for i in range(1, 6):


print(i)

A "while" loop to print numbers from 1 to 5.


i = 1
while i <= 5:
print(i)
i += 1

4. Explain the concept of nested conditional statements and loops. Provide an example of using
nested loops to print a pattern.

Nested Conditional Statements:

In nested conditional statements, one or more "if," "else if" (or "elif"), and "else" statements are
placed inside other "if" or "else" blocks. This is useful when you need to evaluate multiple conditions
in a structured manner.

Example of nested conditional statements in Python:

x = 10
y = 5

if x > y:
print("x is greater than y")
if x > 0:
print("x is positive")
else:
print("x is non-positive")
else:
print("x is not greater than y")

Nested Loops:

Nested loops involve placing one or more loops (e.g., "for" or "while" loops) inside another loop. This
is used to perform repetitive tasks with multiple levels of iteration.

Example of using nested loops to print a pattern in Python:

for i in range(5): # Outer loop for rows


for j in range(i + 1): # Inner loop for columns
print("*", end=" ")
# Print an asterisk with a space (end=" ")
print() # Move to the next line after each row

This code prints a simple right-angled triangle pattern.


Output:

*
* *
* * *
* * * *
* * * * *

5. Discuss the role of loop control statements, such as "break" and "continue," in altering loop
behavior. Provide examples of their usage.

Loop control statements, such as "break" and "continue," are used to alter the normal flow of
execution within loops.

break" Statement: The "break" statement is used to exit the current loop prematurely. When a
"break" statement is encountered, the loop terminates, and the program continues with the first
statement after the loop.

Example of "break" in a "while" loop (Python):

i = 0
while i < 5:
print(i)
if i == 2:
break # Exit the loop when i equals 2
i += 1

Output:

0
1
2
Continue statement: The "continue" statement is used to skip the current iteration of a loop and
move to the next iteration. It allows you to bypass the remaining code within the loop's current
iteration and proceed with the next iteration.

Example of "continue" in a "for" loop (Python):

for i in range(5):
if i == 2:
continue # Skip iteration when i equals 2
print(i)

Output:

0
1
3
4

6. Explain the concept of an infinite loop and provide an example. How can you avoid
unintended infinite loops?

An infinite loop is a programming construct where a loop continues to execute repeatedly without
ever terminating naturally. In an infinite loop, the loop condition always evaluates to true, ensuring
that the loop keeps running indefinitely. Infinite loops can be intentional in some cases, but
unintended infinite loops are typically considered bugs and can lead to software freezing or
becoming unresponsive.

Here's an example of an unintended infinite loop in Python:

while True:
print("This is an infinite loop.")

To avoid unintended infinite loops and the associated issues, consider the following precautions:

1. Ensure a Clear Exit Condition: Always define a clear and appropriate exit condition for
your loops. This condition should eventually become false, allowing the loop to terminate.
Without an exit condition, the loop will run indefinitely.

Example with an exit condition in Python:

count = 0
while count < 5:
print("This loop will run 5 times.")
count += 1

2. Use a Timeout or Watchdog: In some cases, it might be appropriate to set a timeout or a


watchdog mechanism that monitors the loop's execution and terminates it if it runs for an
excessively long time. This can be especially useful in situations where infinite loops can't be
completely avoided.
3. Exception Handling: Implement error-handling mechanisms to catch and handle unexpected
situations that might cause infinite loops. This can include scenarios like network errors or
unexpected input.
4. Test Loop Logic and entire code: Before running your code, review the loop logic as well as
entire code carefully to ensure that the conditions are set up correctly. This helps catch
potential issues before they lead to infinite loops.

7. What is exception handling in programming?

Exception handling is a programming concept and practice that involves anticipating and managing
exceptional or unexpected events, known as exceptions, that may occur during the execution of a
program. Exceptions are situations where the normal flow of a program is disrupted due to errors or
unforeseen circumstances. Exception handling provides a structured way to detect, report, and
gracefully handle these exceptional situations, preventing the program from crashing or producing
unpredictable results.

8. Describe the purpose of "try," "catch," and "finally" blocks in exception handling. Provide an
example of their usage.

Try Block: A try block contains the code that might raise an exception. If an exception occurs within
the try block, the program transfers control to the corresponding catch block.

Catch Block: A catch block specifies how to handle a specific type of exception. It contains code to
handle the exception, such as logging an error message or taking corrective action.

Finally Block: A finally block (optional) is used to specify code that should be executed regardless of
whether an exception occurred. It's commonly used for resource cleanup.

try:
# Code that may raise an exception
num1 = int(input("Enter a numerator: "))
num2 = int(input("Enter a denominator: "))
result = num1 / num2
except ZeroDivisionError:
# Handle division by zero exception
print("Error: Division by zero is not allowed.")
except ValueError:
# Handle invalid input (non-integer) exception
print("Error: Please enter valid integers.")
except Exception as e:
# Handle other exceptions
print(f"An error occurred: {e}")
else:
# Code to execute if no exception occurred
print(f"Result of division: {result}")
finally:
# Code that will always run, whether an exception occurred or not
print("Execution completed.")

9. Define a subprogram. Differentiate between a function and a procedure.


Subprograms, are self-contained, reusable blocks of code within a program. They encapsulate a
specific task or a set of related tasks, allowing you to break down a larger problem into smaller, more
manageable parts. Subprograms enhance code modularity, readability, and maintainability.
Generally, subprogram has three parts.
 Name: Every subprogram has a unique name that distinguishes it from other subprograms.
The name is used to identify and call the subprogram from other parts of the program.
Functions, procedures, and methods all have names.
 Parameters: Subprograms can accept parameters (also called arguments or inputs) that are
used to pass values into the subprogram. Parameters provide a way for data to be passed from
the calling code to the subprogram. Subprograms can have zero or more parameters.
Parameters are essential for making subprograms versatile and applicable to various
situations.
 Return Value (for functions): Functions, which are a specific type of subprogram, can
return a value to the calling code. This returned value is the result of the function's
computation and is sent back to the caller.

Functions are used when you need to compute a value and return it to the caller, while procedures
are used when you need to perform actions or operations without returning a value. Procedures may
modify the data but do not return values.

Example of Function in Python:

def add(a, b):


return a + b

Example of Procedure in Python:

def greet(name):
print("Hello, " + name + "!")

10. Describe the concept of parameter passing in subprograms. Explain the difference between
pass-by-value and pass-by-reference.

Parameter passing in subprograms (such as functions or procedures) refers to the mechanism by


which data is transferred between the calling code (the caller) and the subprogram being called (the
callee). It defines how arguments provided by the caller are passed to the subprogram and how the
subprogram can access and use these arguments.

Pass-by-Value: In pass-by-value, the value of the argument (the actual data) is copied into a
parameter of the subprogram. Changes made to the parameter within the subprogram do not affect the
original argument in the caller's scope. Pass-by-value is generally used for basic data types like
integers, floats, and characters.

Example of Pass-by-value in Python:

def modify_value(x):
x = x + 10 # Modifying the local variable x

num = 5
modify_value(num)
print(num) # Output will be 5 because the original num is not
changed by
the function.
Pass-by-Reference: In pass-by-reference, a reference or memory address of the argument is passed to
the subprogram. This means that any changes made to the parameter within the subprogram directly
affect the original data in the caller's scope.Pass-by-reference is commonly used for complex data
types like arrays, objects, or records.

Pass-by-Object-Reference (Similar to Pass-by-Reference):

In Python, the behavior is closer to pass-by-object-reference, where you can modify the contents of
objects (if they are mutable), but you can't reassign the reference itself.

def modify_list(arr):
arr.append(42) # Modifying the list by adding an element

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output will be [1, 2, 3, 42] because the list was
modified in the function.

11. Define recursion in programming. Provide an example of a recursive function and explain
how it works.

Recursion in programming is a technique where a function calls itself to solve a problem by breaking
it down into smaller, more manageable subproblems. In essence, recursion allows a function to solve
a complex problem by reducing it into simpler instances of the same problem until it reaches a base
case (a terminating condition) where it can provide a direct answer. Recursion is particularly useful
for solving problems that can be expressed in a recursive mathematical or structural form.

A recursive function consists of two main parts:

1. Base Case: This is the condition that defines when the recursion should stop. When the base
case is met, the function stops calling itself and returns a result.
2. Recursive Case: In this part, the function calls itself with a modified set of parameters to
move closer to the base case. The function makes one or more recursive calls to solve smaller
subproblems.

Here's an example of a simple recursive function in Python that calculates the factorial of a non-
negative integer:

def factorial(n):
# Base case: If n is 0, return 1 (0! = 1)
if n == 0:
return 1
# Recursive case: Calculate factorial(n-1) and multiply by
n
else:
return n * factorial(n - 1)

# Example usage:
result = factorial(5) # Calculates 5!
print("Factorial of 5 is:", result)

12. What do you mean by local and global variable in programming?


Local variables are variables that are declared within a function or a block of code. They have a local
scope, meaning they can only be accessed and modified within the specific function or block where
they are declared. Once the function or block execution is complete, the local variables are destroyed,
and their values are no longer accessible. Local variables are typically used for temporary storage
within a specific function or block.

Example in Python:

def my_function():
local_variable = 10
print(local_variable)

my_function()
print(local_variable) # This will raise an error because local_variable is
not accessible outside the function

Global variables, on the other hand, are declared outside of any function or block. They have a
global scope, which means they can be accessed and modified from any part of the code, including
inside functions.

Example in Python:

global_variable = 20
def my_function():
print(global_variable)
my_function()
print(global_variable) # Output: 20
13. What do you mean by scope and lifetime of a variable in programming?
Scope refers to the region of the program where a variable can be accessed or modified. The scope of
a variable is determined by where it is declared within the program.

Lifetime of a variable refers to the duration during which the variable exists in the computer's
memory. It starts when the variable is created and ends when it goes out of scope. There are generally
three types of variable lifetime:

1. Lifetime of Global Variables: These variables have a lifetime equal to the duration of the
program. They are created when the program starts and destroyed when the program
terminates.
2. Lifetime of Local Variables: These variables have a lifetime equal to the duration of the
function call. They are created when the function is called and destroyed when the function
exits.
3. Lifetime of Dynamic Variables: These variables are created dynamically during program
execution and have a lifetime as long as the program runs or until they are explicitly
deallocated. In Python, there isn't a concept of dynamic variables.

14. What do you mean by static and dynamic scope?

Static Scope:

In static scoping, also known as lexical scoping, the scope of a variable is determined by its position
in the source code. Variables declared in an outer block are accessible in the inner block. Here's an
example demonstrating static scoping in Python:

def outer_function():
static_variable = "I am static!"

def inner_function():
print(static_variable) # Accessing static variable from outer_function

inner_function()

outer_function()

Dynamic Scope:

Dynamic scoping, on the other hand, determines the scope of a variable based on the call stack at
runtime. In Python, the language uses static scoping; however, you can simulate dynamic scoping
using function arguments. Here's an example:

def outer_function(dynamic_variable):
def inner_function():
print(dynamic_variable) # Accessing dynamic variable passed as an argument

inner_function()

outer_function("I am dynamic!")

You might also like