C Online Compiler
Example: Sum of Squares using Iteration in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sum of Squares using Iteration #include <stdio.h> int main() { int n; long long sum_of_squares = 0; // Use long long for sum to prevent overflow for larger n int i; // Step 1: Prompt user for input printf("Enter a positive integer (n): "); // Step 2: Read the value of n if (scanf("%d", &n) != 1 || n < 1) { printf("Invalid input. Please enter a positive integer.\n"); return 1; // Indicate an error } // Step 3: Iterate from 1 to n, square each number, and add to sum for (i = 1; i <= n; i++) { sum_of_squares += (long long)i * i; // Cast to long long before multiplication to prevent overflow } // Step 4: Print the result printf("The sum of squares up to %d is: %lld\n", n, sum_of_squares); return 0; }
Output
Clear
ADVERTISEMENTS