Download Lab 10

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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)
 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 : ");
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 ;






}


}
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
 the
example, reverse(3456) displays 6543.
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 : ");
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 ;
}
}
}
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: ");
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();
}
}
}