KaiquanMah commited on
Commit
ae81448
·
verified ·
1 Parent(s): a55dc25

int remainder = num % 2;

Browse files
Week 1: Types, condition clauses and loops/8b. Even or odd? ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Also in Java, the operator % can be used to return the remainder of a division calculation.
3
+
4
+ For example, the operator works like this:
5
+ int remainder = 5 % 2;
6
+ // prints 1, because 5 / 2 == 2, remains 1.
7
+ System.out.println(remainder);
8
+
9
+ The same operator can be used to conveniently test whether a number is even:
10
+ if the remainder of the division by two is one, the number is odd.
11
+
12
+
13
+
14
+ Write a program that asks the user for an integer and then prints the information whether the number is odd or even, as shown in the example output below. Thus, below is shown the execution of the program in duplicate:
15
+
16
+
17
+ Example output 1:
18
+ Give a number: 8
19
+ Number 8 is even
20
+
21
+
22
+ Example output 2:
23
+ Give a number: 3
24
+ Number 3 is odd
25
+
26
+ """
27
+
28
+
29
+
30
+ import java.util.Random;
31
+ import java.util.Scanner;
32
+
33
+
34
+
35
+ public class Test{
36
+ public static void main(String[] args){
37
+ final Random r = new Random();
38
+
39
+ Scanner reader = new Scanner(System.in);
40
+ System.out.print("Give a number: ");
41
+ int num = Integer.valueOf(reader.nextLine());
42
+
43
+ int remainder = num % 2;
44
+ if (remainder == 1) {
45
+ System.out.println("Number "+num+" is odd");
46
+ }
47
+ else {
48
+ System.out.println("Number "+num+" is even");
49
+ }
50
+
51
+
52
+ }
53
+ }
54
+
55
+
56
+
57
+ '''Testing with input 8
58
+ Give a number: 8
59
+ Number 8 is even
60
+
61
+ Testing with input 3
62
+ Give a number: 3
63
+ Number 3 is odd
64
+
65
+ Testing with input 11
66
+ Give a number: 11
67
+ Number 11 is odd
68
+
69
+ Testing with input 6
70
+ Give a number: 6
71
+ Number 6 is even
72
+
73
+ Testing with input 927
74
+ Give a number: 927
75
+ Number 927 is odd
76
+
77
+
78
+
79
+ '''