Example: Write a Java Program to sum all numbers from 1 to 10 using a while loop.
public class Main
{
public static void main(String[] args) {
int i = 1, sum = 0;
while(i <= 10) {
sum = sum + i;
//increment value of i for next iteration
i++;
}
System.out.println("Sum: "+sum);
}
}
Output:
Sum: 55
Example: Write a Java Program to print all-natural numbers from 1 to 10 using a while loop.
public class Main
{
public static void main(String[] args) {
int i = 1;
while(i <= 10) {
System.out.print(i+" ");
i++;
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10

Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.
No comments
Post a Comment