Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables and Special Chars (Ch. 2, 3)

Similar presentations


Presentation on theme: "Variables and Special Chars (Ch. 2, 3)"— Presentation transcript:

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

2 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 COMP103 - C++ Review

3 Important Special Characters
As a Character In a String Return \n Null Single Quote Double Quote Backslash ‘\n’ ‘\0’ ‘\’’ ‘\”’ ‘\\’ “\n” “” “’” “\”” “\\” Backslash (\) indicates special character follows. COMP103 - C++ Review

4 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 <type> <identifier> = <expression>; 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$ COMP103 - C++ Review

5 Variable declarations
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: < type > < identifier >; < type > < identifier > = < expression >; Examples: int sum; int i = j = 0; int total = 3445; char answer = 'y'; double temperature = -3.14; COMP103 - C++ Review

6 Variable declarations
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. Demonstrate the last point by example: IF-1.cpp in subdir Examples-on-Decision-Ch5 COMP103 - C++ Review

7 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'; COMP103 - C++ Review

8 Programming Decisions (Ch. 5) COMP103 - C++ Review

9 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 true false COMP103 - C++ Review

10 Choice (if) Example: find the absolute value
if (value < 0) value = -value; Can put multiple action statements within braces if <it's raining> { <take umbrella> <wear raincoat> } COMP103 - C++ Review

11 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; Example: If-1.cpp COMP103 - C++ Review

12 Relational Operators Relational operators are used to compare two values Math C++ 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 Example: If-Else-Tricky.cpp Correct syntax of “equal” is “==“ COMP103 - C++ Review

13 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 COMP103 - C++ Review

14 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 = COMP103 - C++ Review

15 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 COMP103 - C++ Review

16 Operator Precedence: Examples
5 != 6 || 7 <= 3 is equivalent to (5 !=6) || (7 <= 3) 5 * == 13 && 12 < 19 || !false == 5 < 24 is TRUE Example: Boolean.cpp COMP103 - C++ Review

17 The if-else Statement Syntax if (Expression) Action1 else Action2
 If Expression is true then execute Action1 otherwise execute Action2 Expression Action1 Action2 true false COMP103 - C++ Review

18 The if-else Statement if <it's sunny>{
<go to beach with sun block> } else{ <take umbrella> COMP103 - C++ Review

19 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; Example: If-Else-1.cpp and If-Else-2.cpp (boolean, Char, etc.) COMP103 - C++ Review

20 if-else-if Statements
Example: If-Else-If-1.cpp COMP103 - C++ Review

21 if-else-if Statements
if <Mon, Wed>{ <goto COMP 103> } else if <Tue>{ <goto Lab> else if <12noon or 7PM>{ <eat> else{ <sleep> COMP103 - C++ Review

22 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; COMP103 - C++ Review

23 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; case 7: cout << "Grade = C" << endl; case 6: cout << "Grade = D" << endl; default: cout << "Grade = F" << endl; } Example: Switch.cpp COMP103 - C++ Review

24 Nested if Statements Nested means that one complete statement is inside another if <it's Monday>{ if <it's 1:00pm>{ if <it's raining>{ <bring umbrella> } <go to COMP 103> <call your friends> COMP103 - C++ Review

25 “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). Example: Dangling-Else.cpp COMP103 - C++ Review

26 Programming Functions (Ch. 4) COMP103 - C++ Review

27 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. COMP103 - C++ Review

28 Function Input and Output
Result Parameters Example: Basic-Function.cpp COMP103 - C++ Review

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

30 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: <type> <function name>(<type list>); 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) COMP103 - C++ Review

31 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: <type> <function name>(<parameter list>){ <local declarations> <sequence of statements> } COMP103 - C++ Review

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

33 Printing Cards (void function)
The main() program which calls printcard() #include <iostream> 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 } COMP103 - C++ Review

34 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"; } COMP103 - C++ Review

35 Absolute Value (returns int)
#include <iostream> 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; Example: Basic-Function.cpp COMP103 - C++ Review

36 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 <expression>; The value passed back by return should have the same type as the function. Example: Basic-Function.cpp COMP103 - C++ Review

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

38 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? Example: Pass-by-Value-1.cpp COMP103 - C++ Review

39 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. COMP103 - C++ Review

40 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); Output: 11; 10; 10 Example: Pass-by-Value-2.cpp COMP103 - C++ Review

41 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: <type>& <variable>, ... , <type>& <variable> COMP103 - C++ Review

42 Pass by Reference: Example
The correct implementation of the Increment function #include <iostream> 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 Output : 11; 11 COMP103 - C++ Review

43 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 COMP103 - C++ Review

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

45 Programming Loops (Ch. 6) COMP103 - C++ Review

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

47 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 true false Example: Factorial-while.cpp COMP103 - C++ Review

48 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; COMP103 - C++ Review

49 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 true false ForInit PostExpression COMP103 - C++ Review

50 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; Example: Factorial-For.cpp COMP103 - C++ Review

51 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 COMP103 - C++ Review

52 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; Example: Factorial-do-while.cpp COMP103 - C++ Review

53 Which Loop to Use? For loop While loop Do-while 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. COMP103 - C++ Review

54 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. COMP103 - C++ Review

55 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 !! COMP103 - C++ Review

56 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; MAX COMP103 - C++ Review

57 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 may not become equal zero due to numerical inaccuracies COMP103 - C++ Review

58 Nested Loops Nested loops are loops within 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; } Example: Nested-For.cpp Output COMP103 - C++ Review

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

60 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. Example: Factorial-Recursive.cpp COMP103 - C++ Review

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

62 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; COMP103 - C++ Review

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

64 Programming Arrays COMP103 - C++ Review

65 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). COMP103 - C++ Review

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

67 Array Declaration – 1 Dimension
Syntax: <type> <arrayName>[<dimension>] COMP103 - C++ Review

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

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

70 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 COMP103 - C++ Review

71 Example: Smallest Value (1-dimension)
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]; Smallest Example: 1D-MaxNum.cpp COMP103 - C++ Review

72 2-D Array Example int table[5][4]; COMP103 - C++ Review
Example: Mat-Add.cpp COMP103 - C++ Review

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

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

75 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. COMP103 - C++ Review

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

77 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. COMP103 - C++ Review

78 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. COMP103 - C++ Review

79 Programming Structures (Ch.11, p.567) COMP103 - C++ Review
Structtures: Chapter 11-8, pages COMP103 - C++ Review

80 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. COMP103 - C++ Review

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

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

83 struct basics Declaration of a variable of struct type: Example:
<struct-type> <identifier_list>; Example: StudentRecord Student1, Student2; Student1 and Student2 are variables of StudentRecord type. Name Id Gender Dept Name Id Gender Dept Student1 Student2 COMP103 - C++ Review

84 Example 1: struct basics
The members of a struct type variable are accessed with the dot (.) operator: <struct-variable>.<member_name>; 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 Id Gender Dept Chan Tai Man M COMP COMP103 - C++ Review

85 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 M COMP Chan Tai Man M COMP Student2 COMP103 - C++ Review

86 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.p2.x, L.p2.y) (L.p1.x, L.p1.y) (T.p2.x, T.p2.y) (T.p3.x, T.p3.y) (T.p1.x, T.p1.y) COMP103 - C++ Review

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

88 Arrays of structures An ordinary array: One type of data
An array of structs: Multiple types of data in each array element. COMP103 - C++ Review

89 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]; Chan Tai Man M COMP . . . COMP103 - C++ Review

90 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 x y x y x y COMP103 - C++ Review


Download ppt "Variables and Special Chars (Ch. 2, 3)"

Similar presentations


Ads by Google