This, by far, is the most important thing in coding. Without learning this, you will never be able to write any meaningful program. And it brings a power to us that is not ultimate. But as close to it as possible.
Branching
What is branching?
Going to different branches of a program based on the truth or fallacy of a particular condition is called branching.
I will illustrate this to you using a Flow Chart as follows:
This is the flow chart to find the larger of two numbers.
This program is the one of the simplest that we will write. And we can see that based on the truth or fallacy of the condition, X > Y we need to output either X or else Y.
Thus we need branching.
We can achieve branching using three constructs:
- if
- if - else
- switch - case
if
if - else
switch - case
Looping
What is looping?
Doing a set of instructions a specified number of times or until a particular condition is satisfied.
The following flow chart will illustrate how to find the sum of all the numbers that the user enters until he enters a zero:
In this example, we need to go on taking input from the user until he enters a zero.
We can achieve looping through three constructs:
- for
- while
- do - while
for
while
do - while
Note that the do - while loop will always run once. No matter what the value of the condition. We may use this in some of our programs.
In this post, we saw the various constructs in C that allow us to branch from the flow of control of the program. And also the three looping constructs.
it is essential that you understand whatever was taught in this post very very well. Because this forms the basics of coding.