Program to print Arithmetic Progression series
Given first term (a), common difference (d) and a integer n of the Arithmetic Progression series, the task is to print the series.
Examples :
Input : a = 5, d = 2, n = 10
Output : 5 7 9 11 13 15 17 19 21 23
Approach :
We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 …. …
In this series 2 is the starting term of the series .
Common difference = 5 – 2 = 3 (Difference common in the series).
so we can write the series as :
t1 = a1
t2 = a1 + (2-1) * d
t3 = a1 + (3-1) * d
.
.
.
tn = a1 + (n-1) * d
CPP
#include <bits/stdc++.h>
using namespace std;
void printAP( int a, int d, int n)
{
int curr_term;
curr_term=a;
for ( int i = 1; i <= n; i++)
{ cout << curr_term << " " ;
curr_term =curr_term + d;
}
}
int main()
{
int a = 2;
int d = 1;
int n = 5;
printAP(a, d, n);
return 0;
}
|
Java
class GFG
{
static void printAP( int a, int d, int n)
{
int curr_term;
curr_term=a;
for ( int i = 1 ; i <= n; i++)
{ System.out.print(curr_term + " " );
curr_term =curr_term + d;
}
}
public static void main(String[] args)
{
int a = 2 ;
int d = 1 ;
int n = 5 ;
printAP(a, d, n);
}
}
|
Python3
def printAP(a, d, n):
curr_term = a
for i in range ( 1 , n + 1 ):
print (curr_term, end = ' ' )
curr_term = curr_term + d
a = 2
d = 1
n = 5
printAP(a, d, n)
|
C#
using System;
class GFG
{
static void printAP( int a, int d, int n)
{
int curr_term;
curr_term=a;
for ( int i = 1; i <= n; i++)
{
Console.Write(curr_term + " " );
curr_term += d;
}
}
public static void Main()
{
int a = 2;
int d = 1;
int n = 5;
printAP(a, d, n);
}
}
|
Javascript
<script>
function printAP(a, d, n)
{
let curr_term;
curr_term=a;
for (let i = 1; i <= n; i++)
{ document.write(curr_term + " " );
curr_term =curr_term + d;
}
}
let a = 2;
let d = 1;
let n = 5;
printAP(a, d, n);
</script>
|
PHP
<?php
function printAP( $a , $d , $n )
{
$curr_term = $a ;
for ( $i = 1; $i <= $n ; $i ++)
{ echo ( $curr_term . " " );
$curr_term += $d ;
}
}
$a = 2;
$d = 1;
$n = 5;
printAP( $a , $d , $n );
?>
|
Time complexity: O(n) where n is the total number of terms of a given A.P
Auxiliary Space: O(1)
Last Updated :
21 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...