Write a program in java to find the sum of all natural numbers from 10 to 25 using the formula.
(n*(n+1))/2
Please give the correct answer or else you will be reported multiple times.
Answers
Answer:
Java Program to find Sum of Natural Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
The positive integers 1, 2, 3, 4 etc. are known as natural numbers. Here we will see three programs to calculate and display the sum of natural numbers.
First Program calculates the sum using while loop
Second Program calculates the sum using for loop
Third Program takes the value of n(entered by user) and calculates the sum of n natural numbers
To understand these programs you should be familiar with the following concepts of Core Java Tutorial:
Java For loop
Java While loop
Example 1: Program to find the sum of natural numbers using while loop
public class Demo {
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);
}
}
Output:
Sum of first 10 natural numbers is: 55
Example 2: Program to calculate the sum of natural numbers using for loop
public class Demo {
public static void main(String[] args) {
int num = 10, count, total = 0;
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
Example 3: Program to find sum of first n (entered by user) natural numbers
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num, count, total = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}
Output:
Enter the value of n:
20
Sum of first 20 natural numbers is: 210
Enjoyed this post? Try these related posts
Java Program to find largest of three numbers using Ternary Operator
Java Program to Perform Arithmetic operation using Method Overloading
Java Program to Count Vowels and Consonants in a String
Java program to find the occurrence of a character in a string
Java Program to check Vowel or Consonant using Switch Case
java program to find factorial of a given number using recursion
Explanation:
Answer:
public class Demo {
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);
}
}
Output:
Sum of first 10 natural numbers is: 55
please follow me and mark my answer as Brainliest
this is correct answer