Write a c++ program to compute the sum of square of odd numbers from 1 to n where n is a positive integer. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Write a c++ program to compute the sum of square of odd numbers from 1 to n where n is a positive integer.

a program to compute sum of squares of odd numbers starting from 1

2nd Dec 2016, 5:58 PM
Baba Yunus Abdul Yekin
Baba Yunus Abdul Yekin - avatar
2 Answers
+ 6
You have different ways to do that. Here are 3 different ways: #include <iostream> using namespace std; int main() { int sum = 0; int odd = 0; int count = 0; int n = 100; // change value of n as you like. // method 1 using while loop. while (count < n - 1) { odd++; count++; if (odd % 2 == 1) { sum += (odd * odd); } } cout << "The sum is: " << sum << endl; int sum2 = 0; int odd2 = 0; // method 2 using for loop, shorter code. for (int odd2 = 1; odd2 < n; odd2 += 2) { sum2 += (odd2 * odd2); } cout << "The sum is: " << sum2 << endl; // method 3 CAREFULL THIS METHOD ONLY WORKS IF N IS EVEN. int sum3 = n * (n+1) * (2 * n + 1) / 6; sum3 -= (n / 2 * n + (n / 2)); sum3 /= 2; cout << "The sum is: " << sum3 << endl; return 0; } // end of main check it out: https://www.sololearn.com/Profile/2981791
2nd Dec 2016, 8:57 PM
R2-D2
R2-D2 - avatar
+ 2
here you go: #include <iostream> using namespace std; double sumOfOddRoots_to_n(int n) { double x = n; double res = 0.0; for(double i = 1.0; i <= x; i += 2.0) { res += (i * i); } return res; } int main() { int a; cin>>a; cout<<sumOfOddRoots_to_n(a); return 0; }
2nd Dec 2016, 6:15 PM
NICKALL [EP]
NICKALL [EP] - avatar