Вы находитесь на странице: 1из 4

SOLUTION TEMPLATE

Machine Problem #2: Write a program which produces the given sequence numbers (in
alternate arrangement) using looping statements.

Sample Output:

1, 5, 2, 4, 3, 3, 4, 2, 5, 1,

Code:

public class AlternateNum


{
public static void main(String [] args)
{
int num1, num2 = 5;

for(num1 = 1; num1 < 6; num1++)


{
System.out.print(num1 + ", ");
System.out.print(num2 + ", ");
num2--;
}
}
}
OUTPUT

Herco, Phoebe Kaye Y. Prof. Albert A. Vinluan, M.A.


W 7:00 – 10:00 CS 132L: Introduction to Programming
Machine Problem #4: Write a program to calculate the factorial value of the input number n! Use the
incrementation formula (i++) for your solution instead of decrementaton formula
(i--). Apply the looping statements for your solutions.
Sample Input /Output:

Enter a number: 4
Factorial value: 24

Code:

import java.io.*;
public class Factorial
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int i = 1, Factorial = 1;

System.out.print("Enter a number: ");


int n = Integer.parseInt(br.readLine());

while(i <= n)
{
Factorial *= i;
i++;
}
System.out.print("Factorial value: " + Factorial); OUTPUT
}
}

Herco, Phoebe Kaye Y. Prof. Albert A. Vinluan, M.A.


W 7:00 – 10:00 CS 132L: Introduction to Programming
Machine Problem #8: Write a program to calculate the sum of the sequence number from 1 to n. Thus,
the input is 6, the output should be 21 because: 1+2+3+4+5+6 = 21. Apply the looping statements.

Sample Input /Output:

Enter a number: 6
Sum: 21

Code:

import java.io.*;
public class CalculateSum
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int Sum = 0;

System.out.print("Enter a number: ");


int n = Integer.parseInt(br.readLine());

for(int num = 1; num <= n; num++)


{
Sum += num;
} OUTPUT
System.out.print("Sum: " + Sum);
}
}

Herco, Phoebe Kaye Y. Prof. Albert A. Vinluan, M.A.


W 7:00 – 10:00 CS 132L: Introduction to Programming
Machine Problem #10: Write a program to scan a number n and then output the sum of the power from 1
to n. Thus, if the input is 4, the output should be 288, because:
11 + 22 + 33 + 44
1 + 4 + 27 + 256 = 288
Sample Input /Output:

Enter a number: 4
Sum of the power: 288

Code:

import java.io.*;
public class PowerSum
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int Sum = 0;
int num = 1;
int power = 1;

System.out.print("Enter a number: ");


int n = Integer.parseInt(br.readLine());

for(int x = 1; x <= n; x++)


{
for(int y = 1; y < power; y++)
OUTPUT
{
num *= power;
}
Sum += num;
++power;
num = power;
}
System.out.print("Sum: " + Sum);
}
}

Herco, Phoebe Kaye Y. Prof. Albert A. Vinluan, M.A.


W 7:00 – 10:00 CS 132L: Introduction to Programming

Вам также может понравиться