[go: up one dir, main page]

0% found this document useful (0 votes)
294 views13 pages

Control Statements - Conditional Statements

The document discusses control flow statements in C programming, including conditional statements. 1) Conditional statements like if, if-else, and switch allow a program to conditionally execute code based on evaluations of expressions. They enable decision-making and branching. 2) An if statement executes a block of code if a condition is true. An if-else statement executes one block if the condition is true and another block if false. Nested if statements allow multiple conditions to be checked. 3) Examples show algorithms, flowcharts, and C code to check if a number is even or odd using if-else and to find the largest of two numbers using nested if statements.

Uploaded by

Naveen Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
294 views13 pages

Control Statements - Conditional Statements

The document discusses control flow statements in C programming, including conditional statements. 1) Conditional statements like if, if-else, and switch allow a program to conditionally execute code based on evaluations of expressions. They enable decision-making and branching. 2) An if statement executes a block of code if a condition is true. An if-else statement executes one block if the condition is true and another block if false. Nested if statements allow multiple conditions to be checked. 3) Examples show algorithms, flowcharts, and C code to check if a number is even or odd using if-else and to find the largest of two numbers using nested if statements.

Uploaded by

Naveen Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Programming with C 2017

Control Statements: Conditional Statements


- Introduction, conditional execution (if, if-else, nested if), and selection (switch), unconditional
types (break, continue, goto).

What are Control flow statements?


 A program is set of instructions.
 On default these instructions are sequentially or linearly executed.
 Instructions that break up the flow of execution of the program enable program to conditionally
execute particular blocks of code, employ decision making, looping and branching statements.
 These are the statements which breaks the sequential execution of the program based on some
condition.
CONDITIONAL EXECUTION
Types of Conditional statements/decision making statements/ Control construct
 There are 5 Conditional statements in C
 Simple if control construct / One way selection statement
 if else control construct / Two way selection statement
 nested if else control construct
 else if ladder or cascaded if else construct / Multi way selection statement
 switch control construct / Multi-way statement
if statement (Simple if/ One way selection)
 An if statement is a single selection statement.
 It is used to execute a set of statements if the condition is true, if the condition is false, it skips
executing those set of statements. Hence it is called one way selection.
Syntax: Flowchart: Statement 1;
Statement 1; Statement 2;
Statement 2;
if(condition) if False
condition
{
Statement 3; True
Statement 4; Statement 3;
} Statement 4;
Statement 5;
Statement 5;

1 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

Explanation
 The keyword if must be followed by an expression and expression must be enclosed within
parentheses.
 First statement1 is executed followed by statement2.
 Then Condition is checked
 if false - control directly jumps to statement5 ignoring statement3 and 4.
 if true - control goes to statement3 , statement4 and automatically goes to statement5.
An Example which illustrates if statement: To print given no is an even no.
Algorithm Flowchart Program

To Check even number #include<stdio.h>


Step 1: Start void main()
Step 2: Read N {
Step 3: if( n % 2 == 0) int n;
{ clrscr();
Print “even no” printf(“ Enter the number\n”)
} scanf(“%d”,&n);
Step 4: Stop if(n%2==0)
{
printf(“Even no”);
}
getch();
}

Note: Similarly write Algorithm, Flowchart and C Program for the following
 To print given no is an odd no. Logic: if (n!=0)
 To print given no is a positive no. Logic: if (n>0)
 To print given no is a negative no. Logic: if (n<0)

Disadvantage
 If one action has to be performed when the condition is true and another action has to be
performed when the condition is false then if-statement is not recommended. This disadvantage
is overcome using two- way decision/selection statement called “ if-else statement”.

2 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

if – else statement (two way selection)


 It is used to execute a set of statements if the condition is true, and another set of statements if the
condition is false. Hence it is called two way selections.

Syntax: Flowchart:

