COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo
Lecture Review Software Development Process Requirement analysis Specifications Design and architecture Coding Testing Documentation Maintenance
Lecture Review Arithmetic Operators + - * / Note: Precision problem int/int => int Truncates instead of round-off E.g. 3 / 2 => 1 % (modulus/remainder) E.g. 10 % 3 => 1 int/double =>double double/int => double double/double => double
Lecture Review Operator Precedence Evaluation order of operators ( ) *, / +, - Left associativity Evaluate from left to right if same precedence E.g. (1 + 2) * 3 – 4 / => * 3 => / 5 => – 0 => 9
Lecture Review Assignment Statement Syntax = ; E.g. int a_var; a_var = (1 + 2) * 3 – 4 / 5;
Lecture Review Data Type Conversions Implicit E.g. float z = 2.7; int y = 3; y = z;// y will be set to 2 Explicit Syntax var_1 = type (var_2); var = type (expression); E.g. int x = 1, y = 2; double z; z = x/y; // z will be set to 0.0 z = double (x)/double (y); // z will be set to 0.5 Now: 1.0 / 2.0 => / 2 => 0
Lecture Review Standard I/O Include the “ iostream.h ” Input cin >> … Output cout << … Special output characters \a \t \n \\ \’ \”
Leeture Review Format Manipulation Header Files #include using namespace std;
Lecture Review Defining width Syntax cout ); E.g. cout <<setw(2) <<1.20 <<endl; cout <<setw(7) << <<endl; Cout <<setw(7) <<1.20 <<endl; Output:
Lecture Review Defining sig. fig. Syntax cout ); E.g. cout <<setprecision(2) << <<endl; cout <<setprecision(4) <<101.0/4.0 <<endl; Cout <<setprecision(4) <<1001.0/4.0 <<endl; Output: 1.2e
More on prescision How to define fixed decimal place? Syntax cout.setf(ios::fixed); cout ); E.g. cout.setf(ios::fixed); cout <<setprecision(2) << <<endl; cout <<setprecision(4) <<101.0/4.0 <<endl; Cout <<setprecision(4) <<1001.0/4.0 <<endl; Output:
Summary By the end of this lab, you should be able to: Use arithmetic operators Evaluate expression with standard operator precedence order Write assignment Identify rules of division Apply assignment conversions Employ standard I/O functions cin / cout
Lab2 Random a integer in a given range Syntax E.g. Random [11-20) int rand_no; rand_no = rand()%(20-11)+11; #include int main() { srand(time(0)); int rand_no; rand_no = rand()%( - ) + ; }
Lab2 How about random no. with decimal place? E.g. Random [11.0 – 20.0) int rand_no; double result; rand_no = rand()%( )+110; result = rand_no * 0.1 E.g. Random [11.00 – 20.00) int rand_no; double result; rand_no = rand()%( )+1100; result = rand_no * 0.01