How to write a c program to find the sum of all the triangler numbers between 1-100 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to write a c program to find the sum of all the triangler numbers between 1-100

5th Jul 2020, 5:29 AM
narthana wickramasinghe
narthana wickramasinghe - avatar
6 Answers
0
Do you mean "triangular" numbers as follows: 1 + 2 + 3 + ........+ 100 If yes, you have to compute the Formula: n * (n + 1) / 2. for example you define a function that returns that value. int triang(int num) { return num * (num + 1) / 2; } After that you use it in main: int main() { int n; printf("Enter a number: \n"); scanf("%d", &n); printf("Result = %d", triang(n)); return 0; } You can also use a for loop in the function as follows: int sum = 1 for (int n = 1; n <= 100; n++) { sum += n; return sum; } If you do not mean "triangular". Please explain!
5th Jul 2020, 5:59 AM
yyy
0
No this is the correct way
5th Jul 2020, 6:21 AM
narthana wickramasinghe
narthana wickramasinghe - avatar
0
This code dont give the summation
5th Jul 2020, 8:54 AM
narthana wickramasinghe
narthana wickramasinghe - avatar
0
Of course that code gives the summation!!! I do not post something without checking it!!!! You have to include <stdio.h>!!!! -------------------------------------------------- #include <stdio.h> int triang(int num) { return num * (num + 1) / 2; } After that you use it in main: int main() { int n; printf("Enter a number: \n"); scanf("%d", &n); printf("Result = %d", triang(n)); return 0; }
5th Jul 2020, 11:07 AM
yyy
0
I will try again
5th Jul 2020, 11:49 AM
narthana wickramasinghe
narthana wickramasinghe - avatar
0
Thank you for your anwser I had to add some little adjustment to it
5th Jul 2020, 3:16 PM
narthana wickramasinghe
narthana wickramasinghe - avatar