4fc3892bdd84c1294fa8d479f3d63c7ce454ceef (1).pdf

Full Transcript

Programming Fundamentals – ALF Nomer B. Aguado College of Computing Studies Revision made on June 2024 i VISION Laguna University shall be a socially responsive educational institution...

Programming Fundamentals – ALF Nomer B. Aguado College of Computing Studies Revision made on June 2024 i VISION Laguna University shall be a socially responsive educational institution of choice providing holistically developed individuals in the Asia-Pacific Region MISSION Laguna University is committed to produce academically prepared and technically skilled individuals who are socially and morally upright ii Table of Contents Module 2: Logic Formulation Algorithm Introduction 41 Learning Outcomes 41 Lesson 1: Programming Concepts 42 Program Structure 42 Understanding Simple Program Logic 43 Understanding the Program Development Cycle 45 Understanding the Problem 46 Planning the Logic 47 Coding the Program 48 Using the Software to Translate the Program into Machine Program 48 Testing the Program 50 Putting the Program into Production 51 Maintaining the Program 51 Using Pseudocode Statements and Flowchart Symbols 51 Writing Pseudocode 52 Drawing Flowchart 53 Understanding Programming and User Environment 55 Understanding Evolution of Programming Models 57 Lesson 2: Writing Plan to Program Code 58 C Language Basic Statements 59 Output statement 59 Input statement 59 Assignment statement 60 Miscellaneous statements 60 Data types 60 Format characters 61 Backslash characters 61 Arithmetic operators 61 Relational operators 62 Logical operators 62 Lesson 3: Problem Solving – Putting to Reality 62 Sequential 62 Selective 69 Repetitive 85 Activity 89 Assessment Task 90 iii Summary 95 References 96 Course Code: CC 1101 - Computer Programming 1 (Fundamentals of Programming) Course Description: The course covers the use of general-purpose programming language to solve problems. The emphasis is to train students to design, implement, test and debug programs intended to solve computing problems using fundamental programming constructs. This course is an introductory lecture/lab course on the basic foundation in programming. This course deals with the basic programming concepts with the applications of the common program designing tools such as flow chart and pseudocode; program structures like conditions, loops, and iterations, branching, sorting, and array processing. Course Intended Learning Outcomes (CILO): At the end of this course, the students should be able to: 1. Explain the basic concepts of programming; 2. Formulate solution to programming problem using flowchart and pseudocode; 3. Recognize the basic structure and data types in C language; 4. Perform console input and output, utilize basic operators and perform sequential processing; 5. Utilize the control structures for selection; and 6. Apply the control structures for iterations; Course Requirements: ▪ Assessment Tasks (AT) - 60% ▪ Major Exams (ME) - 40% Periodic Grade 100% Prelim Grade (PG) = (AT x 60%) + (ME x 40%) Midterm Grade (MG) = ((AT x 60%) + (ME x 40%)) x 70%)+(PG x 30%) Final Grade = ((AT x 60%) + (ME x 40%)) x 70%)+(MG x 30%) iv Note: For Midterm Module v MODULE 2 LOGIC FORMULATION: ALGORITHM Introduction Program Logic Formulation is the process of coming out with the basic steps to implement a procedure in computer programming. This is usually resorted to when having top-down design. Furthermore, it is the process of coming up with the appropriate methodology in developing a specific program logic that will perform a prescribed computing task or solve a problem using the computer (Corpuz, 2012). Flowcharts and pseudocodes are the two of most common output of this process. In this lesson, you will be able to learn how to create algorithms to solve problems and express those algorithms in the form of pseudocode. These tools will help you solve machine problems systematically and logically. Learning Outcomes At the end of the lesson, the student is expected to: 1. Formulate simple program logic 2. Apply the steps involved in the program development cycle 3. Demonstrate the use of Pseudocode statements and flowchart symbols 4. Apply the use of sentinel value to end a program 5. Demonstrate and understand Programming and user environments 6. Elaborate the evolution of programming models 7. Explain the basic data processing terms; 8. Describe the data processing cycle; 9. Enumerate and define the different elements of a computer program 10. Formulate expressions with ease 11. Evaluate and simplify expressions 12. Enumerate and explain the classification of commands 41 Lesson 1: Programming Concepts A program is a set of step-by-step instructions that directs the computer to do the tasks you want it to do and produce the results you want. In creating programs, a programmer must choose a programming language to be used. A set of rules that provides a way of telling a computer what operations to perform is called a programming language. Developing a program involves steps similar to any problem-solving task. Program structure: Structure is the framework or pattern to be followed in creating a program. This structure varies from language to language. However, this course will use a structure that the author believe acceptable in most programming languages. This structure is defined as follows: Figure 1. Program Structure Program Heading Declaration Part Variables and other program elements to be used Body of the Program Program flow End Program heading is written, as a comment in other languages, used to introduce the name of a program or tell what the program is all about. Declaration part is where all the variables to be used in the program should be declared or introduced with their specific type (numeric or non-numeric / string). Body of the program is composed of all the statements/commands that are used to run the program. This group of statements is written following a specific logical flow the program is suited for. What is a System (program)? The word System is derived from Greek word Systema, which means an organized relationship between any set of components to achieve some common cause or objective. A system is “an orderly grouping of interdependent 42 components linked together according to a plan to achieve a specific goal.” (System Analysis and Design - Overview - Tutorialspoint, n.d.) For example, traffic management system, payroll system, automatic library system, human resources information system. ❖ Understanding Simple Program Logic A program with syntax errors cannot be fully translated and cannot execute. A program with no syntax errors is translatable and can execute, but it still might contain logical errors and produce incorrect output as a result. For a program to work properly, you must develop correct logic; that is, you must write program instructions in a specific sequence, you must not leave any instructions out, and you must not add extraneous instructions. Suppose you instruct someone to make a cake as follows: Get a bowl Stir Add two eggs Add a gallon of gasoline Bake at 350 degrees for 45 minutes Add three cups of flour The dangerous cake-baking instructions are shown with a Don’t Do It icon. You will see this icon when the book contains an unrecommended programming practice that is used as an example of what not to do. Even though the cake-baking instructions use English language syntax correctly, the instructions are out of sequence, some are missing, and some instructions belong to procedures other than baking a cake. If you follow these instructions, you will not make an edible cake, and you may end up with a disaster. Many logical errors are more difficult to locate than syntax errors—it is easier for you to determine whether eggs is spelled incorrectly in a recipe than it is for you to tell if there are too many eggs or if they are added too soon. Just as baking directions can be provided in Mandarin, Urdu, or Spanish, program logic can be expressed correctly in any number of programming languages. Because this book is not concerned with a specific language, the programming examples could have been written in Visual Basic, C/C++, or Java. For convenience, this book uses instructions written in English! After you learn French, you automatically know, or can easily figure out, many Spanish words. Similarly, after you learn one programming language, it is much easier to understand several other languages. Most simple computer programs include steps that perform input, processing, and output. Suppose you want to write a computer program to double any number you provide. You can write the program in a programming language such as Visual Basic or Java, but if you were to write it using English-like statements, it would look like this: 43 input myNumber set myAnswer = myNumber * 2 output myAnswer Don’t Do It Don't bake a cake like The number-doubling process includes three instructions: The instruction to input myNumber is an example of an input operation. When the computer interprets this instruction, it knows to look to an input device to obtain a number. When you work in a specific programming language, you write instructions that tell the computer which device to access for input. For example, when a user enters a number as data for a program, the user might click on the number with a mouse, type it from a keyboard, or speak it into a microphone. Logically, however, it doesn’t matter which hardware device is used, as long as the computer knows to accept a number. When the number is retrieved from an input device, it is placed in the computer’s memory in a variable named myNumber.Avariable is a named memory location whose value can vary—for example, the value of myNumber might be 3 when the program is used for the first time and 45 when it is used the next time. In this book, variable names will not contain embedded spaces; for example, the book will use myNumber instead of my Number. From a logical perspective, when you input, process, or output a value, the hardware device is irrelevant. The same is true in your daily life. If you follow the instruction “Get eggs for the cake,” it does not really matter if you purchase them from a store or harvest them from your own chickens—you get the eggs either way. There might be different practical considerations to getting the eggs, just as there are for getting data from a large database as opposed to getting data from an inexperienced user working at home on a laptop computer. For now, this book is only concerned with the logic of operations, not the minor details. A college classroom is similar to a named variable in that its name (perhaps 204 Adams Building) can hold different contents at different times. For example, your Logic class might meet there on Monday night, and a math class might meet there on Tuesday morning. The instruction set myAnswer = myNumber * 2 is an example of a processing operation. In most programming languages, an asterisk is used to indicate multiplication, so this instruction means “Change the value of the memory location myAnswer to equal the value at the memory location myNumber times two.” Mathematical operations are not the only kind of processing operations, but they are very typical. As with input operations, the type of hardware used for processing is irrelevant—after you write a program, it can be used on computers of different brand names, sizes, and speeds. In the number-doubling program, the output myAnswer instruction is an example of an output operation. Within a particular program, this statement could cause the output to appear on the monitor (which might be a flat-panel 44 plasma screen or a smartphone display), or the output could go to a printer (which could be laser or ink-jet), or the output could be written to a disk or DVD. The logic of the output process is the same no matter what hardware device you use. When this instruction executes, the value stored in memory at the location named myAnswer is sent to an output device. (The output value also remains in computer memory until something else is stored at the same memory location or power is lost.) Computer memory consists of millions of numbered locations where data can be stored. The memory location of myNumber has a specific numeric address, but when you write programs, you seldom need to be concerned with the value of the memory address; instead, you use the easy-to-remember name you created. Computer programmers often refer to memory addresses using hexadecimal notation, or base 16. Using this system, they might use a value like 42FF01A to refer to a memory address. Despite the use of letters, such an address is still a hexadecimal number. Appendix A contains information on this numbering system. ❖ Understanding the Program Development Cycle A programmer’s job involves writing instructions (such as those in the doubling program in the preceding section), but a professional programmer usually does not just sit down at a computer keyboard and start typing. Figure 5 illustrates the program development cycle, which can be broken down into at least seven steps: 1. Understand the problem. 2. Plan the logic. 3. Code the program. 4. Use software (a compiler or interpreter) to translate the program into machine language. 5. Test the program. 6. Put the program into production. 7. Maintain the program. Figure 5: The program development cycle 45 Understanding the Problem Professional computer programmers write programs to satisfy the needs of others, called users or end users. Examples of end users include a Human Resources department that needs a printed list of all employees, a Billing department that wants a list of clients who are 30 or more days overdue on their payments, and an Order department that needs aWeb site to provide buyers with an online shopping cart. Because programmers are providing a service to these users, programmers must first understand what the users want. When a program runs, you usually think of the logic as a cycle of input-processing-output operations, but when you plan a program, you think of the output first. After you understand what the desired result is, you can plan the input and processing steps to achieve it. Suppose the director of Human Resources says to a programmer, “Our department needs a list of all employees who have been here over five years, because we want to invite them to a special thank-you dinner.” On the surface, this seems like a simple request. An experienced programmer, however, will know that the request is incomplete. For example, you might not know the answers to the following questions about which employees to include: Does the director want a list of full-time employees only, or a list of full- and part-time employees together? Does she want to include people who have worked for the company on a month-to-month contractual basis over the past five years, or only regular, permanent employees? Do the listed employees need to have worked for the organization for five years as of today, as of the date of the dinner, or as of some other cutoff date? What about an employee who worked three years, took a two-year leave of absence, and has been back for three years? The programmer cannot make any of these decisions; the user (in this case, the Human Resources director) must address these questions. More decisions still might be required. For example: What data should be included for each listed employee? Should the list contain both first and last names? Social Security numbers? Phone numbers? Addresses? Should the list be in alphabetical order? Employee ID number order? Length-of-service order? Some other order? Should the employees be grouped by any criteria, such as department number or years of service? Several pieces of documentation are often provided to help the programmer understand the problem. Documentation consists of all the supporting paperwork for a program; it might include items such as original requests for the program from users, sample output, and descriptions of the data items available for input. 46 Understanding the problem might be even more difficult if you are writing an app that you hope to market for mobile devices. Business developers are usually approached by a user with a need, but successful developers of mobile apps often try to identify needs that users aren’t even aware of yet. For example, no one knew they wanted to play Angry Birds or leave messages on Facebook before those applications were developed. Mobile app developers also must consider a wider variety of user skills than programmers who develop applications that are used internally in a corporation. Mobile app developers must make sure their programs work with a range of screen sizes and hardware specifications because software competition is intense and the hardware changes quickly. Fully understanding the problem may be one of the most difficult aspects of programming. On any job, the description of what the user needs may be vague— worse yet, users may not really know what they want, and users who think they know frequently change their minds after seeing sample output. A good programmer is often part counselor, part detective! Planning the Logic The heart of the programming process lies in planning the program’s logic. During this phase of the process, the programmer plans the steps of the program, deciding what steps to include and how to order them. You can plan the solution to a problem in many ways. The two most common planning tools are flowcharts and pseudocode. Both tools involve writing the steps of the program in English, much as you would plan a trip on paper before getting into the car or plan a party theme before shopping for food and favors. You may hear programmers refer to planning a program as “developing an algorithm.” An algorithm is the sequence of steps or rules you follow to solve a problem. In addition to flowcharts and pseudocode, programmers use a variety of other tools to help in program development. One such tool is an IPO chart, which delineates input, processing, and output tasks. Some object-oriented programmers also use TOE charts, which list tasks, objects, and events. In the comprehensive version of this book, you can learn about storyboards and the UML, which are frequently used in interactive, object-oriented applications. The programmer shouldn’t worry about the syntax of any particular language during the planning stage, but should focus on figuring out what sequence of events will lead from the available input to the desired output. Planning the logic includes thinking carefully about all the possible data values a program might encounter and how you want the program to handle each scenario. The process of walking through a program’s logic on paper before you actually write the program is called desk-checking. You will learn more about planning the logic throughout this book; in fact, the book focuses on this crucial step almost exclusively. 47 Coding the Program After the logic is developed, only then can the programmer write the source code for a program. Hundreds of programming languages are available. Programmers choose particular languages because some have built-in capabilities that make them more efficient than others at handling certain types of operations. Despite their differences, programming languages are quite alike in their basic capabilities—each can handle input operations, arithmetic processing, output operations, and other standard functions. The logic developed to solve a programming problem can be executed using any number of languages. Only after choosing a language must the programmer be concerned with proper punctuation and the correct spelling of commands—in other words, using the correct syntax. Some experienced programmers can successfully combine logic planning and program coding in one step. This may work for planning and writing a very simple program, just as you can plan and write a postcard to a friend using one step. A good term paper or a Hollywood screenplay, however, needs planning before writing—and so do most programs. Which step is harder: planning the logic or coding the program? Right now, it may seem to you that writing in a programming language is a very difficult task, considering all the spelling and syntax rules you must learn. However, the planning step is actually more difficult.Which is more difficult: thinking up the twists and turns to the plot of a best-selling mystery novel, or writing a translation of an existing novel from English to Spanish? And who do you think gets paid more, the writer who creates the plot or the translator? (Try asking friends to name any famous translator!) Using Software to Translate the Program into Machine Language Even though there are many programming languages, each computer knows only one language—its machine language, which consists of 1s and 0s. Computers understand machine language because they are made up of thousands of tiny electrical switches, each of which can be set in either the on or off state, which is represented by a 1 or 0, respectively. Languages like Java or Visual Basic are available for programmers because someone has written a translator program (a compiler or interpreter) that changes the programmer’s English-like high-level programming language into the low- level machine language that the computer understands. When you learn the syntax of a programming language, the commands work on any machine on which the language software has been installed. However, your commands then are translated to machine language, which differs in various computer makes and models. If you write a programming statement incorrectly (for example, by misspelling a word, using a word that doesn’t exist in the language, or using “illegal” grammar), the translator program doesn’t know how to proceed and issues an error message identifying a syntax error. Although making errors is never desirable, syntax errors 48 are not a programmer’s deepest concern, because the compiler or interpreter catches every syntax error and displays a message that notifies you of the problem. The computer will not execute a program that contains even one syntax error. Typically, a programmer develops logic, writes the code, and compiles the program, receiving a list of syntax errors. The programmer then corrects the syntax errors and compiles the program again. Correcting the first set of errors frequently reveals new errors that originally were not apparent to the compiler. For example, if you could use an English compiler and submit the sentence The dg chase the cat, the compiler at first might point out only one syntax error. The second word, dg, is illegal because it is not part of the English language. Only after you corrected the word to dog would the compiler find another syntax error on the third word, chase, because it is the wrong verb form for the subject dog. This doesn’t mean chase is necessarily the wrong word. Maybe dog is wrong; perhaps the subject should be dogs, in which case chase is right. Compilers don’t always know exactly what you mean, nor do they know what the proper correction should be, but they do know when something is wrong with your syntax. Programmers often compile their code one section at a time. It is far less overwhelming and easier to understand errors that are discovered in 20 lines of code at a time than to try to correct mistakes after 2,000 lines of code have been written. When writing a program, a programmer might need to recompile the code several times. An executable program is created only when the code is free of syntax errors. After a program has been translated into machine language, the machine language program is saved and can be run any number of times without repeating the translation step. You only need to retranslate your code if you make changes to your source code statements. Figure 1-2 shows a diagram of this entire process. Figure 6: Creating an executable program 49 Testing the Program A program that is free of syntax errors is not necessarily free of logical errors. A logical error results when you use a syntactically correct statement but use the wrong one for the current context. For example, the English sentence The dog chases the cat, although syntactically perfect, is not logically correct if the dog chases a ball or the cat is the aggressor. Once a program is free of syntax errors, the programmer can test it—that is, execute it with some sample data to see whether the results are logically correct. Recall the number-doubling program: input myNumber set myAnswer = myNumber * 2 output myAnswer If you execute the program, provide the value 2 as input to the program, and the answer 4 is displayed, you have executed one successful test run of the program. However, if the answer 40 is displayed, maybe the program contains a logical error. Maybe the second line of code was mistyped with an extra zero, so that the program reads: input myNumber set myAnswer = myNumber * 20 output myAnswer Placing 20 instead of 2 in the multiplication statement caused a logical error. Notice that nothing is syntactically wrong with this second program—it is just as reasonable to multiply a number by 20 as by 2—but if the programmer intends only to double myNumber, then a logical error has occurred. The process of finding and correcting program errors is called debugging. You debug a program by testing it using many sets of data. For example, if you write the program to double a number, then enter 2 and get an output value of 4, that doesn’t necessarily mean you have a correct program. Perhaps you have typed this program by mistake: input myNumber set myAnswer = myNumber + 2 output myAnswer An input of 2 results in an answer of 4, but that doesn’t mean your program doubles numbers—it actually only adds 2 to them. If you test your program with additional data and get the wrong answer—for example, if you enter 7 and get an answer of 9—you know there is a problem with your code. Selecting test data is somewhat of an art in itself, and it should be done carefully. If the Human Resources department wants a list of the names of five-year 50 employees, it would be a mistake to test the program with a small sample file of only long-term employees. If no newer employees are part of the data being used for testing, you do not really know if the program would have eliminated them from the five-year list. Many companies do not know that their software has a problem until an unusual circumstance occurs—for example, the first time an employee has more than nine dependents, the first time a customer orders more than 999 items at a time, or when the Internet runs out of allocated IP addresses, a problem known as IPV4 exhaustion. Putting the Program into Production Once the program is thoroughly tested and debugged, it is ready for the organization to use. Putting the program into production might mean simply running the program once, if it was written to satisfy a user’s request for a special list. However, the process might take months if the program will be run on a regular basis, or if it is one of a large system of programs being developed. Perhaps data-entry people must be trained to prepare the input for the new program, users must be trained to understand the output, or existing data in the company must be changed to an entirely new format to accommodate this program. Conversion, the entire set of actions an organization must take to switch over to using a new program or set of programs, can sometimes take months or years to accomplish. Maintaining the Program After programs are put into production, making necessary changes is called maintenance. Maintenance can be required for many reasons: for example, because new tax rates are legislated, the format of an input file is altered, or the end user requires additional information not included in the original output specifications. Frequently, your first programming job will require maintaining previously written programs. When you maintain the programs others have written, you will appreciate the effort the original programmer put into writing clear code, using reasonable variable names, and documenting his or her work. When you make changes to existing programs, you repeat the development cycle. That is, you must understand the changes, then plan, code, translate, and test them before putting them into production. If a substantial number of program changes are required, the original program might be retired, and the program development cycle might be started for a new program. ❖ Using Pseudocode Statements and Flowchart Symbols When programmers plan the logic for a solution to a programming problem, they often use one of two tools: pseudocode (pronounced sue-doe-code) or flowcharts. Pseudocode is an English-like representation of the logical steps it takes to solve a problem. Pseudo is a prefix that means false, and to code a program means to put it in a programming language; therefore, pseudocode simply means false code, or sentences that appear to have been written in a 51 computer programming language but do not necessarily follow all the syntax rules of any specific language. A flowchart is a pictorial representation of the same thing. Writing Pseudocode You have already seen examples of statements that represent pseudocode earlier in this chapter, and there is nothing mysterious about them. The following five statements constitute a pseudocode representation of a number-doubling problem: Start input myNumber set myAnswer = myNumber * 2 output myAnswer stop Using pseudocode involves writing down all the steps you will use in a program. Usually, programmers preface their pseudocode with a beginning statement like start and end it with a terminating statement like stop. The statements between start and stop look like English and are indented slightly so that start and stop stand out. Most programmers do not bother with punctuation such as periods at the end of pseudocode statements, although it would not be wrong to use them if you prefer that style. Similarly, there is no need to capitalize the first word in a statement, although you might choose to do so. Pseudocode is fairly flexible because it is a planning tool, and not the final product. Therefore, for example, you might prefer any of the following: Instead of start and stop, some pseudocode developers would use other terms such as begin and end. Instead of writing input myNumber, some developers would write get myNumber or read myNumber. Instead of writing set myAnswer = myNumber * 2, some developers would write calculate myAnswer = myNumber times 2 or compute myAnswer as myNumber doubled. Instead of writing output myAnswer, many pseudocode developers would write display myAnswer, print myAnswer, or write myAnswer. The point is, the pseudocode statements are instructions to retrieve an original number from an input device and store it in memory where it can be used in a calculation, and then to get the calculated answer from memory and send it to an output device so a person can see it. When you eventually convert your pseudocode to a specific programming language, you do not have such flexibility because specific syntax will be required. For example, if you use the C# programming language and write the statement to output the answer to the monitor, you will code the following: 52 Console.Write(myAnswer); The exact use of words, capitalization, and punctuation are important in the C# statement, but not in the pseudocode statement. Quick Reference 1-1 summarizes the pseudocode standards used in this book. (Note that the Quick Reference mentions modules; you will learn about modules in Chapter 2. Additional pseudocode style features will be discussed as topics are introduced throughout this book.) QUICK NOTES 1: Pseudocode Standards ▪ Programs begin with start and end with stop; these two words are always aligned. ▪ Whenever a module name is used, it is followed by a set of parentheses. ▪ Modules begin with the module name and end with return. The module name and return are always aligned. ▪ Each program statement performs one action—for example, input, processing, or output. ▪ Program statements are indented a few spaces more than start or the module name. ▪ Each program statement appears on a single line if possible. When this is not possible, continuation lines are indented. ▪ Program statements begin with lowercase letters. ▪ No punctuation is used to end statements. As you learn to create pseudocode and flowchart statements, you will develop a sense for how much detail to include. The statements represent the main steps that must be accomplished without including minute points. The concept is similar to writing an essay outline in which each statement of the outline represents a paragraph. Drawing Flowcharts Some professional programmers prefer writing pseudocode to drawing flowcharts, because using pseudocode is more similar to writing the final statements in the programming language. Others prefer drawing flowcharts to represent the logical flow, because flowcharts allow programmers to visualize more easily how the program statements will connect. Especially for beginning programmers, flowcharts are an excellent tool that helps them to visualize how the statements in a program are interrelated. You can draw a flowchart by hand or use software, such as Microsoft Word and Microsoft PowerPoint, that contains flowcharting tools. You can use several other software programs, such as Visio and Visual Logic, specifically to create flowcharts. 53 Figure 7: I-P-O symbols When you create a flowchart, you draw geometric shapes that contain the individual statements and that are connected with arrows. You use a parallelogram to represent an input symbol, which Figure 7- A: Input symbol indicates an input operation. You write an input statement in English inside the parallelogram, as shown in Figure 7-A. Figure 7- B: Processing symbol Arithmetic operation statements are examples of processing. In a flowchart, you use a rectangle as the processing symbol that contains a processing statement, as shown in Figure7-B. Figure 7- C: Output symbol To represent an output statement, you use the same symbol as for input statements—the output symbol is a parallelogram, as shown in Figure 7-C. Because the parallelogram is used for both input and output, it is often called the input/output symbol or I/O symbol. Some software programs that use flowcharts (such as Visual Logic) use a left- slanting parallelogram to represent output. As long as the flowchart creator and the flowchart reader are communicating, the actual shape used is irrelevant. This book will follow the most standard convention of using the right-slanting parallelogram for both input and output. To show the correct sequence of these statements, you use arrows, or flowlines, to connect the steps.Whenever possible, most of a flowchart should read from top to bottom or fromleft to right on a page. That’s the way we read English, so when flowcharts follow this convention, they are easier for us to understand. To be complete, a flowchart should include two more elements: terminal symbols, or start/stop symbols, at each end. Often, you place a word like start or begin in the first terminal symbol and a word like end or stop in the other. The standard terminal symbol is shaped like a racetrack; many programmers refer to this shape as a lozenge, because it resembles the shape of the medication you might use to soothe a sore throat. Figure 1-6 shows a complete flowchart for the program that doubles a number, and the pseudocode for the same problem. You can see from the figure that the flowchart and pseudocode statements are the same—only the presentation format differs. 54 Figure 8: Flowchart and pseudocode of program that doubles a number Programmers seldom create both pseudocode and a flowchart for the same problem. You usually use one or the other. In a large program, you might even prefer to write pseudocode for some parts and to draw a flowchart for others. When you tell a friend how to get to your house, you might write a series of instructions or you might draw a map. Pseudocode is similar to written, step-by- step instructions; a flowchart, like a map, is a visual representation of the same thing. Quick Note 2: summarizes the flowchart symbols used in this book. QUICK NOTE 2: Flowchart Symbols 55 ❖ Understanding Programming and User Environments Many approaches can be used to write and execute a computer program. When you plan a program’s logic, you can use a flowchart, pseudocode, or a combination of the two.When you code the program, you can type statements into a variety of text editors.When your program executes, it might accept input from a keyboard, mouse, microphone, or any other input device, and when you provide a program’s output, you might use text, images, or sound. This section describes the most common environments you will encounter as a new programmer. Understanding Programming Environments When you plan the logic for a computer program, you can use paper and pencil to create a flowchart, or you might use software that allows you to manipulate flowchart shapes. If you choose to write pseudocode, you can do so by hand or by using a word-processing program. To enter the program into a computer so you can translate and execute it, you usually use a keyboard to type program statements into an editor. You can type a program into one of the following: A plain text editor A text editor that is part of an integrated development environment A text editor is a program that you use to create simple text files. It is similar to a word processor, but without as many features. You can use a text editor such as Notepad that is included with Microsoft Windows. Figure 1-11 shows a C# program in Notepad that accepts a number and doubles it. An advantage to using a simple text editor to type and save a program is that the completed program does not require much disk space for storage. You can use the editor of an integrated development environment (IDE) to enter your program. An IDE is a software package that provides an editor, compiler, and other programming tools. Using an IDE is helpful to programmers because usually it provides features similar to those you find in many word processors. In particular, an IDE’s editor commonly includes such features as the following: It uses different colors to display various language components, making elements like data types easier to identify. It highlights syntax errors visually for you. It employs automatic statement completion; when you start to type a statement, the IDE suggests a likely completion, which you can accept with a keystroke. It provides tools that allowyou to step through a program’s execution one statement at a time so you can more easily follow the program’s logic and determine the source of any errors. 56 When you use the IDE to create and save a program, you occupy much more disk space than when using a plain text editor. For example, the program in Figure 1-12 occupies more than 49,000 bytes of disk space. Although various programming environments might look different and offer different features, the process of using them is very similar. When you plan the logic for a program using pseudocode or a flowchart, it does not matter which programming environment you will use to write your code, and when you write the code in a programming language, it does not matter which environment you use to write it. Understanding User Environments A user might execute a program you have written in any number of environments. For example, a user might execute a program from a command. A command line is a location on your computer screen at which you type text entries to communicate with the computer’s operating system. Many programs are not run at the command line in a text environment, but are run using a graphical user interface, or GUI (pronounced gooey), which allows users to interact with a program in a graphical environment. When running a GUI program, the user might type input into a text box or use a mouse or other pointing device to select options on the screen. A command-line program and a GUI program might be written in the same programming language. However, no matter which environment is used to write or execute a program, the logical process is the same. In this module, you will not concentrate on which environment is used to type a program’s statements, nor will you care about the type of environment the user will see. Instead, you will be concerned with the logic that applies to all programming situations. ❖ Understanding the Evolution of Programming Models People have been writing modern computer programs since the 1940s. The oldest programming languages required programmers to work with memory addresses and to memorize awkward codes associated with machine languages. Newer programming languages look much more like natural language and are easier to use, partly because they allow programmers to name variables instead of using unwieldy memory addresses. Also, newer programming languages allow programmers to create self-contained modules or program segments that can be pieced together in a variety of ways. The oldest computer programs were written in one piece, from start to finish, but modern programs are rarely written that way— they are created by teams of programmers, each developing reusable and connectable program procedures. Writing several small modules is easier than writing one large program, and most large tasks are easier when you break the work into units and get other workers to help with some of the units. 57 Ada Byron Lovelace predicted the development of software in 1843; she is often regarded as the first programmer. The basis for most modern software was proposed by Alan Turing in 1935. Currently, two major models or paradigms are used by programmers to develop programs and their procedures: Procedural programming focuses on the procedures that programmers create. That is, procedural programmers focus on the actions that are carried out—for example, getting input data for an employee and writing the calculations needed to produce a paycheck from the data. Procedural programmers would approach the job of producing a paycheck by breaking down the process into manageable subtasks. Object-oriented programming focuses on objects, or “things,” and describes their features (also called attributes) and behaviors. For example, object-oriented programmers might design a payroll application by thinking about employees and paychecks, and by describing their attributes. Employees have names and Social Security numbers, and paychecks have names and check amounts. Then the programmers would think about the behaviors of employees and paychecks, such as employees getting raises and adding dependents and paychecks being calculated and output. Object- oriented programmers would then build applications from these entities. With either approach, procedural or object oriented, you can produce a correct paycheck, and both models employ reusable program modules. The major difference lies in the focus the programmer takes during the earliest planning stages of a project. For now, this book focuses on procedural programming techniques. The skills you gain in programming procedurally—declaring variables, accepting input, making decisions, producing output, and so on—will serve you well whether you eventually write programs using a procedural approach, an object-oriented approach, or both. The programming language in which you write your source code might determine your approach. You can write a procedural program in any language that supports object orientation, but the opposite is not always true. Lesson 2: Writing plan to Program Code In this section, students will be introduced on how to design or create a program as a solution to a problem given. Basic statements or commands in C language will also be introduced for the actual writing of a program code using a specific computer language. Aside from the introduction of the basic C commands, students will be taught on how to create a program in relation to the different steps in program planning and development, and the application of the logical flow and logical sequence in the program design. 58 C Language Basic Statements: Output Statement: printf(); - this is a statement used to display data on the screen. Format: 1) printf(“string”); 2) printf(“%d”,var); 3) printf(“prompt “,var); 4) printf(expression); Example: 1) printf(“How are you?”); 2) printf(“%d”,age); 3) printf(“The age is %d “,age); 4) printf(“%d”,3 + 5); Input statement: scanf() - this a command or statement that gets data from an input device, usually the keyboard. Format: 1) scanf(“format tag”, &variable); Example: scanf(“%d”,&age); Format 2: printf(“prompt string”); scanf(“%d”,&age); 59 This format causes a prompt to be displayed on screen, pauses until you type or enter a data through the keyboard, and then assign that data to the variable. Example: printf(”Enter Age “); scanf(“%d”,&age); This format displays the message written in place of the prompt before to the question mark. Assignment Statement: operator = - this operator assigns a value to a variable. Format: Var = var, constant, expression Example: A=B A=5 S=3+6 Miscellaneous Statement: clrscr() - this statement clears the screen - this statement is used to document the program by inserting remarks, which are non-executable lines, into the program. With the basic commands introduced in the preceding topics we can now create program codes for simple program. Consider the following problems below: ❖ Data Type (scalar or simple) 1. char Character 2. int Integer 3. float Float 60 4. double Double float 5. void Valueless Format Characters: Tag modifier meaning range %d int -decimal (base 10) -32768 to 32767 %u int -unsigned int 0 to 65535 %ld long int -the l stands for long -2147483648 to 2147483649 %f float -float single precision 3.4E-38 to 3.4E+38 %lf double -long float double precision 1.7E-308 to 1.7E+308 %c char -character -128 to 127 %s string -string Backslash characters: \b backspace \f form feed \n newline \r carriage return \t horiz tab \” double quote \’ single quote \0 null \\ backslash \v vertical tab \a alert Arithmetic operators: - subtraction + addition 61 * multiplication / division % modulus division -- decrement ++ increment Relational operators: > greater than < less than >= greater than or equal = 100 Display “THE NUMBER IS NOT LESS THAN 100” Second option: IF X < 100 Display “THE NUMBER IS LESS THAN 100” ELSE Display “THE NUMBER IS NOT LESS THAN 100” 76 Step 2: Development of an algorithm Pseudocode Variable used: X - is numeric Procedure Initialization Enter any value - X Check the value entered if it is less than 100 or not, then do the appropriate output needed. If X < 100 Display “The number is less than 100” Else Display “The number is not less than 100” Note: Option number 2 in the Process to be applied in Step 1 (Problem Analysis) was chosen because it is the most appropriate conditional statement for the problem. Flowchart: Start X=0 Enter X False Is True X < 100 ? 77 Display Display “The number is not “The number is less than 100” less than 100” End Step 3: Program Coding Program Code: #include #include #include main() { int x = 0; printf(“Enter any value “); scanf(“%d”,&x); if (x < 100) { printf(“THE NUMBER IS LESS THAN 100 “); } else { printf(“THE NUMBER IS NOT LESS THAN 100 “); } getch(); } Problem 2: Create a program that would input gender code (1 for male, 2 for female, and 3 for shemale). The program would then output the corresponding gender in word. 78 Example, gender is 2, “Female” would be displayed, gender is 1, “Male” would be displayed. Step 1: Problem analysis Output needed: Appropriate string word for gender Input needed: Gender code - gc Process to be applied: Check the gender code entered then do the appropriate output needed as shown bellow. IF gc == 1 THEN Display “Male” IF gc == 2 THEN Display “Female” IF gc == 3 THEN Display “She-Male” Step 2: Development of an algorithm Pseudocode Variable used: gc - is numeric Start of Procedure Initialization Enter gender code - gc Check the gender code entered then do the appropriate output needed. Option: if 79 If gc == 1 then Display “Male” If gc == 2 then Display “Female” If gc == 3 then Display “She-Male” End of Procedure Option: if…else if If gc == 1 then Display “Male” else If gc == 2 then Display “Female” else If gc == 3 then Display “She-Male” Option: switch switch(gc) { In case 1: Display “Male” break In case 2: Display “Female” break In case 3: Display “She-Male” break } Flowchart: for using - if Start gc = 0 Enter gc 80 Is True gc==1 ? Display “Male” False Is True gc==2 ? Display “Female” False Is True gc==3 ? False Display “She-Male” END Flowchart: for using if..else if Start gc= 0 Enter gc 81 Is True gc==1 ? Display “Male” False Is True gc==2 ? Display “Female” False Is True gc==3 ? False Display “She-Male” END Step 3: Program Coding Program Code: for option if #include #include #include main() { 82 int gc = 0; printf(“Enter gender code “); scanf(“%d”,&gc); if (gc == 1) { printf(“Male “); } if (gc == 2) { printf(“Female “); } if (gc == 3) { printf(“She-Male “); } getch(); } Program Code: for option if..else if… #include #include #include main() { int gc = 0; printf(“Enter gender code “); scanf(“%d”,&gc); if (gc == 1) { printf(“Male “); } else if (gc == 2) { printf(“Female “); } else if (gc == 3) 83 { printf(“She-Male “); } getch(); } Program Code: for option switch #include #include #include main() { int gc = 0; printf(“Enter gender code “); scanf(“%d”,&gc); switch(gc) { case 1: { printf(“Male “); break; } case 2: { printf(“Female “); break; } case 3: { printf(“She-Male “); break; } } getch(); } 84 REPETITIVE or ITERATION: (Please see the previous discussion about this topic to refresh) Repetitive or Iteration is one among the logical flows where a set of instructions is executed repeatedly until a condition is met or satisfied. As illustrated in figure 3.3 a question is asked in the diamond figure, as such, if the answer needs to branch or perform a statement it will do it then goes back to the same question and stop only if such question is satisfied. Problem 1. Create a program that would enter/accept 5 of two numbers and then display their sum. Terminate the program after 5 sets of entries. Step 1 - Problem Analysis: Output Needed: Variables to be Used: Sum of each sets of two numbers S - for sum Input Needed: 5 sets of Two numbers per sets A - for the first number B - for the second number Process to be applied: Add the two numbers using the formula S = A + B and count each sets 85 Step - 2 - Development of an algorithm In the development of algorithm the IPOS sequence must be observed. Pseudocode: Variables used: S, A, B, C are numeric Start of Procedure Initialization (assigning of the initial value of all variables used) Enter the first number - A Enter the second number - B Add the two numbers using the formula S = A + B Display the sum – S Count the sets of numbers enter – C=C+1 If count C is 5 terminate End of the Procedure Explanation on how the pseudocode was developed. Looking at the pseudocode above, all variables to be used in the program are declared above the procedure. Inside the procedure - end of procedure body, series of commands are listed in accordance with the IPOS sequence. I-nput: Initialization Enter the first number - A Enter the second number – B P-rocess: Add the two numbers using the formula S = A + B Count the sets of entry – C = C + 1 Check the count O-utput: Display the sum of each sets - S 86 S-torage (optional in this case) With the above design structure, flowchart can be drawn easily, based from the created pseudocode. Flowchart: Start A=0, B=0 S=0, C = 0 Enter A, B S=A+B C=C+1 Display S NO Is C >= 5? YES End 87 Step 3: Program Coding Appropriate Turbo C commands introduced in the previous topic will be used. Program Code: #include #include main() { int a, b, s, c; a = 0; b = 0; s = 0; c = 0; clrscr(); scanf(“%d”, &a); scanf(“%d”, &b); s = a + b; printf(“The sum is = %d”,s); c=c+1 If c < 5 then Make a LOOP Else END } 88 After writing the program code it will be ready for Step 4 (encoding), then Step 5 (Running the program, Testing, and Debugging), and finally Step 6( the Documentation). Activity Algorithm and Pseudocode Writing: Answer the following in a separate sheet of paper. 1. Write an algorithm to find the third angle of a triangle if two angles are given. Note: The sum of all angles of a triangle is always 180 degrees. 2. The “Strange Dating Rule” that dates back to 1901 states that “Men should date women half their age plus seven”. Write a pseudocode that will enable a man to determine whether his age and the age of the woman he wants to date with is compatible. 3. Convert the algorithm below into a pseudocode. 1. Enter the number of integers to be compared, call it N. 2. Enter the first and second integers, call them NUM1 and LARGE respectively. 3. Set up a COUNTER and assign a value of 2 to it. 4. Compare NUM1 with LARGE, if NUM1 is greater than LARGE then set the value of LARGE to NUM1. 5. Compare COUNTER with N. If COUNTER is equal to N, display the value of LARGE and exit, otherwise increment the value of COUNTER by 1 and enter the next integer to be compared, call it NUM1. 6. Repeat step 4. 89 Assessment Tasks Direction: In a separate sheet of paper, answer the following items: 1. What is the difference between algorithm and pseudocode? 2. Explain the difference among desk-checking, translating, and debugging. 2. Analyze the pseudocode below and explain what it does. PASSES = 0 FAILURES = 0 STUDENT = 1 While STUDENT = 75 PASSES = PASSES + 1 else FAILURES = FAILURES + 1 STUDENT = STUDENT + 1 Print PASSES Print FAILURES If PASSES > = 8 Print "Raise Tuition" 4. Using the pseudocode in Number 3, perform desk-checking and write the output given the following set of inputs: A. 85 87 74 67 90 83 70 72 88 90 B. 90 95 88 71 89 84 73 92 85 80 5. 6. Problem Solving: Create a program for the problem written below using the basic principle of program planning and development. 1. 2. 3. Write a program that will display two (2) stanzas of your favorite song. The lyrics should be center aligned. Name the program as Song_XXX, where XXX is your initial. See sample output below: 90 Magkasama Tayo sa Kwento ng Pasko Sa iisang awit ngayong Pasko Magkayakap ang tinig ko’t sa’yo Sa ‘ting himig ipagdiriwang ang pag-ibig At ito ay tatawid sa buong daigdig. Sa iisang awit ngayong Pasko Magkayakap maglilingkod sa’yo Sa ‘ting himig nadarama na ang mahalaga Ay magkasama tayo sa Kuwento ng Pasko. 4. Create a program that will display your simple resume and name it Resume_XXX. See sample output below. PERSONAL INFORMATION NAME: Juan dela Cruz BIRTHDAY: January 1, 2000 AGE: 14 ADDRESS: Brgy. Bubukal Sta. Cruz, Laguna HEIGHT: 5’7” WEIGHT: 100 lbs. STATUS: Single EDUCATIONAL BACKGROUND TERTIARY Laguna University BSCS 2014 SECONDARY PGMNHS 2010 PRIMARY Central Elementary School 2006 5. Create a program that would enter two integer numbers and an operation code corresponding to a particular arithmetic operation as: 1 - multiplication, 2 -division, 3 -addition, and 4 -subtraction. The program would then output the result of the operation made from the two input numbers. Display the necessary message if operation code is not valid. Example, 3 is the first number, 4 is the second and 3 is the operation code, 7 would be the output. 91 Exercises Review Questions 1. Computer programs also are known as. a. hardware b. software c. data d. information 2. The major computer operations include. a. hardware and software b. input, processing, and output c. sequence and looping d. spreadsheets, word processing, and data communications 3. Visual Basic, C++, and Java are all examples of computer. a. operating systems b. hardware c. machine languages d. programming languages 4. A programming language’s rules are its. a. syntax b. logic c. format d. options 5. The most important task of a compiler or interpreter is to. a. create the rules for a programming language b. translate English statements into a language such as Java c. translate programming language statements into machine language d. execute machine language programs to perform useful tasks 6. Which of the following is temporary, internal storage? a. CPU b. hard disk c. keyboard d. memory 92 7. Which of the following pairs of steps in the programming process is in the correct order? a. code the program, plan the logic b. test the program, translate it into machine language c. put the program into production, understand the problem d. code the program, translate it into machine language 8. A programmer’s most important task before planning the logic of a program is to. a. decide which programming language to use b. code the problem c. train the users of the program d. understand the problem 9. The two most commonly used tools for planning a program’s logic are. a. flowcharts and pseudocode b. ASCII and EBCDIC c. Java and Visual Basic d. word processors and spreadsheets 10. Writing a program in a language such as C++ or Java is known as the program. a. translating b. coding c. interpreting d. compiling 11. An English-like programming language such as Java or Visual Basic is a programming language. a. machine-level b. low-level c. high-level d. binary-level 12. Which of the following is an example of a syntax error? a. producing output before accepting input b. subtracting when you meant to add 93 c. misspelling a programming language word d. all of the above 13. Which of the following is an example of a logical error? a. performing arithmetic with a value before inputting it b. accepting two input values when a program requires only one c. dividing by 3 when you meant to divide by 30 d. all of the above 14. The parallelogram is the flowchart symbol representing. a. input b. output c. either a or b d. none of the above 15. In a flowchart, a rectangle represents. a. input b. a sentinel c. a question d. processing 16. In flowcharts, the decision symbol is a. a. parallelogram b. rectangle c. lozenge d. diamond 17. The term eof represents. a. a standard input device b. a generic sentinel value c. a condition in which no more memory is available for storage d. the logical flow in a program 18. When you use an IDE instead of a simple text editor to develop a program,. a. the logic is more complicated b. the logic is simpler c. the syntax is different d. some help is provided 94 19. When you write a program that will run in a GUI environment as opposed to a command-line environment,. a. the logic is very different b. some syntax is different c. you do not need to plan the logic d. users are more confused 20. As compared to procedural programming, with object-oriented programming,. a. the programmer’s focus differs b. you cannot use some languages, such as Java c. you do not accept input d. you do not code calculations; they are created automatically Summary Together, computer hardware (physical devices) and software (instructions) accomplish three major operations: input, processing, and output. You write computer instructions in a computer programming language that requires specific syntax; the instructions are translated into machine language by a compiler or interpreter. When both the syntax and logic of a program are correct, you can run, or execute, the program to produce the desired results. For a program to work properly, you must develop correct logic. Logical errors are much more difficult to locate than syntax errors. A programmer’s job involves understanding the problem, planning the logic, coding the program, translating the program into machine language, testing the program, putting the program into production, and maintaining it. When programmers plan the logic for a solution to a programming problem, they often use flowcharts or pseudocode. When you draw a flowchart, you use parallelograms to represent input and output operations, and rectangles to represent processing. Programmers also use decisions to control repetition of instruction sets. To avoid creating an infinite loop when you repeat instructions, you can test for a sentinel value. You represent a decision in a flowchart by drawing a diamond-shaped symbol that contains a question, the answer to which is either yes or no. You can type a programing to a plain text editor or one that is part of an integrated development environment. When a program’s data values are entered from a keyboard, they can be entered at the command line in a text environment or in a GUI. Either way, the logic is similar. 95 Procedural and object-oriented programmers approach problems differently. Procedural programmers concentrate on the actions performed with data. Object-oriented programmers focus on objects and their behaviors and attributes. Program Logic Formulation is the process of coming out with the basic steps to implement a procedure in computer programming. Program is a set of step-by-step instructions that directs the computer to do the tasks you want it to do and produce the results you want. A set of rules that provides a way of telling a computer what operations to perform is called a programming language. The five main steps in the programming process are (1) Defining the problem, (2) Planning the solution, (3) Coding the program, (4) Testing the program, (5) Documenting the program. Algorithm is like a recipe that describes the exact steps needed for the computer to solve a problem or reach a goal. The two common ways of planning the solution to a problem are to draw a flowchart and to write pseudocode, or possibly both. Pseudocode is an English-like nonstandard language that lets you state your solution with more precision than you can in plain English but with less precision than is required when using a formal programming language. Flowchart is a pictorial representation of a step-by-step solution to a problem. Desk-checking is similar to proofreading which involves mentally tracing, or checking, the logic of the program to attempt to ensure that it is error-free and workable. Translator is a program that checks the syntax of your program to make sure the programming language was used correctly, giving you all the syntax-error messages, called diagnostics, and then translates your program into a form the computer can understand. Debugging means detecting, locating, and correcting bugs (mistakes), usually by running the program. Documentation is a written detailed description of the programming cycle and specific facts about the program References Computer Programming. (2020). Retrieved from Computer Programming: https://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm Corpuz, S. (2012, September 10). Program Logic Formulation. Retrieved from Slideshare: https://www.slideshare.net/sarajcorpuz/program-logic-formulation 96 Farrell, Joyce (2015). Programming Logic and Design, Comprehensive version, Eighth Edition Meinecke, L. (2020). What is an Algorithm in Programming? Retrieved from study.com: https://study.com/academy/lesson/what-is-an-algorithm-in-programming-definition- examplesanalysis.html#:~:text=A%20programming%20algorithm%20is %20a, results%%2020are%20called%20the%20outputs. Perry, A. (2020). Pseudocode: Definition & Examples. Retrieved from study.com: https://study.com/academy/lesson/pseudocode-definition-examples- quiz.html#:~:text=Pseudocode%20is%20a%20simple%20way%20of%20writing%20 programming%20code%20in%20English.&text=It%20uses%20short%20phrases%2 0to,it%20in%20a%20specific%20language. Pseudocode Examples. (2020). Retrieved from unf.edu: https://www.unf.edu/~broggio/cop2221/2221pseu.htm Southern, M. (2020). The Difference Between Algorithms, Pseudocode & Programming Languages. Retrieved from Techwalla: https://www.techwalla.com/articles/importance-of-data-flow-diagrams tutorialspoint. (2020). Retrieved from Writing the Algorithm: https://www.tutorialspoint.com/programming_methodologies/programming_methodol ogies_writing_the_algorithm.htm - END OF MODULE FOR MIDTERM PERIOD – Midterm Examination will be given on October 28, 2024, to November 3, 2024. Kindly check you class schedule for this course. 97

Use Quizgecko on...
Browser
Browser