Statement 1; Statement 1;
Statement 2; Statement 2;
if(condition)
{
Statement 3; true if false
Statement 4; condition

}
else
{ Statement 3; Statement 5;
Statement 4; Statement 6;
Statement 5;
Statement 6;
}
Statement 7;
Statement 7;

Explanation
 The keyword if and else must be followed by an expression and expression must be enclosed within
parentheses.
 First statement1 is executed followed by statement2.
 Then Condition is checked
 If true - control goes to if part where statement3 , statement4 are executed and
automatically goes to statement7.
 If false - control goes to else part where statement5, statement6 are executed and
automatically goes to statement7.
 In if-else either true part i.e., if part is executed or false part i.e., else part is executed based in the
condition or test expression.

3 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
An Example which illustrates if-else statement: To print given no is an even no or odd no.
Algorithm Flowchart Program

Algorithm: Check even #include<stdio.h>


Start
void main()
number or odd no
{
S1: Start int n;
Input n clrscr();
S2: Read N
printf(“ Enter the number\n”)
S3: if( n % 2 == 0) scanf(“%d”,&n);
{
true
if(n%2==0)
false
Print “even no” If
n%2==0
printf(“Even no”);
}
else
else printf(“odd no”);
{ Print” odd no”
Print” even no” getch();
Print “odd no” }
}
S4: Stop
Stop

Note: Similarly write Algorithm, Flowchart and C Program for the following
 To check given integer no is a positive no or negative no.
Logic: if(n>0) its positive else negative.
 To find largest of 2 no‟s .
Logic: Let a and b be 2 no’s if(a>b) a is greater else b is greater
 To check given no is even or odd
Logic: Let n be a no’s if(n%2==0) n is even else n is odd.

4 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

Nested if else
 It is used to execute one set of statements out of many set of statements depending upon the outcome
of the conditions.
 It consists of if else control constructs with in another if or else control constructs and hence the
name is nested if else.
Syntax: Flowchart:

if(condition-1)
{
if (condition-2)
Statement1;
else
Statement2;
}
else
{
s Statement3;
}
Statement4;

Explanation
 The keyword if and else must be followed by an expression and expression must be enclosed within
parentheses.
 Then Condition is checked
 If condition-1 is true then again condition-2 is checked if both are true then Statement1 is
executed.
 If condition-1 is true but condition-2 is false means Statement2 is executed.
 If condition-1 itself is false control goes to Statement3 and automatically goes to Statement4.
Advantage:
 When an action has to be performed based on many decisions involving various types of expressions
and variables then nested if statement is used.

Disadvantage:
 Difficult to understand and modify. As depth of nesting increases, the readability of the program
decreases.

5 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
An Example which illustrates if-else statement: To find biggest of three numbers.
Algorithm Flowchart Program

Algorithm: To find largest #include<stdio.h>


