Computer Science, asked by SƬᏗᏒᏇᏗƦƦᎥᎧƦ, 5 months ago

Only those who know should answer .
Spamming not allowed.

Attachments:

Answers

Answered by anindyaadhikari13
7

Required Answer:-

Question:

Design a class to print the sum of the following series.

S = 1 + 12 + 123 + .....1234567

Solution:

Here is the code. This is written in Java. It will calculate the sum of first 7 terms of the series.

public class SeriesSum {

public static void main(String[] args) {

int a=1,b=2,s=0;

for(int i=1;i<=7;i++)

{

s+=a;

a=a*10+b++;

}

System.out.println("Sum is: "+s);

}

}

Dry Run:

When i = 1:

a = 1

b = 2

s = 0 + 1 = 1

Now,

a = 1 × 10 + 2 = 12

b = 3

When i = 2:

a = 12

b = 3

s = 1 + 12

Now,

a = 12 × 10 + 3 = 123

b = 4

When i = 3:

a = 1234

b = 5

s = 1 + 12 + 123

Now,

a = 123 × 10 + 4 = 1234

b = 5

When i = 4:

a = 1234

b = 5

s = 1 + 12 + 123 + 1234

Now,

a = 1234 × 10 + 5 = 12345

b = 6

When i =5:

a = 12345

b = 6

s = 1 + 12 + 123 + 1234 + 12345

Now,

a = 12345 × 10 + 6 = 123456

b = 7

When i = 6:

a = 123456

b = 7

s = 1 + 12 + 123 + 1234 + 12345 + 123456

Now,

a = 123456 × 10 + 7 = 1234567

b = 8

When i = 7:

a = 1234567

b = 8

s = 1 + 12 + 123 + 1234 + 12345 + 123456 + 1234567

In this way, the program calculates the sum of the series.

Output is attached for verification.

Attachments:
Similar questions