Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

Similar presentations


Presentation on theme: "COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)"— Presentation transcript:

1 COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

2 COMP103 - C++ Review2 Valid Variable Names Rules for variable names in C++ (page 33) The first character must be an alphabetic character or underscore Consists only of alpha-numeric and underscore characters Cannot duplicate a reserved word (see Appendix B) Valid Names a PI student_name _PI _assign1 Invalid Names $a for 2name a a int

3 COMP103 - C++ Review3 Important Special Characters Return \n Null Single Quote Double Quote Backslash As a Character In a String ‘\n’ ‘\0’ ‘\’’ ‘\”’ ‘\\’ “\n” “” “’” “\”” “\\”

4 COMP103 - C++ Review4 Constant declarations Constants are used to store values that never change during the program execution. Using constants makes programs more readable and maintainable. Syntax: const = ; Examples: const double US2HK = 7.8; //Exchange rate of US$ to HK$ const double HK2TW = 3.98; //Exchange rate of HK$ to TW$ const double US2TW = US2HK * HK2TW; //Exchange rate of US$ to TW$

5 COMP103 - C++ Review5 Variables are used to store values that can be changed during the program execution. A variable is best thought of as a container for a particular type of data/value. You must specify the variables type when you declare it Syntax: ; = ; Examples: int sum; int i = j = 0; int total = 3445; char answer = ' y ' ; double temperature = -3.14; Variable declarations

6 COMP103 - C++ Review6 Variables are not automatically initialized. For example, after declaration int sum; the value of the variable sum can be anything (garbage). Thus, it is good practice to initialize variables when they are declared. A variable has a type and it can contain only values of that type. For example, a variable of the type int can only hold integer values. Once a value has been placed in a variable it stays there until the program deliberately alters it. Variable declarations

7 COMP103 - C++ Review7 Character data A variable or a constant of char type can hold an ASCII character (see Appendix A of the textbook). When initializing a constant or a variable of char type, or when changing the value of a variable of char type, the value is enclosed in single quotation marks. Examples: const char star = '*'; char letter, one = '1';

8 COMP103 - C++ Review8 Decisions (Ch. 5)

9 COMP103 - C++ Review9 The Basic if Statement Syntax if(Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Expression Action truefalse

10 COMP103 - C++ Review10 Choice ( if ) Example: find the absolute value if (value < 0) value = -value; Can put multiple action statements within braces if { }

11 COMP103 - C++ Review11 Sorting Two Numbers int value1; int value2; int temp; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } cout << "The input in sorted order: " << value1 << " " << value2 << endl;

12 COMP103 - C++ Review12 Relational Operators Relational operators are used to compare two values MathC++Plain English === equals [example: if(a==b) ] BUT (a=b) means put the value of b into a << less than  <= less than or equal to >> greater than  >= greater than or equal to  != not equal to

13 COMP103 - C++ Review13 A Boolean Type C++ contains a type named bool which can have one of two values true (corresponds to non-zero value) false (corresponds to zero value) Boolean operators can be used to form more complex conditional expressions The AND operator is && The OR operator is || The NOT operator is ! Warning & and | are bitmap operators

14 COMP103 - C++ Review14 More Operator Precedence Precedence of operators (from highest to lowest) Parentheses ( … ) Unary operators ! Multiplicative operators * / % Additive operators + - Relational ordering = > Relational equality == != Logical and && Logical or || Assignment =

15 COMP103 - C++ Review15 Examples of bool Assignments to bool type variables bool P = true; bool Q = false; bool R = true; bool S = P && Q; // F bool T = !Q || R; // T bool U = !(R && !Q); // F

16 COMP103 - C++ Review16 Operator Precedence: Examples Examples 5 != 6 || 7 <= 3 is equivalent to (5 !=6) || (7 <= 3) 5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24 is TRUE

17 COMP103 - C++ Review17 The if-else Statement Syntax if (Expression) Action 1 else Action 2  If Expression is true then execute Action 1 otherwise execute Action 2 Expression Action 1 Action 2 true false

18 COMP103 - C++ Review18 The if-else Statement if { } else{ }

19 COMP103 - C++ Review19 Finding the Big One int value1; int value2; int larger; cout << "Enter two integers: "; cin >> value1 >> value2; if (value1 > value2) larger = value1; else larger = value2; cout << "Larger is: " << larger << endl;

20 COMP103 - C++ Review20 if-else-if Statements F F F F T T T T

21 COMP103 - C++ Review21 if-else-if Statements if { } else if { } else if { } else{ }

22 COMP103 - C++ Review22 if-else-if Statement if(score >= 90) cout << "Grade = A" << endl; else if(score >= 80) cout << "Grade = B" << endl; else if(score >= 70) cout << "Grade = C" << endl; else if(score >= 60) cout << "Grade = D" << endl; else cout << "Grade = F" << endl;

23 COMP103 - C++ Review23 switch Statement Equivalent to the previous if-else-if switch(score/10){ case 10: case 9: cout << "Grade = A" << endl; break; case 8: cout << "Grade = B" << endl; break; case 7: cout << "Grade = C" << endl; break; case 6: cout << "Grade = D" << endl; break; default:cout << "Grade = F" << endl; }

24 COMP103 - C++ Review24 Nested if Statements Nested means that one complete statement is inside another if { } } }

25 COMP103 - C++ Review25 “Dangling Else” Problem What is the value of c after the following is executed? int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else c = 3; C++ groups a dangling else with the most recent if (answer: c=1).

26 COMP103 - C++ Review26 Functions (Ch. 4)

27 COMP103 - C++ Review27 Advantages of Functions A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself. These parts are called functions in C++ Functions make programs easier to understand. Functions make programs easier to modify. Functions can be called several times in the same program, allowing the code to be reused.

28 COMP103 - C++ Review28 Function Input and Output Function Result Parameters

29 COMP103 - C++ Review29 Functions in a Program C++ programs usually have the following form: // include statements // function prototypes // main() function // user-defined functions

30 COMP103 - C++ Review30 Function Prototype The function prototype declares the interface, or input and output parameters of the function, leaving the implementation for the function definition. The function prototype has the following syntax: ( ); Example: A function that prints the card (J) given the card number (11) as input: void printcard(int num); (This is a void function - a function that does not return a value)

31 COMP103 - C++ Review31 Function Definition The function definition can be placed anywhere in the program after the function prototypes. You can place a function definition in front of main(). In this case there is no need to provide a function prototype for the function, since the function is already defined before its use. A function definition has following syntax: ( ){ }

32 COMP103 - C++ Review32 Function Call A function call has the following syntax: ( ) There is a one-to-one correspondence between the parameters in a function call and the parameters in the function definition.

33 COMP103 - C++ Review33 Printing Cards (void function) The main() program which calls printcard() #include using namespace std; void printcard(int);// function prototype int main(){ int c1, c2, c3, c4, c5; // pick cards... // print cards printcard(c1); printcard(c2); printcard(c3); printcard(c4); printcard(c5); // find score // print score }

34 COMP103 - C++ Review34 Printing Cards A function that prints the card (J) given the card number (11) as input: void printcard(int cardnum){ if(cardnum==1) cout << "A"; else if(cardnum>=2 && cardnum<=10) cout << cardnum; else if(cardnum==11) cout << "J"; else if(cardnum==12) cout << "Q"; else if(cardnum==13) cout << "K"; }

35 COMP103 - C++ Review35 Absolute Value (returns int) #include int absolute(int x);// function prototype int main(){ int x, y, diff; cout << "Enter two integers: "; cin >> x >> y; diff = absolute(x - y); cout << "The absolute diff is " << diff << endl; return 0; } // Define a function to take absolute value of an int int absolute(int x){ if (x >= 0) return x; else return -x; }

36 COMP103 - C++ Review36 Passing Parameters by Value A function returns a single result (assuming the function is not a void function) One of the statements in the function body should have the form: return ; The value passed back by return should have the same type as the function.

37 COMP103 - C++ Review37 Pass by Value Changes to the parameters inside the function body have no effect outside of the function. Different location in memory

