AABU/IT Faculty Dr. Wael Qassas

1 AABU/IT Faculty Dr. Wael QassasC++ Programming AABU/IT ...
Author: Margery Hamilton
0 downloads 2 Views

1 AABU/IT Faculty Dr. Wael QassasC++ Programming AABU/IT Faculty Dr. Wael Qassas د. وائل القصاص

2 1.1 Computer OrganizationChapter 1 – Introduction to Computers and C++ Programming 1.1 Computer Organization Six logical units of computer Input unit “Receiving” section Obtains information from input devices Keyboard, mouse, microphone, scanner, networks, … Output unit “Shipping” section Takes information processed by computer Places information on output devices Screen, printer, networks, … Information used to control other devices د. وائل القصاص

3 1.1 Computer OrganizationSix logical units of computer Memory unit Rapid access, relatively low capacity “warehouse” section Retains information from input unit Immediately available for processing Retains processed information Until placed on output devices Memory, primary memory Arithmetic and logic unit (ALU) “Manufacturing” section Performs arithmetic calculations and logic decisions د. وائل القصاص

4 1.1 Computer OrganizationSix logical units of computer Central processing unit (CPU) “Administrative” section Supervises and coordinates other sections of computer Secondary storage unit Long-term, high-capacity “warehouse” section Storage Inactive programs or data Secondary storage devices Disks Longer to access than primary memory Less expensive per unit than primary memory د. وائل القصاص

5 1.2 Machine Languages, Assembly Languages, and High-level LanguagesThree types of computer languages Machine language Only language computer directly understands “Natural language” of computer Defined by hardware design Machine-dependent Generally consist of strings of numbers Ultimately 0s and 1s Instruct computers to perform elementary operations One at a time Cumbersome for humans Example: د. وائل القصاص

6 1.2 Machine Languages, Assembly Languages, and High-level LanguagesThree types of computer languages Assembly language English-like abbreviations representing elementary computer operations Clearer to humans Incomprehensible to computers Translator programs (assemblers) Convert to machine language Example: LOAD BASEPAY ADD OVERPAY STORE GROSSPAY د. وائل القصاص

7 1.2 Machine Languages, Assembly Languages, and High-level LanguagesThree types of computer languages High-level languages Similar to everyday English, use common mathematical notations Single statements accomplish substantial tasks Assembly language requires many instructions to accomplish simple tasks Translator programs (compilers) Convert to machine language Interpreter programs Directly execute high-level language programs Example: grossPay = basePay + overTimePay د. وائل القصاص

8 1.3 History of C and C++ History of CEvolved from two other programming languages BCPL and B “Typeless” languages Dennis Ritchie (Bell Laboratories) Added data typing, other features Development language of UNIX Hardware independent Portable programs 1989: ANSI standard 1990: ANSI and ISO standard published ANSI/ISO 9899: 1990 د. وائل القصاص

9 1.3 History of C and C++ History of C++ Extension of CEarly 1980s: Bjarne Stroustrup (Bell Laboratories) “Spruces up” C Provides capabilities for object-oriented programming Objects: reusable software components Model items in real world Object-oriented programs Easy to understand, correct and modify Hybrid language C-like style Object-oriented style Both د. وائل القصاص

10 1.4 C++ Standard Library C++ programs C++ standard libraryBuilt from pieces called classes and functions C++ standard library Rich collections of existing classes and functions “Building block approach” to creating programs “Software reuse” د. وائل القصاص

11 1.5 Basics of a Typical C++ EnvironmentC++ systems Program-development environment Language C++ Standard Library د. وائل القصاص

12 1.5 Basics of a Typical C++ EnvironmentLoader Primary Memory Program is created in the editor and stored on disk. Preprocessor program processes the code. Loader puts program in memory. CPU takes each instruction and executes it, possibly storing new data values as the program executes. Compiler Compiler creates object code and stores it on disk. Linker links the object code with the libraries, creates a.out and stores it on disk Editor Preprocessor Linker CPU . Disk Phases of C++ Programs: Edit Preprocess Compile Link Load Execute د. وائل القصاص

13 1.5 Basics of a Typical C++ EnvironmentInput/output cin Standard input stream Normally keyboard cout Standard output stream Normally computer screen cerr Standard error stream Display error messages د. وائل القصاص

14 1.6 Flowchart It is a graphical way to describe the solution of the problem. Flow Chart Symbols Start and End Selection Data Flow Input / output Calculation د. وائل القصاص

15 Problem : Compute and print the summation of two numbers.Input a,b S = a + b Output s د. وائل القصاص

16 Problem : Compute and print the average of three numbers.Input n1,n2,n3 S = n1+n2+n3 Average = s / 3 Output average د. وائل القصاص

17 Problem : Compute the area of the circle. Where area = 3.14 x R2Input R A = 3.14 * R *R Output A د. وائل القصاص

18 Problem : Read any number from the user, then print positive if it is positive.Input Num Num>0 True Output “Positive” False د. وائل القصاص

19 Problem : Read any number from the user, then print positive if it is positive and print negative otherwise. Input Num False Num>0 True Output “Negative” Output “Positive” د. وائل القصاص

20 Problem : Read Two numbers from the user, then print the greatest one.Input x, y False True X>y Output y Output x د. وائل القصاص

21 Problem : Read three numbers to print the smallest one.Input a, b, c a and a True output a b b output b c c output c د. وائل القصاص

22 Input a, b, c aTrue False a b a Output c Output b Output c Output a د. وائل القصاص

23 Problem : Print the word “Amman” five times.Count = 1 True Count<=5 Output “Amman” False Count = Count + 1 د. وائل القصاص

24 Problem : Print the following numbers. 1 3 5 7 9 11True I<=11 Output I False I = I + 2 د. وائل القصاص

25 Problem : Print the following numbers. 20 17 14 11 8 5 2True I>=2 Output I False I = I - 3 د. وائل القصاص

26 Problem : Compute and print S, Where S = 1+ 2+ 3+ 4+ 5True C<=5 S = S + C False Output S C = C + 1 د. وائل القصاص

27 Problem : Compute and print summation of any 10 numbers entered by the user.True C<=10 INPUT Num False S = S + Num Output S C = C + 1 د. وائل القصاص

28 Problem : Compute and Print the factorial of the number 5Problem : Compute and Print the factorial of the number 5. (where Fact = 5 * 4 * 3 * 2 * 1) Fact = 1 C = 5 True C>=1 Fact = Fact * C False Output Fact C = C - 1 د. وائل القصاص

29 Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * nINPUT n I = 2 True I<=n M = M * I False Output M I = I + 2 د. وائل القصاص

30 1.7 Introduction to C++ ProgrammingC++ language Facilitates structured and disciplined approach to computer program design Following several examples Illustrate many important features of C++ Each analyzed one statement at a time Structured programming Object-oriented programming د. وائل القصاص

31 1.8 A Simple Program: Printing a Line of TextComments Document programs Improve program readability Ignored by compiler Single-line comment Begin with // Preprocessor directives Processed by preprocessor before compiling Begin with # د. وائل القصاص

32 C++ Program A sequence of structured statements written by programmer using C++ language to solve a problem. Using Visual C++ to write your program 1- Start  Programs  Microsoft Visual Studio 6  Microsoft Visual C++ 6 2- File  New  Files  C++ Source file  oK 3- Write your program using C++ statements 4- Compilation: Ctrl + F7 to see if the program has error's 5- Execution: to display the program’s result د. وائل القصاص

33 General form of C++ Program#include using namespace ::std; int main() { C++ statements } Remark: C++ language is case sensitive د. وائل القصاص

34 2 // A first program in C++. 3 #include 4 // Fig. 1.2: fig01_02.cpp // A first program in C++. #include 4 // function main begins program execution int main() { std::cout << "Welcome to C++!\n"; 9 return 0; // indicate that program ended successfully 11 12 } // end function main د. وائل القصاص

35 1.8 A Simple Program: Printing a Line of TextStandard output stream object std::cout “Connected” to screen << Stream insertion operator Value to right (right operand) inserted into output stream Namespace std:: specifies using name that belongs to “namespace” std std:: removed through use of using statements Escape characters \ Indicates “special” character output د. وائل القصاص

36 1.8 A Simple Program: Printing a Line of Textد. وائل القصاص

37 2 // Printing a line with multiple statements. // Fig. 1.4: fig01_04.cpp // Printing a line with multiple statements. #include 4 // function main begins program execution int main() { std::cout << "Welcome "; std::cout << "to C++!\n"; 10 return 0; //indicate that program ended successfully 12 13 } // end function main Multiple stream insertion statements produce one line of output. Welcome to C++! د. وائل القصاص

38 Problem : Compute and print the summation of two numbers.Program #include using namespace ::std; void main() { int a, b, s; cout<<"Please Enter two numbers:"; cin>>a>>b; s = a + b; cout<<"s="< د. وائل القصاص

39 Remarks: - iostream.h: C++ library that contains all input/output statements and other controls. - main( ): the main function of the program which represents the program’s life time. - a, b, and s are three variables of type integer. Their values can be any integer and can be changed. - cin>>: C++ statement to take value(s) from the user. - cout<<: C++ statements to display value(s) to the output screen. - " ": must be around any character constants. - \n or endl: to start new line at output screen. د. وائل القصاص

40 Variables Variables: - Variable is one memory location.-The name of the location is the variable name. -The location content is the value of the variable - You can change the content of the variable at any time in the statements of the algorithm. e.g. Name of the location Inside Memory location employee_name "Ali Ahmed" age hourly_rate د. وائل القصاص

41 Variable names Rules of variable names: 1- must begin with a letter2- can be followed by letters or numbers 3- can use _ 4- No other characters or symbols allowed 5- can’t use Keywords of the C++ language as variables. Examples on allowed variable names: int X,x,Number, IF,iF,a7,Total_sum; float average, _abc; د. وائل القصاص

42 Data Types Variable declarationPredefined Data Types: int : values (e.g , , 12) operations (e.g. + , - , * , / , % , >, <, = =, !=, > =, <= ) float (double) : values (e.g , 1.23E+5 , 0.34E-2) operations (e.g. +, -, *, /, , >, <, = =, !=, > =, <= ) bool : values (true , false) operations (e.g. AND, OR, NOT) char : values (e.g. ‘A’ , ‘t’ , ‘(‘ , ‘5’ , ‘;’ ) operations (e.g. <, > , ≤, etc.) Variable declaration Type Variable_name د. وائل القصاص

43 Constant Values: can be numerical (3, 100, -5, 3Constant Values: can be numerical (3, 100, -5, 3.14) or string (‘A’, ‘$’, “Ahmad”, “Amman”). Constant identifier: one memory location take a value at a first time, which can not be changed. const float pi = 3.14 د. وائل القصاص

44 Problem : Compute and print the average of three numbers.Program #include void main() { int n1, n2, n3; float s, average; cout<<"Please Enter three integers: "; cin>>n1>>n2>>n3; s = n1 + n2 + n3; average = s / 3; cout<<"Average = \t"< د. وائل القصاص

45 Problem : Compute the area of the circle. Where area = π x R2Program #include void main() { const double Pi = 3.14; int r; cout<<"Please enter r : "; cin>>r; double a; a = Pi * r * r; cout<<"Circle's Area = "< د. وائل القصاص

46 Examples on integer division#include void main( ) { int x; x=1/3*3; // /3=0 cout< x=1.0/3*3; } د. وائل القصاص

47 Boolean variables and relational operations#include void main( ) { bool x,y; x= 5 > 7; cout< y= 5 < 7; cout< x=true; y=false; x=5; cout< } د. وائل القصاص

48 Misleading examples X= 7 > 5 > 3;This expression gives false because its evaluated as follows X=(7>5) >3; = > 3; // False; The relational operations are executed from left to right < ,<= ,> , >= have the same priority == , != have lower priority than the above. X = 1 == 1>3; X = 3>4 == 4>3; د. وائل القصاص

49 Priority * , / , % have the same priority ( High )+ , - have the same priority (Low) د. وائل القصاص

50 Examples on arithmetic operationsW= * 3 – 7; The order of execution is as follows: * , then + , then - W= * 3 – 7 / 3 Execution order : * , + , / , - W= 5+2*3/4%1-7/3 …………………….. د. وائل القصاص

51 if Statement in C++ One way if if ( Condition ) statement;Expression One way if if ( Condition ) statement; if ( Condition ) { statements; } د. وائل القصاص

52 Problem : Read any number from the user, then print positive if it is positive.Program #include void main() { int Num; cout<<"Please Enter an integer number:"; cin>>Num; if (Num > 0) cout<<" Positive\n"; } د. وائل القصاص

53 Another Version #include void main() { int Num; bool w; cout<<"Please Enter an integer number:"; cin>>Num; w=Num>0; if (w) cout<<" Positive\n"; } د. وائل القصاص

54 If Statement in C++ Two way ifif ( Condition ) statement; else statement; if ( Condition ) { statements; } else { statements;} د. وائل القصاص

55 Write a program that reads a mark, if mark is 60 or greater, the program prints PASS, else it will print FAIL #include void main() { int mark; cout<<"Please Enter your mark: "; cin>>mark; if (mark>=60) cout<<" PASS\n"; else cout<<"FAIL\n"; } د. وائل القصاص

56 Ternary conditional operatorThree arguments (condition, value if true, value if false) Code could be written: cout <<( mark >= 60 ? “Passed\n”: “Failed\n” ); Condition Value if true Value if false د. وائل القصاص

57 More than one statement in the if#include void main() { int mark; cout<<"Please Enter your mark: "; cin>>mark; if (mark>=60) { cout<<" PASS\n"; cout<<" you can take Object course now\n"; } else cout<<"FAIL "; cout<<"You must take this course again\n"; د. وائل القصاص

58 Write a program that prints the fraction a/b in the form c d/b Example: 7/3 = 2 1/3قراءة ذاتية Self read #include void main ( ) { int a,b,c,d; cout<<"To convert the fraction from the format a/b to c d/b, Enter a,b"; cin>>a>>b; c=a/b; d=a%b; cout< } د. وائل القصاص

59 Enhancement on the previous exampleقراءة ذاتية Self read #include void main ( ) { int a,b,c,d; cout<<"To convert the fraction from the format a/b to c d/b, Enter a,b"; cin>>a>>b; c=a/b; d=a%b; cout< if ( c != 0) cout< if (d!=0) cout<<" "< cout< } د. وائل القصاص

60 Arithmetic ExpressionsCondition Condition: An expression that is evaluated to produce only true or false values. Arithmetic Expressions - It is composed of operands and arithmetic operations ( + , - , *, /, %). - Its result is a numeric value (e.g gives 7) - Operands may be numbers and/or identifiers that have numeric values. د. وائل القصاص

61 Relational Expressions- It is composed from operands and operators. - Operands may be numbers and/or identifiers that have numeric values - Its result is a logical value (true or false). - Operators are relational operators: < , > , <= , >= , = =, != e.g. (a < b) gives true, if value of a is less than value of b false, if value of a is not less than value of b (x != y) also gives true or false according to the values of x and y د. وائل القصاص

62 Logical Expressions - It is called also Boolean expression.- It is composed from operands and operators. - Operands are identifiers that have logical values - Its result is a logical value (true or false) (see later). - Operators are logical: &&(AND) , ||(OR), !(NOT) e.g. X && Y a && b || c د. وائل القصاص

63 Evaluating Logical ExpressionsThe truth table AND table && True False True True False False False False د. وائل القصاص

64 (2) OR table || True False True True True False True False(3) NOT table ! True False False True د. وائل القصاص

65 Arithmetic , Relational , LogicalExpressions: Arithmetic , Relational , Logical 1) Relational expression may contain arithmetic sub expressions, e.g. ( ) < (12 * 4 ) < 12 * 4 2) Logical expression may contain relational and arithmetic subexpressions, e.g. x && y && ( a > b ) (2 + t ) < (6 * w ) && ( p = =q ) د. وائل القصاص

66 Operator Precedence Precedence Description Operator Highestparentheses ( ) unary plus, unary minus, Not +, – , ! *, /, % Binary plus, binary minus + , - <, <=, >, >= Equal, not equal == , != && || Lowest Assignment = د. وائل القصاص

67 X=Y=Z=5+2*4 د. وائل القصاص

68 Examples Find the value of the following expression: (1) 5 + 8 * 2 / 4(1) * / 4 16 4 (This is the final result) د. وائل القصاص

69 Find the value of the following expression( ) / 12 2 10` (this is the final result) د. وائل القصاص

70 Find the value of the following ExpressionAssume that x = True, y = False, z = False, find the value of the expression x && y || z x && y || z False False (the final result) د. وائل القصاص

71 Another example X=true, Y=false, Z= true X || Y && Z trueX=true, Y=false, Z= false د. وائل القصاص

72 Find the value of the following ExpressionAssume that a = 3, b = 5, x = true, y = false, find the value of the expression: ( a < b ) AND y OR x ( a < b ) && y || x True False True (the final result) د. وائل القصاص

73 What is the output of the following code:Program #include void main() { int a=10, b=3; cout<<"\n a+b= \t\t\t\t"<= b*2 || a>b+9 is \t"<<(a+b >= b*2 || a>b+9); cout< د. وائل القصاص

74 Problem : Read any number from the user, then print positive if it is positive and print negative otherwise. Program #include void main() { int Num; cout<<"Please Enter Number:"; cin>>Num; if (Num < 0) cout<<"Negative\n"; else cout<<"Positive\n"; } د. وائل القصاص

75 Confusing Equality (==) and Assignment (=) Operators#include void main( ) { int x=0; if(x=0) cout<<“zero\n”; else cout<<“What happened\n”; } د. وائل القصاص

76 Problem : Read Two numbers from the user, then print the greatest one.Program #include void main() { int x,y; cout<<"Please Enter two numbers:"; cin>>x>>y; cout<<"Max = "; if (x > y) cout< د. وائل القصاص

77 Problem : Read three numbers to print the smallest one.Program #include void main() { int a, b, c; cout<<"Please Enter three numbers:"; cin>>a>>b>>c; cout<<"Min= "; if ((a < b) && (a < c)) cout< د. وائل القصاص

78 Program2 (Nested if) #include void main() { int a, b, c; cout<<"\nPlease Enter three numbers:"; cin>>a>>b>>c; cout<<"\nMin= "; if (a < b) if (a < c) cout< د. وائل القصاص

79 Problem : Read number, if it is positive, Add number 10 to it and print the Number "is positive", but otherwise, subtract number 10 from it and print the Number "is negative". Program #include void main() { int Number; cout<<"Please enter Number:"; cin>>Number; if (Number>0) { Number = Number + 10; cout< د. وائل القصاص

80 Example on dangling elseif ( x>y) if ( x cout<<" Hello"; else cout<<"Hi"; د. وائل القصاص

81 Another idea if ( x>y) {if ( xcout<<"Hi"; د. وائل القصاص

82 Assignment Statement Simple Assignment: Max = 5 ; Max = A ; F = A+B*2;Compound Assignment: A += 10 ;  A = A + 10; A -= C ;  A = A – C; I *= 4 ;  I = I * 4; r /= 2;  r = r / 2; S %= 3 ;  S = S % 3 ; B &= true;  B = B && true; B |= true;  B = B || true; B|=(a د. وائل القصاص

83 Increment and DecrementPostfix C++;  use the value of C, then increment (C = C+1) it. C--;  use the value of C, then decrement (C = C-1) it. Prefix ++C; increment the value of C (C = C+1), then use it . --C; Decrement the value of C (C = C-1), then use it . د. وائل القصاص

84 Examples X=5; Y=7; X++; cout<cout< cout<<++X< Z=X++ + Y; // Z=X+Y; X=X+1; cout< Z=++X +Y; // X=X+1; Z=X+Y; Z=X++ + Y++; // Z=X+Y; X++;Y++; د. وائل القصاص

85 What is the output of the following C++ Source CodeProgram #include void main( ) { int A=10, B=4, R; cout<<"A="< د. وائل القصاص

86 2.8 switch Multiple-Selection StructureTest variable for multiple values Series of case labels and optional default case switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 break; default: //taken if variable matches no other cases statements break; } د. وائل القصاص

87 2.8 switch Multiple-Selection Structure87 2.8 switch Multiple-Selection Structure د. وائل القصاص

88 Example on switch statement#include void main() { int a; cout<<“ Enter an Integer between 0 and 10: “; cin>>a; switch(a) { case 0: case 1: cout<<“hello ”; case 2: cout<<“there ”; case 3: cout<<“Welcome to ”; case 4: cout<<“C++ ”< break; case 5: cout<<“How “; case 6: case 7: case 8: cout<<“are you “< case 9: break; case 10: cout<<“Have a nice day. “< default: cout<<“Sorry, the number is out of range.”< cout<< “ out of switch structure.”< Example on switch statement 88 د. وائل القصاص

89 Another switch examplevoid main( ) { int score; char grade; cin>>score; switch(score/10) { case 0: case 1: case 2: case 3: case 4: case 5: grade = ‘F’; break; case 6: grade = ‘D’; case 7: grade = ‘C’; case 8: grade = ‘B’; case 9: case 10: grade = ‘A’; default: cout<<“Invalid test score.”< cout<<“Grade is”< } // end main 89 Another switch example د. وائل القصاص

90 switch examples void main( ) { char grade;90 switch examples void main( ) { char grade; cout <<“ Enter grade as a letter : ” ; cin>>grade; switch(grade) {case ‘A’: cout<<“The Grade is A”; break; case ‘B’: cout<<“The Grade is B”; case ‘C’: cout<<“The Grade is C”; case ‘D’: cout<<“The Grade is D”; case ‘F’: cout<<“The Grade is F”; default: cout<< “The Grade is invalid”; } د. وائل القصاص

91 switch examples void main( ) { int age;91 switch examples void main( ) { int age; cout<<“Enter your age: “; cin>>age; switch (age>=18) case 1: cout<<“old enough to take a driving license.”< cout<< “old enough to vote.”< break; case 0: cout<<“Not old enough to take a driving license”< cout<< “Not old enough to vote.”< } د. وائل القصاص

92 cout<<"Enter ur mark "; cin>>score; char grade; void main() { int score; cout<<"Enter ur mark "; cin>>score; char grade; switch(score/10) { case 0: case 1: case 2: case 3: case 4: case 5: grade = 'F'; break; case 6: grade = 'D'; break; case 7: grade = 'C'; case 8: grade = 'B'; case 9: case 10: grade = 'A'; default: cout<<"Invalid test score."< cout<<"Your grade is "< } د. وائل القصاص

93 Quiz Write a program to read 2 numbers and read an operation “ + , - , * ,/” , this program uses a switch statement to calculate and print the result of the operation selected. char op int A,B; switch(op){ case ‘+’: cout< case ‘-’: د. وائل القصاص

94 Loop (iteration statements) used to repeat subcode number of times there three loop techniques: 1- for Loop. 2- while Loop. 3- do … while Loop د. وائل القصاص

95 2.7 for Repetition Structure95 2.7 for Repetition Structure General format when using for loops for ( initialization; LoopContinuationTest; increment ) statement Example for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; Prints integers from one to ten No semicolon after last statement د. وائل القصاص

96 For Loop Technique General Form: for (counter_var=initial_val; condition; increasing or decreasing counter_var) { . Statement(s); . } Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go the first statement after for loop. If the loop body contains only one statement, there is no need to begin{ and end } the loop body. د. وائل القصاص

97 Problem : Print the word "Amman" five times.Program #include void main( ) { for (int i=1; i<=5; i++) cout<<"Amman\n"; } Another Program #include void main() { for (int i=5; i>=1; i--) cout<<"Amman\n"; } د. وائل القصاص

98 Problem : Print the following numbers. 1 3 5 7 9 11Program #include void main( ) { for (int k=1; k<=11; k+=2) cout< د. وائل القصاص

99 Problem : Print the following numbers. 20 17 14 11 8 5 2Program #include void main() { for (int m=20; m>=2; m-=3) cout< د. وائل القصاص

100 Another Version of the previous example#include void main( ) { int m; for (m=20; m>=2; m-=3) cout< د. وائل القصاص

101 Another Version of the previous example#include void main( ) { int m=20; for ( ; m>=2; m-=3) cout< د. وائل القصاص

102 Another Version of the previous example#include void main( ) { int m=20; for ( ; m>=2;){ cout< m-=3;} cout< د. وائل القصاص

103 Quiz Write a program that prints the numbers from X to Y, with step Z , using for statement. The program should read X, Y, Z then start the loop د. وائل القصاص

104 Problem : Print the following numbers. 1 2 3 4 … n(entered by user)Program #include void main() { int n; cout<<"\nPlease enter the upper limit:"; cin>>n; for (int i=1; i<=n; i++) cout< د. وائل القصاص

105 Problem : Print the following numbersProblem : Print the following numbers. L (entered By user) (L+1) (L+2) … U (entered By user) Program #include void main() { int L,U; cout<<"Enter the start value:"; cin>>L; cout<<"Enter the end value:"; cin>>U; for (int i=L; i<=U; i++) cout< د. وائل القصاص

106 Problem : Read five numbers from the user and print the positive numbers only.Program #include void main() { int num; for (int i=1; i<=5; i++) { cout<<"Please Enter No "<>num; if (num > 0) cout< د. وائل القصاص

107 Problem : Read five numbers from the user and print the positive numbers only.Continue statement #include void main() { int num; for (int i=1; i<=5; i++) { cout<<"Please Enter No "<>num; if (num < 0) continue; cout< د. وائل القصاص

108 Problem : Compute and print S, Where S = 1+ 2+ 3+ 4+ 5#include void main( ) { int S=0; for (int i=1; i<=5; i++) S+=i; cout<<"Sum is "< Program د. وائل القصاص

109 Problem : Compute and print S, Where Sum = 1+ 3+ 5+ 7+ … + nProgram #include void main( ) { int Sum=0, n; cout<<"Please Enter n"; cin>>n; for (int i=1; i<=n; i+=2) Sum+=i; cout<<"Sum="< د. وائل القصاص

110 Problem : print the following formula Sum = 1+ 3+ 5+ 7+ … + nProgram #include void main( ) { int n; cout<<"Please Enter n"; cin>>n; cout<<"Sum= "; for (int i=1; i<=n; i+=2) cout< د. وائل القصاص

111 Problem : Compute and print the summation of any 10 numbers entered by the user.Program #include void main() { int S=0, N; for (int i=10; i>=1; i--) { cout<<"Please Enter the next number:"; cin>>N; S+=N;} cout<<"S="< د. وائل القصاص

112 Problem : Compute and Print the factorial of the number 5. (Fact = 5 * 4 * 3 * 2 * 1)Program #include void main( ) { int Fact=1; for (int j=5; j>=1; j--) Fact *= j; cout<<"5! = "< د. وائل القصاص

113 A program to find n! #include void main( ) { int Fact=1,n; cout<<"Enter an integer to find its factorial: "; cin>>n; for (int j=n; j>=1; j--) Fact *= j; cout< د. وائل القصاص

114 Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * nProgram #include void main( ) { long M=1; int n; cout<<"please enter the upper Limit:"; cin>>n; for (int i=2; i<=n; i+=2) M *= i; cout<<"M= "< د. وائل القصاص

115 Problem : Compute and Print MnProgram #include void main() { long Result=1; int M, n; cout<<“Enter the Base number:"; cin>>M; cout<<“Enter the exponent:"; cin>>n; for (int i=1; i<=n; i++) Result *= M; cout<<"Result= "< د. وائل القصاص

116 Write a program that finds Mn for positive & negative nH.W. د. وائل القصاص

117 While Technique initialization; while ( loopContinuationTest){ statements increment; } Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go to the first statement after While loop. If the loop body contains only one statement, there is no need to begin{ and end } the loop body. د. وائل القصاص

118 Problem : Print the word "Amman" five times.Program #include void main( ) { int i=1; while (i<=5) { cout<<"Amman\n"; i++; } د. وائل القصاص

119 #include void main() { int i=1; while (i++<=5) { cout<<"Amman\n"; } cout< د. وائل القصاص

120 Problem : Print the following numbers. 1 3 5 7 9 11Program #include void main() { int i=1; while (i <= 11) { cout< i+=2; } } Remark: Write ((i+=2) <= 11 ) condition instead of the above one. What changes you have to do to produce the same output. د. وائل القصاص

121 Problem : Print the following numbers. 20 17 14 … nProgram #include void main() { int n, k=20; cout<<"Enter the lower limit:"; cin>>n; while ( k >= n) { cout< k -= 3; } cout< } Remark: Write k-=3 instead of k in the above condition. What you have to do to produce the same output. د. وائل القصاص

122 Problem : Read five numbers from the user and print the positive numbers only.Program #include void main() { int num, j=0; while ( j++ < 5 ) { cout<<"Enter a number:"; cin>>num; if (num > 0) cout< } Remark: Solve the above problem by using continue statement. د. وائل القصاص

123 Quiz Write a program to calculate the sum of numbers from 1 to 5int i=1 , sum =0; while(i<=5) { sum=sum+i; i++;} cout< د. وائل القصاص

124 #include void main() { int sum=0,i,x,y; cout<<"Enter x,y please: "; cin>>x>>y; i=x; while ( i <=y) { sum=sum+i; i=i+1; } cout<<"The Sum for the numbers from "< 125 Problem : Compute and print Sum, Where Sum = 1+ 3+ 5+ 7+ … + nProgram #include void main() { int n, Sum=0, i=1; cout<<"Enter the upper limit:"; cin>>n; while ( i <= n ) { Sum += i; i += 2; } cout<<"Sum="< } د. وائل القصاص

126 Problem : Read 10 numbers by the user and compute and print the summation of numbers, which are divisible by 3. Program #include void main() { int Num, Sum=0, i=1; while ( i <= 10 ) { cout<<"Enter a number:"; cin>>Num; if (Num % 3 == 0) Sum += Num; i++; } cout<<"\nSum="< د. وائل القصاص

127 Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * nProgram #include void main() { int N, M=1, i=2; cout<<"Enter the upper limit:"; cin>>N; while ( i <= N ) { M *= i; i += 2; } cout<<"\nM="< } د. وائل القصاص

128 #include void main() { int N, M=1, i=2; cout<<"Enter the upper limit:"; cin>>N; cout<<"\nM=1"; while ( i <= N ) { M *= i; cout<<" x "< i += 2; } cout<<"="< } د. وائل القصاص

129 Do .. While Technique General Form: initialization do { . Statement(s); . } while (Condition) ; Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go to the first statement after the loop. The loop body will be executed at least one. د. وائل القصاص

130 Problem : Print the word "Amman" five times.Program #include void main( ) { int i = 1; do { cout<<"Amman\n"; i++; } while (i <= 5); } د. وائل القصاص

131 Execute the following program#include void main() { int Choice, Num; do { cout<<"\n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout< else cout< cout<<"Select your choice.\n"; cout<<“Enter 1 Exit. (Terminate the Run)\n"; cout<<“Any Number to repeat.\n"; cin>>Choice; } while (Choice != 1); } د. وائل القصاص

132 #include void main() { int Num; char Choice; do { cout<<"\n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout< else cout< cout<<"Enter Y to continue, any other character to exit \n"; cin>>Choice; } while (Choice == ‘Y’); } د. وائل القصاص

133 #include void main() { int Num; char Choice; do { cout<<"\n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout< else cout< cout<<"Enter Y to continue, any other character to exit \n"; cin>>Choice; } while ((Choice == 'Y') || (Choice=='y')); } د. وائل القصاص

134 Homework Resolve all problems in the presentation 5 and 6 by using the three loop techniques: For, While, and Do … while Loops. د. وائل القصاص

135 2.10 break and continue Statementsbreak statement Immediate exit from while, for, do/while, switch Program continues with first statement after structure Common uses Escape early from a loop Skip the remainder of switch د. وائل القصاص

136 2 // Using the break statement in a for structure. // Fig. 2.26: fig02_26.cpp // Using the break statement in a for structure. #include 4 using std::cout; using std::endl; 7 // function main begins program execution int main() 10 { 11 int x; // x declared here so it can be used after the loop 13 // loop 10 times for ( x = 1; x <= 10; x++ ) { 16 // if x is 5, terminate loop if ( x == 5 ) break; // break loop only if x is 5 20 cout << x << " "; // display value of x 22 } // end for Exits for structure when break executed. د. وائل القصاص

137 Broke out of loop when x became 524 25 cout<< "\nBroke out of loop when x became "<< x < 26 return 0; // indicate successful termination 28 29 } // end function main Broke out of loop when x became 5 د. وائل القصاص

138 2.10 break and continue StatementsUsed in while, for, do/while Skips remainder of loop body Proceeds with next iteration of loop while and do/while structure Loop-continuation test evaluated immediately after the continue statement for structure Increment expression executed Next, loop-continuation test evaluated د. وائل القصاص

139 2 // Using the continue statement in a for structure. // Fig. 2.27: fig02_27.cpp // Using the continue statement in a for structure. #include 4 using std::cout; using std::endl; 7 // function main begins program execution int main() 10 { // loop 10 times for ( int x = 1; x <= 10; x++ ) { 13 // if x is 5, continue with next iteration of loop if ( x == 5 ) continue; // skip remaining code in loop body 17 cout << x << " "; // display value of x 19 } // end for structure Skips to next iteration of the loop. د. وائل القصاص

140 Used continue to skip printing the value 521 22 cout<< "\nUsed continue to skip printing the value 5" << endl; 24 return 0; // indicate successful termination 26 27 } // end function main Used continue to skip printing the value 5 د. وائل القصاص

141 #include void main() {cout<<"to print a new line on C++ use <<\"\\n\" \n"; } د. وائل القصاص

142 ضمن علامات التنصيص \\ تطبع \ “\ تطبع ” \n تطبع سطر جديد\\ تطبع \ “\ تطبع ” \n تطبع سطر جديد \t تطبع 8 فراغات Tab \b تعود للخلف حرف واحد \r تعود الى اول السطر \a تصدر صوت الجرس للحاسوب د. وائل القصاص

143 Print numbers from 1 to 25 put each 5 numbers in a line use for statement and if statment#include #include void main() { for (int i=1;i<=25;i++) {cout< if(i%5==0) cout< } د. وائل القصاص

144 Nested for Print the following shape ***** cin>>n;for(int i=1;i<=n;i++) { for (int j=1;j<=n;j++) cout<<"*"; cout< } د. وائل القصاص

145 #include void main() { for(int i=1;i<=5;i++) {for (int j=1;j<=5;j++) cout< cout< } د. وائل القصاص

146 Press any key to continue1,1 1,2 1,3 1,4 1,5 2,1 2,2 2,3 2,4 2,5 3,1 3,2 3,3 3,4 3,5 4,1 4,2 4,3 4,4 4,5 5,1 5,2 5,3 5,4 5,5 Press any key to continue د. وائل القصاص

147 Problem : Draw the following shape * ** *** **** *****Nested for Problem : Draw the following shape * ** *** **** ***** #include void main( ) { for (int raw=1; raw<=5; raw++) { for (int C=1; C<=raw; C++) cout<<'*'; cout< د. وائل القصاص

148 Problem : Draw the following shape ***** **** *** ** *#include void main() { for (int i=1; i<=5; i++) { for (int j=i; j<=5; j++) cout<<'*'; cout< د. وائل القصاص

149 Problem : Draw the following shape ***** **** *** ** *#include void main() { for (int i=1; i<=5; i++) { for (int j=5; j>=i; j--) cout<<'*'; cout< د. وائل القصاص

150 What is the output for the following programfor(int i=1;i<=5;i++) { for (int j=1;j<=5;j++) if (i==j) cout<<"*"; else if (i+j==6) cout<<"*"; cout<<" "; cout< د. وائل القصاص

151 Problem : display the multiplication table for the number 3.#include void main() { for (int i=1; i<=10; i++) cout<<"3 x "< } د. وائل القصاص

152 Problem : display the multiplication table for the numbers from 1 to 5. د. وائل القصاص

153 for (int i=1;i<=5;i++) { for(int j=1;j<=5;j++) cout< cout< } د. وائل القصاص

154 Problem : Read any number from the user and print Prime if it is a prime number, or Not prime otherwise. #include void main() { bool Prime = true; int i, num; cout<<"Please enter the number:"; cin>>num; for ( i=2; i if (num%i==0) { Prime = false; break; } if (Prime) cout< else cout< } د. وائل القصاص

155 S=m0 + m1 + … +mn #include void main(){int s=0,n,m,t; cout<<"Enter m please "; cin>>m; cout<<"Enter n please "; cin>>n; for (int i=0;i<=n;i++) { t=1; for (int j=1;j<=i;j++) t=t*m; s=s+t; } cout< د. وائل القصاص

156 #include void main() {int s=0,n,m; int t=1; cout<<"Enter m please "; cin>>m; cout<<"Enter n please "; cin>>n; for (int i=0;i<=n;i++) { s=s+t; t=t*m; } cout< د. وائل القصاص m; cout>n; for (int i=0;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/159/for+%28int+i%3D1%3Bi%3C%3D4%3Bi%2B%2B%29+%7Bint+x%3D1%3B+for%28int+j%3D1%3Bj%3C%3Di%3Bj%2B%2B%29.jpg", "name": "for (int i=1;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/160/for+%28int+i%3D1%3Bi%3C%3D4%3Bi%2B%2B%29+%7Bfor%28int+j%3D0%3Bj%3Ci%3Bj%2B%2B%29+%7Bint+x%3D1%3B.jpg", "name": "for (int i=1;iX; Y=X/180*3.141592; A=sin(Y); B=cos(Y); C=tan(Y); coutnum; for ( i=2; iseed; srand(seed); for( int i=1;ix; y=square(x); coutx; y=square(x); coutL; cout>W; A=area(L,W); coutx>>y>>z; coutz; coutx; if (prime(x)) coutx; y=fabs(x); coutx>>y; print_sum(x,y); print_sum(y,x); print_sum(5,7); } void print_sum(int x,int y) {int s; s=x+y; coutx; y=square(x); coutx; cout 206 Static variables #include void f(int x );void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/206/Static+variables+%23include+%3Ciostream.h%3E+void+f%28int+x+%29%3B.jpg", "name": "Static variables #include void f(int x );", "description": "void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; coutx; coutx; coutx; coutx; coutx; coutx; coutx; coutx>>y; couty; cout 231 Search #include const int Size = 10; void main() {int Vector[Size]; for(int i=0; i cin>>Vector[i]; cout< int Element; cout<<"What is the element that you looking for"; cin>>Element; bool Found = false; for(i=0; i if(Element = = Vector[i]){ Found = true; break; } if (Found) cout< else cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/231/Search+%23include+%3Ciostream.h%3E+const+int+Size+%3D+10%3B+void+main%28%29+%7B.jpg", "name": "Search #include const int Size = 10; void main() {", "description": "int Vector[Size]; for(int i=0; i>Vector[i]; coutVector[i]; coutVector[i]; for(i=0; iVector[i]; for(i=0; iVector[i]; for(i=0; i 252 For(int i=0;i<4;i++) S=S+A[i][3-i];د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/252/For%28int+i%3D0%3Bi%3C4%3Bi%2B%2B%29+S%3DS%2BA%5Bi%5D%5B3-i%5D%3B.jpg", "name": "For(int i=0;ia; couta; cout>b; couta; cout { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/275/int+length%28char+name%5B+%5D%29+%7Bint+i%3B+for%28+i%3D0%3Bname%5Bi%5D%21%3D0%3Bi%2B%2B%29+%3B+return+i%3B.jpg", "name": "int length(char name[ ]) {int i; for( i=0;name[i]!=0;i++) ; return i;", "description": "} د. وائل القصاص.", "width": "1024" } 276 Ex: Write a program that prints the name inversed( from the last char to the first character#include void main() { char name[10]; cout<<"Enter ur name : "; cin>>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout< cout< } د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/276/Ex%3A+Write+a+program+that+prints+the+name+inversed%28+from+the+last+char+to+the+first+character.jpg", "name": "Ex: Write a program that prints the name inversed( from the last char to the first character", "description": "#include void main() { char name[10]; cout>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout=0;j--) cout

157 Nested Loops 1 2 3 4 #include void main() {int j=1; while(j<=4){ int i=1; while(i<=4){ cout< i++; } j++; cout< د. وائل القصاص

158 Problem : Draw the following shape * ** *** **** *****#include void main() { int i=1; while (i<=5) { int j=1; while (j<=i) { cout<<'*'; j++;} cout< i++; } } د. وائل القصاص

159 for (int i=1;i<=4;i++) {int x=1; for(int j=1;j<=i;j++) 1 2 1 2 4 for (int i=1;i<=4;i++) {int x=1; for(int j=1;j<=i;j++) {cout< x=x*2;} cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/160/for+%28int+i%3D1%3Bi%3C%3D4%3Bi%2B%2B%29+%7Bfor%28int+j%3D0%3Bj%3Ci%3Bj%2B%2B%29+%7Bint+x%3D1%3B.jpg", "name": "for (int i=1;iX; Y=X/180*3.141592; A=sin(Y); B=cos(Y); C=tan(Y); coutnum; for ( i=2; iseed; srand(seed); for( int i=1;ix; y=square(x); coutx; y=square(x); coutL; cout>W; A=area(L,W); coutx>>y>>z; coutz; coutx; if (prime(x)) coutx; y=fabs(x); coutx>>y; print_sum(x,y); print_sum(y,x); print_sum(5,7); } void print_sum(int x,int y) {int s; s=x+y; coutx; y=square(x); coutx; cout 206 Static variables #include void f(int x );void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/206/Static+variables+%23include+%3Ciostream.h%3E+void+f%28int+x+%29%3B.jpg", "name": "Static variables #include void f(int x );", "description": "void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; coutx; coutx; coutx; coutx; coutx; coutx; coutx; coutx>>y; couty; cout 231 Search #include const int Size = 10; void main() {int Vector[Size]; for(int i=0; i cin>>Vector[i]; cout< int Element; cout<<"What is the element that you looking for"; cin>>Element; bool Found = false; for(i=0; i if(Element = = Vector[i]){ Found = true; break; } if (Found) cout< else cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/231/Search+%23include+%3Ciostream.h%3E+const+int+Size+%3D+10%3B+void+main%28%29+%7B.jpg", "name": "Search #include const int Size = 10; void main() {", "description": "int Vector[Size]; for(int i=0; i>Vector[i]; coutVector[i]; coutVector[i]; for(i=0; iVector[i]; for(i=0; iVector[i]; for(i=0; i 252 For(int i=0;i<4;i++) S=S+A[i][3-i];د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/252/For%28int+i%3D0%3Bi%3C4%3Bi%2B%2B%29+S%3DS%2BA%5Bi%5D%5B3-i%5D%3B.jpg", "name": "For(int i=0;ia; couta; cout>b; couta; cout { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/275/int+length%28char+name%5B+%5D%29+%7Bint+i%3B+for%28+i%3D0%3Bname%5Bi%5D%21%3D0%3Bi%2B%2B%29+%3B+return+i%3B.jpg", "name": "int length(char name[ ]) {int i; for( i=0;name[i]!=0;i++) ; return i;", "description": "} د. وائل القصاص.", "width": "1024" } 276 Ex: Write a program that prints the name inversed( from the last char to the first character#include void main() { char name[10]; cout<<"Enter ur name : "; cin>>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout< cout< } د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/276/Ex%3A+Write+a+program+that+prints+the+name+inversed%28+from+the+last+char+to+the+first+character.jpg", "name": "Ex: Write a program that prints the name inversed( from the last char to the first character", "description": "#include void main() { char name[10]; cout>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout=0;j--) cout

160 for (int i=1;i<=4;i++) {for(int j=0;jfor( int k=1;k<=j;k++) x=2*x; cout< cout< د. وائل القصاص X; Y=X/180*3.141592; A=sin(Y); B=cos(Y); C=tan(Y); coutnum; for ( i=2; iseed; srand(seed); for( int i=1;ix; y=square(x); coutx; y=square(x); coutL; cout>W; A=area(L,W); coutx>>y>>z; coutz; coutx; if (prime(x)) coutx; y=fabs(x); coutx>>y; print_sum(x,y); print_sum(y,x); print_sum(5,7); } void print_sum(int x,int y) {int s; s=x+y; coutx; y=square(x); coutx; cout 206 Static variables #include void f(int x );void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/206/Static+variables+%23include+%3Ciostream.h%3E+void+f%28int+x+%29%3B.jpg", "name": "Static variables #include void f(int x );", "description": "void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; coutx; coutx; coutx; coutx; coutx; coutx; coutx; coutx>>y; couty; cout 231 Search #include const int Size = 10; void main() {int Vector[Size]; for(int i=0; i cin>>Vector[i]; cout< int Element; cout<<"What is the element that you looking for"; cin>>Element; bool Found = false; for(i=0; i if(Element = = Vector[i]){ Found = true; break; } if (Found) cout< else cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/231/Search+%23include+%3Ciostream.h%3E+const+int+Size+%3D+10%3B+void+main%28%29+%7B.jpg", "name": "Search #include const int Size = 10; void main() {", "description": "int Vector[Size]; for(int i=0; i>Vector[i]; coutVector[i]; coutVector[i]; for(i=0; iVector[i]; for(i=0; iVector[i]; for(i=0; i 252 For(int i=0;i<4;i++) S=S+A[i][3-i];د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/252/For%28int+i%3D0%3Bi%3C4%3Bi%2B%2B%29+S%3DS%2BA%5Bi%5D%5B3-i%5D%3B.jpg", "name": "For(int i=0;ia; couta; cout>b; couta; cout { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/275/int+length%28char+name%5B+%5D%29+%7Bint+i%3B+for%28+i%3D0%3Bname%5Bi%5D%21%3D0%3Bi%2B%2B%29+%3B+return+i%3B.jpg", "name": "int length(char name[ ]) {int i; for( i=0;name[i]!=0;i++) ; return i;", "description": "} د. وائل القصاص.", "width": "1024" } 276 Ex: Write a program that prints the name inversed( from the last char to the first character#include void main() { char name[10]; cout<<"Enter ur name : "; cin>>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout< cout< } د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/276/Ex%3A+Write+a+program+that+prints+the+name+inversed%28+from+the+last+char+to+the+first+character.jpg", "name": "Ex: Write a program that prints the name inversed( from the last char to the first character", "description": "#include void main() { char name[10]; cout>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout=0;j--) cout

161 # ## ### #### د. وائل القصاص

162 Functions Chapter 3 د. وائل القصاص

163 Topics to be covered C++ pre defined functions: User Functions:Math library functions Random function Examples on rand with switch statments User Functions: Function proto type Function definition: Square, Cube examples Examples on the four forms of functions, And their meaning ( when to use each form): void F(void) void F(int) int F(void) int F(int) د. وائل القصاص

164 Call by value & call By reference Functions on arrays Scope of variables &Global variables Recursion : Factorial Febonacci, Sum of numbers from x to y د. وائل القصاص

165 Math library functions:ceil(x),floor(x) fabs(x), fmod(x,y), pow(x,y),sqrt(x) sin(x), cos(x), tan(x) These functions are of type double, and take also double arguments They belong to the library #include د. وائل القصاص

166 Examples double Y; cout<Y=floor(5.2); Y=floor(0.1); floor(-0.1); floor(-1.1); ceil(5.2/3); floor(ceil(5.2/3)); fabs( ); fmod(5,3) ≡ 5%3 fmod(4.2,2); fmod(5.1,2.5) fmod(7.7,2.5) double Y; Y=pow( 5,4); Y=pow(5,-4); Y=pow(5.2,3); Y=pow(16,0.25); Y=pow(0.01,0.5); Y=pow(-4,0.5); runtime error Y=pow(x*3/7,y-1); Y=pow(floor(x/3),ceil(x/4)); Y=sqrt(9); Y=ceil(sqrt(10)); Y=sqrt(0.09); Y=sqrt(-16); runtime error Examples د. وائل القصاص

167 #include #include void main() { double A,B,C,X,Y; cout<<"Enter an Angle : "; cin>>X; Y=X/180* ; A=sin(Y); B=cos(Y); C=tan(Y); cout<<"sin("< cout<<"cos("< cout<<"tan("< } د. وائل القصاص

168 Problem : Read any number from the user and print it is prime if it is, or not prime otherwise.#include #include void main() { bool Prime = true; int i, num; cout<<"Please enter the number:"; cin>>num; for ( i=2; i<=sqrt(num); i++) if (num%i==0) { Prime = false; break; } if (Prime) cout< else cout< } د. وائل القصاص

169 Random number generator#include X=rand(); // gives a random number // between د. وائل القصاص

170 #include #include void main() { int x; for( int i=1;i<=100;i++) {x=rand(); cout< } د. وائل القصاص

171 Generate 20 random numbers between 0 - 9#include #include void main() { int x; for( int i=1;i<=20;i++) {x=rand()%10; cout< } د. وائل القصاص

172 20 numbers between 1 - 10 #include #include void main() { int x; for( int i=1;i<=20;i++) {x=rand()%10+1; cout< } د. وائل القصاص

173 Generate 10 integer random numbers between 5 - 7د. وائل القصاص

174 Using srand function #include void main() {int x,seed; cout<<"Enter the seed for the random generater "; cin>>seed; srand(seed); for( int i=1;i<=10;i++) x=rand(); cout< } د. وائل القصاص

175 Q: Write a program that generates 1200 random numbers between 1-6, and also counts the occurrence of each number? Its expected that the occurrence of each number will be about 200 times. But remember we are talking about random number. No exact values. د. وائل القصاص

176 #include #include void main() { int x,count1=0, count2=0, count3=0, count4=0, count5=0, count6=0; for( int i=1;i<=1200;i++) { x=rand()%6 +1; if (x==1) count1++; if (x==2) count2++; if (x==3) count3++; if (x==4) count4++; if (x==5) count5++; if (x==6) count6++; cout< cout<<1<<" : "< cout<<2<<" : "< cout<<3<<" : "< cout<<4<<" : "< cout<<5<<" : "< cout<<6<<" : "< } د. وائل القصاص

177 A program to count the occurrence of each random number#include #include void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) { x=rand()%6 +1; if (x==1) count[1]++; if (x==2) count[2]++; if (x==3) count[3]++; if (x==4) count[4]++; if (x==5) count[5]++; if (x==6) count[6]++; cout< for(i=1;i<=6;i++) cout< } A program to count the occurrence of each random number د. وائل القصاص

178 The same example using Switch statement#include #include void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) { x=rand()%6 +1; switch(x) case 1: count[1]++; break; case 2: count[2]++; case 3: count[3]++; case 4: count[4]++; case 5: count[5]++; case 6: count[6]++; } for(i=1;i<=6;i++) cout< The same example using Switch statement د. وائل القصاص

179 Do the same prev. example, Count the number of even numbers, and the number of odd numbers. د. وائل القصاص

180 #include #include void main() { int x,even=0,odd=0; for( int i=1;i<=1200;i++) { x=rand()%6 +1; switch(x) case 1: case 3: case 5: odd++; break; case 2: case 4: case 6: even++; } cout<<"Even count is "< cout<<"Odd count is "< د. وائل القصاص

181 #include #include void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) x=rand()%6 +1; count[x]++; cout< for(i=1;i<=6;i++) cout< } د. وائل القصاص

182 3.5 , 3.6 User Defined FunctionsWrite a function that calculates and returns the square value of a double number: د. وائل القصاص

183 #include double square(double); // function prototype void main( ) {double x,y; cout<<"Enter a number :"; cin>>x; y=square(x); cout< 184 #include double square(double); // function prototype void main( ) {double x,y,z; cout<<"Enter a number :"; cin>>x; y=square(x); cout< 185 Another user defined functionWrite a program to calculate and print a rectangle area, the program should use a function to calculate and returns the area of a rectangle to the main program? This function should take the length and the width , and should return the area د. وائل القصاص

186 #include double area(double,double); // function prototype void main( ){ double L,W,A; cout<<"Enter the length:"; cin>>L; cout<<"Enter the width:"; cin>>W; A=area(L,W); cout<<"The area of the rectangle is "< } double area(double X,double Y) { double Z; Z=X*Y; return Z; د. وائل القصاص

187 Write a program that finds and prints the maximum of three integer numbers, The program should use a function to find the maximum value. د. وائل القصاص

188 #include int max(int,int,int); void main(){ int x,y,z; cout<<"Enter 3 numbers please :"; cin>>x>>y>>z; cout<<"The Maximum is "< } int max(int a,int b,int c) {int m; m=a; if (m if (m return m;} د. وائل القصاص

189 #include #include bool prime(int); void main(){ int x; cout<<"Enter a number please :"; cin>>x; if (prime(x)) cout< else cout< } bool prime(int a) {bool p=true; for(int i=2;i<=sqrt(a);i++) if (a%i==0) { p=false; break;} return p;} د. وائل القصاص

190 Build your own fabs function#include double fabs(double); void main(void) { double x,y; cout<<"Enter a number "; cin>>x; y=fabs(x); cout<<"The absolute value of "< } double fabs(double m) if (m>=0) return m; else return -m; د. وائل القصاص

191 Forms of functions Functions that take inputs and returns output:double square(double), int max(int a, int b, int c) …. Functions that take inputs but don’t return output void Printsum(int x,int y) Functions that don’t take any inputs but returns an output: int Read_number(void); Functions that don’t take and inputs and don’t return any input void Print_hello(void); د. وائل القصاص

192 Write a program that uses a function to calculate and print the sum of two numbers.#include void print_sum(int,int); void main( void ) {int x,y; cout<<"Enter two numbers please :"; cin>>x>>y; print_sum(x,y); print_sum(y,x); print_sum(5,7); } void print_sum(int x,int y) {int s; s=x+y; cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/192/Write+a+program+that+uses+a+function+to+calculate+and+print+the+sum+of+two+numbers..jpg", "name": "Write a program that uses a function to calculate and print the sum of two numbers.", "description": "#include void print_sum(int,int); void main( void ) {int x,y; cout>x>>y; print_sum(x,y); print_sum(y,x); print_sum(5,7); } void print_sum(int x,int y) {int s; s=x+y; cout

197 Modify the previous example, make the main calls the print function 10 timesAlso, make the print_welcome function print a random message from 3 different messages د. وائل القصاص

198 #include #include void print_welcome(void); void main(){ for(int i=1;i<=10;i++) print_welcome(); } void print_welcome(void) {int x=rand()%3; switch(x) {case 0: cout<<"Hello \n"; break; case 1: cout<<"Welcome \n";break; case 2: cout<<"Hi, how are u \n"; د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/198/%23include+%3Ciostream.h%3E+%23include%3Ccstdlib%3E.jpg", "name": "#include #include", "description": "void print_welcome(void); void main(){ for(int i=1;i

201 cout<int f1(int a) { cout< int x=13; f2(x); cout<<::x< return x+a; } void f2(int b) {cout< x=x-b; د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/201/cout%3C%3Cx%3C%3Cendl%3B+int+x%3D13%3B+f2%28x%29%3B.jpg", "name": "cout

203 Call By value & call By reference#include int square(int); void main() { int x,y; cout<<"Enter a number "; cin>>x; y=square(x); cout< } int square(int a) // call by value a=a*a; return a; } د. وائل القصاص

204 call by reference #include void square(int &);void main() { int x; cout<<"Enter a number "; cin>>x; cout< square(x); cout< } void square(int & a) // call by reference a=a*a; د. وائل القصاص

205 #include void read_two_numbers(int &,int &); void main() {int x,y; read_two_numbers (x,y); cout< } void read_two_numbers (int & a,int &b) { cout<<"Enter two numbers please “; cin>>a>>b; د. وائل القصاص

206 Static variables #include void f(int x );void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout< د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/206/Static+variables+%23include+%3Ciostream.h%3E+void+f%28int+x+%29%3B.jpg", "name": "Static variables #include void f(int x );", "description": "void main() { f(2); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout

208 Recursive functions Factorial Febonacci series Sum between X, Yد. وائل القصاص

209 Recursive fact #include int fact(int); void main(){ int x; cout<<"Enter a number to calculate its factorial "; cin>>x; cout< } int fact(int n) if (n==0) return 1; else return n*fact(n-1); Recursive fact د. وائل القصاص

210 Recursive fact #include int fact(int); void main(){ int x; cout<<"Enter a number to calculate its factorial "; cin>>x; cout< } int fact(int n) if (n==1) {cout<<"Now returning fact 1\n"; return 1; else {cout<<"Now calling fact "< return n*fact(n-1); Recursive fact د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/210/Recursive+fact+%23include+%3Ciostream.h%3E+int+fact%28int%29%3B+void+main%28%29.jpg", "name": "Recursive fact #include int fact(int); void main()", "description": "{ int x; cout>x; coutx; cout

215 #include int feb(int); void main() { int x; cout<<"Enter a number to calculate its febonacci "; cin>>x; cout< } int feb(int n){ if (n==0) return 0; else if (n==1) return 1; return feb(n-1)+feb(n-2); د. وائل القصاص

216 Febonacci using for #include int feb(int);void main() { int x; cout<<"Enter a number to calculate its febonacci "; cin>>x; cout< } int feb(int n){ int fn_2=0; int fn_1=1; int fn; for(int i=2;i<=n;i++) {fn=fn_2+fn_1; fn_2=fn_1; fn_1=fn; return fn; Febonacci using for د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/216/Febonacci+using+for+%23include+%3Ciostream.h%3E+int+feb%28int%29%3B.jpg", "name": "Febonacci using for #include int feb(int);", "description": "void main() { int x; cout>x; cout

218 Write a function that returns the sum of numbers from X to YWrite a function that returns the sum of numbers from X to Y. The function should calculate the sum recursively ∑ i = y+ ∑ i y y-1 i=x i=x د. وائل القصاص

219 Sum of numbers from X to Y#include int sum(int,int); void main() { int x,y; cout<<"Enter two numbers to calculate the sum "; cin>>x>>y; cout<<"Sum of the series "< } int sum (int a, int b) if (a==b) return b; else return b+sum(a,b-1); د. وائل القصاص

220 Array One Dimensional array Two Dimensional arrayArray is a set of adjacent memory locations of the same data type. All of them have one name, which is the array name. each location has subscript number started by zero. One Dimensional array Data_Type array_name[How many elements] ; Two Dimensional array Data_Type array_name[#Rows][#Columns] ; د. وائل القصاص

221 One Dimensional array int List[5]; List[0] List[1] list[2] list[3] list[4] Print Elements for(i=0; i<5; i++) cout< Read Elements List[0] = 100; List[1] = 30; List[2] = 10; List[3] = -20; List[4] = 5; د. وائل القصاص

222 Definitions and initial valuesint X[4]={4,2,3,1}; int A[10]={0}; int B[100]={1}; int C[7]={1,2,6}; int d[5]; int E[ ]={4,6,2}; د. وائل القصاص

223 Not accepted Statementsint A[4]={4,2,4,5,2}; int E[ ]; int n=5; int X[n]; Corrected by: const int n=5; د. وائل القصاص

224 #include void main() { int A[5] = {10,20,15,100,30}; for (int i=0; i<5; i++) cout< for (i=0; i<5; i++) { cout<<"\nPlease Enter A["< cin>>A[i]; } for (i=0; i<5; i++) cout< } د. وائل القصاص

225 #include void main() { const int Size = 10; char KeyBSym[Size]={ ')', '!', '#', '$', '%', '^', '&', '*', '(' }; for (int i=0; i cout<<"Shift + number "< } د. وائل القصاص

226 #include const int S = 10; void main() { int A[S]; for(int i=0; i cout<<"\nEnter A["< cin>>A[i]; } int PositiveSum = 0, EvenSum = 0, Gthan10_Count = 0; for (i=0; i if (A[i]>0) PositiveSum += A[i]; if (A[i]%2 == 0) EvenSum += A[i]; if (A[i]>10) Gthan10_Count++; } cout<<"\nSummation of positive Elements: "< cout<<"\nSummation of Even Elements: "< cout<<"\n# Element, which are greater than 10: "< cout< د. وائل القصاص

227 #include const int S = 10; void main() { int A[S]; for(int i=0; i cout<<"\nEnter A["< cin>>A[i]; } long Even_Position_Mul = 1, Odd_Position_Mul = 1; for (i=0; i if(i%2==0) Even_Position_Mul *= A[i]; else Odd_Position_Mul *=A[i]; cout<<"\nMultiplication of elements at Even position: "< cout<<"\nMultiplication of elements at Odd position: "< cout< } د. وائل القصاص

228 Find the Maximum element#include const int Size = 10; void main() { int Vector[Size]; cout<<“Enter 10 numbers to find the maximum\n”; for(int i=0; i cin>>Vector[i]; for(i=0; i cout< cout< int Max = Vector[0]; for(i=1; i if (Max Max=Vector[i]; cout<<"\nMax= "< } د. وائل القصاص

229 #include const int Size = 10; void main() { int Vector[Size]; cout<<"Enter 10 numbers to find the maximum\n"; for(int i=0; i cin>>Vector[i]; int Max = Vector[0]; int pos=0; for(i=1; i if (Max {Max=Vector[i]; pos=i;} cout<<"\nMax= "< } د. وائل القصاص

230 #include const int Size = 10; void main() { int Vector[Size]; cout<<"Enter 10 numbers to find the maximum\n"; for(int i=0; i cin>>Vector[i]; int pos=0; for(i=1; i if (Vector[pos] cout<<”Max= "< } د. وائل القصاص

231 Search #include const int Size = 10; void main() {int Vector[Size]; for(int i=0; i cin>>Vector[i]; cout< int Element; cout<<"What is the element that you looking for"; cin>>Element; bool Found = false; for(i=0; i if(Element = = Vector[i]){ Found = true; break; } if (Found) cout< else cout< د. وائل القصاص

232 Another version of search example#include const int Size = 10; void main() { int Vector[Size]; for(int i=0; i cin>>Vector[i]; cout< int Element; cout<<"What is the element that you are looking for: "; cin>>Element; bool Found = false; for(i=0; i if(Element == Vector[i]){ cout< Found=true; } if (!Found) // if (found==false) cout< } د. وائل القصاص

233 Sort the elements: #include const int Size = 5;void main() { int Vector[Size]; for(int i=0; i cin>>Vector[i]; for(i=0; i cout< cout< for(int pass=1; pass for(int i=0; i if (Vector[i]>Vector[i+1]) { int Temp = Vector[i]; Vector[i] = Vector[i+1]; Vector[i+1] = Temp;} cout< د. وائل القصاص

234 #include const int Size = 5; void main() { int Vector[Size]; for(int i=0; i cin>>Vector[i]; for(i=0; i cout< cout< for(int pass=1; pass { cout<<"pass "< for(int i=0; i if (Vector[i]>Vector[i+1]) { cout<<"Swap"< int Temp = Vector[i]; Vector[i] = Vector[i+1]; Vector[i+1] = Temp;} for(int j=0; j cout< } د. وائل القصاص

235 build a swap function functionvoid swap(int & x,int & y) { int temp; temp=x; x=y; y=temp; } د. وائل القصاص

236 Bubble sort using the swap function#include void swap(int &,int &); const int Size = 5; void main() { int Vector[Size]; for(int i=0; i cin>>Vector[i]; for(i=0; i for(int j=i+1; j if (Vector[i]>Vector[j]) swap(Vector[i],Vector[j]); for(i=0; i cout< cout< void swap(int & x,int & y) { int temp; temp=x; x=y; y=temp; } Bubble sort using the swap function د. وائل القصاص

237 Functions with Arrays and Call by reference conceptWe can’t return the array using return statement. We need to use the call by reference technique. BUT when passing an array to a function, it is sent as call by reference. No need to declare it as int &[ ] د. وائل القصاص

238 Write a function that return the sum of an array#include int Arr_Sum(int [ ],int); void main( ) { int A[5]={2,3,4,5,6}; int B[4]={5,3,1,7}; cout<<"The sum of A is "< cout<<"The sum of B is "< } int Arr_Sum(int x[ ],int size) {int S=0; for(int i=0;i S=S+x[ i ]; return S; د. وائل القصاص { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12265941/72/images/238/Write+a+function+that+return+the+sum+of+an+array.jpg", "name": "Write a function that return the sum of an array", "description": "#include int Arr_Sum(int [ ],int); void main( ) { int A[5]={2,3,4,5,6}; int B[4]={5,3,1,7}; cout

241 cout statement with setw( )#include #include void main() { for(int i=1; i<= 5;i++) // without using setw( ) cout< cout< for(i=1; i<= 5;i++) // with using setw( ) cout< } د. وائل القصاص

242 Strings #include void main() { char n[10];char a[10]={'A','h','m','e','d'}; for(int i=0; a[i]!=0 ; i++) cout< cout< } د. وائل القصاص

243 Q1 in the exam #include void main() { int a[4][3];for(int i=0;i<4;i++) for(int j=0;j<3;j++) { cout<<"Enter a number "; cin>>a[i][j]; } for(int k=0;k<3;k++) int s=0; for(int m=0;m<4;m++) s=s+a[m][k]; cout< د. وائل القصاص

244 Two Dimensional array int Matrix[3][4]; 30 1 2 Assign values to Elements Matrix[0][1] = 30; Matrix[1][0] = 100; Matrix[1][2] = 10; Matrix[2][3] = -20; Matrix[2][0]=Matrix[1][2]; Print Elements for(i=0; i<3; i++){ for(j=0; j<4; j++) cout< د. وائل القصاص

245 int A[2][3] = { {1 ,2 , 3 }, {10,20,30}}; int Matrix[3][4]= {{0,30 },{100,0,10}, {0,0,0,-20}}; د. وائل القصاص

246 #include void main() { int A[2][3] = {{1,2,3},{10,20,30}}; int B[2][3] = {100,200,300,40,50,60}; int C[2][3] = {{15,25},{105,205}}; for( int i=0; i<2; i++){ for( int j=0; j<3; j++) cout< cout< cout< for( i=0; i<2; i++){ cout< cout< } د. وائل القصاص

247 #include const int Rows = 3, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } for (i=0; i for(int j=0; j cout< cout< } د. وائل القصاص

248 Find The sum of 2-D array using function#include int A_sum(int [ ][2],int); void main(){ int x[3][2]={6,5,4,3,2,1}; int y[4][2]={5,4,3,2,3,4,1}; cout<<"The sum of the array x is " < cout<<"The sum of the array y is " < } int A_sum(int a[ ][2],int r) { int s=0; for(int i=0;i for(int j=0;j<2;j++) s=s+a[i][j]; return s; Find The sum of 2-D array using function د. وائل القصاص

249 Diagonal Summation 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3 3,0 3,1 3,2 3,3 #include const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } int DSum = 0; for (i=0; i DSum += A[i][i]; cout<<"Diagonal Sum = "< } د. وائل القصاص

250 Repeat the prev example with function#include int Dsum(int [ ][4]); const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } cout<<"Diagonal Sum = "< } int Dsum(int a[ ][4]) {int S=0; for (int i=0; i<4; i++) S+= a[i][i]; return S; } د. وائل القصاص

251 Inverse Diagonal Summation#include const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } int DSum = 0; for (i=0; i for (int j=0; j if ( i+j= = 3) DSum += A[i][j]; cout<<“Inverse Diagonal Sum = "< } د. وائل القصاص

252 For(int i=0;i<4;i++) S=S+A[i][3-i];د. وائل القصاص

253 Inverse Diagonal Summation#include int Sum(int [ ][4]); const int Rows = 4, Columns = 4; void main( ) { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } int DSum = Sum(A); cout<<"Diagonal Sum = "< } int Sum(int X[ ][4]){ int S=0; for(int i=0;i<4;i++) S=S+X[i][3-i]; return S;} د. وائل القصاص

254 Lower Triangular Multiplication0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3 3,0 3,1 3,2 3,3 #include const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } long LTmul = 1; for (i=0; i for(int j=0; j LTmul *= A[i][j]; cout<<"Lower Traingular Mul = "< } د. وائل القصاص

255 Lower Triangular Multiplication#include const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } long LTmul = 1; for (i=0; i for(int j=0; j if (i>j) LTmul *= A[i][j]; cout<<"Lower Traingular Mul = "< } د. وائل القصاص

256 Write a Program that copies an array to another#include const int R = 4, C= 3; void main() { int A[R][C]; int B[R][C]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } for (i=0 ;i for(int j=0;j B[i][j]=A[i][j]; for (i=0; i for(int j=0; j cout< cout< } د. وائل القصاص

257 Write a function that copies a 2-D array to anothervoid copyA(int x[ ][3],int y[ ][3],int r) { for(int i=0;i for(int j=0;j<3;j++) y[i][j]=x[i][j]; } د. وائل القصاص

258 Write a Program that copies an array to another#include const int R = 4, C= 3; void main() { int A[R][C]; int B[R][C]; for (int i=0; i for (int j=0; j cout<<"\nEnter A["< cin>>A[i][j]; } copyA(A,B,4); for (i=0; i for(int j=0; j cout< cout< } د. وائل القصاص

259 Store the following symbols in the array Symbol.* $ $ $ # * $ $ # # * $ #include const int Rows = 4, Columns = 4; void main() { char Symbol[Rows][Columns]; for (int i=0; i for (int j=0; j if (i == j) Symbol[i][j] = '*'; else if (i > j) Symbol[i][j] = '#'; else Symbol[i][j] = '$'; for (i=0; i for(int j=0; j cout< cout< # # # * د. وائل القصاص

260 Matrix Summation #include const int Rows = 3, Columns = 4; void main() { int A[Rows][Columns], B[Rows][Columns], C[Rows][Columns]; cout<<"\nEnter Matrix A elements:\n"; for (int i=0; i for( int j=0; j cin>>A[i][j]; cout<<"\nEnter Matrix B elements:\n"; for (i=0; i cin>>B[i][j]; for(i=0; i for(int j=0; j< Columns; j++) C[i][j] = A[i][j] + B[i][j]; for(i=0; i for(int j=0; j cout< cout< } د. وائل القصاص

261 Write a function to add two Arraysvoid add(int x[ ][4],int y[ ][4],int z[ ][4],int r) { } د. وائل القصاص

262 Compute the average for 5 marks for 10 studentsint marks [10][5]; for(int i=0;i<10;i++) for(int j=0;j<5;j++) { cout<<"Enter mark"< cin>>marks[i][j];} float av[10]; for(i=0;i<10;i++) { float sum=0; sum=sum+marks[i][j]; av[i]=sum/5;} printing…… د. وائل القصاص

263 Transpose int A[3][4], B[4][3]; for(int i=0;i<3;i++)for(int j=0;j<4;j++) cin>>A[i][j]; for(i=0;i<3;i++) B[ j][i]=A[i][j] Printing B …….. د. وائل القصاص

264 Function to calculate the Transpose of an array 3x4void trans34(int x[3][4],int y[4][3]) { for(int r=0;r<3;r++) for(int c=0;c<4;c++) y[c][r]=x[r][c]; } د. وائل القصاص

265 Homework 1- Write program to compute and print the result of Matrix A[n][n] multiplied by Matrix B[n][n] and store the result within Matrix C[n][n]. 2- Write program to Compute and print the result of Matrix A[n][n] multiplied by Vector V[n] and store the result within Vector C[n]. د. وائل القصاص

266 Second exam topics 1- do-while statement. 2- nested for loop3- nested while statement 4- math library functions. 5- functions prototype and definitions. 6- rand () and srand() functions 7- scope rules (local, global and static variables) 8- Recursion 9- call by value and reference 10- Inline function 11- :: scope resolution operator. 12- one dim array only ( definition and passing one dim array to a function). د. وائل القصاص

267 Strings #include void main() { char n[10];char a[10]={'A','h','m','e','d'}; for(int i=0; i<5 ; i++) cout< } د. وائل القصاص

268 #include void main() { char a[10]={'I','b','r','a','h','e','e','m‘}; for(int i=0; a[i]!=0 ; i++) cout< } د. وائل القصاص

269 #include void main() { char a[10]={'A','h','m','e','d'}; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j cout<<" "; cout< } د. وائل القصاص

270 #include void main() { char a[10]="Ahmed"; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j cout<<" "; cout< } د. وائل القصاص

271 #include void main() { char a[10]; cout<<"Enter a name : "; cin>>a; cout< for(int i=0; a[i]!=0 ; i++) {for(int j=0;j cout<<' '; cout< } د. وائل القصاص

272 #include void main() { char a[10]; char b[10]; cout<<"Enter ur first name : "; cin>>a; cout<<"Enter ur second name : "; cin>>b; cout<<"Hello "< for(int i=0; a[i]!=0 ; i++) {for(int j=0;j cout<<' '; cout< } د. وائل القصاص

273 #include void main() { char a[10]; cout<<"Enter a name : "; cin>>a; cout< for(int i=0; a[i]!=0 ; i++) {for(int j=0;j cout<<' '; } cout< د. وائل القصاص

274 Final exam question Write a function that returns the length of a string or array of characters. The function prototype is int length(char[ ]); د. وائل القصاص

275 int length(char name[ ]) {int i; for( i=0;name[i]!=0;i++) ; return i; } د. وائل القصاص name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout=0;j--) cout

276 Ex: Write a program that prints the name inversed( from the last char to the first character#include void main() { char name[10]; cout<<"Enter ur name : "; cin>>name; for(int i=0; name[i]!=‘\0’ ; i++); for(int j=i-1;j>=0;j--) cout< cout< } د. وائل القصاص

277 #include void main( ) {int A[10]={2,3,4,5}; char B[10]={'A','l','i‘}; cout< cout< } د. وائل القصاص

278 Chapter 5 - Pointers and StringsOutline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Calling Functions by Reference 5.7 Pointer Expressions and Pointer Arithmetic 5.8 The Relationship Between Pointers and Arrays 5.9 Arrays of Pointers 5.12 Introduction to Character and String Processing Fundamentals of Characters and Strings String Manipulation Functions of the String-handling Library د. وائل القصاص

279 5.1 Introduction Pointers Powerful, but difficult to masterSimulate call-by-reference Close relationship with arrays and strings د. وائل القصاص

280 5.2 Pointer Variable Declarations and InitializationPointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain the address of a variable that has a specific value (indirect reference) Indirection Referencing a pointer value Pointer declarations * indicates variable is a pointer int *myPtr; declares a pointer to an int, a pointer of type int * Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; count 7 count 7 countPtr د. وائل القصاص

281 5.2 Pointer Variable Declarations and InitializationCan declare pointers to any data type Pointers initialization Initialized to 0, NULL, or an address 0 or NULL points to nothing د. وائل القصاص

282 5.3 Pointer Operators & (address operator)Returns the address of its operand Example int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y yPtr "points to" y yPtr y 5 yptr 500000 600000 address of y is value of yptr د. وائل القصاص

283 5.3 Pointer Operators * (indirection/dereferencing operator)Returns the value of what its operand points to *yPtr returns y (because yPtr points to y). * can be used to assign a value to a location in memory *yptr = 7; // changes y to 7 Dereferenced pointer (operand of *) must be an lvalue (no constants) * and & are inverses Cancel each other out *&myVar == myVar and &*yPtr == yPtr د. وائل القصاص

284 ---------- 10 ---------- ---------- 12FF7C ----------Pointer Pointer is a memory location, which contains a memory address of another memory location, which belong to a variable. We say that the pointer points to the variable. FF7C 12FF7C 12FB8D a ptr #include void main() { int a = 10; int *ptr ; ptr= &a; cout< cout<<&a< cout<<*ptr< cout< } د. وائل القصاص

285 Pointers #include void main() { int a=5;int* b; // pointer to an integer b=&a; cout< cout< } د. وائل القصاص

286 2 // Using the & and * operators 3 #include 4 1 // Fig. 5.4: fig05_04.cpp 2 // Using the & and * operators 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int a; // a is an integer 11 int *aPtr; // aPtr is a pointer to an integer 12 13 a = 7; 14 aPtr = &a; // aPtr set to address of a 15 16 cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr; 18 19 cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr; 21 22 cout << "\n\nShowing that * and & are inverses of" << " each other.\n&*aPtr = " << &*aPtr << "\n*&aPtr = " << *&aPtr << endl; 25 return 0; 26 } د. وائل القصاص

287 Output The address of a is 006AFDF4 The value of aPtr is 006AFDF4The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 006AFDF4 *&aPtr = 006AFDF4 د. وائل القصاص

288 Example 1 #include void main( ) {int a = 10, b = 20; int *ptr_a, *ptr_b; ptr_a = &a; ptr_b = &b; cout<<"a="<<*ptr_a<<"b="<<*ptr_b< a += 10; b += 20; ++*ptr_a; ++*ptr_b; cout<<"a="< ptr_a = ptr_b; cout<<"b="<<*ptr_a< } د. وائل القصاص

289 Example 2 (String) #include void main() {----- A H m a d L i St_name #include void main() { char *St_name; St_name = "Ahmad Ali"; cout< } د. وائل القصاص

290 Example 3 (String) #include void main() {----- A H m a d L i St_name[0] St_name[1] St_name[2] St_name[3] St_name[4] St_name[5] St_name[6] St_name[7] St_name[8] #include void main() { char St_name[20]; cout<<"Please enter your name: "; cin.getline(St_name,20,'\n'); cout< } د. وائل القصاص

291 Example 4 (array name is a static pointer)----- F1 1.2 2.2 3.2 4.2 5.2 #include void main() { float Vector[5] = {3.2, 2.2, 6.2, 4.2, 9.2}; float *ptr; ptr = Vector; // ptr=&Vector[0]; cout<<"ptr:\t\t"< cout<<"Vector:\t\t"< cout<<"&Vector[0]:\t"<<&Vector[0]< for (int i=0; i<5; i++) { cout< ptr++; } } Vector ptr Vactor[0] Vactor[1] Vactor[2] Vactor[3] Vactor[4] B1 B2 F1 F2 F3 F4 F5 د. وائل القصاص

292 5.4 Calling Functions by ReferenceCall by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * operator used as alias/nickname for variable inside of function void doubleNum( int *number ) { *number = 2 * ( *number ); } *number used as nickname for the variable passed in When the function is called, must be passed an address doubleNum( &myNum ); د. وائل القصاص

293 2 // Cube a variable using call-by-reference 1 // Fig. 5.7: fig05_07.cpp 2 // Cube a variable using call-by-reference 3 // with a pointer argument 4 #include 5 6 using std::cout; 7 using std::endl; 8 9 void cubeByReference( int * ); // prototype 10 11 int main() 12 { 13 int number = 5; 14 15 cout << "The original value of number is " << number; 16 cubeByReference( &number ); 17 cout << "\nThe new value of number is " << number << endl; 18 return 0; 19 } 20 21 void cubeByReference( int *nPtr ) 22 { 23 *nPtr = *nPtr * *nPtr * *nPtr; // cube number in main 24 } د. وائل القصاص

294 The original value of number is 5 The new value of number is 125د. وائل القصاص