简体   繁体   中英

Triangle number program in C language?

I want to make a simple triangle number program 1, 3, 6, 10,... that is no more than 100 ,I already made it. but there is little problem

lets take a look at my code:

#include <stdio.h>

int main (void){
    int j=1 , k=1 , i=100 , status;

    while (k <= i){
        j = j + 1;
        k = k + j;
        while ( k < 100){

        printf (" %d\n",k);
        status = 1;
        break;
    }
    }
    if (status == 1){
    printf ("DONE!");
    }
}

output:

3
6
10
15
21
28
36
45
55
66
78
91
DONE !

From here, I have some problem:

  1. I use two While Command,because when I only use one While the output will be bigger than 100 it will be 105 . So there is a way to simplify this by using one while command?
  2. The Output does not start with number 1 , i want to make the program outputting like this:
1
3
6
10
15
21
28
36
45
55
66
78
91
DONE !

but in the end, The output always start with number 3 ?

Your approach is far too complicated. You only need one loop, a running sum and a variable to hold the next value to be added to sum.

Start the running sum at zero, then add 1 and print the sum, then add 2 and print the sum, then add 3 and print the sum... keep doing that until the sum gets above 100.

Like:

#include <stdio.h>

int main(void) {
    int sum = 0;
    int nextToAdd= 1;
    while(1)
    {
        sum += nextToAdd;
        ++nextToAdd;
        if (sum > 100) break;
        printf("%d\n", sum);
    }
    return 0;
}

or if you prefer do-while

#include <stdio.h>

int main(void) {
    int sum = 1;
    int nextToAdd = 1;
    do
    {
        printf("%d\n", sum);
        ++nextToAdd;
        sum += nextToAdd;
    } while(sum <= 100);
    return 0;
}

or if you prefer a for-loop

#include <stdio.h>

int main(void) {
    int sum = 1;
    for (int nextToAdd = 2; sum <= 100; ++nextToAdd)
    {
        printf("%d\n", sum);
        sum += nextToAdd;
    }
    return 0;
}

when you use only one while, when k=91 so k<=100 and the condition of while is true and so you will enter while and k will become 105 and you will print it. so you need one if before printf to check if(k<100) .

also here if you initialized k=0 and replace k+=j and with j++ you will also print 1 .

look:

int main()
{
    int k = 1, j = 2, i = 100;
    while (k <= i) {
        printf("%d\n", k);
        k += j;
        j++;
    }
    printf("DONE!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM