140 likes | 333 Views
Computer Programming. Lab(4). Exercise 1. 2.1 ( Convert Celsius to Fahrenheit ) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows:
E N D
Computer Programming Lab(4)
Exercise 1 2.1(Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: fahrenheit = (9 / 5) * celsius + 32 Hint: In Java, 9/5 is 1,but 9.0/5 is 1.8.
Source code: import java.util.Scanner; public class Exercise02_01 { // Main method public static void main(String[] args) { Scannerinput = newScanner(System.in); // Enter a temperature in Celsius System.out.print("Enter a temperature in Celsius: "); double celsius = input.nextDouble(); // Convert it to Fahrenheit doublefahrenheit = (9.0 / 5) * celsius + 32; // Display the result System.out.println(celsius + " Celsius is " + fahrenheit + " Fahrenheit"); }}
Exercise 2 2.2 (Compute the area and volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas: area = radius * radius * π volume = area * length
Source code: import java.util.Scanner; public class Exercise2_2 { public static void main(String[] args) { Scannerinput = newScanner(System.in); // Enter radius and length of the cylinder System.out.print("Enter the radius and length of a cylinder: "); doubleCradius = input.nextDouble(); doubleClength = input.nextDouble();
Source code: double area = Cradius * Cradius * 3.14; double volume = area * Clength; System.out.println("The area is " + area); System.out.println("The volume is " + volume); } }
Exercise 3 2.6 (Sum the digits in an integer) Write a program that reads an integer between 100 and 999 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
Source code: import java.util.Scanner; publicclass Exercise2_6 { // Main method public static void main(String[] args) { Scannerinput = newScanner(System.in); // Read a number System.out.print("Enter an integer between 100 and 999: "); intnumber = input.nextInt();
Source code: // Find all digits in number intlastDigit = number % 10; intremainingNumber = number / 10; intsecondLastDigit = remainingNumber % 10; remainingNumber = remainingNumber / 10; intthirdLastDigit = remainingNumber % 10;
Source code: // Obtain the reverse number intsum = (lastDigit) + (secondLastDigit) + thirdLastDigit; // Display results System.out.println("The sum of the digits is: "+ sum); } }