### Thread: Im having a problem understanding this c program:

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
8
Rep Power
0

#### Im having a problem understanding this c program:

Can someone explain me the meaning of the coding in line 9?

1 #include <stdio.h>
2
3 int main()
4 {
5 int a, b = 0;
6 int c[10] = {1,2,3,4,5,6,7,8,9,0};
7
8 for(a=0; a<10; ++a)
9 b += (c[a]%2 == 0) ? c[a] : 0;
10
11 printf("%d\n", b);
12 return 0;
13 getch();
14 }
2. Code:
`b += (c[a]%2 == 0) ? c[a] : 0;`
can also be expressed as
Code:
```if (c[a]%2 == 0)
b = b + c[a];
else
b = b + 0;```
Regards,
Dariyoosh

• eramit2010 agrees
• clifford agrees : ... but the else clause is entirely redundant.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
8
Rep Power
0
Thank You very much Dariyoosh :)

http://en.wikipedia.org/wiki/%3F:

Regards,
Dariyoosh
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
8
Rep Power
0
Dariyoosh, it was not really helpful about the syntax of the if statement. If you have another link about the syntax used in line 9 of my program, please share :)
6. Then you have to specify what is exactly your question.

Do you need the syntax of the if statement or the ternary operator which as I understand the line n°9 of your code is about.

Regards,
Dariyoosh
7. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
8
Rep Power
0
I am still a beginner in c programming. The statement in line 9 is called a ternary operator. I'll keep that in mind ;)
can you give me a good source of information on the ternary operator?
8. I don't know what do you need to know more about that, the example that I gave you and in particularly the link that I provided explain the topic.

http://www.teach-me-c.com/blog/c-ternary-operator

Regards,
Dariyoosh
9. Another one (it's for Java but doesn't change the meaning :) )

The ternary operator "?:" earns its name because it's the only operator to take three operands. It is a conditional operator that provides a shorter syntax for the if..then..else statement. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned:

boolean expression ? value1 : value2

Regards,
Dariyoosh
10. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
8
Rep Power
0