Software Development Method Specify the problem. Analyze the problem. Design the algorithm to solve...
-
date post
22-Dec-2015 -
Category
Documents
-
view
231 -
download
0
Transcript of Software Development Method Specify the problem. Analyze the problem. Design the algorithm to solve...
Software Development Method
• Specify the problem.
• Analyze the problem.
• Design the algorithm to solve the problem.
• Implement the algorithm.
• Test and verify the completed problem.
• Maintain and update the problem.
Problem• We need to state the problem clearly and
unambiguously.
• It helps get a clear understanding of what is required for its solution.
• Eliminate unimportant aspects and concentrate on the root problem.
• We might need more information.
• Example: Write a program to calculate the number of calories in a cheese sandwich
Implementation
• Write the algorithm as a C++ program.• First tell the C++ compiler about the problem
data requirements. - What memory cell names you are using. - What kind of data will be stored in each
memory cell.• Next, convert each algorithm step into one or
more C ++statements.
Testing
• Verify the completed program that it works.
• Run the program several times using different sets of data.
• Make sure it works properly in each case.
• In this example, enter a few more test values of BREAD, CHEESE, MAYONNAISE, and PICKLES.
Maintenance• Maintaining and updating the program may be necessary
to correct previously undetected program errors or to comply with external changes in requirements.
• External (manuals) and internal (comments) documentation is necessary.
• Good programming style guidelines must be followed so that others, even the original programmer, may be able to read the program in the future.
• Keep it up-to-date.• 85% of total cost is spent for software maintenance.
A program written in C++ 1 // This program calculates the number calories in a cheese sandwich
2 #include <iostream.h>
3 const int BREAD = 63;
4 const int CHEESE = 106;
5 const int MAYONNAISE = 49;
6 const int PICKLES = 25;
7 int main()
8 {
9 int totalCalories;
10 totalCalories = 2 * BREAD + CHEESE + MAYONNAISE + PICKLES;
11 cout << "There were " << totalCalories;
12 cout << " calories in my lunch yesterday."<< endl;
13 return 0;
14 }
Comments• Line 1 is called comment.
• It tells the reader what the program is going to to.
• Line 1 is ignored by the compiler.
• Comment begins with a double slash (//).
• It extends to the end of the line.
• Another way of comments:Insert your comment between /* and */We can write any number of lines.
Preprocessor directives• Line 2 is a directive to the C++ preprocessor.• Commands that give instructions to the C ++
preprocessor.• C++ preprocessor modifies the text of a C ++
program before it is compiled.• Begins with a number symbol (#) as its 1st
nonblank character.• #include directive instructs the preprocessor to
insert definitions from a standard header file (iostream.h) into a program before compilation.
• This file includes constant, variable, and function declarations needed by the program.
A constant declaration
• Line 3 through 6 instruct the compiler to assign the identifier on the left of the equal
sign a place in memory and to store the value on the right of equal sign in
that place.
• Generally, programmers use all uppercase for constant identifiers.
Function main• Program execution begins at main function.• Every C ++ program has a main function.• The body of a function is enclosed in braces {, }.• A function body has two parts: declaration and
executable statements.• Declarations tell the compiler what memory cells
are needed in the function (totalCalories).• Executable statements are translated into machine
languages before execution.• Main function returns an integer and takes nothing
as an argument (not always).
Reserved Words
• int, void, const are all reserved words
• Appears in lower case.
• Have special meaning in C++.
• Can’t be use for other purposes.
Standard Identifiers
• Have special meaning in C++.
• Standard identifiers cout and cin are names of operations defined in the standard input/output library.
• Can be redefined and used by the programmer for other purposes.
User-Defined Identifiers• Used to name memory cells that will hold data
and program results.• Used to name operations that we define.• The first user-defined identifier is BREAD.• Syntax rules: 1. An identifier must consist only of letters,
digits, and underscores. 2. An identifier cannot begin with a digit. 3. A C++ reserved word cannot be used as
an identifier. 4. An identifier defined in a C++ standard
library should not be redefined.
Uppercase and Lowercase Letters
• Uppercase and lowercase letters are considered different by the C++ compiler.
• xyz, Xyz and XYZ are all different variables. • Normally, standard library functions use all
lowercase letters, while macros use all uppercase chars.
• Programmers should use upper and lowercase letters consistently.
Variable declaration• Variable : Memory cell used to store a
program’s input data and its computational results.
• Variable declaration: Statement that tells the compiler the names of the variables and the type of data stored in each variable.
Example :
int totalCalories;
Gives the name of a variable (total Calories) used to store an intege number.
Methods of variable creation
• Global variable– declared very early stage– available at all times from anywhere– created at the start of the program, and lasts
until the end, it is taking up lots of memory– difficult to debug
Methods of variable creation (continued)
• Local on the fly variables– simply created when they are needed, – only available from within the routine in which
they were created– memory requirement is less– easy to debug
Methods of variable creation (continued)
• Local defined variable– created before they are needed – only available in the routine in which they were
created.– Memory requirement is less– easy to debug– the most usually favored method
Data Types
• data type: set of values and a set of operations on those values.
• A standard data type in C++:
char double or float int(Real numbers) (Integers)(A letter, digit,
or a special symbol)
Data Types In C++ every variable has a type which determines: - A set of values the variable can take (range of the
data type). - A set of operations allowed. - Number of bytes used to represent the variable in
the memory cells.
Example of predefined data type in C: int => integer, range: -32767 ~ 32767; Example: -5, 0, 32767; occupy two bytes/four bytes.
Data Types Example of predefined data type in C++:• float => real number, range: at least 6 decimal
digits (4 bytes). Example: -12.8, 0.0, 6.9. • double => real number (double precision), range:
15 decimal digits of precision (8 bytes).• char => character, occupy one byte. Data type char represents an individual character
value: a letter, a digit, or a special symbol. A character value must be enclosed in single quotes.
Example: 'A' 'b' '2' '%' .
cin and cout
• Data can be placed in memory by assignment or by copying from input devices.
• Input operations transfer data from external sources into the computer.
• Output operations display the results of the program to the computer user.
• Input and output functions in <iostream.h> include cin(input) & cout (output).
• Function calls are used to call or activate these input and output functions.
Programs in MemoryMemory before execution Memory after execution
Machine language calculate calories
program
63
?
memory
BREAD
totalCalories
106
CHEESE
49
MAYONNAISE
25
PICKLE
Machine language calculate calories
program
63
306
memory
BREAD
totalCalories
106
CHEESE
49
MAYONNAISE
25
PICKLE
The return Statement
return (0)
Transfer control from your programto the operating system at the end of the main section, or from a function back to its activator.
0 is the result of function main’sexecution, it indicates that your program executed without error.
Comments in Programs
Comments in programs help others read and understand the programs.
Compiler ignores comments.
They are not translated into machine language
Program Style
• Use structured programming methodology (top-down design).
• Your program must be readable.• Use meaningful variable names and function
names.• Indent your program properly.• A program should be well documented so that
others can read, use, and modify it easily.
Program Style
• Anticipate errors.
• Don’t use goto.
• Use functions extensively
• Avoid global variables and side effects.
• Test your programs as you build it - bottom up testing.
Structured Programming
• Design your program in a top down manner.• Always decompose your problem into
simpler subproblems.• Constructs used for decomposition– Sequence– Selection– Iteration
Decomposition (First round)
• a) Sleep as late as possible.
• b) Get dresses.
• c) If you want breakfast then have breakfast.
• d) Drive to the university.
Sequence: Do steps one after the other.
Step a is followed by step b followed by step c etc.
Selection: If <condition> then do something
or If <condition> then do something1 else do something2.
Problem - Get ready for school
Expansion of step a
While alarm not ringing
Sleep
Iteration: Carry out step(s) a number of times.
Your program must be readableA program should have• A good structure and design.• A good choice of identifiers.• Good indentation and use of blank lines.• Good documentation.• Avoid “clever” programming tricks that – save a little computer time.– make you feel that you are “smart”.– reduce some lines of codeHuman time is the most important resource.
Indent your program properly
• Enhance readability.
• Easy to identify the program’s modules.
• Use blank lines to offset each function.
• Use blank lines to separate individual blocks of code visibly.
How to handle an error?
• Display error message and turn error flag on.
• Possible actions:
– Ignore erroneous data and continue.
– Give warning message.
– Terminate the program.
– Use a diagnostic mode and normal mode of program execution.
Modular programming• Always use the divide and conquer
approach.
• Use functions whenever you identify a clearly distinct task during your process of structures program development.
• A function should avoid global variable.
• A good rule of thumb is to limit each function (including main) to 1 page in length.
% Operation
• 4 % 5 = 4
• 7 % 7 = 0
• 7 % 6 = 1
• 28 % 4 = 0
• 16 % -5 varies
• 16 % 0 undefined
In C++, an additional arithmetic operator, the % (remainder operator) is used with integer operands to find the remainderof integer division.
The % operator requires that both operands be of type int.
Integer Division
• 4 / 16 = 0
• 16 / 4 = 4
• 17 / 4 = 4
• 16 / -3 varies
• 0 / 5 = 0
• 16 / 0 = undefined
When applied to two positive integers, the result of the division must be an integerin C++, the remainder is thrown away.
Increment & Decrement Operators• ++ unary increment operator.• -- unary decrement operator.• If a variable x incremented by 1, you can use x++
rather than x = x + 1 or x += 1.• If a variable x decremented by 1, you can use x--
rather than x = x - 1 or x -= 1.• Preincrement operator ++x.• Postincrement operator x++.• Predecrement operator --x.• Postdecrement operator x--.• What is the difference between preincrementing
and postincrementing?
Preincrementing & Postincrementing #include <iostream.h> main() { int x; x = 5; cout << x << endl; cout << x++ << endl; // post increment cout << x << endl << endl;
x = 5; cout << x << endl; cout << ++x < endl; // preincrement cout << x < endl;
return (0); // successful termination }
556
566
Output
Arithmetic Expression• Arithmetic expressions are used to manipulate type int and
double data. • e.g. n1 + n2 • In C++, an expression is composed of terms and operators.
A term, such as n1 and n2, represents a single data value, which must be one of the following:
- a constant - a variable - a function call - an expression in parentheses • Four arithmetic operators that apply to all numeric data
types are: + (addition), - (subtraction), * (multiplication), and / (division).
Arithmetic Expressions Rules
• Parentheses rules– All expressions in parentheses must be evaluated first. In
nested parenthesized expressions, the innermost expression evaluated first.
• Precedence rules for arithmetic operators Operators in the same expression are evaluated in the
following order: – unary +, - first.
– Multiplication (*), division (/), and mode(%) next.
– Addition (+) and subtraction (-) last.
Arithmetic Expressions Rules
• Associativity rules• Unary operators in the same subexpression and at the same
precedence level (such as + and -) are evaluated right to left (right associativity). Binary operators in the same subexpression and at the same precedence level (such as + and -) are evaluated left to right (left associativity).
• Type rules– If both operands are integers -> result is integer.
– If any of the operands is floating point -> result is floating.
Assignment statement X = expression
• If LHS and RHS are both same type -> no conversion.
• If LHS is floating and RHS is integer -> RHS converted to floating.
• If LHS is integer and RHS is floating -> RHS truncated to integer.
• The value of an assignment statement is the value assigned -> X = RHS value
Assignment statement• Problem: What will be printed by the following
program fragment?
int x = 2, y = 5, z = 3, p, q, r; float a; p = (x + y * z) * 5 +3/5 * 5; r = q = 3.0/5 * 5; a = (5 - 3) / 3; cout << p << endl; cout << q << endl; cout << a << endl;
Assignment statement
P = (x +y * z) * 5 + 3 /5 *5
= (2 + 15) * 5 +3 /5 * 5
= 17 *5 + 3 / 5 *5
= 85 + 3 / 5 * 5
= 85 + 0 * 5
= 85 + 0
= 852 5 3 85
x y z p
Mathematical Formula & C Expression
a = r 2
Mathematical Formula C Expression
a = PI * r * r
x - am =
y - b m = (y - b) / (x - a)
r1 = -b + b 2 - 4ac
2ax = pow (b, 2) - 4 * a * c ;
r1 = (- b + sqrt ( x)) / (2 * a);
Interactive Mode, Batch Mode, and Data Files
• In interactive mode, the user types in data during the execution of the program.
• Prompts are included so that the user knows exactly when to enter each data item.
• Batch mode scans input data from a file prepared prior to program execution.
• Input can be redirected to a file by using < (left angle) command.
• For example, myprog < mydata causes myprog to take input data from file mydata.
Interactive Mode, Batch Mode, and Data Files
• To convert interactive version of miles-to-kilometers program to batch, each preceding prompt statement is replaced by an echo print following scanf line.
• Program output can also be redirected to a disk file instead of the screen.
• For example, metric > myoutput command causes to write the output to file myoutput.
• UNIX or MS-DOS uses the > (right angle) command to redirect output to a file.
• These forms of input/output redirection are done via the operating system.
Common Programming Errors
Bugs: Errors in programs are called.
Debugging: process of correcting errors in program.
Errors
Syntax errorsRun-time errors
Logic errors
Undetected errors
Syntax Errors• Occurs when your code violates one or more
grammar rules of C++.• Detected by the compiler as it attempts to
translate.• If error occurs, program cannot be translated
and program will not be executed.• Example:
– Missing semicolon at the end of a statement.– Undeclared variables– Omit to put a quotation mark.
Run-Time Errors
• Detected and displayed during the execution.
• Occurs when the program directs the computer to perform an illegal operation.
• If errors occur, the computer will stop executing your program.
• Example:
– divide by zero error
– pointer error.
Undetected Errors
• Undetected errors do not prevent a C++ program from running to completion.
• However, may lead to incorrect results. These can be discovered by thorough testing.
• Examples of undetected errors are
- mixing character and numeric data
- transposing variables, etc.
Logic Errors
• Occur when a program follows a faulty algorithm.
• Do not display error message.• Very difficult to detect.• Only sign of a logic error can be unexpected
results.• It can be detected by comparing its output to
calculated results.
• Well-written programs contain comments that explain in English what the program is doing.
• Most programs use libraries that provide tools the programmer need not recreate from scratch.
• By adding a #include line that specifies a header file(such as iostream.h, math.h), you gain access to libraries.
• Every complete C++ program contains a function main. When we run the program, the statements in the body of main are executed in order.
Overview
Overview• Most programs are composed of the following
three phases: input =>computation =>output • Use cin to accept input typed by the user, cout to
display messages and data values on the screen. • Data values come in many different types, each of
which is defined by a domain and a set of operations.
• Variables have three attributes: a name, a value, and a type. All variables used in a C++ program must be declared first.
• The order of operations in an expression is determined by rules of precedence.