Ads

Wap to print the series and find the sum:-

1+2+4+9+28+125

My email-id is:-

pal.soumyadeep123@gmail.com

1+2+4+9+28+125

My email-id is:-

pal.soumyadeep123@gmail.com

Ads

View Answers

January 8, 2010 at 2:16 AM

Hi,

Try This.

public class SumOfSeries {

/**

* @param 'begin' holds the start of the series

* @param 'end' holds the end of the series

* @param 'series' holds the series need to be printed

*/

StringBuffer series=new StringBuffer();

public static void main(String[] args) {

int begin = 0;

int end = 5;

SumOfSeries obj = new SumOfSeries();

int result = obj.Sum(begin, end);

obj.MoidfySeries();

System.out.println("Sum of the series from "+begin+" to "+end+" : "+obj.series+result);

}

public int factorial(int num){

int temp=1;

if(num==0)

return 1;

for(int i=num;i>0;i--)

{

temp = temp*i;

}

return temp;

}

public int Sum(int start, int end){

int sumOfSeries=0;

int fact=0;

int sum = 0;

for(int i=start;i<=end;i++){

fact = factorial(i);

sum = fact+i;

series = series.append(sum).append('+');

sumOfSeries = sumOfSeries + sum;

}

return sumOfSeries ;

}

/**

* This method modifies the series that need to be printed

* by replacing the last character of the String Buffer '+' to '='

*/

public void MoidfySeries(){

int index = series.lastIndexOf("+");

series.setCharAt(index, '=');

}

}

Regards,

javaquest2010

Try This.

public class SumOfSeries {

/**

* @param 'begin' holds the start of the series

* @param 'end' holds the end of the series

* @param 'series' holds the series need to be printed

*/

StringBuffer series=new StringBuffer();

public static void main(String[] args) {

int begin = 0;

int end = 5;

SumOfSeries obj = new SumOfSeries();

int result = obj.Sum(begin, end);

obj.MoidfySeries();

System.out.println("Sum of the series from "+begin+" to "+end+" : "+obj.series+result);

}

public int factorial(int num){

int temp=1;

if(num==0)

return 1;

for(int i=num;i>0;i--)

{

temp = temp*i;

}

return temp;

}

public int Sum(int start, int end){

int sumOfSeries=0;

int fact=0;

int sum = 0;

for(int i=start;i<=end;i++){

fact = factorial(i);

sum = fact+i;

series = series.append(sum).append('+');

sumOfSeries = sumOfSeries + sum;

}

return sumOfSeries ;

}

/**

* This method modifies the series that need to be printed

* by replacing the last character of the String Buffer '+' to '='

*/

public void MoidfySeries(){

int index = series.lastIndexOf("+");

series.setCharAt(index, '=');

}

}

Regards,

javaquest2010

Ads

Related Tutorials/Questions & Answers: