C Online Compiler
Example: Sum of Squares - Iterative Method in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sum of Squares - Iterative Method #include <stdio.h> int main() { // Step 1: Declare variables for 'n' (input) and 'sum' int n; long long sum = 0; // Use long long for sum to prevent overflow for larger 'n' // Step 2: Prompt user for input printf("Enter a positive integer (n): "); scanf("%d", &n); // Step 3: Validate input if (n < 1) { printf("Please enter a positive integer.\n"); return 1; // Indicate an error } // Step 4: Iterate from 1 to 'n', square each number, and add to sum for (int i = 1; i <= n; i++) { sum += (long long)i * i; // Cast i*i to long long to prevent intermediate overflow } // Step 5: Print the result printf("The sum of squares of the first %d natural numbers is: %lld\n", n, sum); return 0; }
Output
Clear
ADVERTISEMENTS