Write a recursive method named series (int a, int n) that takes as a parameter an integer that may compute the following series:
-2,7,52,2702... if a=-2 and n=4
Then, write a full program to solve the above problem using recursion.
SOLUTION FOR THE ABOVE QUESTION
SAMPLE PROGRAM OUTPUT
SOLUTION CODE FOR THE QUESTION
package com.company;
public class Main {
//Now define a method named series
static void series ( int a, int n)
{
int first_num = a;
int while_condition = n;
//print the first num
System.out.print("\n" + first_num + ", ");
//define a loop
while (while_condition != 0) {
if (while_condition % 2 == 0) {
for (int i = 0; i < 2; i++) {
first_num = (first_num * first_num) + (while_condition - 1);
if (while_condition != 0) {
System.out.print(first_num + ", ");
}
}
//update while_condition
while_condition = while_condition - 1;
} else {
for (int i = 0; i < 2; i++) {
first_num = (first_num * first_num) - (while_condition - 1);
if (while_condition != 0) {
System.out.print(first_num + ", ");
}
}
//update while_condition
while_condition = while_condition - 1;
}
}
System.out.println("\n");
}
public static void main(String[] args) {
//declare the given two variables a and n and initialiaze them
int a = -2;
int n = 4;
series(a,n);
}
}
Comments
Leave a comment