+ 1
Find the sum of odd number between two number by for loop
22 Respostas
+ 13
Isn't this what you want?
https://code.sololearn.com/cHWeT00hGe1d
+ 14
int x = 0, y = 0;
int sum = 0;
cout << "Enter 1st num:"; cin >> x;
cout << "Enter 2nd num:"; cin >> y;
for (int i = x; i <= y; ++i){
if (i % 2 != 0) {
cout << i << endl;
sum += i;
}
}
cout << endl << sum;
+ 11
I've optimized the code with both approaches. Baptiste's is a bit tricky but I guess it works faster. Thanks again
+ 10
Let's add Mr.JPM7's 2nd approach real quick! ;)
+ 10
Sorry dear JPM7
When I ran it with x = 12 and y = 15 it gave me 32 rather than 28. Would u mind to check it please? I guess I've done sth wrong.
+ 10
To clarify the Baptiste's proposed code mechanism for asker I summarize it in this way:
for(unsigned i = x + !(x&1); i <= y; i +=2)
The tricky part obviously is,
i = x + !(x & 1)
So, how does it work?
Suppose you enter an even number as x value. You want to for loop starts its job from the first odd number. For achieving that goal you have a variety of options in front of you (like Mr. JPM7's first approach). In this case, Baptiste used a low-level approach by using bitwise AND operator. Inside of the parenthesis, the binary value of x being ANDed with 1 (You probably ask why 1). Let's see what's going to happen behind the scene.
x = 12;
12 -> to binary -> 1100
Now for x & 1 you would have,
1100
& 0001
-----------
0000 = 0
That means, if you had an even number for x, inside the parenthesis you will have 0. For next step,
i = 12 + ! (0)
Negating 0 gives you 1.
i = 12 + 1
i = 13
As you see by doing that you will get your first odd number.
On the other hand, if you feed x with an odd number the process will go in this way:
x = 13
13 -> to binary -> 1101
1101
& 0001
-------------
0001 = 1
i = 13 + ! (1)
i = 13 + 0
i = 13
+ 8
Our party now completed with Schindlabua!
That's a great craft dear. ;)
+ 8
Yes sir. There are so many gotchas in C++ in fact. Thanks again.
+ 3
babak sheykhan Bhai tumne Jo program bataya hai usse to sirf odd number print honge unka sum nahi
+ 3
@Parinay , I think that the program is correct. it will display all odd numbers but also its sum at last. please check it.
+ 3
Bhai ye program nahi chal raha
+ 3
@Parinay ye theek se kaam kr rha hai. jis do number ke beech ka sum chahiye aap use input section me likhe phir enter type kar doosra number usee jagah likhee.
+ 2
@Babak you're welcome!!!
+ 2
why going through even numbers when we only needs odd ones ;)
unsigned sum = 0;
for(unsigned i = x + !(x&1); i <= y; i +=2)
sum += i;
+ 2
You can even do it with zero loops:
https://code.sololearn.com/W1cafFPUlQlt/#js
+ 1
thank you Bhai ho Gaya run
+ 1
Bhai can you tell me what is this sum+=i;
+ 1
@Parinay sum+=i is equivalent to sum=sum+i
+ 1
ok
+ 1
In JPM solution, exchange i+=2 and sum += i