ENSC 151 - Week 0(1) (Complete) PDF
Document Details
Uploaded by Deleted User
Seattle Pacific University
Yuri Rodrigues, PhD
Tags
Summary
This document provides an overview of computer science concepts, including computer hardware, software, programming languages, and algorithms. It discusses topics such as the evolution of programming languages, input and output operations, memory, and the central processing unit (CPU).
Full Transcript
ENSC 151 – Week 0 (1) Professor: Yuri Rodrigues, PhD Based on material from Dr. Maira Monteiro of the Seattle Pacific University, used here with permission Objectives We will learn general concepts to introduce problem solving and C++ programming. For this, the following key conc...
ENSC 151 – Week 0 (1) Professor: Yuri Rodrigues, PhD Based on material from Dr. Maira Monteiro of the Seattle Pacific University, used here with permission Objectives We will learn general concepts to introduce problem solving and C++ programming. For this, the following key concepts are covered: Explore the hardware and software components Learn about the language of a computer and the evolution of programming languages Discover what a compiler is and what it does Examine a C++ program and explore how it is processed Learn what an algorithm is and explore problem-solving techniques Become familiar with the basic components of a C++ program Discover how to input data into memory using input statements Examine ways to use output statements Learn how to debug syntax errors Explore how to properly structure a program, including using comments to document a program Learn how to write a C++ program 2 When Computers Were Human 4 At first there was only Hardware For every problem submitted, the staff had to enter the new instructions by rewiring the entire machine And this took a LOT of time! ENIAC was not a stored- program computer Program and data were stored in RAM (random access memory) 5 Modern Computers Modern computers are stored program computers Memory unit - with instructions and data Central Processing Unit (CPU): Arithmetic/logic unit - arithmetic and logical operations on data Control unit - interpret instructions retrieved from the memory and perform actions based on the results of previous operations Von Neumann (Princeton) Architecture 6 Elements of a Computer Hardware refers to the physical part of the computer. “Hardware is something that you can hit with a hammer.” This includes components like: Input/Output (I/O) devices – mouse, keyboard, monitor, printer, scanner, sound system Storage devices – CD/DVD readers/writers, hard drives, USB drives Motherboard, processor, memory, graphics card, sound card, bus Software is the programs the computer follows to perform functions. Software is virtual. Although programs may be stored on media, the essence of software is information. Hardware: Input and Output (I/O) I/O devices are commonly called peripherals, and they provide an interface with the computer and user. Input devices feed data and programs into computers Keyboard Mouse Scanner Camera Secondary storage Output devices display results Monitor Printer Secondary storage 9 Hardware: Storage Disk stores files and other data, such as program files, song/movie files, or office documents. Non-volatile (they maintain their contents even when powered off). Hard Disk Drive (HDD) Solid State Drive (SSD) 10 Hardware: Memory - is the general term for devices that allow the computer to store data either temporarily or permanently. Temporary memory: only stores data while the computer is on Random-access memory (RAM) is a fast, common type of memory Permanent memory: data is stored even after the computer is off Read-only memory (ROM) is permanent memory that cannot be changed Most permanent memory is considered secondary storage because the memory is stored in a separate device (hard drive, DVD, flash). Since memory in secondary storage is in a separate device, the device is capable of holding more data, but is often slower than main memory. Cache - is a term used to describe memory that stores a subset of data in a larger memory for performance. Processor cache, disk cache, network cache 11 Hardware: Central Processing Unit (CPU) or processor is the “brain” of the computer as it directs data flow inside the machine and knows how to perform basic operations. CPU executes program instructions, performs math operations, fetches/stores data in memory, and controls the data flow of devices. E.g. Intel Pentium/Core/Xeon, AMD Athlon/Phenom, Apple A6 (ARM processor) (iPhone) Clock determines the rate at which the processor's instructions are executed. Processors have clocks that tick at rates such as 1 MHz (1 million ticks/second) to 1 GHz (1 billion ticks/second) Executing about 1 instruction per clock tick, mobile phones and desktop computers execute millions or billions of instructions per second. Moore’s Law states that integrate circuit (IC) capacity roughly doubles every 18 months. 12 Hardware: Central Processing Unit and Main Memory Random access memory (or main memory) is directly connected to the CPU All programs must be loaded into the main memory before they can be executed All data must be brought into main memory before it can be manipulated When computer power is turned off, everything in main memory is lost. Main memory is an ordered sequence of memory cells Each cell has a unique location in the main memory, called the address of the cell Each cell can contain either a programming instruction or data 13 Software Software is programs written to perform specific tasks and is typically realized as an application program. System programs control the computer Operating system monitors the overall activity of the computer and provides services such as: Memory management Input/output activities Storage management Application programs perform a specific task Word processors Spreadsheets Games 14 What is programming? Programming is the process of constructing programs in order to instruct a computer on how to solve problems. It is the act of writing out the steps of an algorithm. A program is a sequence of simple computer instructions in some language that tell the computer the necessary steps to solve a problem or complete a task. A language is the structure and syntax used to communicate to the computer the tasks it is required to perform. Programming basics A computer program consists of instructions executed one at a time. Basic instruction types are: Input: A program gets data, perhaps from a file, keyboard, touchscreen, network, etc. Process: A program performs computations on that data, such x + y. Output: A program puts that data somewhere, such as on a file, screen, network, etc. Programs use variables to refer to data, like x, y, and z. 17 The Language of a Computer Electrical signals are used inside the computer to process information. There are two types: Analog signals: continuously varying continuous waveforms Digital signals: sequences of 0s and 1s Computers use digital signals. Machine language: the language of a computer A sequence of 0s and 1s Binary digit (bit): the digit 0 or 1 Binary code (binary number): a sequence of 0s and 1s The Language of a Computer Byte: a sequence of eight bits Unicode is another coding Kilobyte (KB): 210 bytes = 1024 bytes scheme 65,536 characters ASCII (American Standard Code for Information Interchange) Two bytes (16 bits) to 128 characters store a character A is encoded as 1000001 (66th character) The character 3 is encoded as 0110011 (51st character) Unit Symbol Bits/Bytes Byte 8 bits Kilobyte KB 210 bytes = 1024 bytes Megabyte MB 1024 KB = 210 KB = 220 bytes = 1,048,576 bytes Gigabyte GB 1024MB = 210 MB = 230 bytes = 1,073,741,824 bytes Terabyte TB 1024 GB = 210 GB = 240 bytes = 1,099,511,627,776 bytes Petabyte PB 1024 TB = 210 TB = 250 bytes = 1,125,899,906,842,624 bytes Exabyte EB 1024 PB = 210 PB = 260 bytes = 1,152,921,504,606,846,976 bytes Zettabyte ZB 1024 EB5 210 EB = 270 bytes = 1,180,591,620,717,411,303,424 bytes Language Barrier A program must be written using a language understood by both writer of the algorithm and reader (who will use it). Humans and computers do not speak the same language. Natural languages, such as English, are ambiguous, fuzzily structured and have large (and changing) vocabularies. Computers have no common sense, so computer languages must be very precise with relatively few, exactly defined, rules for the composition of programs strictly controlled vocabularies in which unknown words must be defined before they can be used. 20 Crossing the Language Barrier Human Natural Language (e.g., English, Portuguese, Spanish,…) thought Programming Language (e.g., C, C++, …) Machine Language Machine Language (Computer's Native Tongue) 21 The Evolution of Programming Languages Early computers were programmed in machine language. To calculate wages = rate * hours in machine language: 100100 010001 // Load 100110 010010 // Multiply 100010 010011 // Store Machine programming involves specifying commands directly in binary form. The Evolution of Programming Languages Assembly language was developed to make the programmer’s job easier, i.e., the instruction is an easy-to-remember form called a mnemonic. It is a slightly higher level of commands which look more like English commands that are then translated to machine language before execution. Assembler handles conversion into machine language (alphabetic and numeric symbols are substituted for binary codes). Using assembly language instructions, wages = rate * hours can be written as: 100100 010001 // Load LOAD rate 100110 010010 // Multiply MULT hours 100010 010011 // Store STOR wages Most programmers do not write code in assembly or machine language because it is too low-level and time-consuming. The Evolution of Programming Languages Higher-level languages are more powerful and easier to use. Include Basic, FORTRAN, COBOL, C, C++, C#, Java, and Python. The programmer does not have to specify all the details at a low-level and can use more general commands. Allow programmers to code closer to natural language. Create portable programs that could be run on multiple platforms. In C++, the weekly wages equation (wages = rate * hours ) can be written as: 100100 010001 // Load LOAD rate 100110 010010 // Multiply MULT hours wages = rate * hours; 100010 010011 // Store STOR wages Every language for communicating instructions to the computer must ultimately be translated to machine language for execution. The tools that translate to machine language are called compilers. Compilers verify that code has correct syntax before performing the translation. Program Compilation Process Source code The compiler translates high-level SOURCE code into machine language OBJECT code Compiler Object code Input Output Quick question 1) Compiler 2) Application 3) Machine instruction 4) Assembly 26 Problem solving Algorithm An algorithm is a precise, systematic method for producing a specified result. We use algorithms all the time to complete tasks. A common example is following assembly directions (as with IKEA assembly) or using a recipe. Simpler examples include how to perform arithmetic or look up a person's name in a list. Some algorithms are so simple or ingrained that we do not consciously remember the steps. However, precision is required when communicating the algorithm to others. Algorithm An Algorithm describes a sequence of actions: 1. Unambiguous a. No “assumptions” are required to execute the algorithm b. The algorithm uses precise instructions 2. Executable a. The algorithm can be carried out in practice 3. Terminating a. The algorithm will eventually come to an end, or halt For complex problems, software developers write an algorithm before they attempt to write a computer program. Developing algorithms is a fundamental problem-solving skill. It has uses in many fields outside of Computer Science 29 Problem Solving - Overview Analysis - thoroughly understand the problem statement. Design- before entering any code, outline how you will solve the problem. Both steps need to be performed before coding. Five Essential Properties of Design 1) Inputs specified – must specify the type, amount, and form of data to be used during the problem solving. 2) Outputs specified – must describe the result of the problem (it is possible to have no output). 3) Precision – specify precisely the sequence of steps to be performed including how to handle errors. 4) Reasonable Operations – the operations are doable. 5) Finite – the problem must eventually have a solution (terminate). Five Essential Properties of Design Question: The algorithm on the shampoo bottle says: "Apply shampoo. Lather. Rinse. Repeat." Which one of the five essential properties does this algorithm not meet? A) inputs specified B) outputs specified C) precision D) reasonable operations E) finiteness Be Specific and ORDER COUNTS! Computers (like sarcastic robots) do exactly what you tell them, and are not capable of filling in blanks 1. Get out of bed 1. Get out of bed 2. Take off pajamas 2. Take off pajamas 3. Take a shower 3. Get dressed 4. Get dressed 4. Take a shower 5. Eat breakfast 5. Eat breakfast 6. Drive to work 6. Drive to work Algorithms Question: Put the following steps in order to write an algorithm to construct a campfire. 1) light match 2) place wood in fire pit 3) put match on wood 4) gather wood a) 2,4,3,1 b) 4,2,1,3 c) 1,2,3,4 d) 4,3,2,1 Problem solving – Mr. Noodles Case Simple and effective! A) Inputs specified? D) Reasonable operations? - Noodles - Yes, Operations are doable - 2 cups of water - Soup base E) Finiteness? - Yes, the process terminates B) Outputs specified? - Cooked noodles C) Precision? Cooking directions: - Boil water - Cook noodles for 2-3 minutes - Remove from heat - Add soup base - Stir Group Discussion Write an algorithm for brushing your teeth and check if it has the five essential properties of algorithm design. Does it meet the Five Essential Properties of Design? 1) Inputs specified Possible algorithm: Toothbrush, toothpaste, water A) Wet toothbrush 2) Outputs specified Clean mouth B) Put toothpaste on brush 3) Precision C) Move your brush in small A,B,C,D,E circular movements on all the surfaces of every tooth 4) Reasonable operations Yes D) Brush your tongue 5) Finiteness E) Rinse and spit Yes Developing the Algorithm Example 1 1) Design an algorithm to find the perimeter and area of a rectangle. The perimeter and area of the rectangle are given by the following formulas: perimeter = 2 * (length + width) area = length * width Algorithm Get the length of the rectangle Get the width of the rectangle Find the perimeter with this equation: perimeter = 2 * (length + width); Find the area with this equation: area = length * width; Example 2 (1 of 3) 2) Consider the problem below. Algorithm to determine the average test There are 10 students in a class score Each student has taken five tests Get the five test scores Each test is worth 100 points Add the five test scores The grade is assigned as follows: The sum of the test scores is If the average test score is greater represented by sum than or equal to 90, the grade is A; if the average test score is greater Suppose average stands for the average than or equal to 80 and less than 90, the grade is B; test score: if the average test score is greater than or equal to 70 and less than 80, the grade is C; average = sum / 5; if the average test score is greater than or equal to 60 and less than 70, the grade is D; otherwise, the grade is F. Design the algorithm to calculate the grade for each student and the class average Use the provided data: students’ names and test scores Example 2 (2 of 3) Algorithm to determine the grade: 2) Consider the problem below. There are 10 students in a class if average ≥ 90 Each student has taken five tests grade = A Each test is worth 100 points otherwise The grade is assigned as follows: if 80 ≤ average < 90 If the average test score is greater than or equal to 90, the grade is A; grade = B if the average test score is greater than or equal to 80 and less than otherwise 90, the grade is B; if the average test score is greater if 70 ≤ average < 80 than or equal to 70 and less than 80, the grade is C; grade = C if the average test score is greater otherwise than or equal to 60 and less than 70, the grade is D; if 60 ≤ average < 70 otherwise, the grade is F. grade = D Design the algorithm to calculate the grade for each student and the otherwise class average grade = F Use the provided data: students’ names and test scores Example 2 (3 of 3) 2) Consider the problem below. Main algorithm is presented below: There are 10 students in a class Each student has taken five tests Each test is worth 100 points 1. Repeat the following steps for each student: The grade is assigned as follows: Get the student’s name If the average test score is greater than or equal to 90, the grade is A; Use the algorithm to find the average test score if the average test score is greater than or equal to 80 and less than 90, the grade is B; Use the algorithm to find the grade if the average test score is greater than or equal to 70 and less than Update totalAverage by adding the current student’s 80, the grade is C; if the average test score is greater average test score than or equal to 60 and less than 70, the grade is D; otherwise, the grade is F. 2. Determine the class average as follows: Design the algorithm to calculate classAverage = totalAverage / 10 the grade for each student and the class average Use the provided data: students’ names and test scores In-class activities 1) Write an algorithm that reads the user’s age, checks if the user can apply for a driver’s license, and outputs a message if the user can apply or not. 2) A local restaurant is selling a meal for $9.99. Given the number of meals ordered as input, write an algorithm to output the subtotal for meals and the total after applying a sales tax of 6%. Algorithm for driver’s license issue: Algorithm for ordering meals: BEGIN BEGIN Input: Input: Get the number of meals Get user’s age Constants: Price of meal = 9.99 Constant: Sales tax = 0.06 Age requirement = 16 Compute: IF user’s age >= Age requirement subTotal = number of meals * Price of meal totalDue = subTotal * (1 + Sales tax) OUTPUT You can apply for driver’s license ELSE Output: OUTPUT You can't apply for driver’s license subtotal (price before tax) totalDue (price after tax) END END C++ programming Processing a C++ Program (1 of 2) #include // I/O library using namespace std; // define a scope to the identifiers Function name Empty parameter list Type of int main() { returned value cout to gather one or more inputs The stream extraction operator is >> For example, if miles is a double variable: cin >> miles; Causes the computer to get a value of type double and places it in the variable miles Using more than one variable in cin allows more than one value to be read at a time Example: if feet and inches are variables of type int, this statement: cin >> feet >> inches; Inputs two integers from the keyboard Places them in variables feet and inches respectively Output (1 of 3) The syntax of cout and