Java program to find a sum of digits, odd, even, prime, and natural numbers
There are different ways to sun of numbers in Java.
Input: 7
output: 28
output: 28
Code in Java:
import java.util.Scanner;
public class SumOfFirstNNaturalNumers
{
public static void main(String[] args)
{
Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the N: ");
int N=scan.nextInt();
int sum=0;
for(int i=1; i<=N; i++)
{
sum=sum+i;
}
System.out.println("Sum of First "+ N +" Natural Numbers: ");
System.out.println("="+sum);
}
}
Output:
Enter the N:
10
Sum of First 10 Natural Numbers:
=55
Input: 5 to 15
output: 110
output: 110
Code in Java:
import java.util.Scanner;
public class SumOfNaturalNumbersFromGivenRange
{
public static void main(String[] args)
{
Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the starting number: ");
int n1=scan.nextInt();
System.out.println("Enter the end number: ");
int n2=scan.nextInt();
int sum=0;
for(int i=n1; i<=n2; i++)
{
sum=sum+i;
}
System.out.println(sum);
}
}
Output:
Enter the starting number:
11
Enter the end number:
20
155
Input: 10 to 20
output: 90
Code in Java:
import java.util.Scanner;
public class SumOfEvenNumbers
{
public static void main(String[] args)
{
Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the starting number: ");
int n1=scan.nextInt();
System.out.println("Enter the end number: ");
int n2=scan.nextInt();
int sum=0;
for(int i=n1; i<=n2; i++)
{
if(i%2==0)
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println("Sum of Even Numbers from given range: ");
System.out.println("= "+sum);
}
}
Output:
Enter the starting number:
1
Enter the end number:
10
2
4
6
8
10
Sum of Even Numbers from given range:
= 30
Input: 2461
output: 13
Code in Java:
import java.util.Scanner;
public class SumOfDigitsOfNumber
{
public static void main(String[] args)
{
Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the N: ");
int N=scan.nextInt();
int reminder,sum=0;
while(N>0)
{
reminder=N%10;
sum=sum+reminder;
N=N/10;
}
System.out.println("Sum of Digits: "+sum);
}
}
Output:
Enter the N:
456789
Sum of Digits: 39
Input: 5 to 22
output: 117
output: 117
Code in Java:
import java.util.Scanner;
public class SumOfOddNumbers
{
public static void main(String[] args)
{
Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the starting number: ");
int n1=scan.nextInt();
System.out.println("Enter the end number: ");
int n2=scan.nextInt();
int sum=0;
for(int i=n1; i<=n2; i++)
{
if(i%2!=0)
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println("Sum of Odd Numbers from given range: ");
System.out.println("= "+sum);
}
}
Output:
Enter the starting number:
20
Enter the end number:
30
21
23
25
27
29
Sum of Odd Numbers from given range:
= 125
No comments:
Post a Comment
If you have any doubts, please let me know