10. Write programs in java to find the sum of the following series
a) S = 1 +2²+3³+4⁴
pls answer it
Answers
Required Answer:-
Given Question:
- Write a program in Java to find the sum of the series. S = 1 + 2² + 3³ + 4⁴...n^n
Approach:
This is a very simple program. Read this post and get the answer.
Here comes the program.
package com.student;
import java.util.*;
public class SeriesSum
{
public static void main(String args[])
{
/*
* S = 1 + 2^2 + 3^3... N^N
* Question^^
* Answered by @AnindyaAdhikari
*/
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n - ");
int n=sc.nextInt();
double s = 0.0; //to store susum of the series.
for(int i=1;i<=n;i++)
s+=Math.pow(i, i);
System.out.print("Sum of the series is: "+s);
}
}
How it's solved?
At first, we will import Scanner class. Scanner class is present in utility package of Java. Now, we will create a class, main() method and objects of Scanner class. Now, we will take n as input from the user. The nextInt() method of scanner class is used to take an integer as input. Now, we will declare a variable s to store the sum of the series. Then, a loop is created that will iterate from i=1 to n. We will add each terms of the series inside the loop. (Sum = Sum + i^i). We can see that Math.pow() function is used here to calculate i raised to the power i. Each term of the series is added in this way. Time to print.
Variable Description:
- n (int):- To input the number of terms for the series sum.
- s (double):- To calculate and store the sum of the series.
- i (int):- Loop variables.
Output is attached.
![](https://hi-static.z-dn.net/files/d1b/8ef1ab84cefacb701e1afa60e439c27f.jpg)
![](https://hi-static.z-dn.net/files/da2/b2ba03a726c2226784b3c3d11052cc4a.jpg)
Series:-
1¹+2²+3³+....+n^n
Logic:-
s+=i*i
- where i is a loop variable
- variable s is for storing sum
Code:-
import java.util.*;
class Code
{
public static void main (String ar [])
{
Scanner sc= new Scanner (System.in);
System.out.println("Enter a limit");
int n=sc.nextInt();
int s=0;
for(int i=1;i<=n;i++)
s+=Math.pow(i,i); /*Or u can write s=i*i;
*loop ends
*/
System.out.println("Sum="+s);
}
}