Presentation Transcript
Slide 1:Control statements
Control statements:
C supports 4 control or decision making statements
*If statement
*Switch statement
*Conditional Operator statement
*Goto statement
Slide 2:If statement:
The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically two ways decision statement is of the form
if (test condition)
It allows a computer to evaluate the expression first and depending upon whether the value of condition is true or false. It will transfer the control to a particular statement
Slide 3:If statement:
The general form of simple if statement is
if (condition)
{
statement-block
}
Example:
if(x>40)
{
printf(“x is greater”);
}
Slide 4:If else statement:
if (condition)
{
true block statement
}
else
{
false block statement
}
Slide 5:Example:
#include
main()
{
int a,b;
printf(“enter the value of a:”);
scanf(“%d”,&a);
printf(“enter the value of b:”);
scanf(“%d”,&b);
if(a>40)
{
printf(“ a is greater”);
}
else {
printf(“b is greater”);
}
}
Slide 6:Do statement:
In do statement the programs proceed to evalulate the body of the loop first. At the end of the loop the test condition in the while statement is evaluated. If the condition is true the program continues to evaluate the body of the loop once again.
This process continues as long as the condition is true. When the condition becomes false the loop will be terminated and the control goes to the statement that appears immediately after the while statement
do
{
body of the loop
}
while (test-condition);
Slide 7:For statement:
The for loop is another entry-controlled loop that provides a more concise loop control structure. The general form of the for loop is
for (initialization ;test-condition; increment)
{
body of the loop
}
Slide 8:Switch statement:
C has a built-in multiway decision statement known as a switch. The switch statement tests the value of a given variable against a list of case values and when a match is found a block of statements associated with that case is executed.
The break statement at the end of each block signals the end of a particular case and cause exit from switch statement transferring the control to the statement-x
The default is optional case. It will be executed if the value of the expression does not match with any of the case values.
Slide 9:switch (expression)
{
case value-1;
block-1
break;
case value-2;
block-2
break;
………..
………..
default:
default-block
break;
}
statement-x;
Slide 10:While statement:
The simplest of all the looping structures in C is the while statement. We have used while in many of our earlier programs. The basic format of the while statement is
while (test condition)
{
body of the loop
}