Computer Science, asked by imhh, 1 year ago

Write a program in JAVA to print the output of the following series :
s = 2 - 4 + 8 - 16 ................ upto n terms.

Answers

Answered by Anonymous
1
import java.io.*;
public class Hope {
      public static void main(String[] args) {
            int n = 5;
            double sum = 0;
            for(int i=1; i<=n; i++){
                  double term = (-1)*(Math.pow(-2,i));
                  sum = sum + term;

            }

     
            System.out.println("The sum is " + sum);
       }
}

imhh: n should have been user defined
imhh: The answer should have been :
imhh: import java . io . * ;
class Series_4
{
public static void main ()throws IOException
{
int s = 0 , n , i , j ;
BufferedReader br = new BufferedReader ( new InputStreamReader (System.in) ) ;
System.out.println("Enter the number of terms : ") ;
n = Integer.parseInt(br.readLine()) ;
i = 2 ;
for ( j = 1 ; j <= n ; j++ )
{
if (j % 2 != 0)
{
s = s + i ;
}
else
{
imhh: s = s - i ;
}
i = i * 2 ;
}
System.out.println("The sum of the given series = " + s) ;
}
}
Anonymous: were you expecting someone to copy that code and paste it??
Anonymous: sorry then....i wrote a small code on my own and it works fine...
Anonymous: if you want, take it...otherwise leave it..
Similar questions