Write a program it adds up all the numbers from 1 up to whatever numbers input ,then summing the answer in output. Like if we put 6 input then check answer output is 21 0+1+2+3+4+5+6 use factorial In Java use JFrame please .
Write a program it adds up all the numbers from 1 up to whatever numbers input ,then summing the answer in output. Like if we put 6 input then check answer output is 21
0+1+2+3+4+5+6
use factorial
In Java use JFrame please .
Code:
import java.util.Scanner;
import java.io.*;
class Sumofdigit {
static int sumOfDigitsFrom1ToN(int n)
{
int result = 0;
for (int x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
static int sumOfDigits(int x)
{
int sum = 0;
while (x != 0)
{
sum += x % 10;
x = x / 10;
}
return sum;
}
public static void main(String args[])
{
Scanner num = new Scanner(System.in);
System.out.print("Please enter a number to calculate sum of digits = ");
int n = num.nextInt();
System.out.println("Sum of digits in numbers"
+" from 1 to " + n + " is = "
+ sumOfDigitsFrom1ToN(n));
}
}
Step by step
Solved in 2 steps with 3 images