Скачать презентацию LECTURE Introduction to Programming Logic and Technique DTNhung Скачать презентацию LECTURE Introduction to Programming Logic and Technique DTNhung

28fd156fa079fe4797b3d8881631f5db.ppt

  • Количество слайдов: 97

LECTURE Introduction to Programming Logic and Technique DTNhung – NIIT HAIPHONG LECTURE Introduction to Programming Logic and Technique DTNhung – NIIT HAIPHONG

Start-up 1. Can you list a serial generation language programming? 2. The vocabulary of Start-up 1. Can you list a serial generation language programming? 2. The vocabulary of commonly spoken communication is ____ the vocabulary of a programming language? a. Greater than b. Less than c. Equal to 3. NIIT What programming language do you like? Hai Phong Software Park 2

Solutions 1. 2. 3. NIIT Generations of programming languages n 1 st generation is Solutions 1. 2. 3. NIIT Generations of programming languages n 1 st generation is machine language. n 2 nd generation is assembly language. n 3 rd generation is high-level languages such as BASIC, Pascal, C… a. Greater than Suggestions: Assembly, Pascal, C, C++, Visual Basic, Visual C++, Java, Delphi, ASP, JSP, Pearl… Hai Phong Software Park 3

Introduction to Programming Logic and Technique n Chapter 1 ü n Chapter 2 n Introduction to Programming Logic and Technique n Chapter 1 ü n Chapter 2 n Representing the logic of Programming using Pseudocodes. Chapter 3 n Introducing to Programming Concept Representing the logic of Programming using Flowcharts Chapter 4 Understanding Iterations and Implementing Modular Programming NIIT Hai Phong Software Park 4

 Introducing to Programming Concept ü ü Computer follows an I-P-O cycle. It needs Introducing to Programming Concept ü ü Computer follows an I-P-O cycle. It needs set of instructions called program to specify the input required, process to be followed, and the output required. Input Program is written in a specific language called Programming language, so that computer can understand the instructions. NIIT Hai Phong Software Park Process Output Feedback 5

Introducing to Programming Concepts A set of instructions to perform a particular job is Introducing to Programming Concepts A set of instructions to perform a particular job is called a program. Therefore, for each job that you want the computer to perform, you require a separate program. Instructions in a program can be: Sequential: Instructions that are executed one after the other. Ø Decision Making: Instructions that evaluate an expression (relation or condition) first and then, depending upon whether the value of the expression is 'true' (non-zero) or 'false' (zero), it transfers the control to a particular statement. Ø Iterative: Instructions that are executed repeatedly, depending on the value of an expression (relation or condition) Ø NIIT Hai Phong Software Park 6

Programming Languages n ü ü ü MACHINE LANGUAGE A sequence of 0 s and Programming Languages n ü ü ü MACHINE LANGUAGE A sequence of 0 s and 1 s can be used to describe any physical operation that the computer performs. Therefore, a computer system uses a number system that consists of only two digits, 0 and 1. This number system is known as the binary number system. The language that the computer understands is called the machine language. It is doubtful if you would be comfortable writing a program in machine language. It is certainly difficult for anybody to remember instructions in the form of 0 s and 1 s. NIIT Command Machine code ADD 00000001 SUBTRACT 00000010 MULTIPLY 00000100 DIVIDE 00001000 READ FROM KEYBOARD 00010000 WRITE ON SCREEN 00100000 WRITE ON PRINTER 01000000 Hai Phong Software Park 7

Machine language 1000 010 11 1 01100101 011 0001 0 1 010 1 n Machine language 1000 010 11 1 01100101 011 0001 0 1 010 1 n No need translater (compiler) The binary number system uses the base of 2. For example, 101 in the binary system is equal to 5 in the decimal system. The conversion can be done as: 101=1*22 + 0*21+ 1* 20 =1*4 + 0*2 + 1*1 = 4 + 0 + 1=5 NIIT Hai Phong Software Park 8

Assembly language LD Ax, 9 LD Bx, 10 ADD Ax, Bx LD (100), Ax Assembly language LD Ax, 9 LD Bx, 10 ADD Ax, Bx LD (100), Ax JMP Bx HLT n n n n Assembler 100 0 00 11 11 000 0 0 1 00 0 111 In the above program: The line number one loads register Ax with the value, 9. The line number two loads register Bx with the value, 10. The line number three adds the value of register Bx to the value of register Ax. The line number four stores the value of register Ax in the main memory location, 100. The line number five uses JMP to jump to register Bx to transfer the control to register Bx. The line number six stops the program execution. NIIT Hai Phong Software Park 9

High level language Ø Ø Ø A high-level programming language consists of a set High level language Ø Ø Ø A high-level programming language consists of a set of instructions, which are represented using simple English words. So, when you want the computer to display the output on the screen, you type the instruction ‘WRITE ON SCREEN’ and not ‘ 00100000’. There are many high-level programming languages available, such as C, C++, and Java. Each language has its own advantages. Programming languages also have a vocabulary, which is referred to as the set of keywords of that language, and a grammar, which is referred to as the syntax. NIIT Hai Phong Software Park 10

High level language n n As stated earlier, a program written in any programming High level language n n As stated earlier, a program written in any programming language is a set of logically related instructions. These instructions have two parts, as shown in the following figure: The two parts of a programming language instruction are: n Operation code (opcode): This part instructs a computer about the operation to be performed. n Operand: This part instructs the computer about the location of the data on which the operation specified by the opcode is to be performed. Operation code (Opcode) n Operand (Address) For example, in the instruction Add A and B, Add is the opcode and A and B are operands NIIT Hai Phong Software Park 11

High level language begin numeric n. Number 1, n. Number 2, n. Number 3 High level language begin numeric n. Number 1, n. Number 2, n. Number 3 n. Number 1 = 15 n. Number 2 = 2 n. Number 3 =n. Number 1% n. Number 2 display n. Number 3 end NIIT Hai Phong Software Park 12

Algorithm n n An algorithm is a sequence of steps required to solve a Algorithm n n An algorithm is a sequence of steps required to solve a problem An algorithm follows the I-P-O cycle to solve the problem. n The two levels of algorithm are: n Macro-level: An algorithm that contains brief steps about a process is called a macro-level algorithm. n Micro-level: An algorithm that contains detailed steps about a process is called a micro-level algorithm. n An algorithm is represented using tools such as: n Pseudocode n Flowcharts NIIT Hai Phong Software Park 13

Algorithm n NIIT An algorithm has the following five characteristics: n An algorithm ends Algorithm n NIIT An algorithm has the following five characteristics: n An algorithm ends after a fixed number of steps. n Each step in an algorithm clearly specifies the action to be performed. n The steps in an algorithm specify basic operations. These operations could include calculations, input/output operations, and comparisons. n An algorithm accepts input data, in a defined format, before it can be processed. n An algorithm generates one or more outputs after the input is processed. The resultant information termed as output can be displayed or stored for future reference. Hai Phong Software Park 14

Pseudocode Vocabulary n n n n n • Operator Declare (variables, literals, procedures, functions…): Pseudocode Vocabulary n n n n n • Operator Declare (variables, literals, procedures, functions…): khai báo Assign: gán giá trị Function: hàm • Procedure: thủ tục • Flowchart: lược đồ thuật toán Pseudocode /sj: udoucode/: mã giả • Variable: biến • Constant/literal: hằng Expression: biểu thức NIIT Arithmetic: toán tử toán học Relational: toán tử quan hệ Logical: toán tử logic Operand: toán hạng Precedence: mức ưu tiên Comment: chú thích Dry run table: chạy thô Hai Phong Software Park 15

Algorithm - Pseudocode Begin numeric n. Num 1, n. Result numeric n. Cons = Algorithm - Pseudocode Begin numeric n. Num 1, n. Result numeric n. Cons = 10 Display ‘Enter the first number’ Accept n. Num 1 n. Result = (n. Num 1 * n. Cons) / 73 If n. Result > n. Cons Display “ the number is greater than 10’ else Display “ The number is less than 10’ Display n. Result End NIIT Hai Phong Software Park 16

Pseudocode Advantages of pseudocode are: n It is easier and faster to write as Pseudocode Advantages of pseudocode are: n It is easier and faster to write as it uses English like statements. ü It does not need to be rewritten if any changes are made because each step is independent and may be modified without altering the other steps. ü It can be converted to a program using any programming language. ü n Disadvantages of pseudocode are: v v Pseudocode does not provide a graphical representation of an algorithm. Pseudocode depicting too many nested conditions may be difficult to understand. NIIT Hai Phong Software Park 17

Vocabulary - Pseudocode n n n Declare (variables, literals, procedures, functions…): khai báo Assign Vocabulary - Pseudocode n n n Declare (variables, literals, procedures, functions…): khai báo Assign (values to variables): gán Operator n n n n NIIT Arithmetic: toán tử toán học Relational: toán tử quan hệ Logical: toán tử logic Operand: toán hạng Operator precedence: toán tử ưu tiên Comment: chú thích Dry run table: chạy thô Hai Phong Software Park 18

Pseudocode Begin numeric n. Num 1, n. Result // Declare variables numeric n. Cons Pseudocode Begin numeric n. Num 1, n. Result // Declare variables numeric n. Cons = 10// Direct assignment, initialize first Display ‘Enter the first number’ Accept n. Num 1 //Accept statement n. Result = (n. Num 1 * n. Cons) / 73 If n. Result > n. Cons Display “ the number is greater than 10’ else Display “ The number is less than 10’ Display n. Result value End ================= Variable: n. Num 1, n. Result Constant: n. Cons Expression: n. Result =(n. Num 1*n. Cons)/73 //: Comment Char, numeric: tupe of data NIIT Hai Phong Software Park 19

Flowchart n n n A flowchart is a graphical representation of the steps to Flowchart n n n A flowchart is a graphical representation of the steps to be ollowed for solving a problem. It consists of a set of symbols. Each symbol represents a specific activity. NIIT Hai Phong Software Park 20

Flowchart n n Advantages of Flowcharts are: n Flowcharts are a better method of Flowchart n n Advantages of Flowcharts are: n Flowcharts are a better method of communicating logic. n The flowcharts help in analyzing the problems effectively. n The flowcharts act as a guide during the program development phase. n It is easier to debug errors in logic using a flowchart. n The flowcharts help in maintaining the programs. Disadvantages of Flowcharts are: n A lengthy flowchart may extend over multiple pages, which reduces readability. n As flowcharts symbols cannot be typed, drawing a flowchart using any graphic tool is a time consuming process. n The changes made to a single step may cause redrawing the entire flowchart. n A flowchart representing a complex algorithm may have too many flow lines. This reduces readability, and it is time-consuming to draw and understand the logic Readability. NIIT Hai Phong Software Park 21

Pseudocode NIIT Hai Phong Software Park 22 Pseudocode NIIT Hai Phong Software Park 22

Keywords in Pseudocode NIIT Hai Phong Software Park 23 Keywords in Pseudocode NIIT Hai Phong Software Park 23

Keyword in Pseudocode begin … end: These keywords are used to start and finish Keyword in Pseudocode begin … end: These keywords are used to start and finish pseudocode. Begin is the first line and end is the last line of pseudocode. accept: This keyword is used to obtain an input from a user. display: This keyword is used to present a result or an output. if … else… endif: These keywords are used in decision-making. //: Comment Do … while, for …, repeat … until: Represent loop NIIT Hai Phong Software Park 24

Using Pseudocodes to Represent Sequential Code The pseudocode for adding two numbers is as Using Pseudocodes to Represent Sequential Code The pseudocode for adding two numbers is as follows: // starting the pseudocode begin // input consists of accepting two numbers accept first_number, second_number // process of adding the two numbers compute sum as first_number + second_number // output for displaying the sum display ‘The sum of given two numbers is’ sum // ending the pseudocode end NIIT Hai Phong Software Park 25

Variables and Constants n n The internal memory consists of different locations in which Variables and Constants n n The internal memory consists of different locations in which data is stored. A computer needs to identify the memory locations to be able to retrieve values from or store values in them. A variable refers to the memory location whose value changes during the program execution. A constant refers to the memory location whose value does not change during the program execution. NIIT Hai Phong Software Park 26

Variables and Constant n n You need to declare a variable before using it Variables and Constant n n You need to declare a variable before using it in a program. The declaration of a variable assigns a name to the variable and specifies the type of data the variable can store. Naming conventions: n n The first letter of the variable name might indicate the data type of the variable: c. Name and n. Age The variable name should clearly describe the purpose of a variable: n. Score The variable name should not contain an embedded space or symbols such as ! @ # $ % ^ & * ( ) { } [ ]. , : ; “ ‘ / and . You can use an underscore when a space is required in a variable name, for example, n. Basic_Salary. If a variable name consists of multiple words without spaces in between, capitalize the first letter of each word for readability. Some examples are n. Total. Score and n. Sum. Of. Squares. NIIT Hai Phong Software Park 27

Variables and Constant NIIT Hai Phong Software Park 28 Variables and Constant NIIT Hai Phong Software Park 28

Data Types n Numeric: n n n Numeric variables can contain only numbers. These Data Types n Numeric: n n n Numeric variables can contain only numbers. These variables can be used in arithmetic operations. Character: Character variables can contain any combination of letters, numbers, and special characters. n These variables cannot be used for calculation. Let us look to the code of accepting two numbers and displaying the sum with the data type declarations. n n begin numeric n. Num 1, n. Num 2, n. Sum //declaring variables accept n. Num 1 accept n. Num 2 n. Sum = n. Num 1 + n. Num 2 display n. Sum end NIIT Hai Phong Software Park 29

Assign values n The variables can be assigned values in the following two methods: Assign values n The variables can be assigned values in the following two methods: n n n Direct assignment Accept Statement In the direct assignment method, values can be assigned to variables using the equal to (=) sign, as shown in the following syntax: variable_name=value n Examples: numeric n. Height, n. Age, n. Counter character c. Code n. Height = 172 n. Age = 35 n. Counter = 0 c. Code = “XYZ” NIIT Hai Phong Software Park 30

Assign values n Values can be assigned to variables using the accept statement, as Assign values n Values can be assigned to variables using the accept statement, as shown in the following syntax. accept variable_name n Examples: character c. Name numeric n. Age display “Enter your name” accept c. Name display “Enter your age” accept n. Age NIIT Hai Phong Software Park 31

Variables and Constant Identify the variable and constant data in the following situation. Each Variables and Constant Identify the variable and constant data in the following situation. Each day, the courier service delivers some letters. The number of letters is different each day. Regardless of the number of letters delivered by the courier service, they are paid a carrying charge of $5. Variable: Constant: NIIT Hai Phong Software Park 32

Operators Arithmetic: +, -, *, /, % n Relational: >, <. >=, <=, =, Operators Arithmetic: +, -, *, /, % n Relational: >, <. >=, <=, =, != n Logical: AND, OR, NOT Bảng chân trị (chân lý) n X AND(X, Y) OR (X, Y) NOT(X) 0 0 1 0 1 1 1 0 0 1 NIIT Y 1 1 1 0 Hai Phong Software Park 33

Problem 1 n Create the pseudocode to accept item name, price, and quantity. You Problem 1 n Create the pseudocode to accept item name, price, and quantity. You need to calculate value as the product of price and quantity, and display the calculated value and the item name using variables. Answer: begin accept c. Item_name, n. Price, n. Quantity, n. Sale_value = n. Price * n. Quantity display c. Item_name display n. Sale_value end NIIT Hai Phong Software Park 34

Priority - Precedence Operator Description () ! * / % + < <= Parentheses Priority - Precedence Operator Description () ! * / % + < <= Parentheses Logical NOT Multiplication Division Modulo division Addition Subtraction Less than or equal to >= Greater than Equal to Not equal to Logical AND Logical OR Precedence Level Greater than or equal to > = != AND OR Associativity NIIT 1 2 Left to right 3 Left to right 4 Left to right 5 Left to right 6 Left to right 7 8 Operator Precedence Hai Phong Software Park 35

Conditional Execution n Many problems require decisions to be made. All decisions may or Conditional Execution n Many problems require decisions to be made. All decisions may or may not state an action to be taken if the condition is false. The following types of decision-making constructs can be used in an algorithm. n n NIIT if constructs switch…case constructs Hai Phong Software Park 36

Conditional Execution n n In simple if construct, if the condition specified is true, Conditional Execution n n In simple if construct, if the condition specified is true, the statements contained within the if block are executed. Pseudocode segment to represent the simple if constructs as follows: if begin endif NIIT Hai Phong Software Park 37

Conditional Execution In the if. . . else construct, the statements within the if Conditional Execution In the if. . . else construct, the statements within the if block are executed for condition being true and the statements within the else block are executed for condition being false. if begin to be executed if is false> Hai Phong Software Park 38

If Construct n Problem Statement 1: n n Accept two numbers and print the If Construct n Problem Statement 1: n n Accept two numbers and print the larger of the two numbers. Solution: begin numeric n. Num 1, n. Num 2 accept n. Num 1 accept n. Num 2 if n. Num 1 = n. Num 2 begin display “The numbers are equal” end NIIT Hai Phong Software Park 39

If Construct else if n. Num 1> begin display end else begin display endif If Construct else if n. Num 1> begin display end else begin display endif end NIIT n. Num 2 n. Num 1 n. Num 2. // end of second if statement // end of first if statement Hai Phong Software Park 40

If Construct n Problem Statement 2: n n Print the value of n. X If Construct n Problem Statement 2: n n Print the value of n. X only if the value of n. X is greater than 10 and n. X is an even number. Solution: begin numeric n. X accept n. X if n. X > 10 //first if-statement begin if n. X % 2 =0 //second if-statement display n. X endif // end of second if-statement endif //end of first if statement end NIIT Hai Phong Software Park 41

If Construct Problem Statement 3: To decide about the discount percentage on a TV, If Construct Problem Statement 3: To decide about the discount percentage on a TV, the sales person needs to check the type of TV. If the TV is Black and White [B], the discount will be 5 percent of the selling price. If the type of TV is colored [C], then he has to verify the size of TV screen. For 14 inches screen, discount is 8 percent of the selling price and for 21 inches screen, the discount is 10 percent of the selling price. Write a pseudocode to show the discount percentage. NIIT Hai Phong Software Park 42

If Construct n Solution: begin numeric n. Screen, n. Discount, SP character c. Type If Construct n Solution: begin numeric n. Screen, n. Discount, SP character c. Type accept n. Screen accept SP if c. Type = ‘B’ // first if statement begin compute n. Discount as 5% of SP end else if c. Type = ‘C’ // second if statement begin if n. Screen =14 // third if statement begin compute NIIT end n. Discount as 8% of SP Hai Phong Software Park 43

If Construct else begin if n. Screen = 21 // fourth if statement begin If Construct else begin if n. Screen = 21 // fourth if statement begin compute n. Discount as 10% of SP endif // end of fourth if statement endif // end of third if statement endif // end of second if statement endif // end of first if statement end NIIT Hai Phong Software Park 44

The switch…case construct enables you to make a decision by selecting from number of The switch…case construct enables you to make a decision by selecting from number of choices. The pseudocode of the switch…case construct is as follows: switch (expression) begin case constant 1: execute these statements break case constant 2: execute these statements break default: execute these statements end NIIT Hai Phong Software Park 45

Problem 1 n Consider the following problem statement for switch…case construct. Amy is writing Problem 1 n Consider the following problem statement for switch…case construct. Amy is writing the algorithm for automated telephone call transfer to various departments of the company such as Marketing, Finance, Customer Care, Human Resource (HR), and Information. Write the solution using Pseudocode. NIIT Hai Phong Software Park 46

Problem 1 begin numeric n. Call display “If you want to get connected to Problem 1 begin numeric n. Call display “If you want to get connected to Marketing department, press 1, Finance department press 2, Customer Care department press 3, HR department press 4. If you are not sure press any number other than 1 to 4, the call will be transferred to Information department” accept n. Call NIIT Hai Phong Software Park 47

Problem 1 switch (n. Call) begin case 1: //case 1 begins Transfer call to Problem 1 switch (n. Call) begin case 1: //case 1 begins Transfer call to the Marketing department break case 2: //case 2 begins Transfer call to the Finance department break case 3: //case 3 begins Transfer call to the Customer Care department break case 4: //case 4 begins Transfer call to the HR department break default: //if none of the cases match, the //following line is executed Transfer call to the Information department end NIIT Hai Phong Software Park 48

Vocabulary - Programming n n n n Decision-making construct: cấu trúc ra quyết định Vocabulary - Programming n n n n Decision-making construct: cấu trúc ra quyết định Loop construct: cấu trúc lặp Procedure: thủ tục Function: hàm to invoke: triệu gọi Parameter: tham số scope (local, global): phạm vi biến modular approach of programming: lập trình tiếp cận theo hướng chia module NIIT Hai Phong Software Park 49

Problem Statement 1: n n Problem Statement 1: n Write a pseudocode to display Problem Statement 1: n n Problem Statement 1: n Write a pseudocode to display the sum of two numbers by using variables. Solution: begin accept n. Num 1 //assigning values to variables accept n. Num 2 n. Sum = n. Num 1 + n. Num 2 display n. Sum end NIIT Hai Phong Software Park 50

Problem Statement 2 n Problem Statement 2: n Write a pseudocode where interest is Problem Statement 2 n Problem Statement 2: n Write a pseudocode where interest is calculated and displayed for the given balance and rate. Solution: n begin //start accept Name, Balance, Rate //input compute Interest as Balance x Rate //process display Name and Interest //output end //end NIIT Hai Phong Software Park 51

Problem Statement 3 n Problem Statement 3: n n Write a pseudocode where a Problem Statement 3 n Problem Statement 3: n n Write a pseudocode where a number is incremented by 1 Solution: begin accept Number compute Number as Number + 1 display Number end NIIT //starting //input //process //output //end Hai Phong Software Park 52

Problem 4: Given: n. Num 1 = 5, n. Num 2 = 6 Swap Problem 4: Given: n. Num 1 = 5, n. Num 2 = 6 Swap their value together. Bình NIIT 1 1 Numeric n. Num 1 = n. Num 2 = n. Swap = n. Num 1 = n. Num 2 = n. Num 1, n. Num 2, n. Swap 5 6 0 n. Num 1 n. Num 2 n. Swap Bình rỗng Hai Phong Software Park Bình 2 2 53

A Problem 5: NIIT Hai Phong Software Park 54 A Problem 5: NIIT Hai Phong Software Park 54

Flowchart NIIT Hai Phong Software Park 55 Flowchart NIIT Hai Phong Software Park 55

Problem-solving using Flowcharts NIIT Hai Phong Software Park 56 Problem-solving using Flowcharts NIIT Hai Phong Software Park 56

Problem-solving using Flowcharts NIIT Hai Phong Software Park 57 Problem-solving using Flowcharts NIIT Hai Phong Software Park 57

Drawing Flowchart NIIT Hai Phong Software Park 58 Drawing Flowchart NIIT Hai Phong Software Park 58

Rules of Flowcharting n n n n The entire logic of a flowchart should Rules of Flowcharting n n n n The entire logic of a flowchart should be represented using the standard symbols. The flowchart should be clear, precise, and easy to follow. Flowcharts can have only one start point and one end point. The steps in a flowchart should follow top-to-bottom or left-to-right approach. All necessary inputs should be listed out in logical order. The start and stop symbols should have only a single flow line. The input, process, output, and display symbols should have two flow lines connecting to the previous symbol and to the next symbol. The decision symbol should have one flow line connecting to the previous symbol but two flow lines connecting to the next symbol for each possible solution such as Yes/No, Y/N, True/False. If too many flow lines make the flowchart complex, it is better to use connector symbols to reduce the number of flow lines. Flowcharts should use page connectors if they extend over multiple pages. It is useful to test the logic of flowchart by passing through it with sample test data. NIIT Hai Phong Software Park 59

Conditional Execution using Flowchart NIIT Hai Phong Software Park 60 Conditional Execution using Flowchart NIIT Hai Phong Software Park 60

Conditional Execution using Flowchart NIIT Hai Phong Software Park 61 Conditional Execution using Flowchart NIIT Hai Phong Software Park 61

Conditional Execution using Flowchart NIIT Hai Phong Software Park 62 Conditional Execution using Flowchart NIIT Hai Phong Software Park 62

Nested If- Statements in Flowchart NIIT Hai Phong Software Park 63 Nested If- Statements in Flowchart NIIT Hai Phong Software Park 63

Nested If- Statements in Flowchart NIIT Hai Phong Software Park 64 Nested If- Statements in Flowchart NIIT Hai Phong Software Park 64

Switch - case NIIT Hai Phong Software Park 65 Switch - case NIIT Hai Phong Software Park 65

Interation n n One of the most important characteristics of a computer is its Interation n n One of the most important characteristics of a computer is its ability to execute a series of instructions repeatedly. This ability of the computer gives you the flexibility to control the number of times a task is to be repeated. The following types of loops can be used in a pseudocode: v v while loop repeat…until loop for goto NIIT Hai Phong Software Park 66

For loop n The for loop: n n The for loop is used when For loop n The for loop: n n The for loop is used when the number of iterations of the loop is known before the control enters the loop. The for loop consists of the following three parts separated by semicolons. n n Initialization expression: The numeric variable is initialized using a value. Evaluation expression: The condition is tested at the beginning of iteration of the loop. When the expression evaluates to false, the loop terminates. Increment/decrement expression: The value of the variable is increased. In a for loop, initializing a variable, evaluating a condition, and incrementing the value of the variable are all specified in one statement. NIIT Hai Phong Software Park 67

For loop begin initialize the index for test the index begin increment the index For loop begin initialize the index for test the index begin increment the index //perform the statements if the test is true endfor //end of for loop //perform the statements if the test is false end NIIT Hai Phong Software Park 68

For Loop The pseudocode representation of a for loop is as follows: begin initialize For Loop The pseudocode representation of a for loop is as follows: begin initialize the index for test the index begin increment the index // perform the statements if the test is true endfor //end of for loop // perform the if the test is false end NIIT Hai Phong Software Park 69

Problem Statement 1 n Problem Statement 1: n NIIT Draw a flowchart to calculate Problem Statement 1 n Problem Statement 1: n NIIT Draw a flowchart to calculate the sum of 10 numbers entered by the user. Hai Phong Software Park 70

The while Loop : : while (condition) begin : : end : : NIIT The while Loop : : while (condition) begin : : end : : NIIT Hai Phong Software Park 71

Problem 2 begin numeric n. Marks, n. Total, n. Counter, n. Avg n. Marks Problem 2 begin numeric n. Marks, n. Total, n. Counter, n. Avg n. Marks = 0 n. Total = 0 n. Counter = 0 n. Avg = 0 while (n. Counter < 30) //while the condition is true begin display “Enter the total marks of a student” accept n. Marks n. Total = n. Total + n. Marks n. Counter = n. Counter + 1 //increments the counter by one end n. Avg = n. Total / n. Counter //calculates the average display “The average marks of the class is” display n. Avg //displays the average end NIIT Hai Phong Software Park 72

The repeat…until Loop : : repeat begin : : end until (condition) : NIIT The repeat…until Loop : : repeat begin : : end until (condition) : NIIT Hai Phong Software Park 73

NIIT Hai Phong Software Park 74 NIIT Hai Phong Software Park 74

The goto Statement n n A goto statement is used in situations in which The goto Statement n n A goto statement is used in situations in which the execution of a pseudocode does not follow the steps in a sequential order. To use a goto statement in a pseudocode, you need to use labels. A label identifies the position in a pseudocode where the control of execution can reach using a goto statement. While assigning name to a label, a colon should follow the label name. begin numeric n. Counter=2 Label 1: n. Counter=n. Counter+2 display n. Counter //displays all the even numbers if(n. Counter<=100) goto Label 1 //transfers the control to Label 1 end NIIT Hai Phong Software Park 75

Modular Approach to Programming A program needs to be amended periodically to respond to Modular Approach to Programming A program needs to be amended periodically to respond to changing conditions or requirements. This encouraged programmers to adopt a more disciplined approach to program writing. The techniques that were adopted are known as structured programming techniques. Structured programming includes features that are designed not only to solve the problem at hand but also to make the logic clear to someone reading the program. NIIT Hai Phong Software Park 76

Modular Approach to Programming Long, continuous programs can be broken up into a series Modular Approach to Programming Long, continuous programs can be broken up into a series of individual modules that are related to each other in a specified manner. NIIT Hai Phong Software Park 77

Procedure n Procedure: n n n NIIT In a modular approach, one of the Procedure n Procedure: n n n NIIT In a modular approach, one of the methods of representing a module is procedure. The working of a procedure is termed as a call-return mechanism. The following steps are part of a call–return mechanism: n A procedure is called. n The set of operations stored within the procedure are executed. n The control is returned to the calling code. Hai Phong Software Park 78

Procedure n n n Declaring, Defining, and Invoking Procedures: Procedures need to be declared Procedure n n n Declaring, Defining, and Invoking Procedures: Procedures need to be declared and defined before they can be called. The declaration of procedures is similar to a declaration of any other variable in an pseudocode. Procedures are declared using the following syntax: procedure n The procedure is defined when the procedure is expressed with its body. The syntax of the procedure definition is: procedure begin //the set of statements of a procedure end n The calling of a procedure is also called invoking a procedure. The method for invoking procedure is known as a procedure call. The syntax of a procedure call is: call NIIT Hai Phong Software Park 79

Procedure n Problem Statement 1: n n Accept the test scores for ten students Procedure n Problem Statement 1: n n Accept the test scores for ten students and display their individual averages. The scores of the students cannot be negative. The following table lists the variables used in the solution. Variable Name Student Name character c. Student. Name Score of Test 1 numeric n. Test 1 Score of Test 2 numeric n. Test 2 Score of Test 3 numeric n. Test 3 Average of Test Scores NIIT Data Type numeric n. Average Hai Phong Software Park 80

Procedure n Solution: //code segment to calculate average marks of 10 students procedure Accept Procedure n Solution: //code segment to calculate average marks of 10 students procedure Accept // declaring subprogram Accept procedure Average // declaring subprogram Average begin numeric n. Test 1, n. Test 2, n. Test 3, n. Average character c. Student. Name call Accept // calling subprogram Accept call Average // calling subprogram Avearge display c. Student. Name n. Average end // code for the subprograms comes here : : NIIT Hai Phong Software Park 81

Procedure Accept c. Student. Name Accept Average Accept n. Test 1 Average n. Average=(n. Procedure Accept c. Student. Name Accept Average Accept n. Test 1 Average n. Average=(n. Test 1+n. Test 2 +n. Test 3) / 3 Accept n. Test 2 Display c. Student. Name, n. Average Return Accept n. Test 3 Is n. Test 1>=0 AND n. Test 2>=0 AND n. Test 3>=0 ? Yes No Return Display “Test score cannot be less than zero” NIIT Hai Phong Software Park 82

Procedure n Problem Statement 2: n NIIT The total expenditure on salaries for the Procedure n Problem Statement 2: n NIIT The total expenditure on salaries for the month needs to be calculated. As per company policy an employee receives a minimum of $500. Depict the logic for automating the task by using pseudocode and flowchart. Hai Phong Software Park 83

Solution n Solution: : if c. Choice = “ Y” begin call Accept call Solution n Solution: : if c. Choice = “ Y” begin call Accept call Summation end //invoking Accept //invoking Summation : : procedure Accept //statements of the subprogram : begin accept n. Salary NIIT Hai Phong Software Park 84

Solution if n. Salary >=500 begin return // returning the value end else begin Solution if n. Salary >=500 begin return // returning the value end else begin display ‘Salary cannot be less than $500” endif end // end of the subprogram procedure Summation // statements of the subprogram begin n. Tot. Salary = n. Tot. Salary +n. Salary return n. Tot. Salary end NIIT Hai Phong Software Park 85

Procedure Parameters n Procedure Parameters: n n Parameters are like a bridge between the Procedure Parameters n Procedure Parameters: n n Parameters are like a bridge between the procedure and the calling code. Parameters comprise data that is used and processed by a procedure. Parameters can be variables of the numeric or character data type. Parameters are used to perform the following tasks: n n NIIT Send data to a procedure Retrieve data from a procedure Hai Phong Software Park 86

Function n Function: A function is a block of statements that perform a specific Function n Function: A function is a block of statements that perform a specific task. The underlying fundamental of functions and procedures are very similar, and they can be used interchangeably. The difference between a function and a procedure is that a procedure does not return any value to a calling program while a function returns a value to the calling program after it is executed. The functions in a pseudocode interact with each other by passing and receiving data. Functions also operate on the call–return mechanism. The following are the steps in the call–return mechanism using functions: n n n NIIT The function is called from the calling code. The sets of operations within the functions are executed. The execution is returned to the calling code using a return value Hai Phong Software Park 87

Function n Declaring, Defining, and Invoking Functions: n Functions are declared like any other Function n Declaring, Defining, and Invoking Functions: n Functions are declared like any other procedure or variable. The declaration format is function n The function are defined same as procedures. The only difference is that they have a return statement at the end. The syntax of the function definition is: function begin //the function statements return // The function returns some value end n After a function is declared, it can be invoked from the pseudocode. The method for invoking functions is known as a function call. The syntax for the function call is: call NIIT Hai Phong Software Park 88

Function Parameters n Function Parameters: n n NIIT Function parameters form an interface between Function Parameters n Function Parameters: n n NIIT Function parameters form an interface between the function and the calling code. Functions accept values in the form of parameters. If parameters are specified, they should be separated using commas. Unlike procedures, the functions use the parameters only for receiving data from the calling code. They send value to the calling code using the return statement. Therefore, functions have only input parameters. Hai Phong Software Park 89

Scope of Variables n Scope of Variables: n Variables can be declared within or Scope of Variables n Scope of Variables: n Variables can be declared within or outside the begin…end block of a main pseudocode, procedure, or function. n Depending on the place where variables are declared the variables have two types of scope. n Local Scope n Global Scope n The variables that are declared inside the begin. . . end block of a main pseudocode, function, or procedure have local scope and they are called local variables. NIIT Hai Phong Software Park 90

Scope of Variables n The following pseudocode describes the local scope of the variables. Scope of Variables n The following pseudocode describes the local scope of the variables. begin numeric n. Num display “Enter any number” accept n. Num if (n. Num > 10) begin numeric n. Remainder = n. Num % 2 display n. Remainder endif end NIIT Hai Phong Software Park 91

Scope of Variables Following pseudocode describes the local scope using function. begin numeric n. Scope of Variables Following pseudocode describes the local scope using function. begin numeric n. Num display “Enter any number” accept n. Num if (n. Num > 10) begin call display. Remainder(n. Num) display n. Remainder //an invalid statement endif end function display. Remainder (numeric n. Number) begin numeric n. Remainder = n. Number % 2 display n. Remainder end NIIT Hai Phong Software Park 92

Scope of Variables Procedure Test() begin numeric n. X, n. Y n. X = Scope of Variables Procedure Test() begin numeric n. X, n. Y n. X = 6 n. Y = 10 Display n. X, n. Y Call Test () End Procedure Test() Begin numeric n. X nx = 9 Display n. X, n. Y End NIIT Hai Phong Software Park 93

Scope of Parameters: n The parameters of a procedure or function are variables that Scope of Parameters: n The parameters of a procedure or function are variables that can be accessed only from inside the procedure or the function. n This implies that the parameters act as the local variables of a function or a procedure. n The following comprise the scope of parameters: n Parameters exist only inside the function or procedure for which they are defined. They cannot be accessed from outside the function or procedure. They retain their value until the function or procedure is executed. n Parameters are initialized every time the function or procedure is called. n NIIT Hai Phong Software Park 94

Questions n A compiler is: n n A detailed flowchart is called a: A Questions n A compiler is: n n A detailed flowchart is called a: A high-level language Language-specific A machine language A source code n n The symbol that represents comments in a flowchart is: n n A procedure/subroutine symbol An input symbol An annotation symbol A flow line NIIT Macro flowchart Lengthy flowchart Micro flowchart Detailed flowchart Which of the following is NOT a type of algorithm? n n Flowchart Program Pseudocode Decision table Hai Phong Software Park 95

Question Literals are: n Values that change continuously n Memory locations n Values that Question Literals are: n Values that change continuously n Memory locations n Values that do not change n Names given to variables Which operators are used to test the relationship between two variables or between a variable and a constant? n n A statement consisting of variables, literals, constants, and operators is called a/an: n Function n Identifier n Operator n Expression NIIT Arithmetic operators Logical operators Relational operators Special operators Input is accepted using the keyword accept in: n Pseudocode n A Flowchart n An Algorithm n An Expressiont Hai Phong Software Park 96

THANK YOU Any questions? THANK YOU Any questions?