Please help me to write the code for problem 2, make sure it work Problem 2: The
ID: 3794461 • Letter: P
Question
Please help me to write the code for problem 2, make sure it work
Problem 2: The following code is an example of a FOR loop. The function finds the sum from 1 + 2 + 3 + … x, where x is the input value. Paste the code below into Excel and modify the code so that it instead it adds 12 + 22 + 32 + … x2. Extra credit: Have it check to make sure that x is a positive integer before it does the loop, and tell the user that the input is invalid. Paste your updated code here.
Function LoopSum(x)
'this function takes a positive integer input and finds the sum from 1 to that positive integer 'for example, for input x = 5, the output will be 1+2+3+4+5, that is it will output the number 15.
LoopSum = 0 'start the output variable with a value of 0
For k = 1 To x
LoopSum = LoopSum + k 'each time it goes through the for loop, it adds the current value of k
Next k
End Function
Explanation / Answer
import java.util.*;
public class allmain {
public static void main(String[] args) {
int sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter no of elements you would like to sum:");
int input=sc.nextInt();
for(int i=0;i<input;i++){
System.out.println("enter value :"+(i+1));
int element=sc.nextInt();
if(element>=0)
sum+=element;
else{
System.out.println("invalid number:" );
return;
}
}
System.out.println("the sum for given elements are:"+sum);
}
}
output:
enter no of elements you would like to sum:
4
enter value :1
1
enter value :2
2
enter value :3
1
enter value :4
5
the sum for given elements are:9
output if negitive number given:
enter no of elements you would like to sum:
3
enter value :1
2
enter value :2
-3
invalid number: