0

Please explain how answer of this program is 297

#include <iostream> using namespace std; int main() { int s=0; int num1=7; int num=24; for(int i=1;num1<=num;i++) { if(i!=3){ } num1++; s=s+num1; } cout<<s; return 0; }

23rd Mar 2017, 5:12 PM
Nitish Kulkarni
Nitish Kulkarni - avatar
4 Answers
+ 7
Iteration 1 : num1 = 8 and s = s + 8 = 0 + 8 = 8 Iteration 2 : num1 = 9 and s = s + 9 = 8 + 9 = 17 .................. Last Iteration : num1 = 25 and .......... So, the result is nothing but the sum of numbers from 8 to 25 which is (sum from 1 to 25) - (sum from 1 to 7) which is (325) - (28) which is 297. I presume you know the formula for calculating sum of numbers from 1 to n which is (n)(n+1)/2.
23rd Mar 2017, 5:23 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 5
Yeah, a typo. It's corrected now.
23rd Mar 2017, 5:31 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
0
its (n)(n+1)/2 i think
23rd Mar 2017, 5:31 PM
Nitish Kulkarni
Nitish Kulkarni - avatar
0
we cant calculate sum of numbers from 8 to 25 by this formula.?
23rd Mar 2017, 5:39 PM
Nitish Kulkarni
Nitish Kulkarni - avatar