Control Structure
A program is usually not limited to a linear sequence of instructions.
During its process it may bifurcate, repeat code or take decisions. For that
purpose, C provides control structures:
A block of instructions is a group of instructions separated by semicolons
(;) but grouped in a block delimited by curly bracket signs shown below. If
only one statement is present
Selection Statement/Branching Statement
1. if statement - It executes an instruction or block of
instructions only if a condition is fulfilled. Its form is
if (condition){
statement;
}
where condition is the expression that is being evaluated. If this condition
is true, statement is executed. If in is false,
statement is ignored (not executed) and the program continues on the
next instruction after the conditional structure.
Note: 1. If statement - It does the selection of none/one block out of given
single block.
Note: If only one instruction is present under selection or iterative
statement then Block is Optional.
If we want more than one instruction to be
included under any selection or iterative statement then, block { } is
compulsory. It is always good programming practice to include a block
whether selection iterative statement contains one or more statements.
2. if-else statement -
Syntax:
{
/*statement(s) will execute if the condition is true */
}
else
else
{
/* statement(s) will execute if the condition is false */
/* statement(s) will execute if the condition is false */
}
If the condition evaluates to true, then if block of
code will be executed, otherwise else block of code will be
executed.
Note:
if-else statement: It does the selection of only one block from the
given two blocks.
Flow Diagram :
For example
if (x==100)
{
printf("x is 100");
}
else
{
printf(“x is not 100”);
}
prints out on the screen x is 100 if indeed x is worth 100,
but if is not and only if not-it prints out x is not 100.
3. if-else ladder statement-
if-else ladder allows to select only one block (choice) from the
given N Blocks (choices). If conditional true then statements
present in the block1 will be executed. If the condition 1 is
false then condition 2 is checked. If condition is true then
statements present in the block2 will be executed. Similarly
remaining conditions will be checked and respective block will be
executed. If condition 1, condition2 up to condition N are fake then
last else block (Block N + 1) will be executed.
Note:
if-else Ladder: It does the selection of only one block from the
given N-Blocks.
Nested if-else statement-
It is always legal in C programming to nest if-else statements,
which means you can use one if or else if statement inside another
if or else if statement(s).
Syntax:
The syntax for a nested if statement is as follows:
You can nest else if else in the similar way as you have nested if
statement.
Code
#include <stdio.h> void main() { int a = 100; int b=200; if(a==100) /* Check condition */ { if(b==200) /* if condition is true then check the following */ { printf("Value of a is 100 and b is 200\n"); /*if condition is true then print the following */ } } printf("Exact value of a is: %d\n", a ); printf("Exact value of b is %d\n", b), getch(); }
When the above code is compiled and executed, it produces the
following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
4. Switch case
Note: It does the selection of one or more blocks from the given
N-blocks,
It works in the following way:
switch evaluates expression and checks if it is
equivalent to constant1, if it is , it executes block of
instructions until it finds the break keyword, then the
program will jump to the end of the switch selective structure, if
expression was not equal to constant 1 it will check if expression
is equivalent to constant2, if it is, it will execute block of
instructions 2 until it finds the break keyword. Finally, if
the value of expression has not matched any of the previously
specified constants, (You may specify as many case sentences as
values you want to check), the program will execute the instructions
included in the default: section, if this one exists, since it is
optional.
Notice the inclusion of the break instructions at the end of
each block. This is necessary because if, for example, we did not
include it after block of instructions 1 the program would not jump
to the end of the switch selective block (}) and it would continue
executing the rest of the blocks of instructions until the first
appearance of the break instruction or the end of the switch
selective block.
Iterative/ Multi-pass Statements - Loops are used to
execute the same set of statements n number of times.
1. The for loop - Here is syntax and flow of control in
for loop:
Note : If fixed number of times execution is already known in
advance, then we use for loop.
It works the following way:
1. The initialization step is executed first, and only once. This
step allows you to declare and initialize any loop control
variables. You are not required to put a statement here, as long as
a semicolon appears
2. Next, the condition is evaluated. If it is true, the body of the
loop is executed. If it is false, the body of the loop does not
execute and flow of control jumps to the next statement just after
for loop.
3. After the body of for loop executes, the flow of control jumps
back up to the increment statement. The statement allows you to
update any loop control variables. This statement can be left blank,
as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop
executes and the process repeats itself (body of loop, then
increment step, and then again condition). After the condition
becomes false, for loop terminates Here is an example of countdown
using a for loop.
// countdown using a for loop
Code
#include <stdio.h> main () { for (int n-10; n>0; n--) { printf("%d",n); } printf("FIRE!"); }
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The initialization and increase fields are optional. They
can be avoided but not the semicolon signs among them. For example
we could write:
for (;n<10;)
if we want to specify no initialization and
no increase, or for (;n<10; n++) if we want to
include an increase field but not an initialization.
Optionally, using the comma operator (,) we can specify more than
one instruction in any of the fields included in a for loop,
like in initialization, for example. The comma operator (,) is an
instruction separator, it serves to separate more than one
instruction where only one instruction is generally expected. For
example, suppose that we wanted to initialize more than one
variable in our loop:
for (n=0, i=100; n!=i ; n++, i --)
{
//whatever here...
}
This loop will execute 50 times if neither n nor i are modified
within the loop
n starts with 0 and i with 100, the
condition is (n!=i) (that n be not equal to
i). Because n is increased by one and
i decreased by one, the loop's condition will become false
after the 50th loop, when both n and i will be equal to 50.
2. while loop - It repeats same set of statements
while expression is true
Syntax -
Note: When we don't know in advance, how many times loops
will be executed then we have to use while loop.
For example, we are going to make a program to count down using a
while loop
Code
#include <stdio.h> void main () { int n; printf("Enter the start no"); scanf("%d", &n); while (n>0) { printf("%d", n); --n; } printf ("FIRE!"); }
Output
Enter the starting number 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
while loop begins if the value entered by the user fulfills
the condition n>0 (that n be greater than
0) the block of instructions that follows will execute an
indefinite number of times while the condition
(n>0) remains true.
We must provide some method that forces condition to become
false at some moment, otherwise the loop will continue looping
forever. In this case we have included --n; therefore when
n becomes 0, that is where our countdown ends.
3. The do-while loop
Syntax:
Its functionality is exactly the same as the while loop except
that condition in the do-while is evaluated after the execution of
statement instead of before, granting at least one execution of
statement even if condition is never fulfilled.
For example, the following program echoes any number you enter
until you enter 0.
Code
#include <stdio.h> void main () { long int n; do { printf(“Enter no from 0 to end”); scanf(“%d”, &n); printf(“You entered:=%id\n”,n); } while (n!=0) }
The do-while loop is usually used when the condition that has to
determine its end is determined within the loop statement, like in
the previous case, where the user input within the block of
instructions is what determines the end of the loop. If you
never enter the 0 value in the previous example the loop will
never end.
Jump Statements -
1. The break instruction
:
Using break we can leave a loop even if the condition for its end
is not fulfilled. It can be used to end an infinite loop, or to
force it to end before its natural end. For example,
we are going to stop the count down before it naturally finishes
(an engine failure maybe):
Code
#include <stdio.h> void main () { int i ; for (i=1; i<=10;i++) { if (i%2==0) { printf(“%d “,i); break; } } }
2. The continue
instruction:
The continue instruction cause the program to skip the rest of the
loop of the present iteration as if the end of the statement block
would have been reached. Causing it to jump to the following
iteration.
It causes the control to go directly to the test-condition and
then continue the loop process. On encountering continue, cursor
leave the current cycle of loop, and starts with the next cycle.
For example, we are going to skip the number 5 in our countdown:
Code
#include <stdio.h> void main() { for(int n=10;n>0;n--1) { if(n==5) continue; printf("%d",n); } printf("FIRE!"); }
Output:
10 9 8 7 6 4 3 2 1 FIRE!
3. The goto instruction
It allows making an absolute jump to another point in the program.
You should use this feature carefully since its execution ignores
any type of nesting limitation. The destination point is
identified by a label, which is then used as an argument for the
goto instruction. A label is made of a valid identifier followed
by a colon (:). This instruction does not have a concrete utility
in structured or object oriented programming aside from those that
low-level programming fans may find for it. For example, here is
our countdown loop using goto:
Code
#include <stdio.h> void main() { int n=10; loop: printf("%d",n); n--; if(n>0) goto loop; printf("FIRE!"); }
Output:
10 9 8 7 6 5 4 3 2 1 FIRE!
Difference between for while and do while loop
Difference between the if-else and switch case
switch
• switch is used to select
one or more cases choices out the given n cases/choices
• switch is usually more
compact than lots of nested if else and therefore, more readable
• If you omit the break
between two switch cases, you can fall through to the next case in
many C-like languages. With if else you'd need a goto (which is
not very nice to your readers………. if the language supports goto at
all).
• switch only accepts
primitive types as key and constants as cases. This means it can
be optimized by the compiler using a jump table which is very
fast.
• It is not really clear
how to format switch correctly Semantically, the cases are labels
for goto) which should be flush left. Things get worse when you
have curly braces:
case constant
{ -----------------
-----------------
}
break;
Or should the braces go into lines of their own? Should the
closing brace go behind the break Hoe unreadable would that be?
etc.
if-else
simple if-else and if-else ladder selects only one choices out of
the given n choices.
• if allows complex
expressions in the condition while switch wants a constant
• You can't accidentally
forget the break between ifs but you can forget the else
(especially and paste)
• it accepts all data
types.
Difference between break and continue
Post a Comment