EKT 120/4 Computer Programming KOLEJ UNIVERSITI KEJURUTERAAN UTARA MALAYSIA
AZUWIR MOHD NOR ROOM: Pusat Pengajian CABIN C PHONE: (04) 979 8249 Email: azuwir@kukum.edu.my Office hours: make appoinment or just drop by.
General Information Contributes 4 units: 2 hours will be spent on lectures 4 hours of hands-on programming (KWSP) Tuesday 11:00 1:00pm (Exercise) Thursday 8:30 10:30 pm (assignment) Objective: Students can independently write a computer program to solve calculation problems, especially those related to engineering
Overall Evaluation 4 main components: Assignments/Quizzes (30%) Two exams (15% +15%) One written test, One take home programming test. Mini-project (40%) Details will be informed later The rest involves real programming
Text & Reference Text: Essential C++ for engineers and scientist (Hanly, Jeri R.) 2 nd ed. Pearson Education Reference: Any books on C++. Applications Programming in C++ (Johnsonbaugh & Kalin) ) Prentice Hall C++ programming: From problem Analysis to Program Design (D.S Malik.) Thomson Learning Find one that can help you most
Tips Attendance: don t miss any lecture Don t miss lab! Come to class on time Discuss among your friends BUT DO YOUR OWN WORK! Practice! Practice! Practice!
CHAPTER 1 AN OVERVIEW OF COMPUTERS AND PROGRAMMING LANGUAGES
In this chapter, you will: Learn about different types of computers Explore the hardware and software components of a computer system Learn about the language of a computer Learn about the evolution of programming languages Examine high-level programming languages Discover what a compiler is and what it does Examine how a high-level language program is processed Learn what an algorithm is and explore problem-solving techniques
A BRIEF OVERVIEW OF THE HISTORY OF COMPUTERS Computers that are in use can be classified in the following categories: Main frame computers. Mid size computers. Micro computers (also called personal computers).
ELEMENTS OF A COMPUTER SYSTEM Hardware CPU-The CPU has several components in it. CU (control unit) - It has three main functions. Fetch and decode the instruction. Control the flow of information (instruction or data) in and out of MM (main memory). Control the operation of the internal components of CPU. PC-program counter points to the next instruction to be executed. IR-instruction register holds the instruction that is currently being executed. ALU-arithmetic logic unit. This component is responsible for carrying out all arithmetic and logical operations. ACC-accumulator. Once ALU performs the operation the results are placed in ACC.
Main Memory Directly connected to the CPU. All programs must be loaded into MM before they can be executed. All data must be brought into MM before it can be manipulated. When the power of the computer is turned off every thing in the main memory is lost for good.
Secondary storage Everything in main memory is lost when the computer is turned off. Information stored in main memory must be transferred to some other device for permanent storage. The device that stores information permanently is called secondary storage. Examples of secondary storage are hard disks, floppy disks, Zip disks, CD-ROMs, and tapes.
Input/Output devices For a computer to perform a useful task, it must be able to take in data and programs and display the results of calculations. The devices that feed data and programs into computers are called input devices. The keyboard, mouse, and secondary storage are examples of input devices. The devices that the computer uses to display results are called output devices. A monitor, printer, and secondary storage are examples of output devices.
Software Software are programs written to perform specific tasks. Two types of programs System programs - programs that take control of the computer. Application programs - programs that perform a specific task. (Word processors, spreadsheets, and games are examples of application programs.)
THE LANGUAGE OF A COMPUTER Two types of electrical signal - analog and digital. Since inside the computer digital signals are processed, the language of a computer is a sequence of 0s and 1s. The language of a computer is called the machine language. The digit 0 or 1 is called a binary digit or in short form a bit. A sequence of 0s and 1s is also referred as a binary code.
Bit: A bit is a binary digit 0 or 1. A sequence of 8 bits is called a byte. Coding Scheme ASCII (American Standard Code for Information Interchange). 128 characters A is encoded as 1000001 (66 th character) 3 is encoded as 0110011. EBCDIC (used by IBM)-256 characters Unicode - 65536 characters. Two bytes are needed to store a character.
THE EVOLUTION OF PROGRAMMING LANGUAGES Early computers were programmed in machine language. Suppose we want to represent the equation wages = rate hours to calculate the weekly wages in machine language. If 100100 stands for load, 100110 stands for multiplication and 100010 stands for store, then the following sequence of instructions might be needed to calculate the weekly wages. 100100 0000 010001 100110 0000 010010 100010 0000 010011
Assembly languages - an instruction in assembly language is an easy-to-remember form called a mnemonic. Using the assembly language instructions, the equation to calculate the weekly wages can be written as follows: LOAD MULT STOR rate hour wages Assembler: An assembler is a program that translates a program written in assembly language into an equivalent program in machine language.
High level languages- Basic, FORTRAN, COBOL, Pascal, C++, C In order to calculate the weekly wages, the equation wages = rate hours in C++, can be written as follows: wages = rate * hours; Compiler: A compiler is a program that translates a program written in a high level language to an equivalent machine language.
PROCESSING A HIGH-LEVEL LANGUAGE PROGRAM The following steps are necessary to execute a program written in a high level language, say, C++: 1. Use an editor to create a program (that is type) in C++. This program is called the source program. Source program: A program written in a high-level language. 2. Check that the program obeys the rules of the programming language and translate the program in to an equivalent machine language. All this is accomplished by the compiler. The equivalent machine language program is called an object program. Object program: The machine language version of the highlevel language program.
3. The programs that you write in a high-level language are developed using a software development kit (SDK), which contains many programs that are useful in creating your program. This prewritten code resides in a place called the library. Linker: A program that combines the object program with other programs provided by the SDK and used in the program to create the executable code. 5. The final step is to execute the program. 4. The next step is to load the executable program into the main memory for execution and a program called loader accomplishes this. Loader: A program that loads an executable program into main memory.
PROGRAMMING WITH THE PROBLEM ANALYSIS CODING EXECUTION CYCLE Programming is a process of problem solving. Problem solving techniques Analyze the problem Outline the problem requirements Design steps, called an algorithm, to solve the problem Algorithm: A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time.
Problem solving process 1. (a) Analyze the problem. (b) Outline the problem and its solution requirements. (c) Design steps (algorithm) to solve the problem. 2. (a) Implement the algorithm in a programming language, such as C++. (b) Verify that the algorithm works. 3. Maintenance: Maintenance requires using and modifying the program if the problem domain changes.
Problem Analysis-Coding-Execution Cycle
Analysis of the problem is the first and the most important step. This phase requires us to: 1. Thoroughly understand what the problem is about. 2. Understand the problem requirements. Some of the requirements could be: a. Does the program require interaction with the user? b. Does the program manipulate data? If the program manipulates data, the programmer must know what the data are and how the data are represented, that is, look at sample data. c. Is there any output of the program? If yes, the programmer should know how the results should be generated. 3. If the problem is complex, divide the problem into subproblems. Analyze each sub-problem as above.
Dividing a problem into smaller subproblems is called structured design. The structured design approach is also known as top-down design, stepwise refinement, and modular programming. In structured design, the problem is divided into smaller problems. Each subproblem is then analyzed, and a solution is obtained to solve the subproblem. The solutions of all subproblems are then combined to solve the overall problem. This process of implementing a structured design is called structured programming.
The next step is to design an algorithm to solve the problem. If the problem was broken into subproblems, design algorithms for each subproblem. Once the necessary steps have been designed, check the correctness of the algorithm. Sometimes algorithm s correctness can be tested using sample data. At times some mathematical analysis might be required to test the correctness of the algorithm. Once the algorithm is designed and correctness verified, the next step is to write the equivalent code into the high level language. Then using an editor enter the program into the computer.
The next step is to ensure that the program follows the constructs of the language. Run the code through the compiler. If the compiler generates error, we must go back, look at the code, remove the errors, and run the code again through the compiler. If there are no syntax errors, the compiler generates the equivalent machine code, the linker links the machine code with the systems resources, and the loader can then place the program into the main memory so that it can be executed. The final step is to execute the program. The compiler only guarantees that the program follows the rules of the language. It does not guarantee that the program will run correctly.
Example 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
The algorithm to find the perimeter and area of the rectangle is, therefore: 1. Get the length of the rectangle. 2. Get the width of the rectangle. 3. Find the perimeter using the following equation: perimeter = 2 (length + width) 4. Find the area using the following equation: area = length width
Example Design an algorithm that calculates the monthly paycheck of a sales-person at a local department store. Every salesperson has a base salary. The salesperson also receives a bonus at the end of each month based on the following criteria: If the salesperson has been with the store for five or less years, the bonus is $10 for each year that he or she has worked there. If the salesperson has been with the store for more than five years, the bonus is $20 for each year that he or she has worked there. The salesperson can earn an additional bonus as follows: If the total sale made by the salesperson for the month is more than $5000 but less than $10000, he or she receives a 3% commission on the sale. If the total sale made by the salesperson for the month is at least $10000, he or she receives a 6% commission on the sale.
The algorithm to calculate a salesperson s monthly paycheck. 1. Get basesalary. 2. Get noofserviceyears. 3. Calculate bonus using the following formula: if(noofserviceyears is less than or equal to five) bonus = 10 noofserviceyears otherwise bonus = 20 noofserviceyears 4. Get totalsale.
5. Calculate additionalbonus using the following formula. if (totalsale is less than 5000) additionalbonus = 0 otherwise if(totalsale is greater than or equal to 5000 and totalsale is less than 10000) additionalbonus = totalsale (0.03) otherwise additionalbonus = totalsale (0.06) 6. Calculate paycheck using the equation paycheck = basesalary + bonus + additionalbonus
EKT 120/4 Flow chart Programmers also use flowcharts to help them plan the algorithm for a problem. Uses standardized symbols to show the steps the computer needs to take to accomplish the program s goal.
Flowcharts symbols: Start/end EKT 120/4 Process calculation, initialization etc. Input/output read, display, print etc. predefined process symbol. Specify a function or a group of related statements decision symbol. Used to show selective (conditional) process path Connector for long flowcharts used to connect symbols and indicate the flow of data
Example EKT 120/4 Make a program that calculate and print the addition of two integers. Understand what the problem is about Read 2 integers Calculate the addition of 2 integers Print the results Analysis Input: 2 integers ( int1 and int2) Output: result or answer Formula: ans = int1 + int2
EKT 120/4 Algoritm 1.Print message Key in the first number 2.Read the first number 3.Print message Key in the second number 4.Read the second number 5.Calculate the addition of first number and the second number 6.Print the result
The flowcharts: start Print message Key in the first number Read the first number Print message Key in the second number Read the second number Calculate ans = int1 + int2 Print the result end
1 // Example. Simple Program 2 // A first program in C++ Comments (LINE 1 & 2) Written between /* and */ or following a //. 3 #include <iostream> 4 using namespace std; 5 int main() 6 { 7 cout << "Welcome to C++!\n"; 8 9 return 0; // indicate that program ended successfully 10 } Welcome to C++! A left brace { begins the body of every function and a right brace } ends it. (LINE 6 &10) Prints the string of characters contained between the quotation marks. (LINE 7) The entire line, including cout, the << operator, the string "Welcome to C++!\n" and the semicolon (;), is called a statement. All statements must end with a semicolon. Improve program readability and do not cause the computer to perform any action. preprocessor directive (LINE 3) Message to the C++ preprocessor. Lines beginning with # are preprocessor directives. #include <iostream> tells the preprocessor to include the contents of the file <iostream>, which includes input/output operations (such as printing to the screen). C++ programs contain one or more functions, one of which must be main (LINE 5) Parenthesis are used to indicate a function int means that main "returns" an integer value. More in Chapter 3. return is a way to exit a function from a function.( LINE 9) return 0, in this case, means that the program terminated normally.
EKT 120/4: Debugging a simple C++ program We will do this in lab!
EKT 120/4: Exercise 1. Design an algorithm to find the weighted average of four test scores. The four test scores and their respective weights are given in the following format: testscore1 weigt1 For example, a sample data is as follow: 75 0.20 95 0.35 85 0.15 65 0.30
EKT 120/4: Answer To find the weighted average of test score, first you need to know the each test score and its weight. Next, you multiply each test score with its weight and then add these numbers; the sum is then divided by four to get the average. Therefore, 1. Get testscore1, weighttestscore1 2. Get testscore2, weighttestscore2 3. Get testscore3, weighttestscore3 4. Get testscore4, weighttestscore4
EKT 120/4: Answer 5. Sum = testscore1 * weighttestscore1 + testscore2 * weighttestscore2 + testscore3 * weighttestscore3 + testscore4 * weighttestscore4 6. Average = sum / 4;