Arithmetic and Geometric Sequence
Arithmetic Sequence
The program generates arithmetic sequence of K items. on executing the program, user asked to the following input values a (start value) , d (common difference) and K (number of elements in the sequence) to generate the sequence.
a - starting value
d - common difference
import java.util.Scanner;
public class ArithSequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Generate Arithmetic Sequence n");
Scanner sc = new Scanner(System.in);
System.out.println( "starting value for a ");
int a = sc.nextInt();
System.out.println( "Enter common deference for d ");
int d = sc.nextInt();
System.out.println( "Enter K items in sequence");
int K = sc.nextInt();
sc.close();
System.out.println("nSequence ");
int s=0;
for(int n=0; n < K ; n++ )
{
s = n*d + a;
System.out.print( s + ", ");
}
}
}
Output
Generate Arithmetic Sequence starting value for a 2 Enter common deference for d 2 Enter K items in sequence 10 Sequence 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Geometric Sequence
The program generates Geometric sequence of K items. on executing the program, user asked to the following input values a (start value) , r (common ratio ) and K (number of elements in the sequence) to generate the sequence.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;
public class GeometSequence {
public static void main(String[] args)
{
System.out.println("Print Geometric Sequence n");
Scanner sc = new Scanner(System.in);
System.out.println( "Enter first item(integer) in sequence ");
int a = sc.nextInt();
System.out.println("Enter value for a (firstitem) in sequence");
int cr = sc.nextInt();
System.out.println("Enter K items in sequence");
int K = sc.nextInt();
sc.close();
System.out.println("n Sequence ");
for( int n=0; n<K ; n++ )
{
int s = a* (int)Math.pow(cr, n) ;
System.out.print(s+" , ");
}
}
}
Output
Print Geometric Sequence Enter value for a (first item) in sequence 2 Enter common ratio r of the sequence 3 Enter K items in sequence 10 Sequence 2 , 6 , 18 , 54 , 162 , 486 , 1458 , 4374 , 13122 , 39366
Comments
Post a Comment