First Program calculates the sum using while loop
Second Program calculates the sum using for loop
Example 1: Program to find the sum of natural numbers using while loop
public class abc {
public static void main(String[] args) {
int num = 10, count = 1, total = 0;
while(count <= num)
{
total = total + count;
count++;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
--------------------------------------------------------------------------------------------------------------------------
Program to calculate the sum of natural numbers using for loop
public class abc {
public static void main(String[] args) {
int num = 10, count, tot = 0;
for(count = 1; count <= num; count++){
tot = tot + count;
}
System.out.println("Sum of first 10 natural numbers is: "+tot);
}
}
Second Program calculates the sum using for loop
Example 1: Program to find the sum of natural numbers using while loop
public class abc {
public static void main(String[] args) {
int num = 10, count = 1, total = 0;
while(count <= num)
{
total = total + count;
count++;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
--------------------------------------------------------------------------------------------------------------------------
Program to calculate the sum of natural numbers using for loop
public class abc {
public static void main(String[] args) {
int num = 10, count, tot = 0;
for(count = 1; count <= num; count++){
tot = tot + count;
}
System.out.println("Sum of first 10 natural numbers is: "+tot);
}
}
0 comments:
Post a Comment