+ 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;
3 Respuestas
+ 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
+ 4
Looks OK if you add a semicolon after the incrementation step. Did you run the code?
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?