How to output all the odd and even numbers using a for loop? If someone has already entered two integers.
How to output all the odd and even numbers using a for loop?
more info needed. what are the entered integers for?
as for odd and even numbers, if ( number [remainder operator] 2 = 0 ) then its even number, else its odd.
Reply:use 'mod' for VB
use '%' for C
example
5%2 = returns 1 (set this as ODD)
4%2 = returns 0 (set this as even)
Reply:Use modulos (aka do a mod 2)
Something like (pseudo-code)
intFirst = [user input]
intSecond = [user input]
for i in intfirst to intSecond:
if(i%2 == 0) then
print i+" is an even number"
else
print i+" is an odd number"
end if
in Ruby
intFirst = gets.strip.to_i #ask for input, strip whitespace, convert to integer
intSecond = gest.strip.to_i
#loop through the range and test mod 2
for i in intFirst...IntSecond do
if(i%2 == 0) then
puts i.to_s+" is an even number"
else
puts i.to_s+" is an odd number"
end #end of the if statement
end #end of the for loop
Reply:for x = all odd values in range low to high
print x
for x = all even values in range low to high
print x
Get the remainder of the result of value / 2
If it is 1, value is odd else it is even.
in 'C'
int odd(int x)
{
return (x % 2) ? x : x + 1; // returns an odd value
}
int even(int x)
{
return (x % 2) ? x + 1 : x; // returns an even value
}
int main()
{
int i, x, y;
... code to get two integers into x, y omitted.
for (i = odd(x); i %26lt; odd(y); i += 2)
printf("%d\n", i);
for (i = even(x); i %26lt; even(y); i += 2)
printf("%d\n", i);
return 0;
}
visualarts
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment