Part
– 4: Conditional Command Execution
As we saw in previous lesson we can use
"for" statement to create a loop for executing a command or a block
of commands. In this lesson we will learn more about “for” loops. We will also
learn how to run a command conditionally.
More
about "for" loops
There are three parts inside condition
phrase. In initialization statement you can initialize variables including loop
counter or any other variable. In condition statement you can use any kind of
logical statement. This logical statement will function as the condition of
loop execution. As we mentioned earlier if this condition becomes invalid
(false) loop execution will terminate.
for( initialization; test condition; run
every time command)
command;
Last section in the “for loop” parentheses is
a C language statement which is executed in each loop cycle. In previous
examples we used a statement like i++ and count++. These will increase the
value of a variable each time loop is executed. Increase in this variable can
change the loop condition logical value to invalid (false), if the loop
condition is also based on this variable. Below example will print a
multiplication chart (from 1*1 to 9*9). Run the program and see the results.
Example
4-1: example4-1.c
#include
main()
{
int i,j;
for(i=1;i<10;i++)
{
for(j=1;j<10;j++)
printf("%3d",i*j);
printf("\n");
}
system("pause");
}
"if"
conditional statements
Sometimes you need a command or a block of
commands to be executed when a condition exists or
when a condition does not exist. The
condition is a logical statement similar to the condition used in
while loops. A logical statement is either
valid (has a true value) or it is invalid (false).
if(condition)
command;
if(condition)
{
block of commands;
}
“If statement” is a branching statement
because it provides a way to select a path from several execution paths in a
program. If condition is true the command or block of commands will be
executed.
Example
4-2: example4-2.c
What does this program do?
#include
main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>=0)
printf("Number is positive !\n");
if(n<0)
printf("Number is negative !\n");
system("pause");
}
Now let's see a more complex example.
Example
4-3: example4-3.c
Write a program to solve a second-degree
equation: ax
2+bx+c=0.
#include
#include
main()
{
float delta,a,b,c,x1,x2;
printf("Enter a : ");
scanf("%f",&a);
printf("Enter b : ");
scanf("%f",&b);
printf("Enter c : ");
scanf("%f",&c);
delta=b*b-(4*a*c);
if(delta<0)
{
printf("Equation has no answer
!\n");
system("pause");
exit(0);
}
if(delta==0)
{
x1=-b/(2*a);
printf("Equation has two equal answers
!\n");
printf("x1=x2=%f\n",x1);
system("pause");
exit(0);
}
x1=(-b+sqrt(delta))/(2*a);
x2=(-b-sqrt(delta))/(2*a);
printf("\nX1=%f",x1);
printf("\nX2=%f\n",x2);
system("pause");
}
Our program gets a,b and c, computes delta
(the value under the square root which is delta=
?
?????
)
and 2 possible answers if they exist based on
quardatic equations:
We have used the sqrt() function from the
“math” library and to be able to use the library the only thing we have done,
is to add the “math.h” file to the included header file list.
More
complex "if" statements
Simple form of "if statement” gives you
the choice of executing or skipping a command or block of
commands. If in a program it is needed to
execute a specific command when a condition is true and
execute another command when it is false,
with your current knowledge you may use two simple "if"
statements after each other.
If(condition)
Command;
If(!condition)
command
! Sign reverses the logical value of a
Boolean expression. If it is true the result will become false with '!' sign
and vice versa.
You can use an alternative form of “if
statement” to avoid using two statements. "if statement” has
more complete forms. Below you see one of the
other forms of "if" statement.
If(condition)
Command;
else
command
In this form, an additional "else" section
has been added. When condition is true first command (or block of commands) is
executed otherwise "else" section will be run. Below example is the
revised form of example 4-2. This time it uses “if…else…” instead of 2 normal
“if… statements”.
Example
4-4: example4-4.c
#include
main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>=0)
printf("Number is positive !\n");
else
printf("Number is negative !\n");
system("pause");
}
A
useful example and more complex "if" statement
Next example uses an even more complex form
of “if statement”. This one has several conditional sections and a single else
section.
Example
4-5: example4-5.c
#include
#include
main()
{
int choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting
Program\n");
printf("3- Entertainment Program\n4-
Exit");
printf("\n\nYour choice -> ");
scanf("%d",&choice);
if(choice==1)
printf("\nMath Program Runs. !");
else if(choice==2)
printf("\nAccounting Program Runs.
!");
else if(choice==3)
printf("\nEntertainment Program Runs.
!");
else if(choice==4)
{
printf("\nProgram ends.\n");
exit(0);
}
else
printf("\nInvalid choice");
}
}
Above example is an interesting example of a
menu driven programs. A loop which continues forever, prints menu items on
screen and waits for answer. Every time an answer is entered, a proper action
is performed and again the menu is shown to accept another choice.
Loop continues forever unless you enter 4 as
your menu selection. This selection will run the 'exit (0);' function which
terminates the program.
A more complex form of "if"
statement is used in above example.
if(choice==1)
command;
else if(choice==2)
command;
else if(choice==3)
command;
else if(choice==4)
{
block of commands;
}
else
command;
This kind of "if" command is used
in cases that you need to select from among multiple options. At the end of the
“if statement” there is an else section again.
End
Note
I want to use the opportunity and give you a
caution at the end of this lesson. As there are many commands and programming
techniques in any programming language, you will not be able to remember all of
them. The only way to remember things is to practice them. You need to start
developing your own small programs. Start with lesson exercises and continue
with more sophisticated ones. If you do not do this, all your efforts will
become useless in a while.
I always quote this in my programming classes:
"No one becomes a programmer without programming"