🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Week 3 - Elements of High-Quality Programs.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

OptimalParadox

Uploaded by OptimalParadox

National University

Tags

programming fundamentals variables computer science

Full Transcript

Course Material BSIT Department Elements of High-Quality Programs Fundamentals of Programming Course Material BSIT Department Objectives At the end of the discussion, each students will be able t...

Course Material BSIT Department Elements of High-Quality Programs Fundamentals of Programming Course Material BSIT Department Objectives At the end of the discussion, each students will be able to: Declare and use variables and constants Perform arithmetic operations Describe the advantages of modularization Modularize a program Describe the features of good program design Course Material BSIT Department Declaring and Using Variables and Constants Data type describes: − What values can be held by the item − How the item is stored in memory − What operations can be performed on the item All programming languages support these data types: − Numeric: Numeric data that can be used in arithmetic operations − String: Nonnumeric data Course Material BSIT Department Understanding Unnamed, Literal Constants Computer program uses two types of constants − Numeric constant (or literal numeric constant) ▪ Number that does not change − String constant (or literal string constant) ▪ Appears within quotation marks ▪ Known as alphanumeric values ▪ Can contain alphabetic characters, numbers, and other characters Course Material BSIT Department Figure 2-1: Flowchart and Pseudocode for the Number-Doubling Program Course Material BSIT Department Working with Variables Variables are named memory locations whose contents can vary or differ over time Declaration: Statement that provides a variable's: − Data type − Identifier − Optionally, an initial value Course Material BSIT Department Understanding a Variable’s Data Type Numeric variable − Can hold digits and have mathematical operations performed on it String variable − Can hold text and other special characters ▪ Letters of the alphabet and punctuation marks Type-safety − Prevents assigning values of an incorrect data type Course Material BSIT Department Understanding a Variable’s Identifier Identifier: Program component’s name Programmers choose reasonable and descriptive names for variables Programming languages have rules for creating identifiers − Most languages allow letters and digits within identifiers − Some languages allow hyphens, underscores dollar signs, or other special characters in variable names − Each programming language has a few reserved keywords that are not allowed as variable names as they are part of the language’s syntax Course Material BSIT Department Understanding a Declaration’s Identifier Identifiers are case sensitive Variable names: − Must be one word − Must start with a letter − Should have some appropriate meaning Course Material BSIT Department Table 2-1: Variable Naming Conventions (1 of 2) Convention for naming variables Examples Languages in which commonly used Camel casing is the convention in which the variable starts hourlyWage Java, C# with a lowercase letter and any subsequent word begins lastName with an uppercase letter. It is sometimes called lower camel casing to emphasize the difference from Pascal casing. Pascal casing is a convention in which the first letter of a HourlyWage Visual Basic variable name is uppercase. It is sometimes called upper LastName camel casing to distinguish it from lower camel casing. Hungarian notation is a form of camel casing in which a numHourlyWage C for Windows API variable’s data type is part of the identifier. stringLastName programming Course Material BSIT Department Table 2-1: Variable Naming Conventions (2 of 2) Convention for naming variables Examples Languages in which commonly used Snake casing is a convention in which parts of a variable hourly_wage C, C++, Python, Ruby name are separated by underscores. last_name Mixed case with underscores is a variable naming Hourly_Wage Ada convention similar to snake casing, but new words start Last_Name with an uppercase letter. Kebob case is sometimes used as the name for the style hourly-wage Lisp (with lowercase that uses dashes to separate parts of a variable name. The last-name letters), COBOL (with name derives from the fact that the words look like pieces uppercase letters) of food on a skewer. Course Material BSIT Department Figure 2-2: Flowchart and Pseudocode of Number- Doubling Program with Variable Declarations Course Material BSIT Department Assigning Values to Variables Assignment statement − myAnswer = myNumber * 2 Assignment operator (=) − Example of a binary operator, meaning it requires two operands— one on each side − Always operates from right to left, which means that it has right- associativity or right-to-left associativity ▪ lvalue: Result to the left of an assignment operator Course Material BSIT Department Initializing a Variable Initializing the variable: Declaring a starting value when a variable is declared − num yourPayRate = 24.55 − string yourName = "Juanita" Garbage: Variable’s unknown value Variables must be declared before they are used in the program Course Material BSIT Department Declaring Named Constants Named constant − Similar to a variable, except it can be assigned a value only once − Assign a useful name to a value that will never be changed during a program’s execution Magic number − Unnamed constant whose purpose is not immediately apparent − Example: Both taxAmount = price * SALES_TAX_RATE and taxAmount = price * 0.06 have identical meaning Course Material BSIT Department Knowledge Check Activity Identify the rule pertaining to variable names. a. Variable names should have some appropriate meaning. b. Variable names must start with a number. c. Variable names must be two words. d. Variable names must be written using all uppercase letters. Course Material BSIT Department Knowledge Check Activity: Answer Identify the rule pertaining to variable names. Answer: a. Variable names should have some appropriate meaning. Variable names must be one word, must start with a letter, should have some appropriate meaning, and are case sensitive. Course Material BSIT Department Performing Arithmetic Operations (1 of 2) Standard arithmetic operators: − + (plus sign)—addition − − (minus sign)—subtraction − * (asterisk)—multiplication − / (slash)—division Course Material BSIT Department Performing Arithmetic Operations (2 of 2) Rules of precedence, or order of operations − Dictate the order in which operations in the same statement are carried out − Expressions within parentheses are evaluated first − All the arithmetic operators have left-to-right associativity − Multiplication and division are evaluated next, from left to right − Addition and subtraction are evaluated next, from left to right Course Material BSIT Department Mixing Data Types Dividing an integer by another integer is a special case − Dividing two integers results in an integer, and any fractional part of the result is lost − The decimal portion of the result is cut off, or truncated Remainder operator, called the modulo operator or the modulus operator, is the value that remains after division − 24 Mod 10 is 4 ▪ Because when 24 is divided by 10, 4 is the remainder Course Material BSIT Department Understanding the Advantages of Modularization Modules − Subunit of programming problem − Called subroutines, procedures, functions, or methods − To call a module is to use its name to invoke the module, causing it to execute Modularization − Breaking down a large program into modules − Called functional decomposition Course Material BSIT Department Modularization Provides Abstraction Abstraction: Paying attention to important properties while ignoring nonessential details − Selective ignorance Newer high-level programming languages use English-like vocabulary − One broad statement corresponds to dozens of machine instructions Modules provide another way to achieve abstraction Course Material BSIT Department Modularization Allows Multiple Programmers to Work on a Problem Dividing any large task into modules makes it easier to divide the task among various people Rarely does a single programmer write a commercial program − Professional software developers can write new programs quickly by: ▪ Dividing large programs into modules ▪ Assigning each module to an individual programmer or team Course Material BSIT Department Modularization Allows to Reuse Work Reusability − Feature of modular programs that allows individual modules to be used in a variety of applications − Many real-world examples found Reliability − Assures that a module has been tested and proven to function correctly Course Material BSIT Department Discussion Activity Discuss the reasons why programmers should consider modularizing programs. Course Material BSIT Department Discussion Activity: Answer Modularized programs are easier to understand in that they enable a programmer to see the “big picture.” Abstraction is the process of paying attention to important properties while ignoring nonessential details. Abstraction makes complex tasks look simple. When any large task is divided into modules, programmers gain the ability to more easily divide the task among various people. Professional software developers can write new programs in weeks or months, instead of years, by dividing large programs into modules and assigning each module to an individual programmer or team. The reusability of modular programs allows individual modules to be used in a variety of applications. Reliability is the feature of programs that assures that a module has been proven to function correctly. Reliable software saves time and money. If programmers create the functional components of their programs as stand-alone modules and test them in their current programs, much of the work already will be done when they use the modules in future applications. Course Material BSIT Department Modularizing a Program (1 of 3) Main program: Basic steps, or mainline logic, of the program When a module is created, it includes − Module header − Module body − Module return statement Naming a module is similar to naming a variable − Module names must start with a letter and cannot contain spaces, should have meaning, and are followed by a set of parentheses Course Material BSIT Department Modularizing a Program (2 of 3) When a main program wants to use a module, it calls the module, or invokes it Flowchart symbol used to call a module is a rectangle with a bar across the top − Name of the module being called is placed inside the rectangle − Each module is drawn separately with its own sentinel symbols ▪ Each module begins with its name and ends with a return statement Course Material BSIT Department Figure 2-3: Program That Produces A Bill Using Only Main Program Course Material BSIT Department Figure 2-4: Program That Produces a bill Using Main Program That Calls displayAddressInfo() Module Course Material BSIT Department Modularizing a Program (3 of 3) Encapsulation: Technique of grouping program elements within a module Modularized version of the program is preferred as: − Main program remains short and easy to follow because it contains just one statement to call the module − Module is easy to reuse When statements contribute to the same job, it results in greater functional cohesion Course Material BSIT Department Declaring Variables and Constants within Modules (1 of 2) Any statements can be placed within modules − Includes input, processing, output statements, and variable and constant declarations Variables and constants are usable only in the module in which they are declared − Programmers say the data items are visible, in scope, or local Modules are portable − Portable: Self-contained units that are easily transported Course Material BSIT Department Declaring Variables and Constants within Modules (2 of 2) Global variables and constants − Known to the entire program − Declared at the program level − Visible to and usable in all the modules called by the program − No approved by many programmers Course Material BSIT Department Figure 2-5: The Billing Program with Constants Declared within the Module Course Material BSIT Department Understanding the Most Common Configuration for Mainline Logic Mainline logic of almost every procedural computer program follows a general structure − Housekeeping tasks: Steps one must perform at the beginning of a program to get ready for the rest of the program − Detail loop tasks: Do the core work of the program − End-of-job tasks: Steps one takes at the end of the program to finish the application Course Material BSIT Department Figure 2-6: Flowchart and Pseudocode of Mainline Logic for a Typical Procedural Program Course Material BSIT Department Figure 2-7: Sample Payroll Report Course Material BSIT Department Figure 2-8: Logic for Payroll Report Course Material BSIT Department Creating Hierarchy Charts Program hierarchy chart − Shows the overall picture of how modules are related to one another − Tells which modules exist within a program and which modules call others − Can be a planning tool for developing the overall relationship of program modules before one writes them − Can be documentation tool to help others see how modules are related after a program is written Course Material BSIT Department Figure 2-10: Hierarchy Chart of Payroll Program in Figure 2-8 Course Material BSIT Department Figure 2-11: Billing Program Hierarchy Chart Course Material BSIT Department Think, Pair, Share Suppose you own a cookie factory, and you want to represent the activities in the factory using mainline logic. Take a few minutes to think about the three parts of a typical procedural program and create a flowchart illustrating the activities. Pair up with a partner and discuss your thought process and approach to the problem. Ask each other questions and provide feedback on each other’s solutions. Share your approach and solution with the rest of the class. Course Material BSIT Department Features of Good Program Design Providing program comments where appropriate Choosing identifiers thoughtfully Striving to design clear statements within your programs and modules Writing clear prompts and echo input Continuing to maintain good programming habits as you develop your programming skills Course Material BSIT Department Using Program Comments (1 of 2) Program comments − Written explanations of programming statements that are not part of the program logic − Serve as internal documentation for readers of the program Syntax used differs among programming languages In a flowchart, one can use an annotation symbol to hold information that expands on what is stored within another flowchart symbol Course Material BSIT Department Using Program Comments (2 of 2) Declarations num sqFeet // sqFeet is an estimate provided by the seller of the property num pricePerFoot // pricePerFoot is determined by current market conditions num lotPremium // lotPremium depends on amenities such as whether lot is waterfront Course Material BSIT Department Figure 2-13: Flowchart That Includes Annotation Symbols Course Material BSIT Department Choosing Identifiers (1 of 2) General guidelines − Give a variable or a constant a name that is a noun because it represents a thing − Give a module an identifier that is a verb because it performs an action − Use meaningful names ▪ Self-documenting: Programs that contain meaningful names − Use pronounceable names − Be judicious in the use of abbreviations Course Material BSIT Department Choosing Identifiers (2 of 2) − Avoid digits in a name − Use the rules allowed by the language to separate words in long, multiword variable names − Consider including a form of the verb to be − Name constants using all uppercase letters separated by underscores (_) Programmers sometimes create a data dictionary, which is a list of every variable name used in a program, along with its type, size, and description Course Material BSIT Department Designing Clear Statements Avoiding confusing line breaks Using temporary variables to clarify long statements Course Material BSIT Department Avoiding Confusing Line Breaks Most modern programming languages are free-form − One must make sure the meaning is clear − Programmers are allowed to place two or three statements on a line or to spread a single statement across multiple lines ▪ Both make programs harder to read Course Material BSIT Department Using Temporary Variables to Clarify Long Statements (1 of 2) Temporary variable, or work variable − Not used for input or output − Working variable that is used during a program’s execution Series of temporary variables to hold intermediate results can be used when several mathematical operations are needed to determine a result Course Material BSIT Department Using Temporary Variables to Clarify Long Statements (1 of 2) //Using a single statement to compute commission salesCommission = (sqFeet * pricePerFoot + lotPremium) * commissionRate // Using multiple statements to compute commission basePropertyPrice = sqFeet * pricePerFoot totalSalesPrice = basePropertyPrice + lotPremium salesCommission = totalSalesPrice * commissionRate Course Material BSIT Department Writing Clear Prompts and Echoing Input Prompt − Message displayed on a screen to ask the user for a response − Used both in command-line and GUI interactive programs Echoing input − Repeating input back to a user either in a subsequent prompt or in output Course Material BSIT Department Figure 2-15: Beginning of a Program That Accepts a Name and a Balance as Input Course Material BSIT Department Figure 2-16: Beginning of a Program That Accepts a Name and a Balance as Input and Uses a Separate Prompt for Each Item Course Material BSIT Department Figure 2-17: Beginning of a Program That Accepts a Customer’s Name and Uses It in the Second Prompt Course Material BSIT Department Maintaining Good Programming Habits Every program written will be better if programmers: − Plan before they code − Maintain the habit of first drawing flowcharts or writing pseudocode − Desk-check their program logic on paper − Think carefully about the variable and module names they use − Design their program statements to be easy to read and use Course Material BSIT Department Self-Assessment Define a variable and a constant in programming. What is the order of arithmetic operations in a programming language? What are the advantages of modularization? How can one modularize a program? What are the features of good program design? Course Material BSIT Department Summary Click the link to review the objectives for this presentation. Link to Objectives Course Material BSIT Department References Burd, B. (2021). Beginning Programming with Java for Dummies. (6th ed.). Crutcher, P. (2021). Essential computer science: a programmer’s guide to foundational concepts. Ellison, B. (2022). Java for Beginners: A Crash Course to Learn Java Programming in 1 Week (Programming Languages for Beginners). Horstmann, C. (2019). Core Java: volume II-advanced features. Sebesta, R. (2020). Concepts of Programming Languages. (11th ed.) Farrel (2024). Programming Logic and Design, 10th Edition. © 2024 Cengage.

Use Quizgecko on...
Browser
Browser