Java Examples : Number Series
06-07-2017    8298 times

All The program of the series addition or multiplication is based on some mathematical logic. Programmers should found and understand the mathematics behind it. All the series have some starting value, some logic acts behind the increment of the start value and an end term value. Here we declare some variable sv, inc, n for the start value, increment, term end variable respectively.

#### 1+2+3+4+5+6+7+ …..+ n

import java.util.*;
public class sum1
{
public static void main(String [] args)
{
int sv=1, inc=1, I, n, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();
for(i=0; i<10; i++)
{
s+=sv;
sv+=inc;
}
System.out.println(s);
}
}

#### 1+3+5+7+9+….+n

import java.util.*;
public class sum2
{
public static void main(String [] args)
{
int sv=1, inc=2, n, i, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();for(i=0; i<10; i++)
{
s+=sv;
sv+=inc;
}
System.out.println(s);
}
}

#### 1-3+5-7+9-….

import java.util.*;
public class s1
{
public static void main(String [] args)
{
int sv=1, i,n,inc=2, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();
for(i=0; i<n; i++)
{
if(i%2==0)
{
s+=sv;
}
else
{
s-=sv;
}
sv+=inc;
}
System.out.println(s);
}
}

#### 2+4+6+8+10+….+n

import java.util.*;
public class sum3
{
public static void main(String [] args)
{
int sv=2, inc=2, i, n, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();
for(i=0; i<10; i++)
{
s+=sv;
sv+=inc;
}
System.out.println(s);
}
}

#### 1+4+9+16+…+n2

import java.util.*;
public class sum4
{
public static void main(String [] args)
{
int sv=1, inc=2, n, i, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();

for(i=0; i<10; i++)
{
s+=sv*sv;
sv+=inc;
}
System.out.println(s);
}
}

#### 1+2+4+7+11+16+…..+ n

import java.util.*;
public class sum5
{
public static void main(String [] args)
{
int sv=1, inc=1, n, i, s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the term No");
n=sc.nextInt();
for(i=0; i<4; i++)
{
s+=sv;
sv+=inc;
inc+=1;
}
System.out.println(s);
}
}

#### (i) double series(double n) with one double argument andreturns the sum of the series.sum = 1/1 + 1/2 + 1/3 + ….. 1/n(ii) double series(double a, double n) with two double argumentsand returns the sum of the series.sum = 1/a^2 + 4/a^5 + 7/a^8 + 10/a^11 ….. to n terms

public class Series
{
double series(double n)
{
double s=0;
for (int i=1;i<=n;i++)
{
s+= (double) 1/i;
}
return s;
}
double series(double a, double n)
{
double s=0;
int sv=1,inc=3;;
for (int i=1;i<=n;i++)
{
s+= (double) sv/Math.pow(a,(sv+1));
sv+=inc;
}
return s;
}
}