144k views
7 votes
As in previous prelabs, you can enter all the necessary Java code fragments into the DrJava Interactions pane. If you get an error, enter the corrected code. If you get really mixed up, you can reset the interactions pane and try again. Write a while loop that computes the sum of the first 10 positive integers. Write a for loop that computes the sum the first 10 positive integers. For each loop, you should use two variables. One that runs through the first 10 positive integers, and one that stores the result of the computation. To test your code, what is the sum of the first 10 positive integers

User Rajdeep D
by
3.7k points

1 Answer

6 votes

Answer:

public class Main{

public static void main(String[] args) {

//The While Loop

int i = 1;

int sum = 0;

while(i <=10){

sum+=i;

i++; }

System.out.println("Sum: "+sum);

//The for Loop

int summ = 0;

for(int j = 1;j<=10;j++){

summ+=j; }

System.out.println("Sum: "+summ); } }

Step-by-step explanation:

The while loop begins here

//The While Loop

This initializes the count variable i to 1

int i = 1;

This initializes sum to 0

int sum = 0;

This while iteration is repeated until the count variable i reaches 10

while(i <=10){

This calculates the sum

sum+=i;

This increments the count variable i by 1

i++; }

This prints the calculated sum

System.out.println("Sum: "+sum);

The for loop begins here

//The for Loop

This initializes sum to 0

int summ = 0;

This iterates 1 through 10

for(int j = 1;j<=10;j++){

This calculates the sum

summ+=j; }

This prints the calculated sum

System.out.println("Sum: "+summ); }

User ARA
by
3.2k points