+ 7

Could someone give me a Hint ????

I want to write a cpp program to calculate the sequence of numbers : S=1² +2²+3²+4²+5²+6²+.......n² I appreciate any help from you.. even a small hint. thanks

22nd Jan 2018, 7:27 PM
RiGeL
RiGeL - avatar
9 ответов
+ 8
@RiGeL, following @Gordie's pointers, here's how I think it would work, I know you asked for a hint, but I guess the code will explain itself better than I could, so here it is: #include <iostream> #include <cmath> int main() { double sum {0}, limit {0}; std::cout << "Enter the top number: "; std::cin >> limit; std::cout << limit << "\n\n"; if(limit < 2) return 0; for(double i = 1;i <= limit; i++) { sum += std::pow(i, 2.0d); if(i < limit - 1) std::cout << i << char(253) << "+"; else std::cout << i << char(253); } std::cout << "\n\nTotal: " << sum; return 0; } Hth, cmiiw
22nd Jan 2018, 10:03 PM
Ipang
+ 20
print n*(n+1)*(2*n+1)/6 //n belongs to a natural no //small approach , but for bigger degrees ... u need to use loop only for that like adnam used
22nd Jan 2018, 8:04 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
make an int sum = 0, use for loop from int i = 1, i<=n and inside write sum += i*i (sum += is same as sum = sum +....). This way for n=2 it will be first sum = 0 + 1*1 = 1, then sum = 1 + 2*2 = 5
22nd Jan 2018, 7:41 PM
rafal
+ 6
your most welcome buddy @rigel. keep coding 😀😀😁
22nd Jan 2018, 8:15 PM
adnan
adnan - avatar
+ 6
@Gordie ooh thanks bro 😁....sorry rigel for wrong code....i will be working it on soon. its 3:00am here ..........time to sleep
22nd Jan 2018, 9:31 PM
adnan
adnan - avatar
+ 5
rafal what you are saying is wrong bro . you have to set the initializer value to zero and sum+=(i*i). will give you garbage value and not the sum and square of entered number
22nd Jan 2018, 8:02 PM
adnan
adnan - avatar
+ 4
@adnan Thank you alot bro really Helped😊
22nd Jan 2018, 8:13 PM
RiGeL
RiGeL - avatar
+ 4
@Gaurav Agrawal thank you alot
22nd Jan 2018, 8:14 PM
RiGeL
RiGeL - avatar
+ 2
@Ipang thank you a bunch
23rd Jan 2018, 9:29 PM
RiGeL
RiGeL - avatar