By Shervin Daneshpajouh Legend Legend Legend Legend Software - - PowerPoint PPT Presentation

by shervin daneshpajouh legend legend legend legend
SMART_READER_LITE
LIVE PREVIEW

By Shervin Daneshpajouh Legend Legend Legend Legend Software - - PowerPoint PPT Presentation

By Shervin Daneshpajouh Legend Legend Legend Legend Software Engineering Observation g g Performance tip Portability tip Good programming practice Common programming error Error prevention tip Error prevention tip 3 Shervin Daneshpajouh


slide-1
SLIDE 1

By Shervin Daneshpajouh

slide-2
SLIDE 2
slide-3
SLIDE 3

Legend Legend Legend Legend

Software Engineering Observation g g Performance tip Portability tip Good programming practice Common programming error Error‐prevention tip Error prevention tip

3

Shervin Daneshpajouh

slide-4
SLIDE 4

1 // Fig. 1.2: fig01_02.cpp 2 // A first program in C++. 3 #include <iostream>

Single-line comments. Preprocessor directive to

4 5 // function main begins program execution 6 int main() 7 {

Preprocessor directive to include input/output stream header file <iostream>. Left brace { begins

7 { 8 std::cout << "Welcome to C++!\n"; 9 10 return 0; // indicate that program ended successfully 11

g function body. Statements end with a semicolon ;.

11 12 } // end function main

Welcome to C++!

Name cout belongs to namespace std. Stream insertion operator. Function main appears exactly once in every C++ Corresponding right brace } ends function body. p program.. Keyword return is one of several means to exit function; value 0 indicates

4

function; value 0 indicates program terminated successfully.

slide-5
SLIDE 5

Good Programming Practice Good Programming Practice Good Programming Practice Good Programming Practice

  • Every program should begin with a comment that describes

y p g g the purpose of the program, author, date and time.

  • Use blank lines and space characters to enhance program

readability.

  • Some programmers prefer to declare each variable on a

separate line. This format allows for easy insertion of a p y descriptive comment next to each declaration.

5

Shervin Daneshpajouh

slide-6
SLIDE 6

Common Programming Error Common Programming Error Common Programming Error Common Programming Error

  • Omitting the semicolon at the end of a C++ statement is a

g syntax error.

  • preprocessor directives do not end in a semicolon.
  • The syntax of a programming language specifies the rules for

creating a proper program in that language. A syntax error

  • ccurs when the compiler encounters code that violates C++'s
  • ccurs when the compiler encounters code that violates C

s language rules (i.e., its syntax).

  • Syntax errors are also called compiler errors, compile‐time

il i errors or compilation errors.

  • You will be unable to execute your program until you correct all

the syntax errors in it the syntax errors in it.

  • Some compilation errors are not syntax errors.

6

Shervin Daneshpajouh

slide-7
SLIDE 7

A A Simple Program: Simple Program: f Printing a Line of Text Printing a Line of Text

Standard output stream object

std::cout “Connected” to screen <<

Stream insertion operator Value to right (right operand) inserted into output stream Namespace p

std:: specifies using name that belongs to “namespace”

std

std:: removed through use of using statements

g g

Escape characters

\ Indicates “special” character output Indicates special character output

7

slide-8
SLIDE 8

A A Simple Program: Simple Program: f Printing a Line of Text Printing a Line of Text

E S D i ti Escape Sequence Description \n

  • Newline. Position the screen cursor to the

beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the beg g o e cu e e; do o dv ce o e next line. \a

  • Alert. Sound the system bell.

\\

  • Backslash. Used to print a backslash character.

\" Double quote. Used to print a double quote character.

8

slide-9
SLIDE 9

1 // Fig. 1.4: fig01_04.cpp 2 // Printing a line with multiple statements. 3 #include <iostream> 4 5 // function main begins program execution 6 int main() 7 {

Multiple stream insertion statements produce one line of output.

7 { 8 std::cout << "Welcome "; 9 std::cout << "to C++!\n"; 10 11 return 0; // indicate that program ended successfully 11 return 0; // indicate that program ended successfully 12 13 } // end function main

Welcome to C++! Welcome to C++! 9

slide-10
SLIDE 10

1 // Fig. 1.5: fig01_05.cpp 2 // Printing multiple lines with a single statement 3 #include <iostream> 4 5 // function main begins program execution 6 int main() 7 {

Using newline characters to print on multiple lines.

7 { 8 std::cout << "Welcome\nto\n\nC++!\n"; 9 10 return 0; // indicate that program ended successfully 11 11 12 } // end function main

Welcome to to C++! 10

slide-11
SLIDE 11

Another Another Simple Program: Simple Program: dd dd Adding Two Integers Adding Two Integers

Variables

Location in memory where value can be stored Common data types

int ‐ integer numbers g char ‐ characters double ‐ floating point numbers

Declare variables with name and data type before use

yp

int integer1; int integer2; int sum;

Can declare several variables of same type in one declaration

Comma‐separated list int integer1, integer2, sum; g , g , ;

11

slide-12
SLIDE 12

Another Another Simple Program: Simple Program: dd dd Adding Two Integers Adding Two Integers

Variables

Variable names

Valid identifier

Series of characters (letters digits underscores) Series of characters (letters, digits, underscores) Cannot begin with digit Case sensitive P t bilit Ti

  • Portability Tip
  • C++ allows identifiers of any length, but your C++

implementation may impose some restrictions on the length of

  • identifiers. Use identifiers of 31 characters or fewer to ensure

portability.

12

slide-13
SLIDE 13

Good Programming Practice Good Programming Practice

  • Choosing meaningful identifiers helps make a program self‐

g g p p g documentinga person can understand the program simply by reading it rather than having to refer to manuals or comments.

  • Avoid using abbreviations in identifiers. This promotes program

readability. readability.

  • Avoid identifiers that begin with underscores and double

g underscores, because C++ compilers may use names like that for their own purposes internally. This will prevent names you choose from being confused with names the compilers choose choose from being confused with names the compilers choose.

13

Shervin Daneshpajouh

slide-14
SLIDE 14

Another Another Simple Program: Simple Program: dd dd Adding Two Integers Adding Two Integers

Input stream object

>> (stream extraction operator)

Used with std::cin Waits for user to input value then press Enter (Return) key Waits for user to input value, then press Enter (Return) key Stores value in variable to right of operator

Converts value to variable data type

= (assignment operator)

Assigns value to variable Binary operator (two operands)

Binary operator (two operands)

Example: sum = variable1 + variable2;

14

slide-15
SLIDE 15

1 // Fig. 1.6: fig01_06.cpp 2 // Addition program. 3 #include <iostream> 4 5 // function main begins program execution 6 int main() 7 { 8 int integer1; // first number to be input by user

Declare integer variables. Use stream extraction operator with

8 int integer1; // first number to be input by user 9 int integer2; // second number to be input by user 10 int sum; // variable in which sum will be stored 11 12 std::cout << "Enter first integer\n"; // prompt

Use stream extraction operator with standard input stream to obtain user input. S i l

12 std::cout << Enter first integer\n ; // prompt 13 std::cin >> integer1; // read an integer 14 15 std::cout << "Enter second integer\n"; // prompt 16 std::cin >> integer2; // read an integer

Stream manipulator std::endl outputs a newline, then “flushes

  • utput buffer.”

16 std::cin integer2; // read an integer 17 18 sum = integer1 + integer2; // assign result to sum 19 20 std::cout << "Sum is " << sum << std::endl; // print sum

p Concatenating, chaining or cascading stream insertion

  • perations

21 22 return 0; // indicate that program ended successfully 23 24 } // end function main

  • perations.

Calculations can be performed in output statements: l i f li 18 d 20

15

alternative for lines 18 and 20:

std::cout << "Sum is " << integer1 + integer2 << std::endl;

slide-16
SLIDE 16

fig01_06.cpp fig01_06.cpp

  • utput (1 of 1)
  • utput (1 of 1)

Enter first integer 45 Enter second integer 72 Sum is 117

16

slide-17
SLIDE 17

Memory Memory Concepts Concepts Memory Memory Concepts Concepts

Variable names

Correspond to actual locations in computer's memory Every variable has name, type, size and value When new value placed into variable, overwrites previous

value

Reading variables from memory nondestructive Reading variables from memory nondestructive

17

slide-18
SLIDE 18

Memory Memory Concepts Concepts Memory Memory Concepts Concepts

std::cin >> integer1;

integer1 45

g

Assume user entered 45

integer1 45

std::cin >> integer2;

Assume user entered 72

integer2 72

sum = integer1 + integer2;

integer1 45 integer2 72

sum = integer1 + integer2;

g sum 117

18

slide-19
SLIDE 19

Arithmetic Arithmetic Arithmetic Arithmetic

Arithmetic calculations

*

Multiplication

/

/

Division Integer division truncates remainder g

7 / 5 evaluates to 1

%

Modulus operator returns remainder Modulus operator returns remainder

7 % 5 evaluates to 2

19

slide-20
SLIDE 20

Arithmetic Arithmetic Arithmetic Arithmetic

Rules of operator precedence

Operators in parentheses evaluated first

Nested/embedded parentheses

Operators in innermost pair first Operators in innermost pair first

Multiplication, division, modulus applied next

Operators applied from left to right

( ) i ( ) d f l i ( d )

Addition, subtraction applied last

Operators applied from left to right

Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i t t d) th l t d l ft t i ht (i.e., not nested), they are evaluated left to right. *, /, or % Multiplication Division Modulus Evaluated second. If there are several, they re evaluated left to right. + or - Addition Subtraction Evaluated last. If there are several, they are evaluated left to right.

20

Subtraction evaluated left to right.

slide-21
SLIDE 21

Arithmetic Arithmetic Arithmetic Arithmetic

21

Shervin Daneshpajouh

slide-22
SLIDE 22

Evaluation of a Second Evaluation of a Second‐Degree Degree l i l l i l Polynomial Polynomial

  • y = ax2 + bx + c
  • Order in which a second‐degree polynomial is evaluated.

Suppose variables a, b, c and x in the preceding second‐degree g polynomial are initialized as follows: a = 2, b = 3, c = 7, x = 5. , 3, 7, 5

22

Shervin Daneshpajouh

slide-23
SLIDE 23

Algorithm Algorithm g

slide-24
SLIDE 24

Introduction Introduction Introduction Introduction

Before writing a program

Have a thorough

understanding of problem problem

Carefully plan your

approach for solving it g

While writing a program

Know what “building

bl k ” il bl

Lars Arge

blocks” are available

Use good programming

principles p p

24

slide-25
SLIDE 25

Algorithms Algorithms Algorithms Algorithms

Computing problems

Solved by executing a series of actions in a specific order

Algorithm a procedure determining

b d

Actions to be executed Order to be executed Example: recipe Example: recipe

Program control

Specifies the order in which statements are executed

p

25

slide-26
SLIDE 26

Pseudocode Pseudocode Pseudocode Pseudocode

Pseudocode

Artificial, informal language used to develop algorithms Similar to everyday English

Not executed on computers

Used to think out program before coding

Easy to convert into C++ program Easy to convert into C++ program

Only executable statements

No need to declare variables

26

slide-27
SLIDE 27

Control Control Structures Structures Control Control Structures Structures

Sequential execution

Statements executed in order

Transfer of control

d

Next statement executed not next one in sequence

3 control structures (Bohm and Jacopini)

Sequence structure

Sequence structure

Programs executed sequentially by default

Selection structures

if, if/else, switch

Repetition structures

while do/while for while, do/while, for

27

slide-28
SLIDE 28

Control Control Structures Structures Control Control Structures Structures

C++ keywords

Cannot be used as identifiers or variable names

C++ K eywo rds

Keywords common to the Keywords common to the C and C++ programming languages auto break case char const continue default do double else t fl t f t enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new

  • perator

28 private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t

slide-29
SLIDE 29

Control Control Structures Structures Control Control Structures Structures

Flowchart

Graphical representation of an algorithm Special‐purpose symbols connected by arrows (flowlines) Rectangle symbol (action symbol)

Any type of action

Oval symbol Oval symbol

Beginning or end of a program, or a section of code (circles) Single‐entry/single‐exit control structures

Connect exit point of one to entry point of the next Control structure stacking

29

slide-30
SLIDE 30

Control Control Structures Structures Control Control Structures Structures

30

slide-31
SLIDE 31

if if Selection Structure Selection Structure if if Selection Structure Selection Structure

Selection structure

Choose among alternative courses of action Pseudocode example:

f d d h l If student’s grade is greater than or equal to 60 Print “Passed”

If the condition is true

Print statement executed, program continues to next statement

If the condition is false

P i t t t t i d ti Print statement ignored, program continues

Indenting makes programs easier to read

C++ ignores whitespace characters (tabs, spaces, etc.) g p , p ,

31

slide-32
SLIDE 32

Decision Decision Making: Equality and Relational Making: Equality and Relational Operators Operators

if structure

Make decision based on truth or falsity of condition

If condition met, body executed Else body not executed Else, body not executed Equality and relational operators

Equality operators

q y p

Same level of precedence

Relational operators

S l l f d Same level of precedence

Associate left to right

32

slide-33
SLIDE 33

Decision Decision Making: Equality and Relational Making: Equality and Relational Operators Operators

S tandard algebraic C++ equality Example Meaning of g equality operator or relational operator q y

  • r relational
  • perator

p

  • f C++

condition g C++ condition

Relational operators i t th > > x > y x is greater than y < < x < y x is less than y

>= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y Equality operators = == x == y x is equal to y == x == y x is equal to y

!= x != y x is not equal to y

33

slide-34
SLIDE 34

if if Selection Structure Selection Structure if if Selection Structure Selection Structure

Translation into C++

If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed";

Diamond symbol (decision symbol)

Indicates decision is to be made Contains an expression that can be true or false

T di i f ll h Test condition, follow path if structure

Single‐entry/single‐exit

Single entry/single exit

34

slide-35
SLIDE 35

if if Selection Structure Selection Structure if if Selection Structure Selection Structure

Flowchart of pseudocode statement

A decision can be made on any expression. zero - false zero false nonzero - true Example: 3 - 4 is true

35

slide-36
SLIDE 36

Decision Decision Making: Equality and Relational Making: Equality and Relational Operators Operators

using statements

Eliminate use of std:: prefix Write cout instead of std::cout

36

slide-37
SLIDE 37

1 // Fig. 1.14: fig01_14.cpp 2 // Using if statements, relational 3 // operators, and equality operators. 4 #i l d i 4 #include <iostream> 5 6 using std::cout; // program uses cout 7 using std::cin; // program uses cin 8 using std::endl; // program uses endl

using statements eliminate need for std::

8 using std::endl; // program uses endl 9 10 // function main begins program execution 11 int main() 12 {

eliminate need for std:: prefix. Can write cout and cin Declare variables.

12 { 13 int num1; // first number to be read from user 14 int num2; // second number to be read from user 15 16 cout << "Enter two integers, and I will tell you\n"

Can write cout and cin without std:: prefix. if structure compares values of num1 and num2

16 cout Enter two integers, and I will tell you\n 17 << "the relationships they satisfy: "; 18 cin >> num1 >> num2; // read two integers 19 20 if ( num1 == num2 )

values of num1 and num2 to test for equality. if structure compares values of num1 and num2

( ) 21 cout << num1 << " is equal to " << num2 << endl; 22 23 if ( num1 != num2 ) 24 cout << num1 << " is not equal to " << num2 << endl;

to test for inequality.

25

37

slide-38
SLIDE 38

26 if ( num1 < num2 ) 27 cout << num1 << " is less than " << num2 << endl; 28 29 if ( num1 > num2 ) 30 cout << num1 << " is greater than " << num2 << endl; 31 32 if ( num1 <= num2 )

Statements may be split

  • ver several lines.

32 if ( num1 num2 ) 33 cout << num1 << " is less than or equal to " 34 << num2 << endl; 35 36 if ( num1 >= num2 ) 36 if ( num1 >= num2 ) 37 cout << num1 << " is greater than or equal to " 38 << num2 << endl; 39 40 return 0; // indicate that program ended successfully 40 return 0; // indicate that program ended successfully 41 42 } // end function main

Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 38 22 is greater than or equal to 12

slide-39
SLIDE 39

Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7

39

slide-40
SLIDE 40

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

if

Performs action if condition true

if/else

Different actions if conditions true or false

Pseudocode if student’s grade is greater than or equal to 60 print “Passed” l else print “Failed” C++ code if ( d > 60 ) if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

40

slide-41
SLIDE 41

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

Ternary conditional operator (?:)

Three arguments (condition, value if true, value if

false)

C d ld b itt Code could be written:

cout << ( grade >= 60 ? “Passed” : “Failed” ); Condition Value if true Value if false

41

slide-42
SLIDE 42

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

42

slide-43
SLIDE 43

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

Nested if/else structures

One inside another, test for multiple cases Once condition met, other statements skipped

if student’s grade is greater than or equal to 90 Print “A” else if student’s grade is greater than or equal to 80 Print “B” else if student’s grade is greater than or equal to 70 Print “C” else if t d t’ d i t th l t 6 if student’s grade is greater than or equal to 60 Print “D” else Print “F”

43

slide-44
SLIDE 44

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

Example if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // 80-89 else if ( grade >= 80 ) // 80 89 cout << "B"; else if ( grade >= 70 ) // 70-79 cout << "C"; ; else if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F";

44

slide-45
SLIDE 45

if/else if/elseSelection Structure Selection Structure if/else if/elseSelection Structure Selection Structure

Compound statement

Set of statements within a pair of braces

if ( grade >= 60 ) cout << "Passed.\n"; l { else { cout << "Failed.\n"; cout << "You must take this course again.\n";

}

Without braces,

cout << "You must take this course again.\n";

always executed always executed

Block

Set of statements within braces

45

slide-46
SLIDE 46

References References References References

  • H. M. Deitel ‐ Deitel & Associates, Inc., P. J. Deitel ‐ Deitel & Associates, Inc.

Publisher : Prentice Hall.

46

Shervin Daneshpajouh

slide-47
SLIDE 47

Legend Legend Legend Legend

Software Engineering Observation g g Performance tip Portability tip Good programming practice Common programming error Error‐prevention tip Error prevention tip

47

Shervin Daneshpajouh

slide-48
SLIDE 48

48

Shervin Daneshpajouh