LAB 10. (Sum the digits in an integer) Write a method that computes the sum of the digits in an...
-
Upload
everett-pierce -
Category
Documents
-
view
225 -
download
0
Transcript of LAB 10. (Sum the digits in an integer) Write a method that computes the sum of the digits in an...
LAB 10
(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.
Exercise 1
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 ; } }
(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.
Exercise 2
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 ; } }}
(Display patterns) Write a method to display a pattern as follows:
11 21 2 3...1 2 3 …. n-1 nThe method header ispublic static void displayPattern(int n)
Exercise 3
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(); } } }