external_3.c (404B)
1 // 3. Write a program to compute the sum of the first n terms of: S = 1 - 2 + 3 - 4 + 5… 2 3 #include<stdio.h> 4 5 int sum(int); 6 7 int main() { 8 int n; 9 printf("Enter the value for n: "); 10 scanf("%d", &n); 11 printf("\nSum of the first n terms= %d", sum(n)); 12 return 0; 13 } 14 15 int sum(int n) { 16 int i, res = 0; 17 for(i = 1; i <= n; i++) { 18 if(i % 2 == 0) { 19 res -= i; 20 continue; 21 } 22 res += i; 23 } 24 return res; 25 }