CO Lab 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

Computer Organization

Lab
Dr Sajid Gul Khawaja
LE Kashaf Raheem
Learning Management System (LMS)!!!
› Please enroll on LMS using course code:
– Lecture and Lab: 987436510 (Syn-A), 045867923 (Syn-B)
› All content including assignment, lab manual, lectures etc. will
be available there
› In case you need to contact please use the following contact
details:
– kashafraheem324@gmail.com, +923337153075
– sajid.gul@ceme.nust.edu.pk, +923455192792

4
Guidelines For Lab Work
› Individual to turn-in their own work
› Lab reports will be submitted on LMS in a group of 3 students.
(Sample is available on LMS)
› Each Lab will be marked based on a specific rubric scheme
(shared on next slide)
› Please observe
– Marks will be deducted for ‘plagiarized/copied’ lab reports.
– 10% per day penalty for late labs, capped at 50%
– all labs MUST be checked off to pass the course
– lab assignments (when given) MUST be done in groups of 2 or 3
5
Marking Rubrics

Exceptional Acceptable Amateur Unsatisfactory


Trait [10-8] [7-5] [4-3] [2-0]
Functionality The program works and meets all The code is fairly efficient without The code is unnecessarily The code is huge and does
the specifications and is extremely sacrificing readability and long and inefficient and not meet any
and efficiency efficient without sacrificing understanding and also meets meets only few of its specification.
40% readability and understanding. almost all of its specifications but not specifications.
all.
Output The program produces correct The program works and produces The program produces The program is producing
results and display them correctly the correct results and displays them correct results but does not incorrect results.
20% in an organized way. correctly display them correctly.

Input All the inputs entered by user are In case of wrong input, the programs Some of the inputs are No input validation.
properly validated, in case of continue execution. validated leaving the others.
Validation wrong input entered by user the
20% program displays to the user to
enter the correct input.
Code The code was well documented The code was sufficiently The code was documented The code was not
with proper commenting and documented with comments and with comments and with document properly
Presentation variable names. variable names (to an extent). improper variable names or without comments and
(Commenting/ vice versa. proper variable name.

Readability) 6
20%
Lab Assessment
› Lab Work + Quizzes: 40-50%
› Lab Reports: 5-10%
› Open ended labs: 10%
› Lab Final Exam/Viva: 15-20%
› Project: 15-20%

7
Lesson Plan

Algorithm
Designing and Logic
Processor Development
(Verilog HDL) (Python)

Accessing
Processor using
MARS
(Assembly)

8
Lab. # 1
Introduction to Computers
Algorithms and Python!!!

9
Computing Machines
› Ubiquitous ( = everywhere)
– General purpose: servers, desktops, laptops, PDAs, etc.
– Special purpose: cash registers, ATMs, games, telephone switches,
etc.
– Embedded: cars, hotel doors, printers, VCRs, industrial machinery,
medical equipment, etc.
› Distinguishing Characteristics
– Speed
– Cost
– Ease of use, software support & interface
– Scalability
10
Two recurring themes
› Abstraction
– The concept that we can concentrate on one “level” of the big
picture at a time, with confidence that we can then connect
effectively with the levels above and below.
› Hardware vs. Software
– Abstraction does not mean being clueless about the neighboring
levels.
– Hardware and software are inseparably connected, especially at the
level we will be studying.

11
Two pillars of Computing
› Universal Computational Devices
– Given enough time and memory, all computers can compute the
same things (irrespective of speed, size or cost).
› Turing’s Thesis: every computation can be performed by some “Turing Machine”
- a theoretical universal computational device

› Problem Transformation
– Convert a problem expressed in natural language into electrons
running around a circuit!
› That’s what Computer Science and Computer Engineering are all about: a
continuum that embraces software & hardware.

14
Problem Transformation - levels of abstraction

The desired behavior: Natural Language


the application
Algorithm

Program

Machine Architecture

Micro-architecture

Logic Circuits
The building blocks: Devices
electronic devices
15
› These levels do not necessarily
LEVELS OF correspond to discrete components,
ABSTRACTION but to well defined standard interfaces.
– Standard interfaces provide
Natural Language
› portability
› third party software/hardware
Algorithm
› wider usage
Program
› These levels are to some extent
Machine Architecture arbitrary - there are other ways to
draw the lines.
Micro-architecture

Logic Circuits

Devices

16
THE PROGRAM
LEVEL
Application Program
Most computers run a management
program called the operating system
(OS).
Operating System
Application programs interface to the
machine architecture via the OS.

An example: Program (Software)

This lecture Data

PowerPoint Application Program

Windows XP Operating System

17
Algorithms!

18
Computational problems
› A computational problem specifies an input-output
relationship
– What does the input look like?
– What should the output be for each input?
› Example:
– Input: an integer number n
– Output: Is the number prime?
› Example:
– Input: A list of names of people
– Output: The same list sorted alphabetically

