C Online Compiler
Example: Sum of Squares using Formula in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sum of Squares using Formula #include <stdio.h> int main() { int n; long long sum_of_squares = 0; // Use long long for the sum // 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: Apply the formula // (long long)n is used to ensure the multiplication is done using long long arithmetic // to prevent intermediate overflow before division. sum_of_squares = (long long)n * (n + 1) * (2 * n + 1) / 6; // 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