In: Computer Science
Write a java program that adds up the squares and adds up the cubes of integers from 1 to N, where N is entered by the user:
Upper Limit:
5
The sum of Squares is 55
The sum of Cubes is 225
Do this by using just one loop that generates the integers. DO NOT USE ANY FORMULAS.
All the explanations is given in the comments of the code itself.
Code--
import java.util.*;
public class Program
{
public static void main(String[] args)
{
Scanner sc=new
Scanner(System.in);
int n;
//prompt the user to enter the
upper limit
System.out.println("Upper
Limit:");
n=sc.nextInt();
int sumSq,sumCube;
sumSq=0;
sumCube=0;
//use one for loop to generate the
answer
for(int i=1;i<=n;i++)
{
sumSq=sumSq+(i*i);
sumCube=sumCube+(i*i*i);
}
//display the output
System.out.println("The sum of
Squares is "+sumSq);
System.out.println("The sum of
Cubes is "+sumCube);
}
}
Code Screenshot--
Output Screenshot--
Note--
Please upvote if you like the effort.