You are on page 1of 11

3.

5 C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possible values of a single variable called switch
variable. Here, We can define various statements in the multiple cases for the different values
of a single variable.

Syntax of the Switch Statement in C Programming Language.


switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
//code to be executed if all cases are not matched;
}

The expression in the syntax can be Arithmetic, Relational or Logical expression. Still, the
condition is that the programmer should provide an expression that always returns a single
value as its result, and the result should not be a float or double. The values defined in the
case statements should always be constants; you can't use a variable with a case statement.
The break and the default statements are both optional. The function that both the
statements perform and their need is explained in the later section: Working of the Switch
statement in C programming language.
Flowchart Representing the Working of the Switch Statement in C:

This flowchart given above explains the working of a definitive Switch statement of the C
programming language.

The compiler first evaluates the given expression and compares the result with the value
defined within each case statement sequentially, starting from the top to the bottom. If the
result does not match the value defined in the case statement, the compiler will check
whether the result matches the value defined in the following case statement.

On the other hand, if The Compiler will transfer both the values match, the control to the line
next to that case statement. If the case statement is terminated with a break statement, the
control will jump out of the switch statement. And, when none of the case statements gets
executed, the statements defined within the default statements get executed.

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known
as fall through the state of C switch statement.

Switch Statement in C Example

write a simple C program to mirror the basic functionalities of a simple calculator that takes
two integers, performs the requested operation, and displays the output.

#include <stdio.h>
int main()
{
int choice;
printf("Select an option from the list below:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Modulus\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
int a, b;
// read two numbers
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
switch (choice)
{
case 1:
printf("%d + %d = %d\n", a, b, a + b);
break;
case 2:
printf("%d - %d = %d\n", a, b, a - b);
break;
case 3:
printf("%d * %d = %d\n", a, b, a * b);
break;
case 4:
printf("%d / %d = %d\n", a, b, a / b);
break;
case 5:
printf("%d %% %d = %d\n", a, b, a % b);
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}

The above Program will get the choice from the user as an integer input, then read two
numbers also from the user, perform the requested operation and print the output back to the
user.

The Program uses a switch statement to perform the decision-making. At the end of each case
label, the break statement makes sure the control transfers out of the switch statement and
does not execute the other statements sequentially.

The default statement does not have a break statement cause the control will automatically
get out of the switch statement after the last line.

Input:
3
54
Output:
5 * 4 = 20
3.6 Ternary Operator in C
Ternary Operator in C is an operator which takes three operands or variables, unlike the other
operators which take one or two operands. Ternary operator in C is also known as the
Conditional Operator. It is a way to shorten the simple if-else code of the block.

What is a Ternary Operator in C

Using the Ternary operator in c is a way to shorten the if-else code block in C/C++. So before
you move further in this article, please go through the C if-else statement. (if you are a
beginner).

Ternary Operator in C takes three arguments:

1. The first argument in the Ternary Operator in C is the comparison condition.


2. The second argument in the Ternary Operator in C is the result if the condition is true.
3. The third argument in the Ternary Operator in C is the result if the condition is false.

So, according to the above three arguments in the ternary operator in c, we can say that the
Ternary operator in C allows us to execute different code depending on the first argument, i.e.
based on condition.

The symbol for the Ternary operator in C is ? :.

Syntax

exp1 ? exp2 : exp3

Working of Syntax:

 If the condition in the ternary operator is met (true), then the exp2 executes.
 If the condition is false, then the exp3 executes.

Example:

The following example explains the working of the Ternary Operator in C.

int mxNumber = 10 > 15 ? 10 : 15;

So, if the condition 10 > 15 is true (which is false in this case) mxNumber is initialized with the
value 10 otherwise with 15. As the condition is false so mxNumber will contain 15. This is how
Ternary Operator in C works.

Flow Chart for Ternary Operator in C


Let's understand this flow chart of Ternary Operator in C:-

Suppose we have taken a ternary operator statement exp1? exp2: exp3, if our exp1 met the
condition or yield result in true the control flows to exp2. Similarly, if exp1 gives a false result,
then our control goes to exp3.

Therefore, if the exp1, a condition that is true, then control flows to the True-
Expression otherwise, control goes to the False_Expression. And if there is any next statement,
the control goes to that statement, like in the above example variable mxNumber gets the
value 15.

Isn't it similar to the simple if-else code in C ? YES !! That's why the Ternary Operator in C is
also known as Conditional Operator as its works in the same way as if-else works in C.
Using Ternary Operator in C

This example demonstrates how to utilize the Ternary Operator in C.

#include<stdio.h>
#include<stdlib.h>

int main()
{
int num1, num2,mxNumber;
num1 = 100;
num2 = 20;

// result = condition ? exp1 : exp2;


// isn't the if-else block ? just in one line.

mxNumber = num1 >= num2 ? num1 : num2;

printf("Maximum Number from %d and %d is %d",num1,num2, mxNumber); //output


return 0;
}

Output:

Maximum Number from 100 and 20 is 100

In the above code, we write down the previous code if-else condition in the form of the
ternary operator in c. Using the ternary operator in C, we can easily shorten our code, which is
memory efficient also. The working of the above code is the same as the previous example
code. So it's totally up to you to either use a simple if-else block or Ternary Operator in c both
ways are correct but try to use the ternary operator because it looks neat and clean with a
memory-efficient advantage.
3.7 C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statement can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple loops
which can't be done by using a single break statement. However, using goto is avoided these
days since it makes the program less readable and complicated.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

Flow Diagram of goto Statement in C

As visible in the flow diagram, as soon as we arrive at the goto statement, the control of the
code is transferred to wherever the label has been defined.

In this case, the label has been defined below the goto statement. Hence, the statements
between the goto statement and the label declaration are skipped.
On the other hand, the label can also be declared before the goto statement. In this case, no
statement is skipped, instead, the statements between the goto statement and the label
declaration are repeated.

This has been shown in the image below.

How Does the goto Statement Work in C?

goto statement helps in transferring the execution of the program from one line to another.
That is why it is a jump statement, as it enables us to jump from one part of our program to
another.

This is done by using the goto statement and a label name as defined above in the syntax.
Whenever the compiler arrives at a goto statement, it transfers the execution of the program
from that line to the line where the label has been defined. Then the execution again starts
from that point. Another point to note is that the label can be defined before or after using
the goto statement, but it should be present in the code.

As it is clear, we jumped from one part of the code to another, hence goto is an unconditional
jump statement.
Example : To print numbers using the goto statement

#include <stdio.h>

int main()
{
// we will print numbers from start to end

// initialize start and end variables


int start = 1, end = 10;

// initialize variable to keep track of which number is to be printed


int curr = start;

// defining the label


print_line :

// print the current number


printf("%d ", curr);

if(curr<end)
{
// increment current
curr++;
// use goto to again repeat
goto print_line;
}

// if the current has reached the end, the statements inside if will not be executed
// the program terminates

return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

It is clear from this program that whenever curr is less than the end, we repeat the printing
part until curr becomes equal to the end. At that point, the condition inside if becomes false,
and the goto statement isn't executed.
This is exactly how a goto statement can create a loop in a program, without using for or while
loops. However, in most cases goto statements are used only for flow control, to dictate
where the control of the program should be transferred next.

You might also like