C语言
方法一:使用for循环
```c
include
int main() {
int n;
double sum = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
sum += i;
}
printf("数列的前%d项和为:%.0f\n", n, sum);
return 0;
}
```
方法二:使用递归
```c
include
double sum_recursive(int n) {
if (n == 1) return 1;
return n + sum_recursive(n - 1);
}
int main() {
int n;
scanf("%d", &n);
printf("数列的前%d项和为:%.0f\n", n, sum_recursive(n));
return 0;
}
```
Java
```java
import java.util.Scanner;
public class SumOfSeries {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("数列的前" + n + "项和为:" + sum);
}
}
```
Python
```python
n = int(input("请输入数列的项数n: "))
sum = 0
for i in range(1, n + 1):
sum += i
print("数列的前{}项和为: {}".format(n, sum))
```
JavaScript
```javascript
let n = parseInt(prompt("请输入数列的项数n:"));
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log("数列的前" + n + "项和为:" + sum);
```
这些示例展示了如何使用不同编程语言计算前n项和。你可以根据具体需求和编程环境选择合适的方法。