Conditional Operator With Example || goto Statement With Example

Conditional Operator

The conditional operator evaluates a condition and returns one of two values based on the result of the condition. It is a simple decision-making structure.

Conditional Operator With Example || goto Statement With Example

It is very useful in the situation where one of two options is selected on the basis of a given condition. The conditional operator is also known as ternary operator.

Syntax

The syntax of conditiona:l operator is as follows:

condition ? expression 1  expressions 2

condition

The condition is specified as relational or logical expression. The condition is evaluated to true or false.

expression 1

It is executed if expression evaluates to true.

expression 2

It is executed if expression evaluates to false.

Example

Suppose we have a variable A. The following statement will assign 1 to X if the condition A>50 is true. It will assign 0 to X the condition is false.

X=(A>50)?1:0

The above statement can be written using if else statement as follows:

if (A>50)

X=1;

 else

X=0

'goto' Statement

The 'goto' statement is used to move the control directly to a particular location of the program by using label. A label is a name given to a particular line of the program. A label is created with a valid identifier followed by a colon (:).

Syntax

goto Label;

The Label indicates the lable to which the control is transferred.

How above Program Works?

The above program uses goto statement to repeat a statement The if statement checks the value of n. If the value is 5 or less, the control moves back to the loop label. In this way, the required message appears five times.

Different between if-else-if and switch statement

if-else-if

if-else-if statement can test for equality and for logical expression.

Switch

switch statement can only test for the equality.

It uses multiple expressions for multiple choices.

It uses single expression for multiple choices.

It can check a range of values.

It cannot check a range of values.

It is less compact than switch.

It is more compact than if...else...if

It can evaluate int, float and other data types.

It can only evaluate character or integers.

Post a Comment

1 Comments