C Online Compiler
Example: Sum of Squares - Formulaic Method in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sum of Squares - Formulaic Method #include <stdio.h> int main() { // Step 1: Declare variables for 'n' (input) and 'sum' int n; long long sum; // Use long long for sum to prevent overflow // 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: Apply the mathematical formula // (long long) cast is important here to prevent intermediate multiplication overflow // before division, especially for large 'n'. sum = (long long)n * (n + 1) * (2 * n + 1) / 6; // 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