19
Algorithms
› A tool for solving a well-specified computational problem OR Steps
used to solve a problem
› A well-defined computational procedure that takes some value, or
set of values, as input and produces some value, or set of values, as
output.

Input Algorithm Output


› Steps must be
– Ordered
– Unambiguous
– Complete

20
Problems and Algorithms
› We need to solve a computational problem
– “Convert a weight in pounds to Kg”

› An algorithm specifies how to solve it, e.g.:


– 1. Read 𝑤𝑒𝑖𝑔ℎ𝑡𝑖𝑛𝑝𝑜𝑢𝑛𝑑𝑠
– 2. Calculate
𝑤𝑒𝑖𝑔ℎ𝑡𝑖𝑛𝐾𝑔 = 𝑤𝑒𝑖𝑔ℎ𝑡𝑖𝑛𝑝𝑜𝑢𝑛𝑑𝑠 ∗ 0.455
– 3. Print 𝑤𝑒𝑖𝑔ℎ𝑡𝑖𝑛𝐾𝑔
› A computer program is a computer-executable description of
an algorithm
21
From Algorithms to Programs

Program
Problem Algorithm (in our case
Python)

Algorithm: A sequence of
instructions describing how to
do a task (or process)
22
Developing an Algorithm
Program Development
1. Understand the problem
2. Represent your solution (your algorithm)
– Pseudocode
– Flowchart
3. Implement the algorithm in a program
4. Test and debug your program

24
Step 1: Understanding the Problem
› Input
– What information or data are you given?
› Process This is your algorithm!
– What must you do with the information/data?
› Output
– What are your deliverables?

25
“Weekly Pay” Example

PROBLEM SOLUTION
› Create a program to calculate the › Input: pay rate and number of
weekly pay of an hourly employee hours
– What is the input, process, and
output?
› Process: multiply pay rate by
number of hours
› Output: weekly pay

26
Step 2: Represent the Algorithm
› Can be done with flowchart or
pseudocode
› Flowchart
– Symbols convey different types of actions
› Pseudocode
– A cross between code and plain English

› One may be easier for you – use that


one

27
Three Base constructs of An Algorithm
› Three basic control flow elements which exist in algorithm
– Sequence of operations/expressions/statements
– Decision making
– Iterating an action again and again → Repetition or looping

28
Flowchart Symbols

Start
Start Symbol Input / Output

End
End Symbol Decision Symbol

Data Processing Symbol Flow Control Arrows

31
Step 2B: Flowchart
Example: Compute Pay

Start Get the rate

Display “Number
pay = hours * rate
of hours worked: ”

Display “The pay


Get the hours is $” , pay

Display “Amount
paid per hour: ” End
32
Examples/Short Tasks
Draw Flowcharts for each problem

33
Example 1

PROBLEM SOLUTION
› Write an algorithm in pseudocode › AverageOfTwo
that finds the average of two
numbers › Input: Two numbers
1. Add the two numbers
2. Divide the result by 2
› Output: Return the result
generated step 2
› End

34
Example 2

PROBLEM SOLUTION
› Write an algorithm in the form of › ComputeBMI
a pseudocode that computes
BMI using weight in pound and › Input: Weight (𝑤) and Height (ℎ)
height in inches. 1. Hsquare ← ℎ2
𝑤𝑒𝑖𝑔ℎ𝑡 𝑤
𝐵𝑀𝐼 = 703 ∗ 2. wbyh2 ←
ℎ𝑒𝑖𝑔ℎ𝑡 2 Hsquare

3. BMI ← 703 ∗ wbyh2


› Output: BMI
› End
35
Algorithms and Language
› Notice that developing the algorithm doesn’t involve any
language at all
– Only pseudocode or a flowchart was needed
– An algorithm can be coded in any language
› All languages have 3 important control structures we can use
in our algorithms

36
Steps 3 and 4: Implementation
and Testing/Debugging
› We’ll cover implementation in detail
› Testing and debugging your program involves identifying
errors and fixing them

37
Programming through
Python
Install latest version of IDLE on your laptops
Link: https://www.python.org/downloads/

38
Introduction to Python
› Python is a high-level programming language – like C++/Java
› Open Source and has a large community
› Used by a lot of companies around the world
› The popularity of Python has increased significantly in the last
decade

39
Introduction to Python (Cont’d)
› Interpreted Scripting Language
– Good for writing “quick” code
› Python is object oriented
– Everything is a Python object
› Different code blocks are grouped together by indentation

40
General Information

41
Variables
› No need to declare
› Need to assign (initialize)
– use of uninitialized variable raises exception
› Not typed
– if friendly:
› greeting = "hello world"
– else:
› greeting = 12**2
› print(greeting)
› Everything is a "variable":
– Even functions, classes, modules

42
Indentation and Blocks
› Python uses whitespace and indents to denote blocks of code
› Lines of code that begin a block end in a colon:
› Lines within the code block are indented at the same level
› To end a code block, remove the indentation
› You'll want blocks of code that run only when certain
conditions are met

43
Whitespace
› Whitespace is meaningful in Python:
– Especially indentation and placement of newlines.
› Use a newline to end a line of code.
– Use \ when must go to next line prematurely.
› No braces { } to mark blocks of code in Python…
Use consistent indentation instead.
– The first line with less indentation is outside of the block.
– The first line with more indentation starts a nested block
› Often a colon appears at the start of a new block. (E.g. for
function and class definitions.)
44
Comments
› Start comments with # – the rest of line is ignored.
› Can include a “documentation string” as the first line of any
new function or class that you define.
› The development environment, debugger, and other tools use
it: it’s good style to include one.
– def my_function(x, y):
– “““This is the docstring. This
function does blah blah blah.”””
# The code would go here...

45
None
› “None” represents the lack of a value.
› Like “NULL” in some languages or in databases.
› For instance:

>>> if y!=0:
... fraction = x/y
... else:
... fraction = None

46
Linking this with Algorithm-
Flowchart

47
Input Input

› input is the keyword


› variablename = input("String to be printed as message")
>>>A = input("Please enter marks: ")
Please enter marks: 10
>>>Aint = int(A) #converts the string into integer number
› Important info:
– Input command takes string as an input, an integer value will also be
saved as character
– Need to change type to integer/float/etc. before further processing

48
Output Output

› print is the keyword


› print("String to be printed as message“, variablename)
>>>A = input("Please enter marks: ")
Please enter marks: 10

>>>print("Value of A is ", A)
Value of A is 10

49
Sequence!
Data Processing Symbol
› Mathematical expressions

› Built-in functions/libraries

50
Mathematical Functions
› 𝒂𝒃𝒔(𝒙) – absolute value
› 𝒅𝒊𝒗𝒎𝒐𝒅(𝒂, 𝒃) - divide a by b and return both the quotient
and the remainder
› 𝒉𝒆𝒙(𝒙) - Convert an integer number (of any size) to a
hexadecimal string.
› 𝒐𝒄𝒕(𝒙) - Convert an integer number (of any size) to an octal
string.
› 𝒓𝒐𝒖𝒏𝒅(𝒙[, 𝒏]) - Return the floating-point value x rounded to n
digits after the decimal point.

51
Example: Weight into Kg

PSEUDOCODE PYTHON CODE


› ConvertintoPound weightinkg = input (“Enter the
weight in pounds: ")
› Input: Enter Weight in KG
weightinpound =
1. Convert entered data from float(weightinkg)*0.455
string to floating number
(Python) print(“Weight in pound is",
weightinpound)
2. Multiply the weight in pound
with scaling factor (0.455)
› Output: Weight in Pound
› End
52
Example: Compute Pay

Start Get the rate

Display “Number
pay = hours * rate
of hours worked: ”

Display “The pay


Get the hours is $” , pay

Display “Amount
paid per hour: ” End
53
Solution:

payrate = input("enter the payrate")


daysworked = input("enter the hours worked in a day")
weeklypay = float(payrate)*int(daysworked);
print(weeklypay)
Example: Pythagoras Theorem

PROBLEM SOLUTION
› Write pseudocode of an algorithm › ComputerHypo
which can compute the value of
hypotenuse if user provides value of › Input: 𝑝 and 𝑏
perpendicular and base. 1. Compute 𝑝2
ℎ2 = 𝑏 2 + 𝑝 2
2. Compute 𝑏 2
3. Add gets 𝑝2 + 𝑏 2
4. h gets square-root of Add
› Output: ℎ
› End

55
Program

PSEUDOCODE PYTHON CODE


› ComputeHypo p = float(input(“Enter value of
perpendicular: ”))
› Input: 𝑝 and 𝑏
b = float(input(“Enter value of base:
1. p_square ← 𝑝2 ”))
2. bsquare ← 𝑏 2 h_square = p**2 + b**2
3. hsquare ← (𝑝2 + 𝑏 2 ) h = h_ square **(0.5)
4. h ← square-root of hsquare print(“The resultant value of
› Output: ℎ hypotenuses is : ”, h)
› End

56
Tasks
Make sure to comment your code.
Use appropriate variable name
Know the location where file is being saved
Create different files for different tasks

57
Task 1
› Create an algorithm and code it through python for the
problem that takes two numbers and displays the sum, sub,
divide, multiply and square of numbers entered, on the
console window.

58
Task 2
› Write a program that computes roots of an expression using
quadratic equation
−𝑏 ± 𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎
› The program must get values of a, b and c from the user

59
Task 3
› Write a program that calculates grocery bill by asking you to
enter the number of elements bought for a specific type.
Item Type Unit Price Quantity Multiple
Eggs (dozen) 300 Dozen
Bread 200 Single
Butter 400 Single
Jam 400 Single

61
Next week: Control Flow!
Advice:
Install latest version of IDLE on your laptops
Link: https://www.python.org/downloads/
Or VS Code and integrate python

62

You might also like