structure programming programming in c++ instructor dr.abeer mahmoud computer science department...

73
1 Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams University This presentation is prepared and updated ( enhanced) by Dr. Hala Mousher Ebied & Dr. Safia Abbas, respectively. 1

Upload: buddy-cain

Post on 28-Dec-2015

217 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

1

Structure ProgrammingProgramming in C++

Instructor

Dr.Abeer MahmoudComputer Science Department

Faculty of Computer and Information SciencesAin Shams University

This presentation is prepared and updated ( enhanced) by Dr. Hala Mousher Ebied & Dr. Safia Abbas, respectively.

1

Page 2: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

2

Text Books

• “ Absolute C++”: International Version, by Walter Savitch, University of California, 4th ed. (2010),  ISBN-10: 0131365843.

• “C++ How to Program”, 8th Edition, Paul Deitel, Harvey Deitel.

• Object-oriented Programming in C++, fourth edition, Robert Lafore.

Page 3: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

3

Other online sources

• Programming and data structure.– http://cse.iitkgp.ac.in/pds/notes/

• Introduction to programming using C++– http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL1.html

• Thinking in C++ “book”.– http://www.lib.ru.ac.th/download/e-books/Tic2Vtwo.pdf

• C++ tutorial.– http://www.cplusplus.com/doc/tutorial/

Page 4: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

4

Course Contents

• Introduction.• Variables, types and expressions.• Functions and procedural abstraction.• Files and streams.• Branch and loop statements.• Arrays and strings.• Pointers.• Recursions.

Page 5: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

5

Lecture 1: Agenda • Introduction - computer hardware &Programming Languages

• First Program• Output Using cout• Directives• Comments

• Integer Variables• Input with cin• Variable Names• Arithmetic Expressions

• The arithmetic assignment operators

• Character Variables• Floating Point Types• const Qualifier• Type bool• The setw Manipulator• Variable Type Summary• Type Conversion• Increment Operators• Math Library Functions

5

Page 6: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

6

Main computer components

• A computer is a machine that can perform computation. a computation involves the following three components:

• Input: The user gives a set of input data.•Processing: The input data is processed by a well-defined and finite sequence of steps.•Output: Some data available from the processing step are output to the user.

Usually, computations are carried out to solve some meaningful and useful problems. One supplies some input instances for the problem, which are then analyzed in order to obtain the answers for the instances.

Page 7: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

7

Why digital computers & problems types

• Usually, computer perform computations in order to solve some meaningful and useful problems faster and more accurately. One supplies some input instances for the problem, which are then analyzed in order to obtain the answers for the instances.

• Types of problems– Functional problems A set of arguments a1,a2,...,are send to Some function,

as f(a1,a2,...,an), which in turn calculate the arguments and output to the user.

– Decision problems These form a special class of functional problems whose outputs are "yes" and "no" (or "true" and "false", or "1" and "0", etc).

– Search problems Given an input object, one tries to locate some particular configuration pertaining to the object and outputs the located configuration, or "failure" if no configuration can be located.

– Optimization problems Given an object, a configuration and a criterion for goodness, one finds and reports the configuration pertaining to the object, that is best with respect to the

Page 8: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

8

How does a program run in a computer?

• The inputs, the intermediate values and the instructions defining the processing stage reside in the (main) memory. In order to separate data from instructions the memory is divided into two parts:

• Data area The data area stores the variables needed for the processing stage. The values stored in the data area can be read, written and modified by the CPU.

• Instruction area The instruction area stores a sequence of instructions that define the steps of the program. Under the control of a clock, the computer carries out a fetch-decode-execute cycle in which instructions are fetched one-by-one from the instruction area to the CPU, decoded in the control unit and executed in the ALU. The CPU understands only a specific set of instructions. The instructions stored in memory must conform to this specification.

Page 9: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

9

How does a program run in a computer?

Page 10: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

10

What is programming?

•  Programming is a process done by programmers to instruct a computer on how to do a task .

• It is Planning or scheduling a sequence of steps for a computer to follow to perform a task.

• Basically, telling a computer what to do and how to do it.

• A program is :

– A sequence of steps to be performed by a computer.

– Expressed in a computer language. 

Page 11: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

11

• Unstructured Programming • Procedural Programming • Modular & Structural Programming• Abstract Data Type• Object-Oriented Programming

Object Oriented Programming Lecture-1, 2012

Page 12: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

12

• Small and (simple?) programs. • Consists only of one main

program. • Here ``main program'' stands

for a sequence of commands or statements which modify data which is global throughout the whole program.

Main Program

Data

Object Oriented Programming Lecture-1, 2012

Page 13: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

13

• This programming technique can only be used in a very small program. Why?

• For example, if the same statement sequence is needed at different locations within the program, the sequence must be copied. If an error needed to be modified, every copy needs to be modified.

This has lead to the idea to extract these sequences (procedure), name them and offering a technique to call and return from these procedures.

Object Oriented Programming Lecture-1, 2012

Page 14: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

14

• Unstructured Programming • Procedural Programming • Modular & Structural Programming• Abstract Data Type• Object-Oriented Programming

Object Oriented Programming Lecture-1, 2012

Page 15: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

15

• With procedural programming, you are able to combine sequences of calling statements into one single place.

• A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made .

Main Program

Procedure

Object Oriented Programming Lecture-1, 2012

Page 16: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

16

• With parameters and sub-procedures (procedures of procedures) , programs can now be written more structured and with less errors.

• • For example, if a procedure is correct, every time it is used

it produces correct results.

• Consequently, in cases of errors you can narrow your search to those places which are not proven to be correct.

Object Oriented Programming Lecture-1, 2012

Page 17: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

17

• Now a program can be viewed as a sequence of procedure calls.

• The main program is responsible to pass data to the individual calls, the data is processed by the procedures and the resulting data is presented.

• Thus, the flow of data can be illustrated as a hierarchical graph, a tree.

Object Oriented Programming Lecture-1, 2012

Page 18: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

18

Main Program

Data

Procedure1Procedure2 Procedure3

Object Oriented Programming Lecture-1, 2012

Page 19: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

19

• Unstructured Programming • Procedural Programming • Modular & Structural Programming• Abstract Data Type• Object-Oriented Programming

Object Oriented Programming Lecture-1, 2012

Will be discussed next year

Page 20: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

20

• Modular programming is subdividing your program into separate subprograms.

• Procedures of a common functionality are grouped together into separate modules.

• A program no longer consists of only one single part. It is now divided into several smaller parts which interact through procedure calls.

• The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters.

Object Oriented Programming Lecture-1, 2012

Page 21: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

21

Main Program(Also a module)

Data

Data Data1

Module2

+Data Data2

Module1

+Data Data1

Procedure1Procedure2 Procedure3

Object Oriented Programming Lecture-1, 2012

Page 22: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

22

• A subset of procedural programming that enforces a logical structure on the program being written to make it more efficient and easier to understand and modify. “organizing considering time and space”

• Certain languages such as Ada, and Pascal were designed with features that encourage or enforce a logical program

Object Oriented Programming Lecture-1, 2012

Page 23: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

23

• Three Types of Structures in a structured program

-Statement sequence(s1,s2,…,sn)

-Branch(if-then-else)

-Loop(for,do, and while loops)

- Keep modules!!!

Basic structures for programming?

Object Oriented Programming Lecture-1, 2012

Page 24: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

24

• Unstructured Programming • Procedural Programming • Modular & Structural Programming• Abstract Data Type• Object-Oriented Programming

Object Oriented Programming Lecture-1, 2012

Page 25: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

25

Programming Languages

• There are many different programming languages, and many ways to classify them. For example,– "high-level" programming languages are languages whose

syntax is relatively close to natural language, – whereas the syntax of "low-level" languages includes

many technical references to the (0's and 1's, etc.) • C is in many ways hard to categories. Compared to assembly

language it is high-level, but it nevertheless includes many low-level facilities to directly manipulate the computer's memory.

25

Page 26: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

26

high – level languages

• Are designed to be easy to read and write• Use more complicated instructions than the CPU can follow• Must be translated to zeros and ones for the CPU to execute a

program

26

Page 27: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

27

Machine, Assembler and high level language

• Machine language is a numeric language specifically understood by a computer’s processor (the CPU).

• Assembly language consist of statements written with short mnemonics such as ADD, MOV, ….It has a one-to- oneone-to- one relationship with machine language instructions

• High level language ( such as C++ and Java) has a one–to–one–to–manymany relationship with machine/assembly language instructions

27

Page 28: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

28

How computers understand the instruction?

• Programs are written in a programming language, then translated into machine code by a compiler and linker so that the computer can execute it directly or run it line by line (interpreted) by an interpreter program.

Page 29: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

29

Compilers

• Translate high-level language to machine language

LinkersA Linker combines

– The object code for the programs we writeAnd

– The object code for the pre-compiled routinesInto

– The machine language program, the CPU can run (executable program)

29

Page 30: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

30

Agenda

• Introduction - Programming Languages• First Program

• Output Using cout

• Directives• Comments

• Integer Variables• Input with cin• Variable Names• Arithmetic Expressions

• The arithmetic assignment operators

30

Page 31: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

31

The Origins of C++

• C++ was developed by Bjarne Stroustrup of AT&T Bell

Laboratories in the early 1980's, and is based on the C

language. The name is a pun - "++" is a syntactic construct

used in C (to increment a variable), and C++ is intended as an

incremental improvement of C

31

Page 32: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

32

Building a C++ Program A C++ Program consists of

Source files Header files

Source Files Usually have a *.cpp Compiled individually

Header Files Usually have a *.h extension Contain declarations which are “included” by

source files.

32

Page 33: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

33

First program“Hello C++!”

#include <iostream> //preprocessor directive using namespace std; //”using” directive

int main() //function name “main”{ //start function body

cout << "Hello C++!\n”; //statementreturn 0; // the program has completed successfully

} //end function body

33

Page 34: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

34

Comments on “first program” statements #include <iostream>

• It’s called a preprocessor directive.• It is an instruction to the compiler.• The preprocessor directive #include tells the

compiler to insert another file into your source file.• #include tells the compiler to add the source file

iostreamiostream librarylibrary before compiling. Why do this?– iostreamiostream library library is an example of a header file header file and  handle input from the keyboard and output to the screen (specifically the cin and cout statements that appear later).

34

Page 35: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

35

Comments on “first program” statements , cont.

using namespace std;

• This statement is called a using directiveusing directive. • simply means that we will use functions/objects from the

namespace “std”.• If we didn’t use the using directive, we would need to add the

stdstd name to many program elements. For example,

std::cout << “Every age has a language of its own.”;

35

Page 36: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

36

Comments on “first program” statements , cont.

Main ()• is a sub-program• there is always exactly one such structure called main.

return 0; • means return the value 0 to the computer's operating system

to signal that the program has completed successfully.• More generally, return statements signal that the particular

sub-program has finished.

• A left brace, {, left brace, {, must begin the body of every function.• A corresponding right brace, }, right brace, }, must end each function’s

body. 36

Page 37: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

37

Comments on “first program” statements , cont.

• // indicates that the remainder of each line is a comment.– You insert comments to document your programs and to

help other people read and understand them.– Comments are ignored by the C++ compiler and do not

cause any machine-language object code to be generated.• A comment beginning with //is called a single-line comment

because it terminates at the end of the current line.• You also may use C’s style in which a comment—possibly

containing many lines—begins with /*and ends with */./* thisis a very longMultiline comment*/ 37

Page 38: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

38

Comments on “first program” statements , cont.

cout << "Hello C++!\n“ ;cout << "Hello C++!\n“ ;

• A statement instructs the computer to perform an action.• A string is sometimes called a character string or a string

literal.• We refer to characters between double quotation double quotation marks

simply as stringsstrings.• White-space characters in strings are not ignored by the

compiler.• A statement normally ends with a semicolon (;), also known

as the statement terminator.• Preprocessor directives (like #include) do not end with a

semicolon. 38

Page 39: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

39

Comments on “first program” statements , cont.

cout << "Hello C++!\n“ ;cout << "Hello C++!\n“ ;

• When a cout statement executes, it sends a stream of characters to the standard output stream object—std—which is normally connected to the screen.

• The << operator is referred to as the stream insertion stream insertion operator.operator.– The value to the operator’s right, the right operand, is

inserted in the output stream.

39

Page 40: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

40

Comments on “first program” statements , cont.

cout << "Hello C++!\n“ ;cout << "Hello C++!\n“ ;

• The characters \n \n are not printed on the screen.• The backslash (\) is called an escape character.

– It indicates that a “special” character is to be output.

• When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence.

• The escape sequence \n means newline.– Causes the cursor to move to the beginning of the next line on the

screen.

40

Page 41: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

4141

Page 42: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

42

OR“Hello C++!”

#include <iostream> using namespace std;

void main() {

cout << "Hello C++!\n”; }

42

Page 43: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

43

Modifying our First C++ Programprinting multiple lines of txt with single statement

#include <iostream> using namespace std

int main(){

cout << “welcome\n to\n\n C++!\n”; return 0;

}

43

Page 44: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

44

Another Mediation to First C++ Program

• The statement Cout produce the screen outputcout << Expression1 << Expression2 << ... << ExpressionN;

#include <iostream> using namespace std

int main(){

cout << “welcome\n” << “ to\n\n” << “ C++!\n”; return 0;

}44

Page 45: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

45

Building a C++ Program

MAIN.CPP MAIN.OBJ MAIN.EXE

MAIN.CPP is a source file Contains source code you write.

MAIN.OBJ is an object file Contains object code generated by compiling MAIN.CPP

MAIN.EXE is an executable file Is a “double-clickable” application that may be run. It is

created by the linker which takes object code and generates executables.

45

Page 46: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

46

Agenda

• Introduction - Programming Languages• First Program

• Output Using cout

• Directives• Comments

• variables & identifiers• Integer Variables• Input with cin• Variable Names• Arithmetic Expressions

• The arithmetic assignment operators46

Page 47: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

47

Variables & Identifiers

• programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work we need to introduce the concept of variable.

• we can define a variable as a portion of memory to store a determined value.

• Each variable needs an identifier that distinguishes it from the others

Page 48: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

48

Variable Names=identifier

• The names given to variables are called identifiers. • What are the rules for writing identifiers?

– You can use upper- and lowercase letters, and the digits from 1 to 9.

– You can also use the underscore _. – The first character must be a letter or underscore.

• Identifiers can be as long as you like, but most compilers will only recognize the first few hundred characters.

• C++ is case sensitive: The compiler distinguishes between upper- and lowercase letters, so Var is not the same as var or VAR.

48

Page 49: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

49

keyword• A keyword is a predefined word with a special meaning.• int, class, if, and while are examples of keywords. • A complete list of keywords can be found in Appendix B, page

886, book “object oriented programming in C++”.

• Note:• Declarations of variables can be placed almost anywhere in a

program, but they must appear before their corresponding variables are used in the program.

49

Page 50: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

50

Some Simple C++ Type Declarations Variables

• Program variables are used to store different values at different times during the program execution. These variables are first introduced in our program in the variable declaration

• Example:

intint year, age, another_year, another_age;intint j;

floatfloat interestRate;

charchar aLetter;

stringstring userName;

50

Page 51: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

51

Variables, cont.

int -- integer type: range is system dependent usually 32-bits -- +/- 2,147,483,648 16-bits on older systems -- +/- 32,768

float -- floating point number char -- a single character string -- more than an array of characters (a class)

we’ll look at these in more detail later..

51

Page 52: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

52

Second program#include <iostream> using namespace std; int main() {

int year_now, age; cout << "Enter the current year then press ENTER.\n"; cin >> year_now; cout << "Enter your current age in years.\n"; cin >> age;

return 0; } 52

Page 53: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

53

Run the program

• After we have compiled the program above, we can run it. The result will be something like

Enter current year then press ENTER. 2012Enter your current age in years. 26

53

Page 54: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

54

Statement cin

cin >> year;has resulted in the variable year being assigned the value 2012

at the point when the user pressed ENTER after typing in "2012".

A cin statement uses the input stream object cin (of namespace std) and the stream extraction operator, >>, to obtain a value from the keyboard.

54

Page 55: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

55

How to Assign Valuesvoid main()

{ int num1 = 0;

int num2 = 1;

...

}

Assignment at declaration time insert an equals sign followed by an initial value

Assignment of previously declared variable start with the variable name, follow with equals sign,

end with value to be assigned.55

Page 56: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

56

Arithmetic Expressionsvoid main()

{ int num1;

int num2;

int sum;

cout << “Enter First integer: “;

cin >> num1;

cout << “Enter Second integer: “;

cin >> num2;

sum = num1 + num2 ;

cout << “Sum is “ << sum << endl<< “\n”;

}

56

Page 57: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

57

Arithmetic Expressions, cont.

57

Page 58: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

58

The endl Manipulator

• It causes a linefeed to be inserted into the stream, so that subsequent text is displayed on the next line. It has the same effect as sending the ‘\n’ character,

58

Page 59: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

59

Arithmetic Operators

59

Page 60: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

60

Arithmetic Operators, cont.

• Most programs perform arithmetic calculations.• The asterisk (*) indicates multiplication. • The percent sign (%)is the modulus operator that will be discussed

shortly.– C++ provides the modulus operator, %, that yields the

remainder after integer division.– The modulus operator can be used only with integer operands.

• The arithmetic operators in pervious table are all binary operators.• Integer division (i.e., where both the numerator and the

denominator are integers) yields an integer quotient.– Any fractional part in integer division is discarded (i.e.,

truncated)—no rounding occurs.

60

Page 61: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

61

Arithmetic Operators, cont.

• Parentheses are used in C++ expressions in the same manner as in algebraic expressions.

• For example, to multiply aa times the quantity b+cb+c we write: a *(b+c).

61

Page 62: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

62

Arithmetic Operators, cont.

• C++ applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra.

62

Page 63: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

63

Example

63

Page 64: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

64

Arithmetic Operators, cont.

• There is no arithmetic operator for exponentiation in C++, so x2 is represented as x*x.

64

Page 65: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

65

The arithmetic assignment operatorsmain()

{ int j = 0,k = 5;

k = k - 5;

}

The same variable may appear on both sides of an assignment operator on the right hand side of the assignment operator, the variable in

question represents its value prior to the execution of this statement.

on the left hand side of the assignment operator, the variable receives a new value which is the result of the evaluation on the right hand side.

In our example above, k ends up being “0”.

65

Page 66: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

66

The arithmetic assignment operators, cont.

main()

{ int j = 0,k = 5;

k -= 5; // really like k = k - 5;

}

When performing any other operation on a variable and stuffing the value back into the same variable, use a shortcut (like +=, -=, *=, %=)

66

Page 67: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

67

The arithmetic assignment operators, cont.

67

Page 68: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

68

The best way to learn a programming language is to try writing programs

and test them on a computer

68

Page 69: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

69

Your Turn

• 1. Dividing a program into functionsa. is the key to object-oriented programming.b. makes the program easier to conceptualize.c. may reduce the size of the program.d. makes the program run faster.

• 2. A function name must be followed by ________.• 3. A function body is delimited by ________.• 4. Why is the main() function special?• 5. A C++ instruction that tells the computer to do something is

called a ________.

69

Page 70: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

70

Your Turn, cont.

• 9. True or false: A variable of type char can hold the value 301.

• 10. What kind of program elements are the following?a. 12b. ‘a’c. 4.28915d. JungleJime. JungleJim()

70

Page 71: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

71

Your Turn, cont.

• 11. Write statements that display on the screena. the character ‘x’b. the name Jimc. the number 509

• 12. True or false: In an assignment statement, the value on the left of the equal sign is always equal to the value on the right.

• 15. Write a statement that gets a numerical value from the keyboard and places it in the variable temp.

71

Page 72: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

72

Your Turn, cont.

• 19. The expression 11%3 evaluates to ________.

• 21. Write a statement that uses an arithmetic assignment operator to increase the value of the variable temp by 23. Write the same statement without the arithmetic assignment operator.

72

Page 73: Structure Programming Programming in C++ Instructor Dr.Abeer Mahmoud Computer Science Department Faculty of Computer and Information Sciences Ain Shams

73

Answers• 1- b,c.• 2-parentheses• 3- braces { }• 4- It’s the first function executed when the program starts• 5- statement• 9- false• 10- a. integer constant

– b. character constant– c. floating-point constant– d. variable name or identifier– e. function name

• 11. – a. cout << ‘x’;– b. cout << “Jim”;– c. cout << 509;

• 12- false; they’re not equal until the statement is executed• 15- cin >> temp;• 19- 2• 21-

– temp += 23;– temp = temp + 23;