Conditional Statements - Notes, Computer Science Engineering, Semester Notes | EduRev

Created by: Dheeraj Singla

: Conditional Statements - Notes, Computer Science Engineering, Semester Notes | EduRev

 Page 1


6 Conditional Statements
Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.
6.1 Introduction
Up to now we have been dealing with programs that read numbers, do ?xed calcu-
lations in a pre-speci?ed order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the ?rst dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.
6.2 Conditional Statements
In “C” conditional execution is mainly accomplished by theif statement which in
its simplest form is:
if (<-- logical statement -->)
{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}
When the “<logical statement>”is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,
1. There is no “;”afterthe if() statement. This is a very common source of
programming bugs!
2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.
3. The <-- text --> line means “replace with valid “C” statement”.
4. Each line of optional code ends with a “;”.
Logical Statements
The simplest logical statements are formed by variables combined with the logical
operators which are:
SESSION 00/01 VERSION 2.2, JANUARY 2001
Page 2


6 Conditional Statements
Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.
6.1 Introduction
Up to now we have been dealing with programs that read numbers, do ?xed calcu-
lations in a pre-speci?ed order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the ?rst dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.
6.2 Conditional Statements
In “C” conditional execution is mainly accomplished by theif statement which in
its simplest form is:
if (<-- logical statement -->)
{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}
When the “<logical statement>”is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,
1. There is no “;”afterthe if() statement. This is a very common source of
programming bugs!
2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.
3. The <-- text --> line means “replace with valid “C” statement”.
4. Each line of optional code ends with a “;”.
Logical Statements
The simplest logical statements are formed by variables combined with the logical
operators which are:
SESSION 00/01 VERSION 2.2, JANUARY 2001
> Greater Than
< Less Than
== Equals (Note: double== sign)
>= Greater than or equal to
<= Less than or equal to
!= Notequalto
so for a simple example we have:
float x;
<code to set the value of x>
if(x>5)
{
printf("The values of x is greater than 5\n");
}
which will print out the message if and only if x > 5.
A few points to note are:
1. The “indentation” is not part of the PROGRAM, but laying the code out with
“indented” if() will make it much easier to read. The emacs editor will do
most of this for you if you insert a <TAB> before each line.
2. The “equals” (==) operator and the “not-equals” (!=) should not be used with
float ordouble types since they compare every bit so are highly dependent
on how the number is stored and ultra sensitive to rounding errors. (See more
on this later!)
More on Logical Statements
To form more complex logical statements the logical comparison can be combined
with the three logical operators
|| OR
&& AND
! NOT
Note: The logical AND and OR operators are double characters. There are single
character operators| and& which are the “bitwise operators”. These bitwise oper-
ators are normally used in system or hardware control code and are not considered
in this course. Again using the wrong single bitwise operators when you intended
to use the double logical operator is a common source of program bugs!
These operators are evaluated after the comparison operators, but it is good pro-
gramming practice to put in brackets to make the order of evaluation clear (to you)!
For example a condition ofx< 5 ORx>10 can be written as:
if( (x < 5) || (x > 10))
{
<-- First conditional statement -->;
SESSION 00/01 VERSION 2.2, JANUARY 2001
Page 3


6 Conditional Statements
Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.
6.1 Introduction
Up to now we have been dealing with programs that read numbers, do ?xed calcu-
lations in a pre-speci?ed order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the ?rst dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.
6.2 Conditional Statements
In “C” conditional execution is mainly accomplished by theif statement which in
its simplest form is:
if (<-- logical statement -->)
{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}
When the “<logical statement>”is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,
1. There is no “;”afterthe if() statement. This is a very common source of
programming bugs!
2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.
3. The <-- text --> line means “replace with valid “C” statement”.
4. Each line of optional code ends with a “;”.
Logical Statements
The simplest logical statements are formed by variables combined with the logical
operators which are:
SESSION 00/01 VERSION 2.2, JANUARY 2001
> Greater Than
< Less Than
== Equals (Note: double== sign)
>= Greater than or equal to
<= Less than or equal to
!= Notequalto
so for a simple example we have:
float x;
<code to set the value of x>
if(x>5)
{
printf("The values of x is greater than 5\n");
}
which will print out the message if and only if x > 5.
A few points to note are:
1. The “indentation” is not part of the PROGRAM, but laying the code out with
“indented” if() will make it much easier to read. The emacs editor will do
most of this for you if you insert a <TAB> before each line.
2. The “equals” (==) operator and the “not-equals” (!=) should not be used with
float ordouble types since they compare every bit so are highly dependent
on how the number is stored and ultra sensitive to rounding errors. (See more
on this later!)
More on Logical Statements
To form more complex logical statements the logical comparison can be combined
with the three logical operators
|| OR
&& AND
! NOT
Note: The logical AND and OR operators are double characters. There are single
character operators| and& which are the “bitwise operators”. These bitwise oper-
ators are normally used in system or hardware control code and are not considered
in this course. Again using the wrong single bitwise operators when you intended
to use the double logical operator is a common source of program bugs!
These operators are evaluated after the comparison operators, but it is good pro-
gramming practice to put in brackets to make the order of evaluation clear (to you)!
For example a condition ofx< 5 ORx>10 can be written as:
if( (x < 5) || (x > 10))
{
<-- First conditional statement -->;
SESSION 00/01 VERSION 2.2, JANUARY 2001
<-- Second conditional statement -->;
.....
}
These two types of operators can be combined to form very complex statements.
int as logical variable
Unlike most other high level languages “C” does not have a special “logical vari-
able”
1
.In“C” theint variable is used as the logical, so for example we can write:
int do_more;
do_more = ( x < 4);
if ( do_more )
{
<-- conditional statements -->;
}
The actual value ofdo more will be
TRUE 1
FALSE 0
Technical aside: The if() statement will take any NON-ZERO value to be TRUE.
This is a feature of the “C” language that should be used with extreme care!
6.3 Double Conditionals
The extended syntax of theif() statement is the very usefulif() fg else fg if (<logical statement>)
{
<-- First line of optional true code -->;
<-- Second line of optional true code -->;
<-- ....-->;
<-- nth line of optional true code -->;
}
else
{
<-- First line of optional false code -->;
<-- Second line of optional false code -->;
<-- .... -->;
<-- nth line of optional false code -->;
}
When the logical statement is evaluated, if it isTRUE then the code in the ?rst fg is
executed, else the code in the second fg is executed.
The use of the if() fg else fg gives good “block” structured code that is easy to
read, and thus is more likely to be correct!
1
Most programmers consider this a serious omission in the language
SESSION 00/01 VERSION 2.2, JANUARY 2001
Page 4


6 Conditional Statements
Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.
6.1 Introduction
Up to now we have been dealing with programs that read numbers, do ?xed calcu-
lations in a pre-speci?ed order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the ?rst dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.
6.2 Conditional Statements
In “C” conditional execution is mainly accomplished by theif statement which in
its simplest form is:
if (<-- logical statement -->)
{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}
When the “<logical statement>”is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,
1. There is no “;”afterthe if() statement. This is a very common source of
programming bugs!
2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.
3. The <-- text --> line means “replace with valid “C” statement”.
4. Each line of optional code ends with a “;”.
Logical Statements
The simplest logical statements are formed by variables combined with the logical
operators which are:
SESSION 00/01 VERSION 2.2, JANUARY 2001
> Greater Than
< Less Than
== Equals (Note: double== sign)
>= Greater than or equal to
<= Less than or equal to
!= Notequalto
so for a simple example we have:
float x;
<code to set the value of x>
if(x>5)
{
printf("The values of x is greater than 5\n");
}
which will print out the message if and only if x > 5.
A few points to note are:
1. The “indentation” is not part of the PROGRAM, but laying the code out with
“indented” if() will make it much easier to read. The emacs editor will do
most of this for you if you insert a <TAB> before each line.
2. The “equals” (==) operator and the “not-equals” (!=) should not be used with
float ordouble types since they compare every bit so are highly dependent
on how the number is stored and ultra sensitive to rounding errors. (See more
on this later!)
More on Logical Statements
To form more complex logical statements the logical comparison can be combined
with the three logical operators
|| OR
&& AND
! NOT
Note: The logical AND and OR operators are double characters. There are single
character operators| and& which are the “bitwise operators”. These bitwise oper-
ators are normally used in system or hardware control code and are not considered
in this course. Again using the wrong single bitwise operators when you intended
to use the double logical operator is a common source of program bugs!
These operators are evaluated after the comparison operators, but it is good pro-
gramming practice to put in brackets to make the order of evaluation clear (to you)!
For example a condition ofx< 5 ORx>10 can be written as:
if( (x < 5) || (x > 10))
{
<-- First conditional statement -->;
SESSION 00/01 VERSION 2.2, JANUARY 2001
<-- Second conditional statement -->;
.....
}
These two types of operators can be combined to form very complex statements.
int as logical variable
Unlike most other high level languages “C” does not have a special “logical vari-
able”
1
.In“C” theint variable is used as the logical, so for example we can write:
int do_more;
do_more = ( x < 4);
if ( do_more )
{
<-- conditional statements -->;
}
The actual value ofdo more will be
TRUE 1
FALSE 0
Technical aside: The if() statement will take any NON-ZERO value to be TRUE.
This is a feature of the “C” language that should be used with extreme care!
6.3 Double Conditionals
The extended syntax of theif() statement is the very usefulif() fg else fg if (<logical statement>)
{
<-- First line of optional true code -->;
<-- Second line of optional true code -->;
<-- ....-->;
<-- nth line of optional true code -->;
}
else
{
<-- First line of optional false code -->;
<-- Second line of optional false code -->;
<-- .... -->;
<-- nth line of optional false code -->;
}
When the logical statement is evaluated, if it isTRUE then the code in the ?rst fg is
executed, else the code in the second fg is executed.
The use of the if() fg else fg gives good “block” structured code that is easy to
read, and thus is more likely to be correct!
1
Most programmers consider this a serious omission in the language
SESSION 00/01 VERSION 2.2, JANUARY 2001
6.4 Multiple Conditional
The full syntax of the if() includes the else if() giving the rather complex
structure of:
if (<-- logical statement 1 -->)
{
<-- optional code if logical statement 1 is TRUE -->;
}
else if(<-- logical statement 2 -->)
{
<-- optional code if logical statement 2 is TRUE-- >;
}
.
.
else if{<-- logical statement n -->)
{
<-- optional code if logical statement n is TRUE -->;
}
else
{
<-- optional code is all logical statements are FALSE -->
}
which allow a whole “chain” of logical statement to be “tried-out” with the correct
code executed. The logic of suchelse if “chains” is very dif?cult to get right and
even more dif?cult to DEBUG. If you do need to use this structure then you should
“draw” the structure out on paper ?rst before you try and code it.
6.5 Theexit() Function
The exit(); function basically “stops” execution of the program exactly as if the
program had completed. Up to now you have been using this at the end of your
program but it can also be used to conditionally exit the program. The syntax is
simple being
exit(int status);
where status is an integer value that is returned to the operating system. The
function exit(); is de?ned in the standard library header <stdlib.h> so you
must add #include <stdlib.h> to the top of your program to use this function.
This header ?le also de?nes two integer value:
EXIT SUCCESS Pass “success” back to operating system.
EXIT FAILURE Pass “failure” back to operating system.
This is useful for complex programs than interact with the actual system. The
typical use ofexit() is to stop your program if an error has occurred, for example:
SESSION 00/01 VERSION 2.2, JANUARY 2001
Page 5


6 Conditional Statements
Read and study this section with care. It is fundamental to programming and con-
tains new ideas and some complex syntax.
6.1 Introduction
Up to now we have been dealing with programs that read numbers, do ?xed calcu-
lations in a pre-speci?ed order and output results. This is not much of a PROGRAM!
The main power of computing is conditional control over which statements (parts
of the program) are executed in which order, and how many times. This is generally
called Flow Control and will be considered in two sections, the ?rst dealing with
Conditional Statements and the second dealing with Loops, which you will deal
with after the next checkpoint.
6.2 Conditional Statements
In “C” conditional execution is mainly accomplished by theif statement which in
its simplest form is:
if (<-- logical statement -->)
{
<-- First line of optional code -->;
<-- Second line of optional code -->;
<-- .... -->;
<-- nth line of optional code -->;
}
When the “<logical statement>”is TRUE then the piece of optional code is
executed, else it is skipped over.
Note the following points about the syntax,
1. There is no “;”afterthe if() statement. This is a very common source of
programming bugs!
2. The optional code is enclosed in fg brackets that must match. The EMACS
editor will help here.
3. The <-- text --> line means “replace with valid “C” statement”.
4. Each line of optional code ends with a “;”.
Logical Statements
The simplest logical statements are formed by variables combined with the logical
operators which are:
SESSION 00/01 VERSION 2.2, JANUARY 2001
> Greater Than
< Less Than
== Equals (Note: double== sign)
>= Greater than or equal to
<= Less than or equal to
!= Notequalto
so for a simple example we have:
float x;
<code to set the value of x>
if(x>5)
{
printf("The values of x is greater than 5\n");
}
which will print out the message if and only if x > 5.
A few points to note are:
1. The “indentation” is not part of the PROGRAM, but laying the code out with
“indented” if() will make it much easier to read. The emacs editor will do
most of this for you if you insert a <TAB> before each line.
2. The “equals” (==) operator and the “not-equals” (!=) should not be used with
float ordouble types since they compare every bit so are highly dependent
on how the number is stored and ultra sensitive to rounding errors. (See more
on this later!)
More on Logical Statements
To form more complex logical statements the logical comparison can be combined
with the three logical operators
|| OR
&& AND
! NOT
Note: The logical AND and OR operators are double characters. There are single
character operators| and& which are the “bitwise operators”. These bitwise oper-
ators are normally used in system or hardware control code and are not considered
in this course. Again using the wrong single bitwise operators when you intended
to use the double logical operator is a common source of program bugs!
These operators are evaluated after the comparison operators, but it is good pro-
gramming practice to put in brackets to make the order of evaluation clear (to you)!
For example a condition ofx< 5 ORx>10 can be written as:
if( (x < 5) || (x > 10))
{
<-- First conditional statement -->;
SESSION 00/01 VERSION 2.2, JANUARY 2001
<-- Second conditional statement -->;
.....
}
These two types of operators can be combined to form very complex statements.
int as logical variable
Unlike most other high level languages “C” does not have a special “logical vari-
able”
1
.In“C” theint variable is used as the logical, so for example we can write:
int do_more;
do_more = ( x < 4);
if ( do_more )
{
<-- conditional statements -->;
}
The actual value ofdo more will be
TRUE 1
FALSE 0
Technical aside: The if() statement will take any NON-ZERO value to be TRUE.
This is a feature of the “C” language that should be used with extreme care!
6.3 Double Conditionals
The extended syntax of theif() statement is the very usefulif() fg else fg if (<logical statement>)
{
<-- First line of optional true code -->;
<-- Second line of optional true code -->;
<-- ....-->;
<-- nth line of optional true code -->;
}
else
{
<-- First line of optional false code -->;
<-- Second line of optional false code -->;
<-- .... -->;
<-- nth line of optional false code -->;
}
When the logical statement is evaluated, if it isTRUE then the code in the ?rst fg is
executed, else the code in the second fg is executed.
The use of the if() fg else fg gives good “block” structured code that is easy to
read, and thus is more likely to be correct!
1
Most programmers consider this a serious omission in the language
SESSION 00/01 VERSION 2.2, JANUARY 2001
6.4 Multiple Conditional
The full syntax of the if() includes the else if() giving the rather complex
structure of:
if (<-- logical statement 1 -->)
{
<-- optional code if logical statement 1 is TRUE -->;
}
else if(<-- logical statement 2 -->)
{
<-- optional code if logical statement 2 is TRUE-- >;
}
.
.
else if{<-- logical statement n -->)
{
<-- optional code if logical statement n is TRUE -->;
}
else
{
<-- optional code is all logical statements are FALSE -->
}
which allow a whole “chain” of logical statement to be “tried-out” with the correct
code executed. The logic of suchelse if “chains” is very dif?cult to get right and
even more dif?cult to DEBUG. If you do need to use this structure then you should
“draw” the structure out on paper ?rst before you try and code it.
6.5 Theexit() Function
The exit(); function basically “stops” execution of the program exactly as if the
program had completed. Up to now you have been using this at the end of your
program but it can also be used to conditionally exit the program. The syntax is
simple being
exit(int status);
where status is an integer value that is returned to the operating system. The
function exit(); is de?ned in the standard library header <stdlib.h> so you
must add #include <stdlib.h> to the top of your program to use this function.
This header ?le also de?nes two integer value:
EXIT SUCCESS Pass “success” back to operating system.
EXIT FAILURE Pass “failure” back to operating system.
This is useful for complex programs than interact with the actual system. The
typical use ofexit() is to stop your program if an error has occurred, for example:
SESSION 00/01 VERSION 2.2, JANUARY 2001
float x,y;
<-- code to calculate value of x -->;
if(x<0)
{
printf("Value of x < 0. Fatal Error\n");
exit(EXIT_FAILURE);
}
else
{
y = sqrt(x};
}
which will stop the program (with a sensible message!), if x is negative before it
tries to take the square root of it.
Note: If you do “stop” the program with exit(); as a result of an error always
print out a sensible explanation of what happened. There is nothing worse than a
program that exits with no explanation and does not do what you expected it to.
6.6 Additional Statements
There are two additional conditional constructs in “C” these being:
switch Statement
switch is a complex and very useful dispatch construct that can be used to replace
complex if else() chains. It is mainly used in multi-option programs and is
beyond the scope of this course.
If you are “keen” see Bronson page 172, but I suggest you wait until you have some
experience with theif() construct ?rst!
goto Statement
goto is a unconditional jump to a marked location in a program. This is a dangerous
construct that can lead to highly confusing code. There are two schools of thought
regarding the goto. One says it “should be used only when nothing else works”
and the other says “it should never be used”. Due to the other good conditional
constructs there is no requirement ever to use agoto.See Bronson page 548 if you
really must!
What Next?
You have now completed suf?cient “C” to attempt Checkpoint 3.
SESSION 00/01 VERSION 2.2, JANUARY 2001
Read More

Share with a friend