0% found this document useful (0 votes)
4 views

Pallavi Singh - 03 Java Programming Elements Level 2 Lab Practice

The document outlines best programming practices, emphasizing the use of variables, proper naming conventions, and indentation. It includes sample programs demonstrating these practices, such as displaying results, calculating distances, and performing various arithmetic operations. Additionally, it provides exercises for practice, covering topics like temperature conversion, income calculation, and simple interest.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Pallavi Singh - 03 Java Programming Elements Level 2 Lab Practice

The document outlines best programming practices, emphasizing the use of variables, proper naming conventions, and indentation. It includes sample programs demonstrating these practices, such as displaying results, calculating distances, and performing various arithmetic operations. Additionally, it provides exercises for practice, covering topics like temperature conversion, income calculation, and simple interest.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Best Programming Practice

1. All values as variables including Fixed, User Inputs, and Results


2. Avoid Hard Coding of variables wherever possible
3. Proper naming conventions for all variables
String name = "Eric";
double height = input.nextDouble();
double totalDistance = distanceFromToVia + distanceViaToFinalCity;
4. Proper Program Name and Class Name
5. Follow proper indentation

1. Sample Program 1 - Write a program to display Sam with Roll Number 1, Percent Marks
99.99, and the result ‘P’ indicates Pass(‘P’) or Fail (‘F’).
IMP => Follow Good Programming Practice demonstrated below in all Practice Programs
// Creating Class with name DisplayResult indicating the purpose is to display
// result. Notice the class name is a Noun.
class DisplayResult {
public static void main(String[] args) {

// Create a string variable name and assign value Sam


String name = "Sam";

// Create a int variable rollNumber and assign value 1


int rollNumber = 1;

// Create a double variable percentMarks and assign value 99.99


double percentMarks = 99.99;

// Create a char variable result and assign value 'P' for pass
char result = 'P';

// Display the result


System.out.println("Displaying Result:\n" +name+ " with Roll Number " +
rollNumber+ " has Scored " +percentMarks+
"% Marks and Result is " +result);
}
}

2. Sample Program 2 - Eric Travels from Chennai to Bangalore via Vellore. From Chennai to
Vellore distance is 156.6 km and the time taken is 4 Hours 4 Mins and from Vellore to
Bangalore is 211.8 km and will take 4 Hours 25 Mins. Compute the total distance and total
time from Chennai to Bangalore

1
// Create TravelComputation Class to compute the Distance and Travel Time
class TravelComputation {

public static void main(String[] args) {

// Create a variable name to indicate the person traveling


String name = "Eric";

// Create a variable fromCity, viaCity and toCity to indicate the city


// from city, via city and to city the person is travelling
String fromCity = "Chennai", viaCity = "Velore", toCity = "Bangalore";

// Create a variable distanceFromToVia to indicate the distance


// between the fromCity to viaCity
double distanceFromToVia = 156.6;

// Create a variable timeFromToVia to indicate the time taken to


// travel from fromCity to viaCity in minutes
int timeFromToVia = 4 * 60 + 4;

// Create a variable distanceViaToFinalCity to indicate the distance


// between the viaCity to toCity
double distanceViaToFinalCity = 211.8;

// Create a variable timeViaToFinalCity to indicate the time taken to


// travel from viaCity to toCity in minutes
int timeViaToFinalCity = 4 * 60 + 25;

// Create a variable totalDistance to indicate the total distance


// between the fromCity to toCity
double totalDistance = distanceFromToVia + distanceViaToFinalCity;

// Create a variable totalTime to indicate the total time taken to


// travel from fromCity to toCity in minutes
int totalTime = timeFromToVia + timeViaToFinalCity;

// Print the travel details


System.out.println("The Total Distance travelled by " + name + " from " +
fromCity + " to " + toCity + " via " + viaCity +
" is " + totalDistance + " km and " +
"the Total Time taken is " + totalTime + " minutes");
}
}

2

3
Level 2 Practice Programs
1. Write a program to take 2 numbers and print their quotient and reminder
Hint => Use division operator (/) for quotient and moduli operator (%) for reminder
I/P => number1, number2
O/P => The Quotient is ___ and Reminder is ___ of two number ___ and ___

import java.util.Scanner;
public class ComputeQuotientReminder{
public static void main(String[] args){
int dividend,divisor;
Scanner input=new Scanner(System.in);
System.out.println("Enter First Number");// taking first number from
user
dividend=input.nextInt();
System.out.println("Enter Second Number"); // Second number
divisor=input.nextInt();
int remainder=dividend % divisor;
int quotient=dividend/divisor;
System.out.print("The Quotient is "+quotient+" and Reminder is
"+remainder+" of two number " +dividend+" "+ divisor
);
}}

2. Write an IntOperation program by taking a, b, and c as input values and print the
following integer operations a + b *c, a * b + c, c + a / b, and a % b + c. Please also
understand the precedence of the operators.
Hint =>
a. Create variables a, b, c of int data type.
b. Take user input for a, b, and c.
c. Compute 3 integer operations and assign result to a variable
d. Finally print the result and try to understand operator precedence.
I/P => fee, discountPrecent
O/P => The results of Int Operations are —-, -—, and —-

4
import java.util.Scanner;
public class PrecedenceCheck{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
int a,b,c;
int operation_1=0,operation_2=0,operation_3=0,operation_4=0;
System.out.println("Enter Number 1");
a=input.nextInt();
System.out.println("Enter Number 2");
b=input.nextInt();
System.out.println("Enter Number 3");
c=input.nextInt();
operation_1= a + b *c;
operation_2= a * b + c;
operation_3= c + a / b;
operation_4= a % b + c;
// Following the precedence rule PEMDAS
System.out.print("The results of Int Operations are
"+operation_1+","+operation_2+","+operation_3+","+operation_4);
}}

3. Similarly, write the DoubleOpt program by taking double values and doing the same
operations.

import java.util.Scanner;
public class PrecedenceCheckForDouble{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
double a,b,c;
double operation_1=0,operation_2=0,operation_3=0,operation_4=0;
System.out.println("Enter Number 1");
a=input.nextDouble();
System.out.println("Enter Number 2");
b=input.nextDouble();
System.out.println("Enter Number 3");
c=input.nextDouble();
operation_1= a + b *c;
operation_2= a * b + c;
operation_3= c + a / b;

5
operation_4= a % b + c;
// Following the precedence rule PEMDAS for Double inputs
System.out.print("The results of Int Operations are
"+operation_1+","+operation_2+","+operation_3+","+operation_4);
}}

4. Write a TemperaturConversion program, given the temperature in Celsius as input outputs


the temperature in Fahrenheit
Hint =>
a. Create a celsius variable and take the temperature as user input
b. Use the Formulae Celsius to Fahrenheit: (°C × 9/5) + 32 = °F and assign to
farenheitResult and print the result
I/P => celcius
O/P => The ____ celsius is _____ fahrenheit
import java.util.Scanner;

public class CelsiusToFahrenheit {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter temperature in Celsius: ");

double celsius = input.nextDouble();

double fahrenheitResult = (celsius * 9 / 5) + 32; // Convert


Celsius to Fahrenheit

System.out.println("The " + celsius + " Celsius is " +


fahrenheitResult + " Fahrenheit.");

6
5. Write a TemperaturConversion program, given the temperature in Fahrenheit as input
outputs the temperature in Celsius
Hint =>
c. Create a fahrenheit variable and take the user's input
d. User the formulae to convert Fahrenheit to Celsius: (°F − 32) x 5/9 = °C and
assign the result to celsiusResult and print the result
I/P => fahrenheit
O/P => The ____ fahrenheit is _____ celsius
import java.util.Scanner;

public class FahrenheitToCelsius {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter temperature in Fahrenheit: ");

double fahrenheit = input.nextDouble();

double celsiusResult = (fahrenheit - 32) * 5 / 9; // Convert


Fahrenheit to Celsius

System.out.println("The " + fahrenheit + " Fahrenheit is " +


celsiusResult + " Celsius.");

6. Create a program to find the total income of a person by taking salary and bonus from user
Hint =>
a. Create a variable named salary and take user input.
b. Create another variable bonus and take user input.
c. Compute income by adding salary and bonus and print the result
I/P => salary, bonus
O/P => The salary is INR ___ and bonus is INR ___. Hence Total Income is INR ___
import java.util.Scanner;

7
public class TotalIncome {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter your salary (INR): ");

double salary = input.nextDouble();

System.out.print("Enter your bonus (INR): ");

double bonus = input.nextDouble();

double totalIncome = salary + bonus; // Calculate total income

System.out.println("The salary is INR " + salary + " and bonus


is INR " + bonus + ". Hence, Total Income is INR " + totalIncome);

7. Create a program to swap two numbers


Hint =>
a. Create a variable number1 and take user input.
b. Create a variable number2 and take user input.
c. Swap number1 and number2 and print the swapped output
I/P => number1, number2
O/P => The swapped numbers are ___ and ___
import java.util.Scanner;

public class SwapNumbers {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

8
System.out.print("Enter the first number: ");

int number1 = input.nextInt();

System.out.print("Enter the second number: ");

int number2 = input.nextInt();

// Swapping the numbers

int temp = number1;

number1 = number2;

number2 = temp;

System.out.println("The swapped numbers are " + number1 + " and


" + number2);

8. Rewrite the Sample Program 2 with user inputs


Hint =>
a. Create variables and take user inputs for name, fromCity, viaCity, toCity
b. Create variables and take user inputs for distances fromToVia and viaToFinalCity in
Miles
c. Create Variables and take time taken
d. Finally, print the result and try to understand operator precedence.
I/P => fee, discountPrecent
O/P => The results of Int Operations are ___, ___, and ___

9. An athlete runs in a triangular park with sides provided as input by the user in meters. If the
athlete wants to complete a 5 km run, then how many rounds must the athlete complete
Hint => The perimeter of a triangle is the addition of all sides and rounds is
distance/perimeter
I/P => side1, side2, side3

9
O/P => The total number of rounds the athlete will run is ___ to complete 5 km
10. Create a program to divide N number of chocolates among M children.
Hint =>
a. Get an integer value from user for the numberOfchocolates and numberOfChildren.
b. Find the number of chocolates each child gets and number of remaining chocolates
c. Display the results
I/P => numberOfchocolates, numberOfChildren
O/P => The number of chocolates each child gets is ___ and the number of remaining
chocolates are ___
11. Write a program to input the Principal, Rate, and Time values and calculate Simple Interest.
Hint => Simple Interest = Principal * Rate * Time / 100
I/P => principal, rate, time
O/P => The Simple Interest is ___ for Principal ___, Rate of Interest ___ and Time ___
12. Create a program to convert weight in pounds to kilograms.
Hint => 1 pound = 2.2 kg
I/P => weight
O/P => The weight of the person in pound is ___ and in kg is ___

10

You might also like