0% found this document useful (0 votes)
55 views41 pages

Deekshith Xerox

print copy

Uploaded by

sharasthya26
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)
55 views41 pages

Deekshith Xerox

print copy

Uploaded by

sharasthya26
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/ 41

PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

CHAPTER 4: INTRODUCTION TO PROBLEM SOLVING


CHAPTER BLUEPRINT PLAN FOR FINAL EXAM
VSA SA LA E TOTAL
1 MARK 2 MARKS 3 MARKS 5 MARKS
2 MCQ 1 2 1 15 MARKS

MCQ
1. What is the first step in problem solving as per the document?
A) Testing the solution B) Coding the algorithm
C) Analyzing the problem D) Debugging the program
Answer: C) Analyzing the problem
2.What is an algorithm?
A) A set of exact steps to solve a problem B) A programming language
C) A type of computer hardware D) A method of debugging
Answer: A) A set of exact steps to solve a problem
3.What does the term "computerisation" refer to?
A) The use of computers to develop software for automating tasks
B) The physical components of a computer system
C) The process of debugging a program
D) The network connectivity of computers
Answer: A) The use of computers to develop software for automating tasks
4.Which of the following is NOT a characteristic of a good algorithm?
A) Precision B) Uniqueness C) Infinite steps D) Finiteness
Answer: C) Infinite steps
5.What does the process of 'coding' involve?
A) Writing an algorithm B) Testing the program D) Debugging the code
C) Converting the algorithm into a format understood by the computer
Answer: C) Converting the algorithm into a format understood by the computer
6.What shape is used to represent a process in a flowchart?
A) Parallelogram B) Rectangle C) Diamond D) Circle
Answer: B) Rectangle
7.In a flowchart, which symbol represents the start or end?
A) Diamond B) Rectangle C) Oval D) Parallelogram
Answer: C) Oval
8.What is the purpose of developing an algorithm before writing code?
A) To debug the program B) To convert it into machine language
C) To have a clear solution plan D) To test the program
Answer: C) To have a clear solution plan
9.Which step comes immediately after developing an algorithm?
A) Debugging B) Testing C) Coding D) Analyzing the problem
Answer: C) Coding
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

10. What does GIGO stand for?


A) Garbage In, Garbage Out B) Good Input, Good Output
C) Great Input, Great Output D) Generated Input, Generated Output
Answer: A) Garbage In, Garbage Out
11.What does 'finiteness' in an algorithm mean?
A) The algorithm stops after a finite number of steps B) The algorithm has infinite steps
C) The algorithm has unique steps D) The algorithm processes data infinitely
Answer: A) The algorithm stops after a finite number of steps
12.Which of the following is an essential skill for a computer science student?
A) Problemsolving B) Debugging C) Coding D) All of the above
Answer: D) All of the above
13.What is the output of an algorithm?
A) Input data B) A set of instructions C) The result of the process D) A debugging report
Answer: C) The result of the process
14.What does the parallelogram symbol in a flowchart represent?
A) Process B) Decision C) Input/Output D) Start/End
Answer: C) Input/Output
15. Which of the following steps is NOT part of the problemsolving process mentioned in the
document?
A) Analyzing the problem B) Developing an algorithm
C) Compiling the code D) Testing and debugging
Answer: C) Compiling the code
16. What should be done after finalizing the algorithm?
A) Debugging B) Testing C) Coding D) Analyzing the problem
Answer: C) Coding
17. Why is it important to document the coding procedures?
A) To make the code run faster B) To understand the logic at a later stage
C) To avoid writing an algorithm D) To reduce the size of the program
Answer: B) To understand the logic at a later stage
18.What is the role of testing in the problemsolving process?
A) To analyze the problem C) To check if the program meets user requirements
B) To write the algorithm D) To convert the algorithm into code
Answer: C) To check if the program meets user requirements
19. Which of the following is a key component of analyzing a problem?
A) Writing the program code C) Testing the solution
B) Listing the principal components of the problem D) Debugging the program
Answer: B) Listing the principal components of the problem
20.What is the primary purpose of using an algorithm?
A) To debug the program B) To test the program
C) To increase reliability, accuracy, and efficiency D) To compile the program
Answer: C) To increase reliability, accuracy, and efficiency
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

21. What does the diamond shape in a flowchart represent?


A) Process B) Decision C) Input/Output D) Start/End
Answer: B) Decision
22.Which programming language can be used to write a program after developing an
algorithm?
A) Only Python B) Any highlevel language C) Only Java D) Only C++
Answer: B) Any highlevel language
23.What must be done if the program generates incorrect output?
A) Analyze the problem B) Develop a new algorithm
C) Check for logical errors D) Ignore the output
Answer: C) Check for logical errors
24.Why is a roadmap important for a programmer?
A) To debug the program B) To clearly visualize the instructions to be written
C) To reduce the size of the program D) To increase the speed of the program
Answer: B) To clearly visualize the instructions to be written
25. What is the function of a 'terminator' symbol in a flowchart?
A) To represent a decision point B) To indicate the start or end of the process
C) To show data input/output D) To represent a process or action
Answer: B) To indicate the start or end of the process
26.What should be done after coding the algorithm?
A) Analyzing the problem B) Testing and debugging
C) Developing the algorithm D) Writing the problem statement
Answer: B) Testing and debugging
27. Why is precision important in an algorithm?
A) To reduce the number of steps B) To ensure the steps are clearly stated and defined
C) To make the algorithm run faster D) To avoid using highlevel language
Answer: B) To ensure the steps are clearly stated and defined

28. Which step in problemsolving involves identifying the logical steps to reach a solution?
A) Analyzing the problem B) Developing the algorithm
C) Coding D) Testing and debugging
Answer: B) Developing the algorithm
29. Which shape in a flowchart represents input or output data?
A) Oval B) Rectangle C) Parallelogram D) Diamond
Answer: C) Parallelogram
30. Why is uniqueness important in an algorithm?
A) To ensure each step is uniquely defined B) To make the algorithm run faster
C) To reduce the number of steps D) To avoid using highlevel language
Answer: A) To ensure each step is uniquely defined

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

31.What is the primary objective of problemsolving in computer science?


A) To debug the program B) To automate tasks efficiently
C) To reduce the size of the program D) To increase the speed of the program
Answer: B) To automate tasks efficiently
32. In a flowchart, what is used to represent a decision?
A) Oval B) Rectangle C) Diamond D) Parallelogram
Answer: C) Diamond
33.What should be the next step if an algorithm is not producing the correct output?
A) Ignoring the error B) Rewriting the problem statement
C) Revising the algorithm to check for logical errors D) Converting it into a flowchart
Answer: C) Revising the algorithm to check for logical errors
34.Why is it necessary to document the coding process?
A) To write more complex code B) To ensure the code is understandable and maintainable
C) To reduce the size of the code D) To avoid using highlevel language
Answer: B) To ensure the code is understandable and maintainable
35.What role does testing play in the problemsolving process?
A) To identify any logical errors in the algorithm B) To write the final algorithm
C) To analyze the problem statement D) To convert the algorithm into code
Answer: A) To identify any logical errors in the algorithm
36.What is the purpose of a flowchart?
A) To represent an algorithm visually B) To write the code
C) To debug the program D) To test the solution
Answer: A) To represent an algorithm visually
37.Which of the following is NOT a step in the problemsolving process?
A) Analyzing the problem B) Writing the program
C) Testing and debugging D) Developing the algorithm
Answer: B) Writing the program
38.What is 'finiteness' in the context of an algorithm?
A) The algorithm must have a finite number of steps B) The algorithm must run indefinitely
C) The algorithm should have unique steps D) The algorithm must have infinite steps
Answer: A) The algorithm must have a finite number of steps
39.Why is it necessary to debug a program?
A) To increase the size of the code B) To ensure the program runs without errors
C) To write the algorithm D) To develop the problem statement
Answer: B) To ensure the program runs without errors
40.What does a rectangle represent in a flowchart?
A) Decision B) Input/Output C) Start/End D) Process
Answer: D) Process
41.Which step involves checking if a program meets user requirements?
A) Analyzing the problem B) Developing the algorithm C) Coding D) Testing
Answer: D) Testing
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

42.What is the outcome of an algorithm?


A) Analyzing the problem B) Writing the program
C) Producing a result D) Debugging the program
Answer: C) Producing a result
43.What is the significance of 'precision' in an algorithm?
A) To reduce the number of steps B) To ensure each step is clearly defined
C) To make the algorithm faster D) To avoid using highlevel language
Answer: B) To ensure each step is clearly defined
44.Why is it important to develop an algorithm before coding?
A) To reduce the size of the program B) To have a clear solution plan
C) To debug the code D) To increase the speed of the program
Answer: B) To have a clear solution plan
45. What is the role of testing in programming?
A) To analyze the problem B) To write the code
C) To identify and fix errors D) To develop the algorithm
Answer: C) To identify and fix errors
46. What shape represents the start or end in a flowchart?
A) Rectangle B) Parallelogram C) Oval D) Diamond
Answer: C) Oval
47.Which of the following best describes 'uniqueness' in an algorithm?
A) Each step is distinct and clearly defined B) The algorithm has infinite steps
C) The algorithm runs indefinitely D) The algorithm is written in a highlevel language
Answer: A) Each step is distinct and clearly defined
48.What should be done if a program produces unexpected results?
A) Ignore the results B) Reanalyze the problem
C) Debug and test the program D) Write a new algorithm
Answer: C) Debug and test the program
49.What does the term 'coding' refer to in problemsolving?
A) Writing the problem statement C) Testing the program
B) Converting the algorithm into a programming language D) Analyzing the problem
Answer: B) Converting the algorithm into a programming language
50.Why is 'debugging' an essential part of problemsolving in programming?
A) To write the algorithm B) To fix errors in the code
C) To reduce the size of the program D) To develop the problem statement
Answer: B) To fix errors in the code

2 Marks Questions
1. Define an algorithm.
An algorithm is a finite set of instructions or a step-bystep procedure for solving a
problem or performing a task.

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

2. What is pseudocode?
Pseudocode is a non-formal language that helps programmers to write algorithms. It is
a detailed description of instructions that a computer must follow in a particular order
and is intended for human reading.
3. Explain the term "flowchart."
A flowchart is a graphical representation of the steps in an algorithm or a process, using
various symbols to denote different types of actions or steps.
4. What are conditionals in programming?
Conditionals are statements that allow a program to take different actions based on whether a
certain condition is true or false. They are used to check possibilities and perform operations
depending on the outcome of the condition.
5. What is the purpose of a flowchart?
The purpose of a flowchart is to visually represent the sequence of steps in a process or
algorithm, making it easier to understand and analyze the flow of control and the logic of the
process.
6. Describe the term "sequence" in the context of algorithms.
In the context of algorithms, "sequence" refers to the execution of steps one after the other in
a specific order, without any branching or repetition.
7. What does iterative mean in algorithm design?
In algorithm design, "iterative" refers to the process of repeating a set of instructions a
certain number of times or until a specific condition is met. This repetition is known as a
loop.
8. Why is it important to verify an algorithm?
It is important to verify an algorithm to ensure that it correctly and efficiently solves the
problem it is intended to address and to confirm that it produces the correct output for all
possible inputs.
9. What is a loop in programming?
A loop in programming is a control structure that allows the repeated execution of a block of
code as long as a specified condition is met
10. What is the significance of decision making in algorithms?
Decision making in algorithms is significant because it allows the algorithm to choose
different paths of execution based on certain conditions, enabling it to handle a variety of
situations and inputs.
11. Write pseudocode to add two numbers.
Pseudocode for adding two numbers:
INPUT num1
INPUT num2
COMPUTE Result = num1 + num2
PRINT Result

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

12. Define "space complexity" in algorithm analysis.


Space complexity in algorithm analysis refers to the amount of memory space an algorithm
needs to run to completion, taking into account both the fixed and variable space
requirements.
13. Define "time complexity" in algorithm analysis.
Time complexity in algorithm analysis refers to the amount of time an algorithm takes to run
as a function of the length of the input. It helps to estimate the efficiency of the algorithm.
14. What are the components of a flowchart?
The components of a flowchart include various symbols such as:
• Ovals for start and end points
• Rectangles for processing steps
• Diamonds for decision points
• Arrows for flow of control
15. Explain the difference between pseudocode and a flowchart.
Pseudocode is a textual representation of an algorithm written in a human-readable format,
while a flowchart is a graphical representation of the same algorithm, using symbols to
depict different types of actions and the flow of control.
16. Describe the term "branching" in algorithms.
Branching in algorithms refers to the process of making decisions within the algorithm,
where the flow of control can take different paths based on certain conditions.
17. What is the role of an algorithm in problem-solving?
The role of an algorithm in problem-solving is to provide a clear, step-by-step procedure to
solve a specific problem, ensuring that the solution is correct, efficient, and can be executed
by a computer program.
3 Marks Questions
1. Write an algorithm to find the greatest of two numbers.
o Algorithm: STEP 1. Start
STEP 2. Input number1
STEP 3. Input number2
STEP 4. If number1 > number2, then
▪ Print "number1 is greater"
STEP 5. Else
▪ Print "number2 is greater"
STEP 6. End
2. Explain the importance of pseudocode before actual coding.
o Importance of Pseudocode:
▪ Helps in planning and organizing thoughts.
▪ Ensures all steps of the algorithm are considered.
▪ Easy to read and understand.
▪ Bridges the gap between human logic and programming language syntax.
▪ Facilitates debugging by identifying logical errors before coding.
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

3. Describe the process of writing a flowchart for a given algorithm.


o Process of Writing a Flowchart:
▪ Identify the major steps in the algorithm.
▪ Use standard flowchart symbols (ovals for start/end, rectangles for processes, diamonds for
decisions).
▪ Connect the symbols with arrows to show the flow of control.
▪ Ensure the flowchart is logically correct and covers all scenarios.
▪ Review and refine the flowchart for accuracy and clarity.
4. How can you improve an algorithm that fails for certain inputs?
o Improving an Algorithm:
▪ Identify the inputs that cause the algorithm to fail.
▪ Analyze the algorithm to understand why it fails for those inputs.
▪ Modify the algorithm to handle those specific cases.
▪ Test the algorithm with a variety of inputs to ensure robustness.
▪ Optimize the algorithm to improve efficiency and performance.
5. Write pseudocode for calculating the area and perimeter of a rectangle.
o Pseudocode: INPUT length
INPUT width
COMPUTE area = length * width
COMPUTE perimeter = 2 * (length + width)
PRINT area
PRINT perimeter
6. Explain the importance of conditionals with an example.
o Importance of Conditionals:
▪ Allow the program to make decisions based on certain conditions.
▪ Enable the program to execute different actions based on different inputs.
▪ Example: In a temperature control system, if the temperature is below 20°C, the heater
turns on; if it is above 25°C, the air conditioner turns on.
7. Describe the algorithm for checking whether a number is within a specific range.
o Algorithm:
STEP Start
STEP 2. Input number
STEP 3. Input lower_bound
STEP 4. Input upper_bound
STEP 5. If number >= lower_bound and number <= upper_bound, then
▪ Print "number is within the range"
STEP 6. Else
▪ Print "number is out of range"
STEP 7. End

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

8. Explain how to handle time addition in pseudocode when minutes exceed 60.
o Pseudocode:
INPUT hours1, minutes1
INPUT hours2, minutes2
total_minutes = minutes1 + minutes2
extra_hours = total_minutes / 60
remaining_minutes = total_minutes % 60
total_hours = hours1 + hours2 + extra_hours
PRINT total_hours, remaining_minutes
9. Discuss the significance of decision-making algorithms with a real-life example.
o Significance:
▪ Decision-making algorithms allow systems to choose between different actions based on
conditions.
▪ Example: In an e-commerce application, a recommendation system suggests products
based on user preferences and past purchases, improving user experience and sales.
10. What steps should be taken if an algorithm has multiple approaches?
o Steps:
▪ Analyze each approach for correctness and efficiency.
▪ Compare the approaches based on their time and space complexity.
▪ Test each approach with various inputs to identify the best one.
▪ Choose the most efficient and robust approach.
▪ Document the reasons for choosing that particular approach.
11. Explain the importance of verifying an algorithm with an example.
o Importance:
▪ Verifying ensures the algorithm produces correct results for all inputs.
▪ Example: In a sorting algorithm, verification involves checking that the output list is sorted
for different input lists, including edge cases like empty lists or lists with repeated
elements.
12. Describe the pseudocode to classify numbers as "Single Digit," "Double Digit," or
"Big."
o Pseudocode:
INPUT number
IF number >= 0 AND number <= 9 THEN
PRINT "Single Digit"
ELSE IF number >= 10 AND number <= 99 THEN
PRINT "Double Digit"
ELSE
PRINT "Big"

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

13. Write an algorithm to calculate the water bill based on consumption.


o Algorithm:
STEP 1. Start
STEP 2. Input consumption
STEP 3. If consumption <= 30, then
▪ bill = consumption * 2
STEP 4. Else if consumption <= 50, then
▪ bill = 30 * 2 + (consumption - 30) * 3
STEP 5. Else
▪ bill = 30 * 2 + 20 * 3 + (consumption - 50) * 5
STEP 6. Print bill
STEP 7. End
14. What improvements can be made to an algorithm that only accepts positive integers up to
100?
o Improvements:
▪ Add input validation to check if the input is within the range.
▪ Provide feedback to the user if the input is out of range.
▪ Optimize the algorithm to handle edge cases.
▪ Ensure the algorithm handles different data types correctly.
▪ Include error handling to manage invalid inputs gracefully.
15. Explain the algorithm for determining the winner in a coin-flipping game.
o Algorithm:
STEP 1. Start
STEP 2. Input number_of_flips
STEP 3. Initialize heads_count and tails_count to 0
STEP 4. For each flip, do
▪ If the result is heads, increment heads_count
▪ Else, increment tails_count
STEP 5. If heads_count > tails_count, then
▪ Print "Heads win"
STEP 6. Else if tails_count > heads_count, then
▪ Print "Tails win"
STEP 7. Else
▪ Print "It's a tie"
STEP 8. End
16. Write the pseudocode to print all multiples of 5 between 10 and 25.
o Pseudocode:
FOR number FROM 10 TO 25
IF number % 5 == 0 THEN
PRINT number

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

17. How do you write an algorithm to read the marks of three subjects and
calculate the aggregate?
o Algorithm:
STEP 1. Start
STEP 2. Input marks1, marks2, marks3
STEP 3. aggregate = marks1 + marks2 + marks3
STEP 4. Print aggregate
STEP 5. End
18. What is the significance of iterative steps in an algorithm?
o Significance:
▪ Iterative steps allow the repetition of certain actions until a condition is met.
▪ They help in simplifying complex problems by breaking them down into repetitive tasks.
▪ Improve the efficiency of algorithms by reducing redundancy.
▪ Essential for tasks like searching, sorting, and processing data in loops.
▪ Enable handling of large datasets and continuous processes.
19. Describe the process of designing an algorithm to add hours and minutes.
o Process:
STEP 1. Start
STEP 2. Input hours1, minutes1
STEP 3. Input hours2, minutes2
STEP 4. total_minutes = minutes1 + minutes2
STEP 5. extra_hours = total_minutes / 60
STEP 6. remaining_minutes = total_minutes % 60
STEP 7. total_hours = hours1 + hours2 + extra_hours
STEP 8. Print total_hours, remaining_minutes
STEP 9. End
5 Marks Questions (15 questions)
1. Write a detailed algorithm to determine the winner in a coin-flipping game.
o Algorithm:
STEP 1. Start
STEP 2. Input the number of coin flips (n)
STEP 3. Initialize counters: player1_wins = 0, player2_wins = 0
STEP 4. For each flip from 1 to n:
▪ Flip the coin and get the result (heads or tails)
▪ If the result is heads, increment player1_wins
▪ If the result is tails, increment player2_wins
STEP 5. If player1_wins > player2_wins, then:
▪ Print "Player 1 wins"
STEP 6. Else if player2_wins > player1_wins, then:
▪ Print "Player 2 wins"
STEP 7. Else:
▪ Print "It's a tie"
STEP 8. End
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

2. Explain the importance of flowcharts in problem-solving.


o Importance of Flowcharts:
▪ Visual Representation: Provides a clear and visual way to understand the flow of a process.
▪ Simplifies Complex Processes: Breaks down complex processes into understandable parts.
▪ Identifies Bottlenecks: Helps in pinpointing inefficiencies or bottlenecks in a process.
▪ Facilitates Communication: Acts as a common language for team members from different
backgrounds.
▪ Example: A flowchart for a customer service process can help identify steps where delays
occur, improving efficiency.

3. Describe the algorithm for adding hours and minutes, including the necessary
conditionals.
o Algorithm:
STEP 1. Start
STEP 2. Input hours1, minutes1
STEP 3. Input hours2, minutes2
STEP 4. total_minutes = minutes1 + minutes2
STEP 5. extra_hours = total_minutes / 60
STEP 6. remaining_minutes = total_minutes % 60
STEP 7. total_hours = hours1 + hours2 + extra_hours
STEP 8. If total_hours >= 24, then:
▪ total_hours = total_hours % 24
STEP 9. Print total_hours, remaining_minutes
STEP 10. End
4. Write the pseudocode and draw the flowchart for calculating the area and perimeter
of a rectangle.
o Pseudocode:
INPUT length
INPUT width
COMPUTE area = length * width
COMPUTE perimeter = 2 * (length + width)
PRINT area
PRINT perimeter
o Flowchart:

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

5. Explain the importance of verifying algorithms with multiple examples.


o Importance:
▪ Ensures Correctness: Verification confirms that the algorithm produces the correct output
for various inputs.
▪ Identifies Edge Cases: Helps in discovering and handling edge cases that might not be
apparent initially.
▪ Improves Reliability: Builds confidence in the algorithm's reliability and robustness.
▪ Enhances Understanding: Multiple examples provide a deeper understanding of how the
algorithm works.
▪ Reduces Errors: Early detection of errors prevents issues later in the development process.
6. Write a detailed algorithm to classify numbers as "Single Digit," "Double Digit," or "Big."
o Algorithm:
STEP 1. Start
STEP 2. Input number
STEP 3. If number >= 0 and number <= 9, then:
▪ Print "Single Digit"
STEP 4. Else if number >= 10 and number <= 99, then:
▪ Print "Double Digit"
STEP 5. Else:
▪ Print "Big"
STEP 6. End
7. Describe the steps involved in writing an algorithm for the total water bill calculation.
o Steps:
STEP 1. Start
STEP 2. Input water consumption
STEP 3. If consumption <= 30, then:
▪ bill = consumption * 2
STEP 4. Else if consumption > 30 and <= 50, then:
▪ bill = (30 * 2) + ((consumption - 30) * 3)
STEP 5. Else:
▪ bill = (30 * 2) + (20 * 3) + ((consumption - 50) * 5)
STEP 6. Print bill
STEP 7. End
8. Explain the process of improving an algorithm that fails for certain inputs.
o Process:
STEP 1. Identify the inputs causing the failure.
STEP 2. Analyze the algorithm to understand why it fails for these inputs.
STEP 3. Modify the algorithm to handle these specific cases.
STEP 4. Test the modified algorithm with a variety of inputs.

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

STEP 5. Example: If a sorting algorithm fails for an array containing negative numbers,
modify the algorithm to include handling of negative values, then test it with arrays
containing negative numbers.
9. Write a detailed pseudocode to calculate the factorial of a number.
o Pseudocode:
INPUT number
IF number == 0 THEN
factorial = 1
ELSE
factorial = 1
FOR i FROM 1 TO number
factorial = factorial * i
PRINT factorial
10. Describe the process of writing an algorithm that accepts only positive integers up
to 100.
o Process:
STEP 1. Start
STEP 2. Input number
STEP 3. If number < 1 or number > 100, then:
▪ Print "Invalid input"
STEP 4. Else:
▪ Print "Valid input"
STEP 5. End
11. Explain the steps involved in designing an algorithm for a coin-flipping game with
detailed conditionals.
o Steps:
STEP 1. Start
STEP 2. Input the number of flips
STEP 3. Initialize counters for heads and tails
STEP 4. For each flip:
▪ If heads, increment heads counter
▪ If tails, increment tails counter
STEP 5. If heads counter > tails counter, then:
▪ Print "Heads win"
STEP 6. Else if tails counter > heads counter, then:
▪ Print "Tails win"
STEP 7. Else:
▪ Print "It's a tie"
STEP 8. End

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

