0
can anyone tell me how to code this excercise
Create a program that calculates the sum 1+2+3+…+n where n is a number entered by the user. can anyone code this excercise by using while loop
3 odpowiedzi
+ 3
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int i = 1;
int sum = 0;
while(i <= n){
if(i < n){
System.out.print(i + " + ");
}else{
System.out.print(i + " = ");
}
sum += i;
i++;
}
System.out.print(sum);
}
}
+ 2
int n = 5; //scanner input
int sum = 0;
int i = 1;
while(i <= n) {
System.out.print(sum + " + " + i + " = ");
sum += i;
System.out.println(sum);
i++;
}
0
imagine result for n=5000
int n = 5000; //here use input from Scanner()
int sum=0, i=0;
while(++i <= n) {
sum += i;
}
System.out.println("sum of numbers (from 0 to "+n+") = "+sum);