[go: up one dir, main page]

0% found this document useful (0 votes)
46 views11 pages

Lec 02 Variable Sequence

The document discusses problem solving through algorithms. It begins by defining problem solving as following a structured procedure to find a solution. The steps of the problem solving process are then outlined as analysis, design, implementation, and testing. Examples are given of converting decimal to binary using this process. Key aspects of problem solving discussed include taking an iterative approach and starting with specific solutions that can later be generalized. Common algorithm building blocks like sequences, conditionals, and loops are introduced. Finally, two examples of algorithms to convert age to days and calculate factorials are presented using pseudo code, flow charts, and actual code.

Uploaded by

uh2683505
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)
46 views11 pages

Lec 02 Variable Sequence

The document discusses problem solving through algorithms. It begins by defining problem solving as following a structured procedure to find a solution. The steps of the problem solving process are then outlined as analysis, design, implementation, and testing. Examples are given of converting decimal to binary using this process. Key aspects of problem solving discussed include taking an iterative approach and starting with specific solutions that can later be generalized. Common algorithm building blocks like sequences, conditionals, and loops are introduced. Finally, two examples of algorithms to convert age to days and calculate factorials are presented using pseudo code, flow charts, and actual code.

Uploaded by

uh2683505
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/ 11

Recape : Lecture 01

1. Problem-Solving:
- Q: How do we solve a problem?
- Ans: Follow a structured procedure to find a solution. For example, consider the task of
converting Decimal to Binary; our goal is to find the solution.
2. Steps for Computing Problem-Solving:
a. Analysis:
- Understand the problem, focusing on Decimal to Binary conversion.
1. Define inputs and outputs.
a. Prompt the user for input and display the output.
User input: "Enter the decimal number: 22"
Binary equivalent: "(100110)₂"
2. Determine if the number is positive or negative.
3. Identify if it is a whole or decimal number.
4. Establish the logic for decimal to binary conversion.
b. Design:
- Outline potential solutions using pseudo-code or a flowchart.
a. Take the user's decimal input.
b. Divide by 2; record quotient and remainder.
c. Repeat the process on the quotient until it's zero.
d. Write the remainders in reverse order to form the final
result.
c. Implementation:
- Convert the chosen solution into actual C/C++ code.
#include <iostream>
using namespace std;
int main() {
int num, array[10], k = 0, n;
cout << "Enter any number greater than 0:";
cin >> num;
while (num > 0)
{
array[k] = num % 2;
num = num / 2;
k++;
}
cout << "Binary representation of the entered number is:";
for (n = k - 1; n >= 0; n--)
{
cout << array[n];
}
}

d. Test:
- Evaluate the implemented solution with different inputs/data. If satisfactory, it's okay;
otherwise, go back to steps 1 to 4 for further refinement.
• Property of problem-solving process/ Key Aspects of Problem-Solving

a. Iterative Approach:
• Repeatedly go through analysis, design, implementation, and testing phases.
• A repetitive process involving exploration/Search and discovery.

b. From Specific to General Solutions:


• Start by solving for positive whole numbers in the decimal to binary conversion.
• If successful, extend the solution to cover both positive and negative real
numbers (handle negative numbers by finding the binary of the corresponding
positive real number and taking its two's complement).

c. Experience Matters:
o Skillful solution to the problem selection based on analysis and experience:

o Selection of the most suitable algorithm by considering runtime analysis.


(Sorting)
o Reuse existing solutions:
o Solutions developed for one problem (e.g., calculating the area of a
circle) can be applied to solve related problems (e.g., finding the area
of a ring).

The solution to the problem is also called an Algorithm (as the results of analysis and
design)
• Algorithm: (Resulting from Analysis and Design)

Sequence of steps that can be taken to solve a given problem”


“[precise] Sequence of [finite] steps that can be taken to solve a given problem

Steps:
- Break down into smaller steps or subtasks.
- For instance, the detailed steps to move from one point to another.

Sequence
- A precisely ordered set of steps to solve a particular problem.
- For example, consider the algorithm for frying an egg (or converting binary to
decimal)
- Heat a frying pan by pouring oil into it.
- Crack the egg and place it in the frying pan.
- Cook the egg until it is fried.

• Examples of Algorithm:
o Decimal to binary conversion
o Sorting (Bubble sort)
o Searching (binary search)

• Algorithm Representation: Software developers convey algorithms through


three distinct forms:

a. Pseudo Code - Visualizing Actual Code:


• It closely resembles actual code.
• Advantages: Nearly a programming language, making the transition from
natural language to actual code easier.

• Disadvantages: Lack of standardization; developers must establish their


conventions for elements like input, output, and variable names to ensure code
comprehension.

b. Flow Charts - Graphical Solutions Representation:


• Visual diagrams depicting the algorithm's flow.
• Advantages: More accessible, particularly for those without programming
expertise.
• Disadvantages: Can become unwieldy as the algorithm grows in complexity.

c. Actual Code: - Implementation using a programming language like C.


- Each representation has its own merits and drawbacks.
Lecture 2:
• Algorithm building blocks: All categories of Algorithmic/programming problems
can be addressed by employing any one of the following elements or their
combinations.

1. Sequence: A direct execution of steps in a specified order.


a. For instance, consider the task of taking your age in years as input and
displaying it in days. In this scenario, we rely solely on a sequence of
steps to accomplish the task.
2. Conditionals
a. Real world example: Toss a coin; if it lands heads, proceed with the
task; otherwise, do not.
b. Example: [If a number is negative, convert it to its binary
representation and then take its 2’s complement.]
3. Loops
a. Real world example: [Continue filling the tank until it reaches full
capacity.]
b. Example: [Divide the number by 2 repeatedly until it becomes zero.
Problem statement: Develop an algorithm that converts the input of years into its
equivalent value in days.

Sample execution
Enter your age: 2
Age in days = 730

Pseudo code Flow chart Actual code


#include <iostream>

using namespace std;

Start int main()


integer age, ans {
int age;
print "Enter your age:" cout << "Enter your age: ";

input age // get age from user


cin>> age;
ans = 365 * age
age = 365 * age;

print "Age in days is: ", ans // print age


cout << "Age in days = "<< age;
End
return 0;
}
Example 2:
Problem Statement: Determine the factorial of the given input number.
Sample execution:
Please enter the number for factorial: 4
Factorial : 24

Pseudo code Flow chart Actual code


#include <iostream>
Start #include <iostream>
integral factorial, number; using namespace std;
integers
print "Please enter the number for factorial " int main()
; {
input number; //declaration of variables
int factorial, number;
while ( number > 1 ) // initializaation of the variable
{ factorial = 1;
factorial = factorial * number; number = 1;
number = number - 1;
} //prompt the user to enter limit of integers
cout << "Please enter the number for
print "The factorial is ", factorial; factorial " ;
cin >> number;
End while(number > 1 )
{
factorial = factorial * number;
number = number - 1;
}

cout << "The factorial is " << factorial;

return 0;
}
Variable: "Balti"
• The program (actual code) is running within the computer's memory
(RAM/cache) under the control of the processor.

• Memory dedicated to instructions and data has parts:


o Address
o Contents

• The program (actual code) is comprised of two main components:


o Data
o Instructions or code

• For data, such as age data stored in memory:


o Contents can be accessed using an address or label.
o It is more convenient for programmers to access memory locations using
labels.
o Labels, in this context, are also referred to as variables.
o A variable implies that the contents can change from one statement to next
o A variable/label comprises:
▪ datatype (integral/ real)
▪ name (age/num1): Variable name should be in lower/camel case and
descriptive
▪ value/ data. (using assigment operator/input function)

• We also have arithmatic operators: +, -, *, /, %

Example:
Declare an integral variable "age" and assign it the value 19:

integer age // variable declaration statement


age = 19 // variable assignment statement

OR
integer age = 19 // variable definition or initialization statement

Problem statement: Create an algorithm that takes the user's age in years as
input and displays it on the next line.

Sample Execution:
Kindly input your age in years: 20
The age you entered is 20.
Pseudo code
Start
integer age

print "Please enter your age in year:"

input age

print "Your age in days is: ", age

End

Problem statement: Develop an algorithm that converts the input of years into its
equivalent value in days. (use of assignment and arithmetic operators)

Sample execution
Enter your age: 2
Age in days = 730

Pseudo code

Start
integer age, ans

print "Please enter your age in year:"

input age

ans = 365 * age

print "Your age in days is: ", ans

End

Use of modulus operator:


- Decimal to binary conversion, we need remainder
- Even or odd

Examples : write pseudo code:


1) Find sum of 3 numbers
Sample execution:
Please enter first number: 10
Please enter second number: 20
Sum of entered numbers : 30

2) Calculate the average of three quiz exams.

Sample execution:
Please enter first quiz: 9
Please enter second number: 8
Please enter second number: 7
Average of three quiz exams : 8

3) Find Area of circle

Sample executiton:
Enter radius: 3
Area of the circle : 28.26

4) Find Area of of rectangle

Sample executiton:
Enter length of rectangle : 3
Enter the width of circle : 4
Area of the rectangle : 12
Programming Fundamentals – Spring 2024
(BS-IT-F23 Morning)
Assignment # 1 part I (Sequential statements )

Instructions:
• Attempt the following tasks exactly in the given order.
• Indent your pseudo-code properly.
• Use meaningful variable names. Use the camelCase notation to name variables.
• Use meaningful prompt lines/labels for all input/output that is performed by your algorithms.

You are required to write algorithm in pseudo-code form and draw flowchart for each of the following
tasks:

Task # 1
A company has determined that its annual profit is typically 13 percent of total sales. Design an algorithm
that asks the user to enter the amount of total sales, and then determines and displays the annual profit
that will be made from that amount.

Task # 2
Design an algorithm that will ask the user to enter the amount of a purchase. The algorithm should then
compute the federal and provincial sales tax. Assume that the federal sales tax is 6 percent and the
provincial sales tax is 4 percent. The algorithm should display the amount of the purchase, the federal
sales tax, the provincial sales tax, the total sales tax, and the total of the sale (which is the sum of the
amount of purchase plus the total sales tax).

Task # 3
A car’s mileage in kilometers per liter (KMPL) can be calculated with the following formula:

𝑲𝑴𝑷𝑳 = 𝑲𝒊𝒍𝒐𝒎𝒆𝒕𝒆𝒓𝒔 𝒅𝒓𝒊𝒗𝒆𝒏 / 𝑳𝒊𝒕𝒆𝒓𝒔 𝒐𝒇 𝒑𝒆𝒕𝒓𝒐𝒍 𝒖𝒔𝒆𝒅


Design an algorithm that asks the user for the number of kilometers driven and the liters of petrol used.
It should calculate the car’s KMPL and display the result on the screen.

Task # 4
Design an algorithm that asks the user how many eggs he/she has bought and then tells the user how
many dozen eggs he/she has and how many extra eggs are left over. A sample run of your algorithm is
given below. Text shown in red is entered by the user.

Sample run:

How many Eggs you bought: 42


You bought 3 dozen and 6 extra Eggs

Hint: Use the division operator (/) and the modulus (%) operator.

You might also like