Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
68 views

Lab 2 - Basic Program in Java

This document provides an overview of concepts for Lab 2 on basic Java programming, including conditional statements, loops, and methods. It includes examples of if-then and if-then-else statements to assign grades based on test scores. It also covers the general form of the for loop statement and provides an example program to print numbers 1 through 10. The objective is to get a basic understanding of implementing these constructs in Java through practice tasks and evaluation tasks.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Lab 2 - Basic Program in Java

This document provides an overview of concepts for Lab 2 on basic Java programming, including conditional statements, loops, and methods. It includes examples of if-then and if-then-else statements to assign grades based on test scores. It also covers the general form of the for loop statement and provides an example program to print numbers 1 through 10. The objective is to get a basic understanding of implementing these constructs in Java through practice tasks and evaluation tasks.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Lab Manual for Advance Computer Programming

Lab-02
Basic Program in Java
Lab 2: Basic Program in Java

Table of Contents
1. Introduction 13

2. Activity Time boxing 13

3. Objective of the experiment 13

4. Concept Map 13
4.1. The if-then and if-then-else Statements 13
4.1.1. The if-then Statement 13
4.1.2. The if-then-else Statement 14
4.2. The for Statement 15
4.3. Methods in Java 16

1. Homework before Lab 17


2. Problem Solution Modeling 17

3. Procedure& Tools 17
4. Tools 17
5. Setting-up JDK 1.7 [Expected time = 5mins] 17
5.1.1 Compile a Program 17
5.1.2 Run a Program 17
6. Walkthrough Task[Expected time = 30mins] 18

7. Practice Tasks 18
Practice Task 1 [Expected time = 15mins] 19
Practice Task 2 [Expected time = 15mins] 19
Practice Task 3 [Expected time = 15mins] 19
Practice Task 4 [Expected time = 15mins] 19
8. Out comes 19
9. Testing 19

10. Evaluation Task (Unseen) [Expected time = 55 mins for two tasks] 20

11. Evaluation criteria 20

12. Further Reading 20


13. Books 20
14. Slides 20

Department of Computer Page 12


Science,
C.U.S.T.
Lab 2: Basic Program in Java

Lab2: Basic Programs in Java

1. Introduction
You have looked at the basic characteristics of Java and the benefits of using Java over C++. The
objective of this lab is to get basic understanding of java programs using conditional statements,
loops and functions.

Relevant Lecture Material

a) Revise Lecture No. 3 and 4


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 474-494
2. Revise the object-oriented concepts of inheritance, abstract classes and
polymorphism.

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-up Path for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 10 to 15mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins

3. Objective of the experiment

 To get basic understanding of conditional statements, loops, and functions in java and
how they are implemented using Java.

4. Concept Map
This section provides you the overview of the concepts that will be discussed and implemented
in this lab.

4.1. The if-then and if-then-else Statements

4.1.1. The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test evaluates to true. For example, the
Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already
in motion. One possible implementation of the applyBrakes method could be as follows:

