Computer Science, asked by Mister360, 11 days ago

Language :- JAVA

Program the first 10 odd number

Answers

Answered by BrainlyProgrammer
12

Question:-

  • Program the first 10 odd numbers
  • Java

Answer:-

1st Approach:-

//Java program to print the first 10 odd numbers

package Programmer ; // Optional statement, no need to write this Statement

public class OddPrint {

public static void main (String ar []) {

int a=1;

for (int I=1;I<=10;I++,a+=2)

System.out.println(a);

}

}

2nd Approach(Shortest):-

//Java program to print first 10 odd numbers

package Programmer; // Optional statement, no need to write this Statement

public class OddPrint {

public static void main (String ar []){

for(int I=1;I<=20;I+=2){

System.out.println(I);

}

}

}

Explaination of Approach 1:-

  • a is intialized to 1
  • The program runs a loop from 1 to 10
  • a is printed
  • Next loop.. I get updated with +1 and at the same time a is updated with +2
  • When I becomes 11, loop terminates and hence the program ends

Explaination of Approach 2:-

  • There is no difference in working but the only difference is that in this case the loop runs from 1 to 20 and is printed directly followed by updation with +2.
  • When I is 21, loop terminates and hence the program ends.

_

Output Attached.

_

Attachments:
Similar questions