-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathlab2_1.c
More file actions
35 lines (28 loc) · 647 Bytes
/
lab2_1.c
File metadata and controls
35 lines (28 loc) · 647 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
/*
Task:
Write a function `int sum_to_n(int n)` that computes
the sum of all integers from 1 up to n using a for loop.
In main():
- Ask user for a positive integer n
- If n < 1, print an error
- Otherwise, call sum_to_n and print the result
*/
int sum_to_n(int n) {
int sum=0;
for (int i=1; i<=n; i++) {
sum +=i;
}
return sum; // placeholder
}
int main(void) {
int n;
printf("Enter a positive integer n: ");
scanf("%d", &n);
if (n<1) {
printf("error\n");
} else {
printf("The sum is: %d\n", sum_to_n(n));
}
return 0;
}