Computer Science, asked by kanwermanju06, 1 month ago

WAP a program to print all odd numbers from 30 to 50 in reverse order.​

Answers

Answered by Ari114
0

please mark as a BRAINLIST

How can a program be written to print odd numbers from 1 to 50?

MacBook Pro.

It’s really a fairly trivial program. However, I’m going to make the answer annoyingly complex instead. I’m doing this as I assume you’re just doing this as an assignment and therefore should really more understand the logic of what you’re doing, rather than just the answer.

With this, and any coding challenge, you want to break it down to the base question. If I want to print all odd numbers, first I need to decide what an odd number is. Without that definition, the problem is unsolvable.

Luckily, in this case, Math provides the answer we need. We know that an odd number can be expressed in the format x=2n+1 , where n is any whole number. From this we can extrapolate through algebra that any odd number x, divided by 2, should have a remainder of 1.

For example, 5/2=2r1(2∗2=4+1=5)

In most, if not all programming languages, we can easily obtain the remainder using the modulus operand (in Java, it is %). So, you would be able to easily generate the following example (in Java):

public static void main(String[] args){

for(int x = 0; x <= 50; x++){

if(x%2==1){

System.out.println(x);

}

}

}// End naive solution

This is our basic algorithm and the initial run-through will look much like this. However, there’s a simpler way utilizing our same proof. If an odd number can be expressed by x=2n+1 , and knowing simply that 2∗n is the same as (2+2+2…) , so we have x=(2+2+2…)+1 . If we start our index at 1 and step by 2, we print only odd numbers by definition.

public static void main(String[] args){

// start at 1, step by 2

for(int x = 1; x <= 50; x+=2){

// no modulus needed.

System.out.println(x);

}

}

Hope that helps.

Similar questions