Go to Top

Saturday, 1 October 2011

To print and find the sum of a given series

Question 46 : S = 1 + 12 + 123 + 1234 + ..... + n terms.

Print and find sum of the series.

Java Program : 

class series_2
{
 int n,sum=1;
 series_2(int a)
 {
     n=a;
     cal();
    }
    void cal()
    {
        int s=1;
        System.out.print("The series : 1+");
        for(int i=2;i<=n;i++)
        {
            s=(s*10)+i;
            sum=sum+s;
            if(i==n)
            {
                System.out.print(s);
                break;
            }
            System.out.print(s+"+");
        }
        System.out.print("\nSum of the series : "+sum);
    }
}

4 comments:

  1. this might work better:
    class asn25b
    {
    public static void main(int n)
    {
    int sum=1;
    int s=1;
    for(int i=2;i<=n;i++)
    {
    s=(s*10)+i;
    sum=sum+s;
    if(i==n)
    {
    break;
    }
    }
    System.out.println("Sum of the series : "+sum);
    }
    }

    ReplyDelete
  2. class SumSeries
    {
    void main(int n)
    {
    int i;long a=0,s=0;
    for(i=1;i<=n;i++)
    {
    a=10*a+i;
    s+=a;
    }
    System.out.println("The Required Output = \t\t"+s);
    }
    }

    ReplyDelete
  3. how to do this program using for loop

    ReplyDelete

ShareThis