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);
    }
}

6 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
  4. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  5. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete

ShareThis