### Conditional operator problem ?

Can u help me with the code below, idea is to sum the numbers in range of brKarika
lets say br Karika =4 and numbers are:
3 11 4 7
so
suma[1]=3+13
suma[2]=3+13+4
suma[3]=3+11+4+7

 ``123456789101112`` ``````int brKarika; cout << "Unesi broj karika u pronadenom lancu" << endl; cin >> brKarika; vector suma; suma.resize(brKarika); for (int i=0; i> karika; suma[i] = (i == 0) ? karika : suma[i-1] + karika; // kumulativno zbrajamo cvrstoce }``````

suma[i] = (i == 0) -> this part is confusing me, can somebody explain it to me
for karika values inputed we check if value suma of indx i is equal to ??, cuz i==0 wil return true in first step, but suma[0] can be any number, help needed please guys.

Last edited on
 suma[i] = (i == 0) -> this part is confusing me, can somebody explain it to me

It's the ternary operator. Google "C++ ternary operator" for information.
It is the conditional operator, the ternary operator in C++. It has the general form of:
 (test-expression)?(expression-2):(expression-3)

If test-expression is true, then expression-2 is executed and if it is false, expression-3 is executed.

Example:
 ``12345`` ``````. . int x = 3; (x > 3)?(cout << "Hello";):(cout << "Goodbye";);``````

The output the of the following would be:
 ``` Goodbye ```

Hope that helped.
ok then in my case test expression is suma[i]=(i==0)
i still dont understand expression?? that is why i asked in first place, i get how conditional operator works, but dont get how this expression does?
 in my case test expression is suma[i]=(i==0)
Not exactly. The expression being tested is just `(i==0)`

This line:
 `` `` `` suma[i] = (i == 0) ? karika : suma[i-1] + karika;``

can be re-written like this:
 ``1234`` `````` if (i == 0) suma[i] = karika; else suma[i] = suma[i-1] + karika;``````

Please see "Conditional operator ( ? )" here:
http://www.cplusplus.com/doc/tutorial/operators/
Last edited on
that is what i wanted to know, i've checked the link and my mind started to understand :)
after that i returned here and saw your post with the same link :)

cuz actually i will stick to writing if conditions, sometimes conditional operotor and it sintax confuses me

tnx a lot man .
have a nice day
Topic archived. No new replies allowed.