1 / 7

LAB 10

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 )

zanna
Download Presentation

LAB 10

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. LAB 10

  2. 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.

  3. 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 ; • } • }

  4. 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.

  5. 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 ; } } }

  6. 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)

  7. 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(); } } }

More Related