Showing posts with label Series. Show all posts
Showing posts with label Series. Show all posts

Print Sum of Series 1/1^2 + 1/2^2 + 1/3^2 …………1/n^2 in Java.



import java.util.Scanner;
public class Series 
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the no of terms ");
  int n = sc.nextInt();
  double sum = 0;
  for (int i = 1; i <= n; i++)
   sum = sum + (double) 1 / Math.pow(i, 2);
  System.out.println("Sum of series = " + sum);
 }
}

Output:
Enter the no of terms 
5
Sum of series = 1.4636111111111112
BUILD SUCCESSFUL (total time: 2 seconds)



Print Sum of series 1+ (1+2) + (1+2+3)……. (1+2+3+…….n) in Java



import java.util.Scanner;
public class Series  
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the no of terms ");
  int n = sc.nextInt();
  int sum = 0, i = 0;
  for (int j = 1; j <= n; j++) 
  {
   for (i = 1; i <= j; i++) 
   {
    sum = sum + i;
   }
   i = 1;
  }
  System.out.println("Sum of series = " + sum);
 }
}

Output:
Enter the no of terms 
4
Sum of series = 20
BUILD SUCCESSFUL (total time: 2 seconds)


Print Series 1, 11, 111, 1111……..n terms in Java.



import java.util.Scanner;
public class Series  
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter the number of terms: ");
  int n = sc.nextInt();
  int s = 0, c;                                          // s for terms of series, c for n terms
  for (c = 1; c <= n; c++)                          // To generate n terms
  {
   s = s * 10 + 1;
   System.out.print(s + " ");
  }                                                           //for  ends
 }
}


Output:
Enter the number of terms: 7
1, 11, 111, 1111, 11111, 111111, 1111111...... 
BUILD SUCCESSFUL (total time: 3 seconds)


Print Series 1, 12, 123, 1234, …………n in Java.



import java.util.Scanner;
public class Series 
{
 public static void main(String args[]) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter the number of terms: ");
  int n = sc.nextInt();
  int s = 0, c;                       // s for terms of series, c for counter to generate n terms
  for (c = 1; c <= n; c++) {
   s = s * 10 + c;
   System.out.print(s + " ");
  }
 }
}


Output:
Enter the number of terms: 6
1,  12,  123,  1234,  12345,  123456....... 
BUILD SUCCESSFUL (total time: 3 seconds)