38 COMP103 - C++ Review38 Pass by Value: Example 1 For example, consider the following code: int sum(int a, int b){ a = a + b; return a; } void main(){ int x, y, z; x = 3; y = 5; z = sum(x,y); } What is the value of x, y, and z at the end of the main() program?

39 COMP103 - C++ Review39 Pass by Value: Example 1 The answer: 3, 5, and 8. (x,y,z) Even though the value of parameter a is changed, the corresponding value in variable x does not change. This is why this is called pass by value. The value of the original variable is copied to the parameter, but changes to the value of the parameter do not affect the original variable. In fact, all information in local variables declared within the function will be lost when the function terminates. The only information saved from a pass by value function is in the return statement.

40 COMP103 - C++ Review40 Pass by Value: Example 2 void Increment(int Number) { Number = Number + 1; cout << "Number =" << Number << endl; } void main() { int I = 10; cout << "I is: " << I << endl; Increment(I); cout << "I is: " << I << endl; }

41 COMP103 - C++ Review41 Passing Parameters by Reference To have a function with multiple outputs, we have to use pass by reference. Reference (address) of parameter is passed to the function, instead of its value. If the function changes the parameter value, the changes will be reflected in the program calling it. How to pass parameters by reference: &,..., &

42 COMP103 - C++ Review42 Pass by Reference: Example The correct implementation of the Increment function #include using namespace std; void Increment(int& Number){ Number = Number + 1; cout << "Number: " << Number << endl;// 11 } void main(){ int I = 10; Increment(I); cout << "I is: " << I << endl;// 11 } Pass-by-Reference-1.cpp

43 COMP103 - C++ Review43 Example: Exchange two numbers If we use pass by value, it will not work!!! a and num1 are in the same location in memory Also b and num2

44 COMP103 - C++ Review44 Pass by value and by reference

45 COMP103 - C++ Review45 Loops (Ch. 6)

46 COMP103 - C++ Review46 Iterative Constructs Provide Ability to control how many times a statement list is executed Three constructs while statement for statement do-while statement

47 COMP103 - C++ Review47 The while Statement Syntax while (Expression) Action How it works: If Expression is true then execute Action Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Expression Action truefalse

48 COMP103 - C++ Review48 Example: N! ( while ) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; while(n <= number){ factorial *= n; n++; } cout << "The factorial of " << number << " is " << factorial << endl;

49 COMP103 - C++ Review49 The for Statement Syntax for (ForInit; ForExpression; PostExpression) Action How it works: Execute “ForInit” statement As long as “ForExpression” is true Execute Action Execute PostExpression ForExpression Action truefalse ForInit PostExpression

50 COMP103 - C++ Review50 Example: N! ( for ) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; for (n=1; n<=number; n++) factorial *= n; cout << "The factorial of " << number << " is " << factorial << endl;

51 COMP103 - C++ Review51 The Do-While Statement Syntax do Action while (Expression) How it works: Execute Action if “Expression” is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action true false Expression

52 COMP103 - C++ Review52 Example: N! (do-while) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; do{ factorial *= n; n++; }while(n <= number); cout << "The factorial of " << number << " is " << factorial << endl;

53 COMP103 - C++ Review53 Which Loop to Use? For loop Usually best for sums, products, and counting loops. While loop You want to repeat an action without knowing exactly how many times it will be repeated. There are situations when the action should not be executed. Do-while loop The action should always be executed at least once. Otherwise, the do-while loops and while loops are used in similar situations.

54 COMP103 - C++ Review54 How to Stop a Loop Known number of iterations before the loop stops (for) Test for a user-controlled condition before or after each iteration (while, do-while) Use the break command.

55 COMP103 - C++ Review55 Stop a loop: break The break command is the same as the one used previously in switch. break leaves the current loop immediately. It is recommended that break be used for situations where the loop needs to be terminated immediately (e.g., due to user intervention or if a fatal error occurs). Use with care !!

56 COMP103 - C++ Review56 Example: Maximum ( while with break ) int value;//input value int max=0;//maximum value while(true){ cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; if(value==-1) break; } cout << "The maximum value found is " << " is " << max << endl;

57 COMP103 - C++ Review57 Common Loop Errors while(balance != 0.0); { balance = balance - amount; } This will lead to an infinite loop! for(n=1; n<=count; n++); { cout << "hello" << endl; } "hello" only printed once! while(balance != 0.0){ balance = balance - amount; } balance may not become equal zero due to numerical inaccuracies

58 COMP103 - C++ Review58 Nested Loops // Program to output the // multiplication table int i; //Outer loop counter int j;//Inner loop counter for(i=1; i<=10; i++){ for(j=1; j<=10; j++) cout << i*j << " "; cout << endl; } Output 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 …  Nested loops are loops within loops.

59 COMP103 - C++ Review59 Recursion (Ch.6, Section 6-9)

60 COMP103 - C++ Review60 Recursion Recursion is one way to decompose a task into smaller subtasks. The smallest example of the same task has a non- recursive solution. Example: The factorial function n! = n * (n-1) * (n-2) *... * 1 or n! = n * (n-1)! and 1! = 1 A recursive solution may be simpler to write (once you get used to the idea) than a non-recursive solution. But a recursive solution may not be as efficient as a non- recursive solution of the same problem.

61 COMP103 - C++ Review61 Recursion General Form How to write recursively? int rec(parameters){ if(stopping condition) return stopping value; value = rec(revised parameters); return value; }

62 COMP103 - C++ Review62 Example: N! Recursion int fac(int n){ int product; if(n <= 1) return 1; product = n * fac(n-1); return product; } void main(){ int number = 3; cout << fac(number) << endl; }

63 COMP103 - C++ Review63 Execution trace fac(3) : 3 <= 1 ? No. product 3 = 3 * fac(2) fac(2) : 2 <= 1 ? No. product 2 = 2 * fac(1) fac(1) : 1 <= 1 ? Yes. return 1 product 2 = 2 * 1 = 2 return product 2 product 3 = 3 * 2 = 6 return product 3 fac(3) has the value 6

64 COMP103 - C++ Review64 Arrays Programming

65 COMP103 - C++ Review65 Arrays An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles).

66 COMP103 - C++ Review66 Arrays 1-dimensional array. 3-dimensional array (3rd dimension is the day). Oct 15 Oct 16 Oct 14

67 COMP103 - C++ Review67 Array Declaration – 1 Dimension Syntax: [ ]

68 COMP103 - C++ Review68 Subscripting – 1 Dimension // array of 10 uninitialized ints int A[10]; A[3] = 1; int x = A[3]; -- 1 A 4 5 6 3 0 2 8 9 7 1 A[4]A[5]A[6]A[3]A[0]A[2]A[8]A[9]A[7]A[1] 1 --

69 COMP103 - C++ Review69 Array Initialization – 1 Dimension

70 COMP103 - C++ Review70 Example Definitions – 1 Dimension Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all legal array definitions. int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 doubles int Values[MaxListSize];// array of 1000 ints

71 COMP103 - C++ Review71 const int N=10; int A[N]; int SmallestValueSoFar, i;... // A[] is input by user SmallestValueSoFar = A[0]; for (i=1; i<N; i++) if (A[i] < SmallestValueSoFar) SmallestValueSoFar = A[i]; Example: Smallest Value (1-dimension)

72 COMP103 - C++ Review72 2-D Array Example int table[5][4];

73 COMP103 - C++ Review73 Passing Arrays to Functions (Ch.8, p.388-397) Programming

74 COMP103 - C++ Review74 Passing Array Elements Individual elements can be passed to a function like ordinary values.

75 COMP103 - C++ Review75 Passing Arrays as Parameters Arrays can be passed to functions in their entirety.  All that is required is the address of the first element and dimensions of the array.  The remainder of the array will be passed by reference automatically.  Using “[ ]” in the formal parameter specification indicates that the variable is an array.

76 COMP103 - C++ Review76 Example: Multiple an array by 2

77 COMP103 - C++ Review77 The const type modifier  If the function must not change any element of the array then const should be used in the formal parameter specification of that array.

78 COMP103 - C++ Review78 Passing Multidimensional Arrays How to pass a multidimensional array to a function: void displayBoard(int b[][4]); // function prototype requires variable name for arrays void main(){ int board [4][4];... displayBoard(board);... } void displayBoard(int b[][4]){ // could also be:void displayBoard(int b[4][4]){ // but NOT:void displayBoard(int b[][]){... } When passing a multidimensional array, only the size of the 1st dimension is optional, the 2nd, 3rd, etc. dimensions must be specified.

79 COMP103 - C++ Review79 Programming Structures (Ch.11, p.567)

80 COMP103 - C++ Review80 Structures A structure is a collection of related data items, possibly of different types. In C++, structure is a user defined type, called struct. A struct is heterogeneous (of different types of data) whereas an array is homogeneous (of same type of data) Examples: Student record student id, name, major, gender, start year, … Bank account: account number, name, currency, balance, … Address book: name, address, telephone number, … In database applications, structures are called records.

81 COMP103 - C++ Review81 struct basics Definition of a structure: struct { ;... } ; Example: struct Date { int day; int month; int year; } ; The “Date” structure has 3 members, day, month & year. Each identifier defines a member of the structure.

82 COMP103 - C++ Review82 struct examples Example: struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; Example: struct StudentRecord{ char Name[15]; int Id; char Dept[5]; char Gender; }; The “StudentRecord” structure has 4 members. The “BankAcount” structure has simple, array and structure types as members.

83 COMP103 - C++ Review83 struct basics Declaration of a variable of struct type: ; Example: StudentRecord Student1, Student2; Student1 and Student2 are variables of StudentRecord type. Student1Student2 Name IdGender Dept Name IdGender Dept

84 COMP103 - C++ Review84 Chan Tai Man 12345 M COMP Example 1: struct basics The members of a struct type variable are accessed with the dot (.) operator:. ; Example: strcpy(Student1.Name, "Chan Tai Man"); Student1.Id = 12345; strcpy(Student1.Dept, "COMP"); Student1.gender = 'M'; cout << "The student is "; switch (Student1.gender){ case 'F': cout << "Ms. "; break; case 'M': cout << "Mr. "; break; } cout << Student1.Name << endl; Student1 Name IdGender Dept

85 COMP103 - C++ Review85 Chan Tai Man 12345 M COMP Example 2: struct-to-struct assignment The value of one struct type variable can be assigned to another variable of the same struct type. Example: strcpy(Student1.Name, "Chan Tai Man"); Student1.Id = 12345; strcpy(Student1.Dept, "COMP"); Student1.gender = 'M'; Student2 = Student1; Student1 Chan Tai Man 12345 M COMP Student2

86 COMP103 - C++ Review86 Example 3: Nested structures We can nest structures inside structures. Examples: struct point{ double x, y; }; point P; struct line{ point p1, p2; }; line L; struct triangle{ point p1, p2, p3; }; triangle T; (P.x, P.y) (L.p1.x, L.p1.y) (L.p2.x, L.p2.y) (T.p2.x, T.p2.y) (T.p1.x, T.p1.y) (T.p3.x, T.p3.y)

87 COMP103 - C++ Review87 Example 4: Nested structures We can nest structures inside structures. struct line{ point p1, p2; }; line L; (L.p1.x, L.p1.y) (L.p2.x, L.p2.y) line p1 p2 x y

88 COMP103 - C++ Review88 Arrays of structures An ordinary array: One type of data An array of structs: Multiple types of data in each array element. 0 1 2 … 98 99

89 COMP103 - C++ Review89 Arrays of structures Example: StudentRecord Class[100]; strcpy(Class[98].Name, "Chan Tai Man"); Class[98].Id = 12345; strcpy(Class[98].Dept, "COMP"); Class[98].gender = 'M'; Class[0] = Class[98];... 0 1 2 … 98 99 Chan Tai Man 12345 M COMP

90 COMP103 - C++ Review90 Arrays inside structures We can use arrays inside structures. Example: struct square{ point vertex[4]; }; square Sq; Assign values to Sq using the given square (4, 3)(10, 3) (4, 1)(10, 1) x y


Download ppt "COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)"

Similar presentations


Ads by Google