Write a program to generate the sequence: −5, 10, −15, 20, −25…… upto n, where n is an integer input by the user.
python
Program to generate the sequence: -5, 10, -15, 20, -25... upto n
n = int(input("Enter the value of n: "))
for i in range(1, n + 1): term = 5 * i * ((-1) ** i) print(term, end=" ")
print() # For new line after the sequence
Explanation:
The program takes an integer n as input from the user. A for loop is used with range(1, n+1) to iterate from 1 to n. The sequence follows a pattern where each term is a multiple of 5 with alternating signs.
The formula used is: term = 5 × i × (-1)^i
- For i = 1: × (-1) = -5
- For i = 2: × 1 = 10
- For i = 3: × (-1) = -15
- For i = 4: × 1 = 20
- For i = 5: × (-1) = -25
The (-1)^i factor handles the alternating sign pattern—negative for odd values of i and positive for even values. Each term is printed on the same line using end=" " parameter.
Sample Output:
Enter the value of n: 6 -5 10 -15 20 -25 30
Explanation
This question tests the student's ability to identify patterns in sequences and implement them using loops. The sequence -5, 10, -15, 20, -25... has two key characteristics: (1) each term is a multiple of 5, and (2) signs alternate starting with negative. The textbook context demonstrates the use of range() function in for loops for generating sequences, which is directly applicable here. Students can use either the mathematical formula approach with (-1)^i or an if-else condition to handle alternating signs.
Solution Steps
Step 1: Identify the pattern - terms are multiples of 5 with alternating signs (negative for odd positions, positive for even positions)
Step 2: Take integer input n from user to determine how many terms to generate
Step 3: Use for loop with range(1, n+1) to iterate through positions 1 to n
Step 4: Calculate each term using formula: term = 5 × i × (-1)^i
Step 5: Print each term with space separator using end=' ' parameter