Problem:
Develop an algorithm that prints out n values of the sequence 1 -1 1 -1 1 -1 ...
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrintOutSequence {
static int n = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in sequence : ");
n = s.nextInt();
generateTheSequence();
s.close();
}
private static void generateTheSequence(){
List<Integer> series = new ArrayList<Integer>();
System.out.print("The series is: ");
for(int i = 0; i<n; i++){
if((i %2) == 0){
series.add(1);
}
else{
series.add(-1);
}
}
System.out.print(series + " ");
}
}
Output:
Enter the No. of terms in sequence :
10
The series is: [1, -1, 1, -1, 1, -1, 1, -1, 1, -1]
Develop an algorithm that prints out n values of the sequence 1 -1 1 -1 1 -1 ...
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrintOutSequence {
static int n = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in sequence : ");
n = s.nextInt();
generateTheSequence();
s.close();
}
private static void generateTheSequence(){
List<Integer> series = new ArrayList<Integer>();
System.out.print("The series is: ");
for(int i = 0; i<n; i++){
if((i %2) == 0){
series.add(1);
}
else{
series.add(-1);
}
}
System.out.print(series + " ");
}
}
Enter the No. of terms in sequence :
10
The series is: [1, -1, 1, -1, 1, -1, 1, -1, 1, -1]
No comments:
Post a Comment