Alok Y - 13 days ago 12

C Question

I'm trying to write a program in C which calculates any number of triangular numbers. Below is the code.

`printf("How many triangular numbers you want?\n");`

int number = GetInt();

for (int count = 1; count <= number; count++)

{

int triangularnumber = 0;

for (int n = 1; n <= number; n++)

{

triangularnumber += n;

printf("Triangular number %i is %i\n", n, triangularnumber);

}

}

Suppose I want to calculate the first two triangular numbers, I'm getting the output as follows.

`Triangular number 1 is 1`

Triangular number 2 is 3

Triangular number 1 is 1

Triangular number 2 is 3

As you can see its getting repeated. How do I fix this?

Answer

Change the inner part to this:

```
int triangularnumber = 0;
for (int n = 1; n <= count; n++)
{
triangularnumber += n;
}
printf("Triangular number %i is %i\n", count, triangularnumber);
```

The print was repeated because it was in the inner for loop and also the inner for loop would always calculate the nth-triangular number because you only stopped at the input number.

Your program is not really efficient like this, so maybe think about improvements (hint: only one for loop).

Source (Stackoverflow)

Comments