70 likes | 231 Views
LAB 10. Exercise 1. ( Sum the digits in an integer ) Write a method that computes the sum of the digits in an integer. Use the following method header: public static int sumDigits ( int n )
E N D
Exercise 1 • (Sum the digits in an integer) Write a method that computes the sum of the digits in an integer. Use the following method header: • public static intsumDigits(intn) • For example, sumDigits(234) returns 9 (2+3+4) (Hint: Use the % operator to extract digits, and the / operator to remove the extracted digit. Use a loop to repeatedly extract and remove the digit until all the digits are extracted.
import java.util.Scanner; • public class Lab10_EX1 { • public static void main(String[] args) { • Scanner input = new Scanner (System.in); • System.out.print("Enter a number : "); • intnum = input.nextInt(); • System.out.println("Sum = " + sumDigits(num)); • } • public static intsumDigits(int n) • { • int sum = 0 ; • while ( n > 0 ) • { • sum = sum + (n%10); • n = n / 10 ; • } • return sum ; • } • }
Exercise 2 • (Display an integer reversed ) Write a method with the following header to display an integer in reverse order: • public static void reverse(int n) • For example, reverse(3456)displays 6543. • the program prompts the user to enter an integer and displays its reversal.
import java.util.Scanner; public class Lab_EX2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number : "); intnum = input.nextInt(); reverse(num); } public static void reverse(int n) { int reminder = 0; while ( n > 0 ) { reminder = n % 10 ; System.out.print(" " + reminder ); n = n / 10 ; } } }
Exercise 3 • (Display patterns) Write a method to display a pattern as follows: • 1 • 1 2 • 1 2 3 • ... • 1 2 3 …. n-1 n • The method header is public static void displayPattern(int n)
import java.util.Scanner; public class Lab10_EX3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number for the pattern: "); intnum = input.nextInt(); displayPattren(num); } public static void displayPattren(int n) { for (inti=1 ; i <= n ; i++) { for (int j=1 ; j <= i ; j++) System.out.print(j + " " ); System.out.println(); } } }