Is this logic wrong? Q - Wap to add up all odd integers till 15. P.S - New to programming and this is my first language | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is this logic wrong? Q - Wap to add up all odd integers till 15. P.S - New to programming and this is my first language

int i; int sum; for (i = 1; i<=15; i+=2) { cout<<i; sum = sum + i } cout<<"The sum of odd integers are:" << sum;

23rd Oct 2019, 3:50 PM
Dipanjan Basu
Dipanjan Basu - avatar
3 Answers
+ 5
All code is OK except for one thing, you declared variable 'sum' but didn't initialized it. So 'sum' could have some garbage value like 1, -9, 15, etc (it can be any value). So it's good practice to initialize variables at the time of their declaration. Assign 0 to sum before loop sum = 0; Or initialize it when declaring int sum = 0; Other than that, everything is fine
23rd Oct 2019, 4:05 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 4
Looks OK if you add a semicolon after the incrementation step. Did you run the code?
23rd Oct 2019, 3:58 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
0
Yes I tried to run the code in dev c++ it showed errors. They solution had a different approach where they looped all the numbers till 15 naturally and then they used the if statement where used if (i%2! =0) as far I think the logic is the same just a different approach?
23rd Oct 2019, 4:03 PM
Dipanjan Basu
Dipanjan Basu - avatar