Example Lab 3.1
[1] Question :
(Checking whether a number is odd)
Write a program that reads an integer and checks whether it is odd.
[2] Example Code :
------------------------------------------------------------------------------------------------------------------------
// Step 1 : Prompt the input
Scanner input = new Scanner(System.in);
// Step 2 : Enter an integer
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Step 3 : Selection statement + Display Result
if (___________________ )
System.out.println("_____________________________");
else
System.out.println("_____________________________");
-------------------------------------------------------------------------------------------------------------------------
[3] Answer :
--------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
public class Lab3_1 {
public static void main(String[] args) {
// Step 1 : Prompt the input
Scanner input = new Scanner(System.in);
// Step 2 : Enter an integer
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Step 3 : Selection statement + Display Result
if (number % 2 != 0 )
System.out.println("Is "+ number + " an odd number? True");
else
System.out.println("Is "+ number + " an odd number? False"); }
}
-------------------------------------------------------------------------------------------------------------------------
[4] Output :
Enter an integer: 17
Is 17 an odd number? True
Enter an integer: 500
Is 500 an odd number? false
DCT 1093 - Lab 3 - Selections (Lab 3.1)
Thursday, 10 January 2013
You can leave a response
zT-FKMPT
Jabatan Sains Komputer . Fakulti Komputer, Media, & Pengurusan Teknologi . TATIUC