void applyBrakes() {
Department of Computer Page 13
Science,
C.U.S.T.
Lab 2: Basic Program in Java

// the "if" clause: bicycle must be moving


if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end
of the if-then statement. In addition, the opening and closing braces are optional, provided that
the "then" clause contains only one statement:

void applyBrakes() {
// same as above, but without braces
if (isMoving)
currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code
more brittle. If a second statement is later added to the "then" clause, a common mistake would
be forgetting to add the newly required braces. The compiler cannot catch this sort of error;
you'll just get the wrong results.

4.1.2. The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates
to false. You could use an if-then-else statement in the applyBrakes method to take some action
if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply
print an error message stating that the bicycle has already stopped.

void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for
a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
public static void main(String[] args) {

int testscore = 76;

Department of Computer Page 14


Science,
C.U.S.T.
Lab 2: Basic Program in Java

char grade;

if (testscore >= 90) {


grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is:

Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.

4.2. The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often
refer to it as the "for loop" because of the way in which it repeatedly loops until a particular
condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination;


increment) {
statement(s)
}

When using this version of the for statement, keep in mind that:

 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

Department of Computer Page 15


Science,
C.U.S.T.
Lab 2: Basic Program in Java

The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:

class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}

The output of this program is:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

4.3. Methods in Java

A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us to
reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++ and Python. Methods are time savers and help us
to reuse the code without retyping the code.

Considering the following example to explain the syntax of a method −

public static int methodName(int a, int b) {


// body
}

Here,

 public static − modifier


 int − return type
 methodName − name of the method
 a, b − formal parameters

Department of Computer Page 16


Science,
C.U.S.T.
Lab 2: Basic Program in Java

 int a, int b − list of parameters

Method definition consists of a method header and a method body.

1. Homework before Lab

You must solve the following problems at home before the lab.

Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.

5.1.1 Problem description:


Write down codes to calculate the GPA of the student after getting the grades of all the courses
that the student has registered in the current semester.

2. Procedure& Tools
In this section you will study how to setup and configure JDK.

Tools

Java Development Kit (JDK) 1.7

Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

2.1.1 Compile a Program

Use the following command to compile the program.

javac Interface.java

After the execution of the above statement bytecode of your class will be generated with same
name as the .java file but its extension will change to .class.
Similarly, compile all classes implementing the interfaces.
Now you will need JVM to run the program.

2.1.2 Run a Program

After successfully completing the section 6.2.1, the only thing left is to execute the bytecode on
the JVM. Run the file containing main method in it. Use the following command to run the
program.
Department of Computer Page 17
Science,
C.U.S.T.
Lab 2: Basic Program in Java

java DriverClass

If the above command executed successfully then you will see output of the program.

Walkthrough Task[Expected time = 30mins]

This task is designed to guide you towards creating your own abstract class and interface and
running the program.

Write the following code in ExampleMinNumber.java file:


public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

Run the ExampleMinNumber.java using (javac ExampleMinNumber.java) command


Output:
Minimum value = 6

3. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\fs\assignments$\Advanced Computer Programming\Lab2

Practice Task 1 [Expected time = 15mins]

Write a program that asks the user to type 10 integers. The program must compute how many
even and odd numbers were entered.
Department of Computer Page 18
Science,
C.U.S.T.
Lab 2: Basic Program in Java

Practice Task 2 [Expected time = 15mins]

Write a program in java using repetition structures to print the following pattern. You are not
allowed to use nested loops.

****
***-
**--
*---

Practice Task 3 [Expected time = 15mins]

Write a java program that creates and integer array having 30 elements. Get input in this array
(in main function). After that, pass that array to a function called “Find_Max_Divisors” using
reference pointer. The function “Find_Max_Divisors” should find (and return) in the array that
number which has highest number of divisors. In the end, the main function displays that
number having highest number of divisors

Practice Task 4 [Expected time = 15mins]

Write a java functions bool isPalindrome(char arr[],int size) which take character array and
check whether array is palindrome or not. Palindrome is a word, phrase, or sequence that reads
the same backwards as forwards. Example madam, racecar etc

Out comes

After completing this lab, student will be able to implement the concepts of conditions, loops,
and functions in java.

Testing

This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs, then your program is right.

For Practice Tasks, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly
elaborated the concept of aggregation and composition in terms of ownership and life cycle.

Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1
T2
T3
Department of Computer Page 19
Science,
C.U.S.T.
Lab 2: Basic Program in Java

T4

4. Evaluation Task (Unseen) [Expected time = 55 mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

5. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 3: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

6. Further Reading

This section provides the references to further polish your skills.

Books

Text Book:
 Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
 Java Beginners Guide:
http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-
guide-1720064.pdf

Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\jinnah$\

Department of Computer Page 20


Science,
C.U.S.T.

You might also like