12. Write a detailed algorithm to print all multiples of 5 between 10 and 25.
o Algorithm: STEP 1. Start
STEP 2. For number from 10 to 25:
▪ If number % 5 == 0, then:
▪ Print number
STEP 3. End
13. Describe the process of writing an algorithm to read the marks of three subjects and
calculate the percentage.
o Process: STEP 1. Start
STEP 2. Input marks for subject1, subject2, and subject3
STEP 3. total_marks = subject1 + subject2 + subject3
STEP 4. percentage = (total_marks / 300) * 100
STEP 5. Print percentage
STEP 6. End
14. Explain the significance of iterative and branching steps in algorithm design with
examples.
o Significance:
▪ Iterative Steps: Allow repetitive actions, simplifying the process of handling multiple data
elements. Example: Looping through an array to calculate the sum of its elements.
▪ Branching Ste: Enable decision-making by allowing different actions based on conditions.
Exapsmple:
rative
steps reducUsing if-else statements to handle different cases in a grading system.
▪ Enhance Efficiency: Itee redundancy, while branching steps handle diverse scenarios,
making the algorithm robust and efficient.
▪ Improve Clarity: Clearly defined iterative and branching steps make the algorithm easier
to understand and maintain.
▪ Adapt to Complex Problems: Combine iterative and branching steps to solve complex
problems by breaking them into manageable parts.
15. Explain the steps involved in Problem Solving.
1. Analysing the Problem:
o Understand the problem thoroughly before seeking a
solution.
o Carefully read and analyze the problem statement.
o List the principal components and decide the core
functionalities of the solution.
o Identify the inputs and expected outputs.
2. Developing an Algorithm:
o Devise a solution plan represented in natural language, called an algorithm.
o Refine the algorithm until it captures all aspects of the desired solution.
o Select the most suitable algorithm if multiple solutions are possible.
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

3. Coding:
o Convert the finalized algorithm into a format understood by the computer using a high-
level programming language.
o Record coding procedures and document the solution for future reference and maintenance.
4. Testing and Debugging:
o Test the program to ensure it meets user requirements and responds within the expected
time.
o Verify that the program generates correct output for all possible inputs.
o Fix any syntactical or logical errors encountered during testing.
o Follow standard testing methods like unit, integration, system, and acceptance testing to
ensure the software meets all business and technical requirements.
o Debug the program to rectify any defects found during testing.

16. Explain the characteristics of a good algorithm.


Characteristics of a good algorithm
• Precision — the steps are precisely stated or defined.
• Uniqueness — results of each step are uniquely defined and only depend on the input and
the result of the preceding steps.
• Finiteness — the algorithm always stops after a finite number of steps.
• Input — the algorithm receives some input.
• Output — the algorithm produces some output

EXERCISES (CHAPTER END QUESTIONS)


Question 1: Write pseudocode that reads two numbers and divides one by another and
displays the quotient.
Answer 1:
Start
Input number1
Input number2
If number2 is not 0, then
Set quotient = number1 / number2
Print quotient
Else
Print "Division by zero is not allowed."
End
Question 2: Two friends decide who gets the last slice of a cake by flipping a coin five
times. The first person to win three flips wins the cake. An input of 1 means player 1
wins a flip, and a 2 means player 2 wins a flip. Design an algorithm to determine who
takes the cake?

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Answer 2:
Start
Initialize player1_wins to 0
Initialize player2_wins to 0
For i from 1 to 5 do
Input flip_result
If flip_result is 1 then
Increment player1_wins
Else If flip_result is 2 then
Increment player2_wins
End If
If player1_wins is 3 then
Print "Player 1 wins the cake"
Exit
Else If player2_wins is 3 then
Print "Player 2 wins the cake"
Exit
End If
End For
End
Question 3: Write the pseudocode to print all multiples of 5 between 10 and 25
(including both 10 and 25).
Answer 3:
Start
For number from 10 to 25 do
If number mod 5 is 0 then
Print number
End If
End For
End
Question 4: Give an example of a loop that is to be executed a certain number of times.
Answer 4:
Start
For i from 1 to 10 do
Print "This is iteration number " + i
End For
End
Question 5: Suppose you are collecting money for something. You need ₹200 in all.
You ask your parents, uncles, and aunts as well as grandparents. Different people may
give either ₹10, ₹20, or even ₹50. You will collect till the total becomes 200. Write the
algorithm.
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Answer 5:
Start
Initialize total_collected to 0
While total_collected < 200 do
Input amount_given
If amount_given is 10 or 20 or 50 then
total_collected = total_collected + amount_given
End If
End While
Print "Total collected: " + total_collected
End
Question 6: Write the pseudocode to print the bill depending upon the price and
quantity of an item. Also print Bill GST, which is the bill after adding 5% of tax in the
total bill.
Answer 6:
Start
Input price
Input quantity
Set total_bill = price * quantity
Set gst = total_bill * 0.05
Set bill_gst = total_bill + gst
Print "Total Bill: " + total_bill
Print "Bill after GST: " + bill_gst
End
Question 7: Write pseudocode that will perform the following: a) Read the marks of
three subjects: Computer Science, Mathematics, and Physics, out of 100. b) Calculate
the aggregate marks. c) Calculate the percentage of marks.
Answer 7:
Start
Input computer_science_marks
Input mathematics_marks
Input physics_marks
Set aggregate_marks = computer_science_marks + mathematics_marks +
physics_marks
Set percentage_marks = (aggregate_marks / 300) * 100
Print "Aggregate Marks: " + aggregate_marks
Print "Percentage Marks: " + percentage_marks
End
Question 8: Write an algorithm to find the greatest among two different numbers
entered by the user.
Answer 8:
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Start
Input number1
Input number2
If number1 > number2 then
Print "The greatest number is " + number1
Else
Print "The greatest number is " + number2
End
Question 9: Write an algorithm that performs the following: Ask a user to enter a
number. If the number is between 5 and 15, write the word GREEN. If the number is
between 15 and 25, write the word BLUE. If the number is between 25 and 35, write
the word ORANGE. If it is any other number, write that ALL COLOURS ARE
BEAUTIFUL.
Answer 9:
Start
Input number
If number >= 5 and number <= 15 then
Print "GREEN"
Else If number > 15 and number <= 25 then
Print "BLUE"
Else If number > 25 and number <= 35 then
Print "ORANGE"
Else
Print "ALL COLOURS ARE BEAUTIFUL"
End
Question 10: Write an algorithm that accepts four numbers as input and find the
largest
and smallest of them.
Answer 10:
pseudocode
Copy code
Start
Input number1
Input number2
Input number3
Input number4
Set largest = number1
Set smallest = number1
If number2 > largest then
Set largest = number2
If number3 > largest then
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Set largest = number3


If number4 > largest then
Set largest = number4
If number2 < smallest then
Set smallest = number2
If number3 < smallest then
Set smallest = number3
If number4 < smallest then
Set smallest = number4
Print "Largest number is " + largest
Print "Smallest number is " + smallest
End
Question 11: Write an algorithm to display the total water bill charges of the month
depending upon the number of units consumed by the customer as per the following
criteria:
• for the first 100 units @ ₹5 per unit
• for next 150 units @ ₹10 per unit
• more than 250 units @ ₹20 per unit Also add meter charges of ₹75 per month
to calculate the total water bill.
Answer 11:
Start
Input units_consumed
Set meter_charges = 75
If units_consumed <= 100 then
total_bill = units_consumed * 5
Else If units_consumed <= 250 then
total_bill = (100 * 5) + ((units_consumed - 100) * 10)
Else
total_bill = (100 * 5) + (150 * 10) + ((units_consumed - 250) * 20)
End If
total_bill = total_bill + meter_charges
Print "Total Water Bill: " + total_bill
End
Question 12: What are conditionals? When are they required in a program?
Answer 12: Conditionals are statements that perform different actions based on
whether a given condition is true or false. They are required in a program to make
decisions and execute certain sections of code depending on specific conditions.

13. Match the pairs

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Question 14: Following is an algorithm for going to school or college. Can you suggest
improvements in this to include other options? Reach_School_Algorithm a) Wake up
b) Get ready c) Take lunch box d) Take bus e) Get off the bus f) Reach school or college
Answer 14:
Reach_School_Algorithm
a) Wake up
b) Get ready
c) Take lunch box
d) If going by bus then
Take bus
Get off the bus
Else If going by car then
Get in the car
Get out of the car
Else If walking then
Walk to school or college
End If
f) Reach school or college
Question 15: Write a pseudocode to calculate the factorial of a number. (Hint: Factorial
of 5, written as 5! = 5 × 4 × 3 × 2 × 1).
Answer 15:
Start
Input number
Set factorial = 1
For i from 1 to number do
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

factorial = factorial * i
End For
Print "Factorial of " + number + " is " + factorial
End
Question 16: Draw a flowchart to check whether a given number is an Armstrong
number. An Armstrong number of three digits is an integer such that the sum of the
cubes of its digits is equal to the number itself.
Answer 16:

Question 17: Following is an algorithm to classify numbers as “Single Digit”, “Double


