Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+ 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading