Task: Read N and compute the sum using for
, then while
, then do…while
. Print all three results and confirm they match.
/*
Program: Sum of First N Natural Numbers using three loops (U2)
What it does:
- Reads N (>=0) and computes the sum using: for, while, do-while.
- Prints all three sums and verifies they match.
*/
#include <stdio.h>
int main(void) {
int N;
long long s_for = 0, s_while = 0, s_do = 0;
printf("Enter N (>=0): ");
if (scanf("%d", &N) != 1 || N < 0) {
printf("Invalid N. Use a non-negative integer.
");
return 0;
}
/* for loop */
for (int i = 1; i <= N; ++i) s_for += i;
/* while loop */
int j = 1;
while (j <= N) { s_while += j; ++j; }
/* do-while loop */
int k = 1;
if (N >= 1) {
do { s_do += k; ++k; } while (k <= N);
} else {
s_do = 0;
}
printf("Sum via for = %lld
", s_for);
printf("Sum via while = %lld
", s_while);
printf("Sum via do = %lld
", s_do);
printf("All equal? %s
", (s_for == s_while && s_for == s_do) ? "Yes" : "No");
return 0;
}