CS1101: Programming Methodology Aaron Tan

advertisement
CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101x/
Aaron Tan
This is Week 3
 Last week:
 Java Basics
 Variables, assignment statements, arithmetic
operators, input and output, etc.
 Object-oriented programming? Not yet!
 This week:
 Selection constructs
 First part of Chapter 4 Control Statements
 ‘if’, ‘switch’, logical operators
2
It Pays to Explore!
 IVLE forum
 I don’t like such questions 
 Can you tell me the output of this program?
 What is wrong with my program?
 My friend told me this is the way to do it. Is he
correct?
 I love such questions 
 I’ve tried this program. The result is different from

my expectation, which is … I was surprised! But
why it doesn’t give me my expected result?
I surfed the Internet and found this. I tried but I don’t
understand. Can you explain it?
3
Quiz Time…
 10 MCQs
4
Exercise #1
 Given this code to find the maximum
among 3 integer values in variables
num1, num2 and num3:
 // To find the maximum among 3 integer
// values in variables num1, num2, num3.
int max = 0;
if (num1 > num2 && num1 > num3)
max = num1;
if (num2 > num1 && num2 > num3)
max = num2;
if (num3 > num1 && num3 > num2)
max = num3;
 Spot the errors
5
Exercise #1
 Another version:
 // To find the maximum among 3 integer
// values in variables num1, num2, num3.
int max = 0;
if (num1 > max)
max = num1;
else if (num2 > max)
max = num2;
else if (num3 > max)
max = num3;
 Spot the errors
6
Exercise #2
 Download the file IfAndSwitch.java from
the Lectures page in the course website:
 http://www.comp.nus.edu.sg/~cs1101x/2_res
ources/lectures.html
 Correct the errors in the code
 Change the ‘if’ statements into a ‘switch’
statement.
7
Exercise #3 (Prep for Exercise #4)
 Given a 7-digit integer, extract the
individual digits from the integer.
 Sample run is shown below
Enter a 7-digit number: 8504215
Digits are: 8,5,0,4,2,1,5
 You should use int variables for the 7 digits
(digit1, digit2, …)
 Do not use ‘if’ statement.
8
Exercise #4
 Algorithm for NRIC check code
 NRIC consists of 7 digits.
 Eg: 8730215
 Step 1: Multiply the digits with corresponding
weights 2,7,6,5,4,3,2 and add them up.
 Eg: 82 + 77 + 36 + 05 + 24 + 13 + 52 =
16+49+18+0+8+3+10 = 104
 Step 2: Divide step 1 result by 11 to obtain
the remainder.
 Eg: 104 % 11 = 5
9
Exercise #4
 Algorithm for NRIC check code (cont…)
 Step 3: Subtract step 2 result from 11

 Eg: 11 – 5 = 6
Step 4: Match step 3 result in this table for the check
code
1 2 3 4 5 6 7 8 9 10 11
A

B
C
D
E
F
G
H
I
Z
J
 Eg: The check code corresponding to 6 is ‘F’.
Therefore, the check code for 8730215 is ‘F’.
10
This is Week 3
 Next week?
 Repetition statements
 ‘while’, ‘do while’, ‘for’
11
Reminder
 Trial Lab
 Deadline: 27 August (Wednesday), 2359hr.
12
End of file
13
Download