0% found this document useful (0 votes)
11 views

Exercise On Output Formatting

Uploaded by

Malupit Rush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Exercise On Output Formatting

Uploaded by

Malupit Rush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

/*

This is to demonstrate how to display output based on required format.


We will separate the computation and display using modular design.
*/

import java.util.*;

public class OutputFormatter{

static int vGetInt(String prompt, int lb, int ub){


Scanner scanner = new Scanner(System.in);

// your input and validation routine goes here

static String exprListEven(int n){


String expr = "Even(" + n + ") : {";
for(int j=1; j<=n; j++){
int even = 2*j;
expr += even;
if(j<n) expr += ", ";
}
expr += "}";
return expr;
}

static String exprListOdd(int n){

// your odd list epression formulation here

static String exprSum(int n){


String expr = "S(" + n + ") = ";
for(int j=1; j<=n; j++){
expr += j;
if(j<n) expr += " + ";
}
return expr;
}

static String exprFac(int n){

// your factorial expression formulation here

static int Sum(int n){


int sum = 0;
for(int j=1; j<=n; j++)
sum += j;
return sum;
}

static long Fac(int n){


//your factorial computation here

static void println(String str){ System.out.println(str); }

// --------------------------------------------------------

public static void main(String[] args){


int n;

println("List the first n Even numbers");


n = vGetInt("integer", 1, 20);
println(exprListEven(n) + "\n");

println("List the first n Odd numbers");


n = vGetInt("integer", 1, 20);
println(exprListOdd(n) + "\n");

println("Let's do Summation of n");


n = vGetInt("integer", 1, 20);
println(exprSum(n) + " = " + Sum(n) + "\n");

println("Let's do Factorial of n");


n = vGetInt("integer", 1, 10);
println(exprFac(n) + " = " + Fac(n) + "\n");

}
}

Sample Dialog:
List the first n Even numbers
Enter integer [1 to 20] : 10
Even(10) : {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

List the first n Odd numbers


Enter integer [1 to 20] : 10
Odd(10): {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

Let's do Summation of n
Enter integer [1 to 20] : 10
S(10) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Let's do Factorial of n
Enter integer [1 to 10] : 10
10! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 = 3628800

You might also like