Print Arithmetic Sequence by for-loop
public class ArithmeticSequenceExample {
static void arithmeticProgression(int val, int ratio, int n) {
for (int i = 1; i <= n; i++) {
System.out.print((val + (i - 1) * ratio) + " ");
}
}
public static void main(String[] args) {
int val = 1;
int ratio = 2;
int n = 10;
arithmeticProgression(val, ratio, n);
}
}
Output
1 3 5 7 9 11 13 15 17 19
Print Arithmetic Sequence by Recursion
public class ArithmeticSequenceExample {
static void arithmeticProgression(int ratio, int n, int val) {
System.out.print(val + " ");
if (n == 0)
return;
arithmeticProgression(ratio, n - 1, val + ratio);
}
public static void main(String[] args) {
int val = 1;
int ratio = 2;
int n = 10;
arithmeticProgression(ratio, n - 1, val);
}
}
Output
1 3 5 7 9 11 13 15 17 19