Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

First N Terms of AP

Generate arithmetic-progression terms from a starting value and difference. Students use zero-based range positions and see how each position sets the term.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 9 of 13
first-n-terms-of-ap.py
1# Take inputs
2a = int(input("Enter first term (a): "))
3d = int(input("Enter common difference (d): "))
4n = int(input("Enter number of terms (n): "))
5
6# Print AP
7print(f"First {n} terms of AP:")
8for i in range(n):
9 term = a + i * d
10 print(term, end=" ")
11print()

Output

Enter first term (a): 2
Enter common difference (d): 3
Enter number of terms (n): 5
First 5 terms of AP:
2 5 8 11 14

In this one

  • Use a common difference
  • Index terms from zero
  • Generate a fixed term count

How it works

  1. 1

    Read a, d, and n.

  2. 2

    Visit positions zero through n - 1.

  3. 3

    Print a + i * d for each position.

Edge cases

Can d be negative?

Can d be negative?

Yes. The terms then decrease.

What does n = 0 do?

What does n = 0 do?

It prints the heading but no terms.

What's going on

The term at position i is a + i * d. Since range(n) starts at zero, the first printed term is a, not a + d.

Each successive position adds one more copy of the common difference. With a equal to two and d equal to three, the beginning is 2, 5, 8. n controls the number of terms, not the largest allowed value.

Can d be negative? Yes. The terms then decrease.

What does n = 0 do? It prints the heading but no terms.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why start i at zero?

Pick an answer to check it.

Question 2

Can d be negative?

Pick an answer to check it.

Questions people ask

Can d be negative?

Yes. The terms then decrease.

What does n = 0 do?

It prints the heading but no terms.

Why start i at zero?

The first term should equal a.