Professional Documents
Culture Documents
}
b) Use four System.out.print statements.
public class number1_4 {
public static void main (String [ ] args)
{System.out.print("1 ");
System.out.print("2 ");
System.out.print("3 ");
System.out.print("4");
}
}
c) Use one System.out.printf statement.
public class number1_4 {
public static void main (String [ ] args)
{
System.out.printf("%d %d %d %d ",1,2,3,4);
}
}
2.15 (Arithmetic) Write an application that asks the user to enter two integers,
obtains them from the user and prints their sum, product, difference and quotient
(division).
import java.util.Scanner;
public class Arthimetic
{
public static void main(String [] args)
{ Scanner input = new Scanner(System.in);
int a;
int b;
int sum, quo, pro, dif;
System.out.print("enter the first number a= ");
a= input.nextInt();
System.out.print("enter the second number b= ");
b=input.nextInt();
sum=a+b;
que=a/b;
pro=a*b;
dif=a-b;
System.out.printf("the sum of %d and %d is %d%n",a,b, sum);
System.out.printf("the difference of %d and %d is %d%n",a,b, dif);
System.out.printf("the product of %d and %d is %d%n",a,b, pro);
System.out.printf("the quotient of %d divide by %d is %d%n", quo);
}
2.16 (Comparing Integers) Write an application that asks the user to enter two
integers, obtains them from the user and displays the larger number followed by the
words "is larger". If the numbers are equal, print the message "These numbers are
equal".
import java.util.Scanner;
public class comparing {
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int a, b;
System. out .print ("enter the first number a=");
a=input.nextInt();
System.out.print("enter the second number b=");
b=input.nextInt();
if(a>b)
System.out.printf("%d is larger", a);
if(b>a)
System.out.printf("%d is larger", b);
if(a==b)
System.out.printf("these numbers are equal");
}
}
2.17 (Arithmetic, Smallest and Largest) Write an application that inputs three integers from the
user and displays the sum, average, product, smallest and largest of the numbers. Use the
techniques shown in Fig. 2.15. [Note: The calculation of the average in this exercise should result
in an integer representation of the average. So, if the sum of the values is 7, the average should
be 2, not 2.3333….
import java.util.Scanner;
public class ArithmeticSmallestLargest
{
int a, b, c;
int largest, smallest;
int sum;
int product; int average;
largest = a;
if (b > largest)
largest = b;
if (c > largest)
largest = c;
smallest = c;
if (b < smallest)
smallest = b;
if (c < smallest)
smallest = c;
sum =a+ b+ c;
product = a * b * b;
average = sum / 3;
**************
****
*****
******
2.24 (Largest and Smallest Integers) Write an application that reads five integers and
determines
and prints the largest and smallest integers in the group. Use only the programming techniques
you
learned in this chapter.
********* *** * *
* * * * *** * *
* * * * ***** * *
*******
*******
*******
*******
*******
********* *** * *