Search code examples
cloopssumgenerate

How can I add a + as a String using C Language?


I am trying to generate numbers from 1-5 using for loop and display their sum. I am aiming to have an output that looks like this:

1 + 2 + 3 + 4 + 5 = 15

But instead, I get the output:

+ 1 + 2 + 3 + 4 + 5 = 15

    #include <stdio.h>

    void main()
    {   
        int a, sum = 0;
        for (a = 1; a <= 5; a++) 
        { 
            printf("+\t%d\t",a);
            sum = sum + a;
        }
        printf("=\t%d", sum);       
    }

Solution

  • This is encountered very frequently whenever outputting lists separated by some value. The problem is that you have 5 values to output, but only 4 separators. If you don't do anything special, then you will output 5 separators which is exactly what's happening in your example. Even if you move the separator to after your value, you'll still have one too many.

    The way I prefer to do it is this:

    for (a = 1; a <= 5; ++a)
    {
        if (a > 1) printf("\t+\t");
        printf("%d", a);
        sum += a;
    }
    

    The reason I prefer this approach, versus outputting some value outside of the loop, is because often the thing you're outputting is more complicated, possibly involving additional calculation or function calls and I don't like duplicating that code.

    So, I only output a separator if I know that I'm about to output the other thing. That means, output a separator for every loop iteration except the first.

    I also like doing it prefix-style because usually the condition for the first item in a loop is simpler than the condition for the last item. It's also compatible with a different approach involving a flag:

    int first = 1;
    for (a = 1; a <= 5; ++a)
    {
        if (!first) printf("\t+\t");
        first = 0;
        printf("%d", a);
        sum += a;
    }
    

    There are many other ways you'll see this kind of pattern occur. And there may be various forms of optimizing it that reduce readability. But this approach is simple and easy to follow.