Digit” or “Big”. Verify for (5, 9, 47, 99, 100, 200) and correct the algorithm if required.
Answer 17:
Classify_Numbers_Algo
INPUT Number
IF Number < 10 then
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Print "Single Digit"


Else If Number < 100 then
Print "Double Digit"
Else
Print "Big"
End If
Verification:
For 5, 9, 47, 99, 100, 200:
- 5 and 9 should be classified as "Single Digit"
- 47 and 99 should be classified as "Double Digit"
- 100 and 200 should be classified as "Big"
Question 18: For some calculations, we want an algorithm that accepts only positive
integers up to 100.
Accept_1to100_Algo
INPUT Number
IF (0 < Number) AND (Number <= 100) then
ACCEPT
Else
REJECT
End If
a) On what values will this algorithm fail? b) Can you improve the algorithm?
Answer 18: a) This algorithm will fail for the value 0 because 0 is not considered a
positive integer. b) Improved algorithm:
Accept_1to100_Algo
INPUT Number
IF (Number > 0) AND (Number <= 100) then
ACCEPT
Else
REJECT
End If

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

CHAPTER 5: GETTING STARTED WITH PYTHON


CHAPTER BLUEPRINT PLAN FOR FINAL EXAM
VSA 1 MARK SA 2 MARKS LA 3 MARKS E 5 MARKS
2 MCQ 1 1 2[ 1 HOT]
1 FIB
MCQ
1. What is a program in computer science?
a) A set of machine language instructions b) A collection of hardware components
c) An ordered set of instructions to be executed by a computer d) A highlevel language
Answer: c) An ordered set of instructions to be executed by a computer
2. Which language is called machine language?
a) Python b) C++ c) Assembly d) 0s and 1s Answer: d) 0s and 1s
3. What is source code?
a) Machine language code b) Highlevel language code
c) Assembly language code d) Hardware description Answer:b)Highlevel language code
4. Which of the following uses an interpreter?
a) C++ b) Assembly c) Python d) Machine language Answer: c) Python
5. Which quote is attributed to Donald Knuth in the textbook?
a) "Programming is fun." b) "Computer programming is an art."
c) "Machines are powerful." d) "Highlevel languages are easy."
Answer: b) "Computer programming is an art."
6. Which of the following is NOT a feature of Python?
a) High-level language b) Case sensitive c) Platform dependent
d) Rich library of predefined functions Answer: c) Platform dependent
7. What is the symbol for the Python prompt in interactive mode?
a) $ b) % c) & d) >>> Answer: d) >>>
8. What is the extension of Python source code files?
a) .java b) .py c) .exe d) .txt Answer: b) .py
9. Which mode in Python allows the execution of individual statements instantaneously?
a) Script mode b) Interactive mode c) Batch mode d) Compiled mode
Answer: b) Interactive mode
10. Which of the following is a Python keyword?
a) print b) import c) function d) main Answer: b) import
11. Which of the following is a valid identifier in Python?
a) 123abc b) abc123 c) a!bc d) None of these Answer: b) abc123
12. What is a variable in Python?
a) A reserved word b) A function c) An object uniquely identified by a name
d) A type of operator Answer: c) An object uniquely identified by a name

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

13. Which symbol is used for comments in Python?


a) // b) # c) @ d) & Answer: b) #
14. In Python, everything is treated as a(n):
a) Variable b) Function c) Object d) Keyword Answer: c) Object
15. Which function returns the identity of an object in Python?
a) id( ) b) identity( ) c) object_id( ) d) get_id( ) Answer: a) id( )
16. What are the two execution modes in Python?
a) Compiled and Interpreted b) Interactive and Script
c) Synchronous and Asynchronous d) Batch and Realtime Answer: b) Interactive and Script
17. Which of the following is NOT a feature of Python?
a) Free and open source b) Case sensitive c) Platform independent
d) Requires a compiler Answer: d) Requires a compiler
18. Which of the following is NOT a keyword in Python?
a) while b) assert c) print d) pass Answer: c) print
19. What is the output of the following Python code: `print("Hello, World!")`?
a) Hello, World! b) "Hello, World!"
c) print("Hello, World!") d) Syntax Error Answer: a) Hello, World!
20. Which of the following statements is true about Python?
a) Python is a low-level language. b) Python is case sensitive.
c) Python cannot be used for web development. d) Python uses a compiler for execution.
Answer: b) Python is case sensitive.
21. What is the correct syntax for a single line comment in Python?
a) // This is a comment b) /* This is a comment */
c) # This is a comment d) < This is a comment > Answer: c) # This is a comment
22. Which of the following is NOT a Python data type?
a) Integer b) String c) Boolean d) Character Answer: d) Character
23. How do you create a variable in Python?
a) Using the var keyword b) By simply assigning a value to it c) Using the let keyword
d) By declaring it first Answer: b) By simply assigning a value to it
24. Which of the following is used for indentation in Python?
a) Curly braces b) Parentheses c) Tabs or spaces d) Semicolons
Answer: c) Tabs or spaces
25. What will be the output of the following code: `print(2 + 3 * 4)`?
a) 20 b) 14 c) 24 d) 12 Answer: b) 14
26. Which Python function is used to get input from the user?
a) input( ) b) read( ) c) scanf( ) d) get_input( ) Answer: a) input( )
27. What does the following Python code do: `name = input("Enter your name: ")`?
a) Prints "Enter your name: " d) Generates a syntax error
b) Assigns the string "Enter your name: " to the variable name
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

c) Prompts the user to enter their name and stores it in the variable name
Answer: c) Prompts the user to enter their name and stores it in the variable name
28. Which of the following is an invalid variable name in Python?
a) var1 b) _var c) 1var d) var_1 Answer: c) 1var
29. What is the output of the following code: `print(10 / 3)`?
a) 3.3333333333333335 b) 3 c) 3.0 d) 10 Answer: a) 3.3333333333333335
30. Which of the following is NOT an arithmetic operator in Python?
a) + b) / c) * d) && Answer: d) &&
31. What is the correct way to create a string in Python?
a) `string s = "Hello"` b) `s = 'Hello'` c) `s = Hello`
d) `string s = 'Hello'` Answer: b) `s = 'Hello'`
32. Which of the following methods can be used to convert a string to a list in Python?
a) list( ) b) split( ) c) convert( ) d) str( ) Answer: b) split( )
33. Which of the following is NOT a valid Python data type?
a) List b) Tuple c) Dictionary d) Array Answer: d) Array
34. What is the output of the following code: `print("Hello" + " " + "World")`?
a) Hello World b) HelloWorld c) "Hello World" d) Hello + World
Answer: a) Hello World
35. Which operator is used for exponentiation in Python?
a) ^ b) ** c) exp( ) d) pow( ) Answer: b)
36. Which of the following is a mutable data type in Python?
a) String b) Tuple c) List d) Integer Answer: c) List
37. What is the output of the following code: `print(2**3)`?
a) 5 b) 6 c) 8 d) 9 Answer: c) 8
38. Which function is used to read input from the user in Python 3.x?
a) input( ) b) raw_input( ) c) scan( ) d) read( ) Answer: a) input( )
39. Which of the following statements will create a tuple in Python?
a) t = [1, 2, 3] b) t = {1, 2, 3} c) t = (1, 2, 3) d) t = 1, 2, 3 Answer: c) t = (1, 2, 3)
40. What is the output of the following code: `print(type([ ]))`?
a) <class 'tuple'> b) <class 'list'> c) <class 'set'> d) <class 'dict'> Answer: b) <class 'list'>
41. Which of the following operators is used for string concatenation in Python?
a) + b) & c) . d) concat() Answer: a) +
42. What is the correct way to declare a variable in Python?
a) var x = 5 b) x := 5 c) int x = 5 d) x = 5 Answer: d) x = 5
43. What will be the output of the following code: `print(10 % 3)`?
a) 1 b) 3 c) 10 d) 0.3 Answer: a) 1
44. Which method is used to remove an item from a list in Python by its value?
a) remove( ) b) pop( ) c) delete( ) d) discard( ) Answer: a) remove( )
45. What is the output of the following code: `print(5 == 5)`?
a) True b) False c) Syntax Error d) 5 Answer: a) True
46. Which method can be used to convert a list into a tuple in Python?
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

a) tuple( ) b) list_to_tuple( ) c) to_tuple( ) d) convert( ) Answer: a) tuple ( )

47. Which of the following is used to define a block of code in Python?


a) Indentation b) Curly braces c) Parentheses d) Square brackets Answer: a) Indentation
48. Which function is used to get the type of an object in Python?
a) type( ) b) isinstance( ) c) id( ) d) obj_type( ) Answer: a) type( )
FILL-IN THE BLANK (SAMPLE).
1. Python is an example of a _______-level programming language. (high)
2. In Python, strings are enclosed in _______ or _______. (single, double)
3. Python's core data types include _______, ______, and _______.(integers, floats, strings)
4. _______ are used to document Python functions and modules. (doc strings)
5. Python uses _______ to indicate a block of code. (Indentation)
6. _______ are objects in Python that cannot be changed after assignment. (tuples)
2-Mark Questions
1. What is a programming language?
A programming language is a language used to specify a set of instructions to a computer to
carry out a specific task.
2. Define a program.
A program is an ordered set of instructions to be executed by a computer to carry out a
specific task.
3. What is machine language?
Machine language, also known as low-level language, is the language of 0s and 1s that is
directly understood by the computer.
4. What is the difference between high-level language and machine language?
High-level languages are easier for humans to write and understand, whereas
machine language is composed of binary code (0s and 1s) and is directly understood by the
computer.
5. Name any two high-level programming languages.
Python and Java.
6. What is source code?
Source code is a program written in a high-level language.
7. What is the role of a compiler?
A compiler translates the entire source code into machine language as a whole and generates
error messages if any.
8. What is the role of an interpreter?
An interpreter processes program statements one by one, translating and executing them until
an error is encountered or the program is successfully executed.
9. Define Python as a high-level language.
Python is a high-level, interpreted, and case-sensitive programming language known for its
readability and simplicity.
10. What does it mean that Python is an interpreted language?
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Python being an interpreted language means that its programs are executed by an interpreter,
which processes each statement one by one.
11. How does Python handle case sensitivity?
Python is case-sensitive, meaning identifiers like NUMBER and number would be
considered different.
12. Mention any two features of Python.
Python is portable and platformindependent, and it has a rich library of predefined functions.
13. What is the extension of a Python script file?
The extension of a Python script file is .py.
14. Explain the interactive mode in Python.
In interactive mode, individual statements can be executed instantaneously, and results are
displayed immediately.
15. What is script mode in Python?
In script mode, a Python program is written in a file, saved, and then executed as a whole.
16. What are Python keywords?
Python keywords are reserved words that have specific meanings to the interpreter and
cannot be used as identifiers.
17. Define identifiers in Python.
Identifiers are names used to identify variables, functions, or other entities in a program.
18. What are variables in Python?
Variables in Python are names that refer to objects stored in memory.
19. How are comments added in Python?
Comments in Python are added using the # symbol; everything following the # till the end of
the line is treated as a comment.
20. What is an object in Python?
An object in Python is an instance of a data type that has a unique identity, attributes, and
behaviour.
21. What is implicit conversion?
Implicit conversion is the automatic conversion of one data type to another by the interpreter.
22. What is explicit conversion?
Explicit conversion is the manual conversion of one data type to another using functions like
int(), float(), str(), etc.
3-Mark Questions
1. Explain the process of program execution in Python using an interpreter.
o Python uses an interpreter to execute programs. The interpreter processes the program
statements one by one, translating and executing each statement sequentially until an error
is encountered or the entire program is executed. If an error occurs, execution stops. This
contrasts with a compiler, which translates the entire source code into object code before
execution .

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

2. What is the significance of the Python prompt >>>?


o The >>> prompt in Python indicates that the interpreter is ready to accept instructions. This
prompt is displayed in the Python interactive mode, also known as the Python shell, where
users can type commands or statements to be executed immediately .
3. Describe the use of indentation in Python.
o Indentation in Python is used to define the blocks of code. Unlike other programming
languages that use braces or keywords, Python relies on indentation levels to group
statements. Consistent indentation is crucial because it directly affects the program's
structure and execution .
4. Explain the concept of 'interactive mode' with an example.
o Interactive mode in Python allows users to type and execute Python commands directly at
the >>> prompt. This mode is useful for testing and debugging code snippets.
For example:>>> print("Hello, World!")
Hello, World!
This command is executed immediately, and the result is displayed on the screen .
5. What are the rules for naming an identifier in Python?
o Identifiers in Python must follow these rules:
1. Must start with a letter (a-z, A-Z) or an underscore (_).
2. Can contain letters, digits (0-9), and underscores.
3. Cannot start with a digit.
4. Python keywords cannot be used as identifiers.
5. Identifiers are case-sensitive .
6. Explain with an example how variables are declared in Python.
o Variables in Python are declared by assigning a value to a name.
For example:
x = 10
name = "Alice"
Here, x is an integer variable with a value of 10, and name is a string variable with a value of
"Alice" .
7. How does Python handle data types?
o Python handles data types dynamically, meaning variables do not need to be declared with
a specific type. Python supports various data types, including integers, floats, strings, lists,
tuples, dictionaries, and sets. The type of a variable is determined at runtime based on the
value assigned to it .
8. Describe the purpose of comments in a Python program.
o Comments in Python are used to document the code and make it easier to understand. They
are ignored by the interpreter and can be single-line comments starting with # or multi-
line comments enclosed in triple quotes (''' or """). Comments help explain the logic and
purpose of the code, making it easier to maintain and collaborate with others .

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

9. Explain the significance of the id() function in Python.


o The id() function in Python returns the unique identity (memory address) of an object. This
identity is guaranteed to be unique and constant for the object during its lifetime. The id( )
function is useful for understanding the object's behavior and identity management in
memory .
10. Differentiate between None and False in Python keywords.
o None is a special constant in Python representing the absence of a value or a null value. It
is often used to signify that a variable has no value. False, on the other hand, is a Boolean
value indicating the logical false. It is used in logical operations and comparisons. While
None and Falseare distinct, both can be used in condition checks where None evaluates to
False in a Boolean context .
11. What is meant by 'Python is platform-independent'?
o Python is considered platform-independent because Python programs can run on various
operating systems without modification. This is possible because Python code is
interpreted, and the Python interpreter abstracts the underlying platform details. As long as
the system has a compatible Python interpreter installed, the same Python code can run on
Windows, macOS, Linux, and other platforms .
12. Describe how Python uses indentation for blocks and nested blocks.
o In Python, indentation is used to define the scope of loops, functions, and other constructs.
Consistent indentation levels indicate a block of code. For nested blocks, each new block is
indented further, usually by four spaces. This indentation helps Python understand the
grouping of statements, replacing the need for braces or keywords used in other languages .
13. Explain the term 'portable' in the context of Python.
o The term 'portable' in the context of Python refers to the ability to write Python code that
can run on different operating systems and environments without requiring changes. Python
achieves portability through its interpreter, which handles platform-specific details,
allowing the same code to execute on any system with a compatible Python interpreter .
14. What are Python libraries and why are they important?
o Python libraries are collections of modules and packages that provide pre-written code to
perform common tasks. They are important because they save developers time and effort by
offering reusable code for various functionalities, such as data manipulation, web
development, machine learning, and more. Popular Python libraries include NumPy,
Pandas, Matplotlib, and TensorFlow .
15. Describe how to download and install Python.
o To download and install Python:
1. Visit the official Python website (https://www.python.org/).
2. Download the installer for your operating system.
3. Run the installer and follow the on-screen instructions.
4. Ensure that the option to add Python to the system PATH is selected.
5. Verify the installation by opening a command prompt or terminal and typing python --
version .
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

16. What is meant by 'Python is free and open source'?


o Python being 'free and open source' means that it is freely available for anyone to use,
modify, and distribute. The source code of Python is openly accessible, allowing developers
to contribute to its development and customize it as needed. This openness fosters a large
and active community that continually improves the language and its ecosystem .
5-Mark Questions
1. Discuss the differences between a compiler and an interpreter.
o Translation Unit: A compiler translates the entire source code into machine code at once,
while an interpreter translates one statement at a time.
o Execution Speed: Compiled programs generally run faster because the translation happens
before execution. Interpreted programs run slower as each instruction is translated
during execution.
o Error Detection: Compilers detect errors in the entire program during the compilation
stage, while interpreters detect errors line by line, making it easier to debug incrementally.
o Intermediate Code: Compilers generate an intermediate object code that can be executed
later, while interpreters do not produce an intermediate code.
o Usage: Interpreters are often used for scripting and testing because of their immediate
feedback, whereas compilers are used for production software due to their efficiency.
2. Discuss the various features of Python that make it a preferred language for
beginners.
o Simplicity: Python's syntax is clear and readable, making it easy to learn and write code.
o Interpreted Language: Python's interactive mode allows beginners to test code snippets and
see results immediately, facilitating learning.
o Extensive Libraries: Python has a rich set of libraries and frameworks that support various
tasks such as web development, data analysis, and machine learning.
o Community Support: Python has a large and active community that provides extensive
resources, tutorials, and documentation, aiding beginners in learning.
o Versatility: Python can be used for a wide range of applications, from simple scripting to
complex web applications, making it a valuable skill for beginners.
3. Explain the concept of 'everything is an object' in Python with examples.
o Object-Oriented: In Python, every value is an object, and each object has a type, known as
its class. This applies to numbers, strings, functions, classes, and even modules.
o Integers as Objects: For example, when you create an integer a = 5, a is an object of type
int.
o Strings as Objects: Similarly, when you create a string s = "Hello", s is an object of type
str.
o Functions as Objects: Functions in Python are objects too. For example, def func(): pass
defines a function func which is an object of type function.
o Modules as Objects: Modules are objects as well. When you import a module like import
math, the math module is an object of type module.

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

4. Explain the different data types available in Python with examples.


o Integers: Whole numbers, e.g., x = 10.
o Floats: Decimal numbers, e.g., y = 10.5.
o Strings: Text data, enclosed in quotes, e.g., name = "Alice".
o Lists: Ordered collections of items, e.g., my_list = [1, 2, 3, "apple"].
o Dictionaries: Collections of key-value pairs, e.g., my_dict ={"key1": "value1", "key2":
"value2"}.
o Tuples: Immutable ordered collections, e.g., my_tuple = (1, 2, 3).
o Sets: Unordered collections of unique items, e.g., my_set = {1, 2, 3}.
o Booleans: True or False values, e.g., is_valid = True.
5. Discuss the significance of Python in the context of modern programming and software
development.
o Versatility: Python's ability to handle various domains such as web development, data
science, artificial intelligence, and automation makes it highly versatile.
o Productivity: Python's simple syntax and readability contribute to faster development and
reduced maintenance costs.
o Community and Support: Python's large community and extensive libraries provide robust
support and resources for developers.
o Adoption in Industry: Many leading companies and organizations use Python for their
development needs, enhancing its credibility and demand in the job market.
o Educational Tool: Python's simplicity and ease of learning make it an excellent language
for teaching programming in schools and universities.
6. Explain the use of comments in Python with examples and describe their importance.
o Single-line Comments: Use the # symbol, e.g., # This is a comment.
o Multi-line Comments: Use triple quotes, e.g., ''' This is a multiline comment '''.
o Documentation: Comments help in documenting the code, explaining what specific blocks
or lines of code do.
o Debugging: Comments can be used to temporarily disable code for debugging purposes.
o Collaboration: Comments are essential for collaborative projects as they help team
members understand each other's code.
7. Describe the rules for naming identifiers in Python and explain why these rules are
important.
o Start with a Letter or Underscore: Identifiers must begin with a letter (a-z, A-Z) or an
underscore (_).
o Contain Letters, Digits, or Underscores: Subsequent characters can be letters, digits (0-9),
or underscores.
o Case-sensitive: Identifiers are case-sensitive, meaning Var and var are different.
o No Keywords: Keywords cannot be used as identifiers, e.g., def, class, etc.
o Meaningful Names: Using meaningful names makes the code more readable and
maintainable.
o Avoid Confusion: Following these rules prevents errors and makes the code easier to
understand and maintain.
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

8. Explain the concept of high-level and low-level programming languages and their
differences.
o High-level Languages: These languages are closer to human languages and abstract away
most of the hardware details. Examples include Python, Java, and C++.
o Low-level Languages: These languages are closer to machine code and provide little
abstraction from the hardware. Examples include Assembly and Machine Code.
o Ease of Use: High-level languages are easier to learn and use, while low-level languages
require more detailed knowledge of the hardware.
o Portability: High-level languages are generally more portable across different hardware
platforms, whereas low-level languages are specific to a particular type of hardware.
o Performance: Programs written in low-level languages can be more efficient and faster
but are more complex to write and maintain compared to high-level languages.
9. Discuss the use of Python in web development and provide examples of popular web
services built with Python.
o Frameworks: Python has powerful web frameworks like Django and Flask that simplify
web development.
o Backend Development: Python is widely used for server-side programming, handling
requests, and connecting to databases.
o APIs: Python is commonly used to develop RESTful APIs, facilitating
communication between different parts of a web service.
o Popular Web Services: Examples of popular web services built with Python include
Instagram, Pinterest, and Dropbox.
o Integration: Python can easily integrate with other technologies and services, making it a
versatile choice for web development.
10. Explain with examples the different types of operators available in Python.
o Arithmetic Operators: Used for mathematical operations, e.g., +
(addition), - (subtraction), * (multiplication), / (division).
x = 10 + 5 # 15
y = 10 - 5 # 5
o Comparison Operators: Used to compare values, e.g., == (equal to),
!= (not equal to), > (greater than).
a=5
b = 10
result = (a == b) # False
o Logical Operators: Used to combine conditional statements, e.g., and,
or, not.
x = True
y = False
result = x and y # False
o Assignment Operators: Used to assign values to variables, e.g., =, +=, -=.
a=5
a += 3 # 8
o Bitwise Operators: Used to perform bit-level operations, e.g., &
(AND), | (OR), ^ (XOR).
a = 10 # 1010 in binary
b = 4 # 0100 in binary result = a & b # 0000 (0 in decimal)
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

11. Discuss the role of Python in education and why it is a good choice for learning
programming.
o Ease of Learning: Python's simple and readable syntax makes it an excellent choice for
beginners.
o Versatility: Python can be used for various applications, from web development to data
science, providing a broad learning experience.
o Active Community: Python's large and active community offers extensive resources,
tutorials, and support for learners.
o Immediate Feedback: Python's interactive mode allows learners to test code snippets and
receive immediate feedback, facilitating learning.
o Real-world Applications: Learning Python provides practical skills that are in high
demand in the job market, enhancing career prospects.
12. Explain various types of Errors.
o Syntax Errors: Errors in the structure of the code, such as missing colons, parentheses, or
incorrect indentation.
o Runtime Errors: Errors that occur during program execution, such as division by zero or
accessing a variable that has not been defined.
o Logical Errors: Errors in the logic of the code that produce incorrect results, even though
the code runs without crashing.
EXERCISES (CHAPTER END QUESTIONS)
Question 1
Which of the following identifier names are invalid and why?
1. Serial_no.
2. 1st_Room
3. Hundred$
4. total-Marks
5. True
Answer:
• Identifier name can’t contain dot.
• 1st_Room: Invalid because identifiers cannot start with a digit.
• $ symbol is special character that can’t be part of an identifier name.
• total-Marks: Invalid because identifiers cannot contain hyphens (-).
• True: Invalid because True is a keyword in Python and cannot be used as an identifier.
Question 2
Write the corresponding Python assignment statements:
1. Assign 10 to variable length and 20 to variable breadth.
2. Assign the average of values of variables length and breadth to a variable sum.
3. Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.
4. Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first,
middle and last.
5. Assign the concatenated value of string variables first, middle and last to
variable fullname. Make sure to incorporate blank spaces appropriately between
different parts of names.
Answer:
1. length = 10
breadth = 20
2. sum = (length + breadth) / 2
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

3. stationery = ['Paper', 'Gel Pen', 'Eraser']


4. first = 'Mohandas'
middle = 'Karamchand'
last = 'Gandhi'
5. fullname = first + ' ' + middle + ' ' + last
Question 3
Write logical expressions corresponding to the following statements in Python and
evaluate the expressions (assuming variables num1, num2, num3, first, middle,
last are already having meaningful values):
1. The sum of 20 and –10 is less than 12.
2. num3 is not more than 24.
3. 6.75 is between the values of integers num1 and num2.
4. The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.
5. List Stationery is empty.
Answer:
1. (20 + -10) < 12 # True
2. num3 <= 24
3. num1 < 6.75 < num2
4. first < middle < last
5. len(stationery) == 0
Question 4
Add a pair of parentheses to each expression so that it evaluates to True.
1. 0 == 1 == 2
2. 2 + 3 == 4 + 5 == 7
3. 1 < -1 == 3 > 4
Answer:
1. (0 == 1) == 2 # False == 2, which is False
2. (2 + 3) == (4 + 5) == 7 # 5 == 9 == 7, which is False
3. (1 < -1) == (3 > 4) # False == False, which is True
Question 5
Write the output of the following:
1.
num1 = 4
num2 = num1 + 1
num1 = 2
print(num1, num2)
2.
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print(num1, num2)
3.

DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print(num1, num2, num3)
Answer:
1. 2 5
2. 6 4
3. This code will result in an error because num3 is not defined.
Question 6
Which data type will be used to represent the following data values and why?
1. Number of months in a year
2. Resident of Delhi or not
3. Mobile number
4. Pocket money
5. Volume of a sphere
6. Perimeter of a square
7. Name of the student
8. Address of the student
Answer:
1. int - The number of months is a whole number.
2. bool - It is a binary state (True or False).
3. str - Mobile numbers can contain leading zeros and are not used for calculations.
4. float - Pocket money can have decimal values.
5. float - Volume can be a decimal value.
6. float - Perimeter can be a decimal value.
7. str - Names are textual data.
8. str - Addresses are textual data.
Question 7
Give the output of the following when num1 = 4, num2 = 3, num3 = 2:
1. += num2 + num3
print(num1)
2. num1 = num1 ** (num2 + num3)
print(num1)
3. num1 **= num2 + num3
4. num1 = '5' + '5'
print(num1)
5. print(4.00 / (2.0 + 2.0))
6. num1 = 2 + 9 * ((3 * 12) - 8) / 10
print(num1)
7.
num1 = 24 // 4 // 2
print(num1)
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

8. num1 = float(10)
print(num1)
9. num1 = int('3.14')
print(num1)
10. print('Bye' == 'BYE')
11. print(10 != 9 and 20 >= 20)
12. print(10 + 6 * 2 ** 2 != 9 // 4 - 3 and 29 >= 29 / 9)
13. print(5 % 10 + 10 < 50 and 29 <= 29)
14. print((0 < 6) or (not(10 == 6) and (10 < 0)))
Answer:
1. 9
2. 4096
3. 4096
4. 55
5. 1.0
6. 25.4
7. 3
8. 10.0
9. Error (cannot convert '3.14' to an integer)
10. False
11. True
12. True
13. True
14. True
Question 8
Categorise the following as syntax error, logical error or runtime error:
1. 25 / 0
2. num1 = 25; num2 = 0; num1/num2
Answer:
1. Runtime error (division by zero)
2. Runtime error (division by zero)
Question 9
A dartboard of radius 10 units and the wall it is hanging on are represented using a two-
dimensional coordinate system, with the board’s center at coordinate (0,0). Variables x and
y store the x-coordinate and the y-coordinate of a dart that hits the dartboard. Write a
Python expression using variables x and y that evaluates to True if the dart hits (is within)
the dartboard, and then evaluate the expression for these dart coordinates:
1. (0,0)
2. (10,10)
3. (6, 6)
4. (7,8)
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

Answer:
(x**2 + y**2) <= 100
1. True (0,0 is at the center)
2. False (10,10 is outside the dartboard)
3. True (6,6 is within the dartboard)
4. True (7,8 is within the dartboard)
Question 10
Write a Python program to convert temperature in degree Celsius to degree Fahrenheit. If
water boils at 100 degree C and freezes at 0 degree C, use the program to find out what is
the boiling point and freezing point of water on the Fahrenheit scale.
Answer:
boiling_point_C = 100
freezing_point_C = 0
# Conversion formula: F = C * 9/5 + 32
boiling_point_F = boiling_point_C * 9/5 + 32
freezing_point_F = freezing_point_C * 9/5 + 32
print(f"Boiling point of water: {boiling_point_F}°F")
print(f"Freezing point of water: {freezing_point_F}°F")Output:
Boiling point of water: 212.0°F
Freezing point of water: 32.0°F
Question 11
Write a Python program to calculate the amount payable if money has been lent
on simple interest. Principal or money lent = P, Rate of interest = R% per annum
and Time = T years. Then Simple Interest (SI) = (P x R x T)/ 100. Amount payable
= Principal + SI. P, R and T are given as input to the program.
Answer:
P = float(input("Enter the principal amount: "))
R = float(input("Enter the rate of interest: "))
T = float(input("Enter the time in years: "))
SI = (P * R * T) / 100
amount_payable = P + SI
print(f"Simple Interest: {SI}")
print(f"Amount Payable: {amount_payable}")
Question 12
Write a program to calculate in how many days a work will be completed by three
persons A, B and C together. A, B, C take x days, y days and z days respectively
to do the job alone. The formula to calculate the number of days if they work
together is xyz/(xy + yz + xz) days where x, y, and z are given as input to the program.
Answer:
x = float(input("Enter the number of days A takes to complete the work: "))
y = float(input("Enter the number of days B takes to complete the work:"))
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

z = float(input("Enter the number of days C takes to complete the work: "))


total_days = (x * y * z) / (x * y + y * z + x * z)
print(f"The work will be completed in {total_days} days if A, B, and C work together.")
Question 13
Write a program to enter two integers and perform all arithmetic operations on them.
Answer:
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")
print(f"Modulus: {a % b}")
print(f"Exponentiation: {a ** b}")
print(f"Floor Division: {a // b}")
Question 14
Write a program to swap two numbers using a third variable.
Answer:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
temp = a
a=b
b = temp
print(f"After swapping: a = {a}, b = {b}")
Question 15
Write a program to swap two numbers without using a third variable.
Answer:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Question 16
Write a program to repeat the string "GOOD MORNING" n times. Here ‘n’ is
an integer entered by the user.
Answer:
n = int(input("Enter the number of times to repeat the string: "))
result = "GOOD MORNING " * n
print(result)
Question 17
Write a program to find average of three numbers.
Answer:
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
average = (num1 + num2 + num3) / 3
print(f"The average of the three numbers is {average}")
Question 18
Write a Python program to find the volume of spheres with radius 7cm, 12cm,
16cm, respectively.
Answer:
import math
# Input from the user for three spheres (assuming fixed number)
radius1 = float(input("Enter the radius of sphere 1 in cm: "))
radius2 = float(input("Enter the radius of sphere 2 in cm: "))
radius3 = float(input("Enter the radius of sphere 3 in cm: "))
# Calculating and printing volumes for each sphere
volume1 = (4/3) * math.pi * radius1**3
volume2 = (4/3) * math.pi * radius2**3
volume3 = (4/3) * math.pi * radius3**3
# Printing the volumes
print(f"The volume of a sphere with radius {radius1} cm is {volume1} cubic cm")
print(f"The volume of a sphere with radius {radius2} cm is {volume2} cubic cm")
print(f"The volume of a sphere with radius {radius3} cm is {volume3} cubic cm")
Question 19
Write a program that asks the user to enter their name and age. Print a message
addressed to the user that tells the user the year in which they will turn 100 years old.
Answer:
import datetime
name = input("Enter your name: ")
age = int(input("Enter your age: "))
current_year = datetime.datetime.now().year
year_turning_100 = current_year + (100 - age)
print(f"Hello, {name}! You will turn 100 years old in the year
{year_turning_100}.")
Question 20
The formula E=mc2
states that the equivalent energy (E) can be calculated as the
mass (m) multiplied by the speed of light (c = about 3×1083 \times 10^83×108 m/s)
squared. Write a program that accepts the mass of an object and determines its
energy.
Answer:
c = 3 * 10**8 # speed of light in m/s
DILIP KUMAR H A
PRAGATHI CO-ED PU COLLEGE, Vijayapura INTRODUCTION TO PROBLEM SOLVING

mass = float(input("Enter the mass of the object in kg: "))


energy = mass * c**2
print(f"The energy equivalent of the mass is {energy} joules.")
Question 21
Presume that a ladder is put upright against a wall. Let variables length and angle
store the length of the ladder and the angle that it forms with the ground as it
leans against the wall. Write a Python program to compute the height reached by
the ladder on the wall for the following values of length and angle:
1. 16 feet and 75 degrees
2. 20 feet and 0 degrees
3. 24 feet and 45 degrees
4. 24 feet and 80 degrees
Answer:
#import the math module, to use sin & radians function
import math
length = int(input("Enter the length of the ladder: "))
degrees = int(input("Enter the alignment degree: "))
#Converting degrees to radian
radian = math.radians(degrees)
#Computing sin value
sin = math.sin(radian)
# Calculating height and rounding it off to 2 decimal places
height = round(length * sin,2)
#displaying the output
print("The height reached by ladder with length",length,"feet and
aligned at",degrees,"degrees is",height, "feet.")
*************

DILIP KUMAR H A

You might also like