Use for loop to write a Java program to calculate the sum of all numbers from 1
ID: 670802 • Letter: U
Question
Use for loop to write a Java program to calculate the sum of all numbers from 1 to a given positive number inclusive. Name the class as Sum, declare a field as sum, initialize sum in the constructor, and name the method as sumOfNumbers. Display the result as string. Comments are required to explain the code. Maximum 10 points will be deducted if the comments are not included or not completed. Directly copy the source code and paste into your solution. Screenshot is required to show your running result.
also paste as a text it and provide me snapshot as mentioned thanks...
I need it for FOR LOOP.
Explanation / Answer
import java.io.Console;
import java.util.Scanner;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/** * * How to find sum of digits in Java */ public class SumOfDigits
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number to calculate sum of digits"); int number = sc.nextInt();
// Remember number/
10 reduces one digit from number
// and number%10 gives you last digit int sum = 0;
int input = number;
while (input != 0)
{
int lastdigit = input % 10;
sum += lastdigit;
input /= 10;
}
System.out.printf("Sum of digits of number %d is %d", number, sum);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.