What are Control StatementsSince program are a sequence of statements that are executed linearly one after another. Sometimes we need to change the normal program's flow and here control statements comes in action.
Control statements are statements that are intended to change the normal program's flow.
To understand better lets take an example: Suppose we are travelling from city A to city B. There can be two approaches used to travel from A to B:
- First approach(Uses normal program flow) will travel until he finds any obstacle(Road block). In case of any road blocks it terminates the travel program.
- The second approach(Uses control statements) will travel until he finds any obstacle(Road block). If he finds any road blocks it checks for an alternate path. If an alternate path is available then selects the alternate path to city B else terminates the travel program.
There are basically three types of control statements:
Conditional statements:Conditional statements are also called as true one or more statements are executed. They are most commonly used statements in programming. And if any consequence occurs in programming to run any condition based statement(Statements that requires some condition to be fulfilled prior to their execution) we use conditional statements.
Conditional statements can be of five types:
Repetitive statements:As the name specifies repetitive statements are used to repeat something. Repeat something but what, repetitive statements are used to repeat one or more statements n times. But whats the need of repetition, the need for repeating statements can be explained via a general and basic example.
Lets take an example of functioning of a processor:
There are basically three types of repetitive statements provided in C but languages like C++, Java, C# etc provides an extra iterative statement.
- For loop
- While loop
- Do-while loop
Jump statements:Jump statements are also one of the important control statements and are sometimes used in combination with repetitive statements. Unlike conditional and repetitive statements jump statements provide an unconditional way to transfer the program's flow from one part to another. There are three types of jump statements: