Q 1 : Write a program to print sum of following series of given terms ?
Terms=5Series = (1)+(1+2)+(1+2+3)+(1+2+3+4) + (1+2+3+4+5)
Sum=35
Solution :
Using Nested Loop
import java.util.*;
class nextedloop
{
public static void main(String args [])
{
int term,result=0,j,tsum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter terms");
term=sc.nextInt();
for(int i=1;i<=term;i++)
{
for(j=1,tsum=0;j<=i;j++)
tsum+=j;
result+=tsum;
}
System.out.print("\nResult="+result);
}
}
Using function
import java.util.*;
class P10
{
static int sumDigit(int n)
{
int m,sum;
for(m=1,sum=0;m<=n;m++)
sum+=m;
return sum;
}
public static void main(String args [])
{
int term,result=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter terms");
term=sc.nextInt();
for(int i=1;i<=term;i++)
result+=sumDigit(i);
System.out.println("\nResult="+result);
}
}
No comments:
Post a Comment