Presentation is loading. Please wait.

Presentation is loading. Please wait.

LAB 10.

Similar presentations


Presentation on theme: "LAB 10."— 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 int sumDigits(int n) 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 : "); int num = input.nextInt(); System.out.println("Sum = " + sumDigits(num)); } public static int sumDigits(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 : "); int num = 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: "); int num = input.nextInt(); displayPattren(num); } public static void displayPattren(int n) { for (int i=1 ; i <= n ; i++) for (int j=1 ; j <= i ; j++) System.out.print(j + " " ); System.out.println();


Download ppt "LAB 10."

Similar presentations


Ads by Google