of 3 no void main()
S1: Start {
S2: Read a,b,c inta,b,c;
S3: if( a>b) clrscr();
{ printf(“ Enter the 3 numbers\n”);
if( a>c) scanf(“%d%d%d”,&a,&b,&c);
{ if(a>b)
Print “a largest” {
} if(a>c)
else {
{ printf(“a largest”);
Print “c largest” }
} else
} {
else printf(“c largest”);
{ }
if( b>c) else
{ {
Print “b largest” if(b>c)
} {
else printf(“b largest”);
{ }
Print “c largest” else
} {
} printf(“c largest”);
S4: Stop }
}
getch();
}

Note: Similarly write Algorithm, Flowchart and C Program for the following
 To check given integer no is a positive no or negative no or zero.
 To find the greatest of three numbers.
 Magic number program.

6 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

else if ladder / cascaded if else


 It is used to execute one set of condition out of many set of conditions with its statements set.
Syntax: Flowchart:
Statement 1;
Statement 2;
if(condition 1)
{
Statement 3;
}
else if(condition 2)
{
Statement 4;
}
else if(condition 3)
{
Statement 5;
}
else
{
Statement 6;
}
Statement 7;

Explanation
 The keyword if and else must be followed by an expression and expression must be enclosed within
parentheses.
 First statement1 is executed followed by statement2.
 Then Condition 1 is checked
 if true control goes to Statement3 and automatically goes to Statement7.
 If false Condition 2 is checked
 If Condition 2 is true control goes to Statement4 and automatically goes to Statement7.
 If false Condition 3 is checked
 If Condition 3 is true control goes to Statement5 and automatically goes to Statement7
 If false Statement6 and automatically goes to Statement 7.
Note: Write Algorithm, Flowchart and C Program for the following:
 To check an alphabet is vowel or consonant.
 To illustrate the simple calculator operations with condition for division operation.

7 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
An Example which illustrates else if ladder control statement:
1) To find biggest of three numbers. 2) Grading based on marks
Algorithm Flowchart Program
Algorithm: To find largest of #include<stdio.h>
3 no void main()
S1: Start {
S2: Read a,b,c inta,b,c;
S3: if( a>b && a>c) clrscr();
{ printf(“ Enter the 3 numbers\n”)
Print “a largest” scanf(“%d%d%d”,&a,&b,&c);
} if( a>b && a>c)
else if( b>a && b>c) {
{ printf(“a largest”);
Print “b largest” }
} else if( b>a && b>c)
else {
{ printf(“b largest”);
Print “c largest” }
} else
S4: Stop {
printf(“c largest”);
}
getch();
}
Algorithm: Grading based on #include<stdio.h>
marks void main()
S1: Start {
S2: Read marks int marks;
S3: if (marks >= 80) printf(“ Enter the marks/n”);
grade = „A‟; if (marks >= 80)
else if (marks >= 65) printf(“grade = „A‟ ”);
grade = „B‟; else if (marks >= 65)
else if (marks >= 50) printf(“grade = „B‟ ”);
grade = „C‟; else if (marks >= 50)
else printf(“grade = „C‟ ”);
grade = „D‟; else
S4: Stop printf(“grade = D ”);
getch();
}

8 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

Switch statement
 Switch statements are used in following scenarios
 When a decision has to be made between many alternative cases.
 When the selection condition reduces to an integer value.
 The multiple selection mechanism is implemented using switch.
 switch is alternative for two way selection multiple if-else-if.

Syntax: Flowchart:
switch(an integer value)
{
case value1: Statement1;
break;
case value2: Statement2;
break;
case value3: Statement3;
break;
default: Statement4;
break;
}
Explanation
 The switch statement is a multi-way decision that tests whether an expression matches one of a
number of constant integer values / cases and branches accordingly.
 Each case is labelled by one or more integer-valued constants or constant expressions.
 If a case matches the expression value, execution starts at that case.
 All case expressions must be different.
 The case labelled default is executed if none of the other cases are satisfied.
 A default is optional; if it isn't there and if none of the cases match, no action takes place. Cases and
the default clause can occur in any order.
 The break statement causes an immediate exit from the switch.
More about switch statement:
 The expression of a switch statement must result in an integral type, meaning an integer (byte, short,
int, long) or a char.
 The expression cannot be a boolean value or a floating point value (float or double)
 No two case labels can have the same constant value.

9 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
An Example which illustrates switch control statement:
Program to simulate a simple calculator that performs athematic operations only on integers. Error
message should be reported if any attempt is made to divide by 0.
Algorithm Program
Algorithm: Simple calculator #include<stdio.h>
S1: Start void main()
S2: Read a,b. {
S3: switch(choice) int a,b,res;
{ char choice;
Case „+‟: res = a+ b; clrscr();
Output res; printf(“ Enter your choice\n”);
break; scanf(“%c”,&choice);
Case „-‟: res = a- b; printf(“ Enter the values of a &b\n”);
Output res; scanf(“%d%d”,&a,&b,);
break; switch(choice)
Case „*‟: res = a-*b; {
Output res; case „+‟: res = a+ b;
break; printf(“%d”, res);
Case „/‟: if(b==0) break;
{ case „-‟: res = a- b;
“Divided by 0 error” printf(“%d”, res);
} break;
else case „*‟: res = a-*b;
{ printf(“%d”, res);
res = a/b; break;
Output res; case „/‟: if(b==0)
break; {
} printf(“error :Divided by 0”);
}
default: output “invalid op” else
} {
res = a/ b;
S4: Stop printf(“%d”, res);
}
break;
default: printf( “invalid op”);
}

getch();
}

Note: Write Algorithm, Flowchart and C Program for the following:


 To check an alphabet is vowel or consonant.
 Grading based on marks.

10 Mr. Rajesh S M, Assistant Professor


Programming with C 2017

Unconditional Jump Statements - ( break, continue, goto, exit )


The break statement:
 The break statement is an unconditional jump statement.
 The break statement can be used as the last statement in each case's statement list in switch.
 A break statement causes control to transfer to the end of the switch statement.
 If a break statement is not used, the flow of control will continue into the next case.
“What is a use of break statement?”
The break statement in C programming language has the following two usages:
 When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement.
 If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.

Flow without break Flow with break


switch (option) switch (option)
{ {
case 'A': case 'A':
aCount++; aCount++;
case 'B': break;
bCount++; case 'B':
case 'C': bCount++;
cCount++; break;
} case 'C':
cCount++;
break;
}

Common Programming Error:


 Not including break statement as the last statement in a case block will also result in
execution of the next case block. This will give undesired results.
The continue Statement
 Like the break statement, the continue statement can be placed only in the body of a for loop,
or a while loop, or a do...while loop.
 When a continue statement executes, control is sent to the beginning of the loop.
 The statements between the continue statement and the end of the loop aren't executed.

11 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
Flow without continue Flow with continue

for(exp1;exp2;exp3) for(exp1;exp2;exp3)
{ {
Action 1; Action 1;
------------ continue;
------------ ------------
Action N; Action N;
}

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
for(i=1;i<=3;i++) for(i=1;i<=3;i++)
{ {
printf(“INDIA”); printf(“INDIA\n”);
printf(“is our country\n”); continue;
} printf(“is our country\n”);
getch() }
} getch()
}

OUTPUT: OUTPUT:
INDIA is our country INDIA
INDIA is our country INDIA
INDIA is our country INDIA

The goto Statement


 The goto statement is used to transfer the control of the program from one point to another.
 It is something referred to as unconditionally branching.
 The goto is used in the form
goto label;
 Label statement: The label is a valid „C‟ identifier followed by a colon. We can precode any
statement by a label in the form
Label : statement ;
 This statement immediately transfers execution to the statement labelled with the label
identifier.

12 Mr. Rajesh S M, Assistant Professor


Programming with C 2017
Example : #include<stdio.h> OUTPUT: INDIA
void main() INDIA
{ INDIA
int i=1; INDIA
Back: printf(“INDIA\n”); INDIA
if(i!=5)
{
i++;
goto back;
}
}

The exit() statement:


 The function exit() will terminate the process/program that calls the exit.
Note:
void exit ( int status );
 On call the process will terminate normally. It will perform regular cleanup as normal for a
normal ending process.
 Parameters: A status value returned to the parent process.
 Return value: The argument status is returned to the host environment. Normally you say 1
or higher if something went wrong and 0 if everything went ok.
 “What is the difference between exit(0) and exit(1)?”
 exit(0): indicates successful program termination & it is fully portable.
 exit(1): indicates unsuccessful termination. However, it's usage is non-portable.
 “What are the differences between continue and break statement?”
 A break statement results in the termination of the statement to which it applies
(switch, for, do, or while).
 A continue statement is used to end the current loop iteration and return control to the
loop statement / start.

13 Mr. Rajesh S M, Assistant Professor

You might also like