Page 90 - iprime_V2.2_class8
P. 90
WRITING SOME MORE PROGRAMS
Till now, we have learned conditional, loop, and jump statements of Java. We have also created
related programs in Java. Let us now create some additional programs.
Program 1: Write a Java program to print all the even numbers between 1 and N by using the
'while' loop. The value of N should be taken from the user as input.
public class Program1
{
public static void main(int N)
{
int i = 1;
System.out.println("Even numbers between 1 to "+ N+ " are:");
while (i <= N)
{
if(i%2==0)
{
System.out.println(i);
}
i++;
}
}
}
In the preceding program, we need to provide the value
of variable N from runtime.
Output
Program 2: Write a Java program to print the sum of all the odd numbers up to 10 by using the
'for' loop.
public class Program2
{
public static void main(String args[])
{
int i, sum=0;
for(i=1; i<=10; i++)
{
if(i%2 != 0)
{
sum+=i;
}
}
System.out.println("The sum of all the odd numbers up to 10 is: " + sum);
}
}
88 iPRIME (Ver. 2.2)–VIII

