Control Structures

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 94

Cap-118

Control structures
Outline
• Control structure
Decision Statements
• If statement
• If-else statement
• Switch statement
Program
• Program is a set of instruction executed one by one.

• Depending upon the circumstances sometimes it is


desirable to alter the sequence of execution of
statements.

1. Wake up;
2. Get ready;
3. If you have enough
time, then eat breakfast;
4. Go to school.
Control Statements
• The C language programs until now follows a
sequential form of execution of statements.
• C language provides statements that can alter the
flow of a sequence of instructions. These statements
are called control statements.
• These statements help to jump from one part of the
program to another. The control transfer may be
conditional or unconditional.
Control Structure
• A control structure refers to the way in which the
programmer specifies the order of executing the
statements.
• Three control structures
– Sequence structure
• Programs are executed sequentially by default.
– Selection structures
• if, if…else, switch
– Repetition structures (iteration)
• while, do…while, for
Condition Statements
• The C condition statements or the decision
statements, checks the given condition
• Based upon the state of the condition, a sub-
block is executed.
• Decision statements are the:
– if statement
– if-else statement
– switch statement
Daily routine
Start

Go!!!

Where
Class To Movie
Go?

Stop Stop
if statement

Yes If you have No


time?
if Statement
• If statement
– It is decision making statement uses keyword if.
– It allows the computer to evaluate the expression
first
• and then, depending on whether the value is
‘true’ or ‘false’, i.e. non zero or zero it transfers the
control to a particular statement.
A decision can be made on any expression.
zero - false
nonzero - true
Example:
3 < 4 is true
if Statement
Syntax

if (expression)
statement;
 
or
 
if (expression)
{
block of statements;
}
if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a C Evaluate to either non-zero or zero.
reserved word

if ( condition )/* no semi-colon */


statement;

If the condition is non-zero, the statement is executed.


If it is zero, the statement is skipped.
Rain ???
Is it going to rain?

Look up sky for clouds

yes no
Clouds?

No rain
Raining
Program to
check
whether
number is
less than 10.

Enter the number: 6


Number is less than 10
#include <stdio.h>
void main()
{
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

getch();
}
Control Flow
if..else statement

Yes If you have No


time?
if..else statement
• The if statement executes only when the
condition following if is true.
• It does nothing when the condition is false.
• The if..else statement takes care of the
true and false conditions.
if..else statement
• if..else has two blocks.
• One block is for if and it is executed when
condition is non-zero(true).
• The other block is of else and its executed
when condition is zero (false).
Syntax
if (expression)
{
block of statements;
}
else
{
block of statements;
}
if..else statement
• The else statement cannot be used without
if.
• No multiple else statements are allowed
with one if.
• else statement has no expression.
• Number of else cannot be greater than
number of if.
Example
#include<stdio.h>
void main( )
{
int a;
printf("n Enter a number:");
scanf("%d", &a);
if(a>0)
{
printf( "n The number %d is positive.",a);
}
else
{
printf("n The number %d is negative.",a);
}
getch();

}
Ternary conditional operator (?:)
• C code:
if ( marks>= 60 )
printf( "Pass\n");
else
printf( "Fail\n");
• Same code using ternary operator:
– Takes three arguments (condition, value if true, value if
false)
– Our code could be written:
printf("%s\n", grade >= 60 ? "Pass" : "Fail");
– Or it could have been written:
grade >= 60 ? printf(“Pass\n”) : printf(“Fail\
n”);
Example :
Program to
check
whether
number is
less than 10.

Enter the number: 7


Number is less than 10
or
Enter the number: 100
Number is greater than 10
Control Flow

MESSAGE
DISPLAY
Nested if..else
• A nested if is an if statement that is the target of
another if statement.
• Nested if statements means an if statement inside
another if statement.
• C allows us to nest if statements within if
statements. i.e, we can place an if statement inside
another if statement.
Nested If

Syntax

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is
true }
}
#include<stdio.h>
void main()
{
int a=10;
clrscr();
if(a>5)
{
if(a>8)
{
printf("A is greater than 5 and 8");
}
else
{
printf("Greater than 5 but less than 8");
}
}
else
{
printf("not less than 10");
}
getch();
}
Forms of if
The if statement can take any of the following forms:
if ( condition ) {
if ( condition )
do this ;
do this ;
and this ;
or
}
if ( condition ) {
else {
do this ;
do this ;
and this ;
and this ;
}
}

if ( condition )
do this ;
if ( condition ) else if ( condition )
do this ; do this ;
else else {
do this ; do this ;
and this ;
}

Else if ladder
user can decide among multiple options.
• The if statements are executed from the top down.
• As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be executed.
• Syntax
if (condition)
statement;
else if (condition)
statement; . .
else statement;
#include<stdio.h>
void main() Program to
{
float marks;
scanf(“%f”, &marks);
print grades
if (marks>90){
printf(“Grade A”);
of students
}
else if (marks>80) {
marks.
printf(“Grade B”);
}
else if(marks>70){
printf(“Grade C”);
}
else if (marks >60) {
printf(“Grade D”);
}
}

66.70
Grade D
or
78.00
Grade C
Program to relate two integers using =, > or < //checks if number1 is greater than
number2.
#include <stdio.h> else if (number1 > number2)
void main() {
{ printf("Result: %d > %d", number1,
int number1, number2; number2);
printf("Enter two integers: "); }
scanf("%d %d", &number1, &number2);
// if both test expression is false
//checks if two integers are equal. else
if(number1 == number2) {
{ printf("Result: %d < %d",number1,
printf("Result: %d = %d",number1,number2); number2);
} }

getch();
}
Forms of if
Decision control Syntax Description
statements
if if (condition){ In these type of statements, if condition is
Statements;} true, then respective block of code is
executed.
if…else if (condition){  In these type of statements, group of
Statement1; statements are executed when condition is
Statement2;} true.  If condition is false, then else part
else {  statements are executed.
Statement3; 
Statement4;}
else if if (condition1){  If condition 1 is false, then condition 2 is
ladder Statement1;} checked and statements are executed if it
else is true. If condition 2 also gets failure, then
if(condition2){  else part is executed.
Statement2;}
else 
Statement 3;
break statement
• break is a keyword.
• break allows the programmer to terminate
the loop.
• A break statement causes control to transfer
to the first statement after the loop or block.
• The break statement can be used in nested
loops. If we use break in the innermost loop
then the control of the program is terminated
only from the innermost loop.
Break statement are used for terminates any type
of loop e.g, while loop, do while loop or for loop
or switch statements. The break statement
terminates the loop body immediately and passes
control to the next statement after the loop. In
case of inner loops, it terminates the control of
inner loop only.
Use break statement
Break statement are mainly used with loop and
switch statement. often use the break statement
with the if statement.
•with loop statement
•with switch case
•with if statement
How break works
switch Statement

Day= No Day=
Monday Sunday

Yes
switch Statement
• The control statement that allows to make a decision
from the number of choices is called switch.
• Also called switch-case-default.
• The switch statement provides another way to decide
which statement to execute next.
• The switch statement evaluates an expression, then
attempts to match the result to one of several possible
cases.
• Each case contains a value and a list of statements.
• The flow of control transfers to statement associated
with the first case value that matches.
switch Statement
Syntax
switch (expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
case constant3:
statements;
break;
default:
statements;
}
Rules of using switch case
1. Case label must be unique
2. Case label must end with colon
3. Case label must have constant expression
4. Case label must be of integer, character type like case
2, case 1+1, case ‘a’
5. Case label should not be floating point
6. Default can be placed anywhere in switch
7. Multiple cases cannot use same expression
8. Relational operators are not allowed in switch
9. Nesting of switch is allowed.
10. Variables are not allowed in switch case label..
Syntax error in switch statement
Variable cannot be
switch(pt){
case count: used as label
printf(“%d”, count);
break;
case 1<8:
Relational operators
printf(“A point”); are not allowed
break;
case 2.5:
printf(“A line”);
Floating point number
break; cannot be used
case 3 + 7.7:
printf(“A triangle”);
case 3 + 7.7:
Floating point number
printf(“A triangle”); cannot be used and
break; same expression cannot
case count+5: be used
printf(“A pentagon”);
break;
} constant expression
should be used
Program to
show switch
statement in
geometry

Enter the number of nodes: 2


A line
#include<stdio.h> case 4:
void main( ) printf("Wednesday");
{ break;
int day; case 5:
printf("nEnter the number of the printf("Thursday");
day:"); break;
case 6:
scanf("%d",&day); printf("Friday");
break;
switch(day) case 7:
{ printf("Saturday");
case 1: break;
printf("Sunday"); default:
break; printf("Invalid choice");
case 2: }
printf("Monday"); return 0;
break;
case 3: }
printf("Tuesday");
break;
Looping statements
Looping statement are the statements execute
one or more statement repeatedly several number
of times. In C programming language there are
three types of loops; while, for and do-while.
Why use loop ?
•When you need to execute a block of code
several number of times then you need to use
looping concept in C language.
Advantage with looping statement
•Reduce length of Code
•Take less memory space.
•Burden on the developer is reducing.
•Time consuming process to execute the program
is reduced.
Types of Loops.
There are three type of Loops available in 'C'
programming language.
•while loop
•for loop
•do..while
Difference between conditional and looping
statement
Conditional statement executes only once in the
program where as looping statements executes
repeatedly several number of time.
While loop
In while loop First check the condition if condition
is true then control goes inside the loop body
other wise goes outside the body. while loop will
be repeats in clock wise direction.
How while loop works?
• The while loop evaluates the test expression.
• If the test expression is true (nonzero), codes
inside the body of while loop are exectued. The
test expression is evaluated again. The process
goes on until the test expression is false.
• When the test expression is false, the while loop
is terminated.
• while (expression)
• {
• Statement 1;
• Statement 2;
• ……………
• Statement n;
• }
Example…
void main()
{
int i;
clrscr();
i= 1;
while(i<=5)
{
printf(“%d\n”,i);
i++;
}
getch();
}
Do-While

In this case the loop condition is tested at the


end of the body of the loop. Hence the loop is
executed at least one. The do-while loop is an
unpopular area of the language, most
programmers’ tries to use the straight while if it
is possible.
#include<stdio.h>
#include<conio.h>
do int main()
{
{ int  i;
clrscr();
Statement 1; i=1;
do
Statement 2; {
printf(“%d\n”,i);
…………… i++;
}
Statement n;  
while(i<5);
} getch();
return 0;
while(expression); }
For loop

For loop is a statement which allows code to be


repeatedly executed. For loop contains 3 parts
Initialization, Condition and Increment or
Decrements.
How for loop works?
• The initialization statement is executed only
once.
• Then, the test expression is evaluated. If the test
expression is false (0), for loop is terminated.
But if the test expression is true (nonzero),
codes inside the body of for loop is executed
and the update expression is updated.
• This process repeats until the test expression is
false.
• for (initialization, condition, step)
• {
• Statement 1;
• Statement 2;
• ……………
• Statement n;
• }
The for Statement in C
• The syntax of for statement in C:
Syntax
for (initialization-expression;
loop-repetition-condition;
update-expression){
statement;
}

• The initialization-expression set the initial value of the


loop control variable.
• The loop-repetition-condition test the value of the
loop control variable.
• The update-expression update the loop control
variable.
calculate the sum of first n natural numbers

#include <stdio.h>
void main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when n is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

getch();
}
Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
loops
• Eg:
Outer loop
for (i=1;i<=100;i++){
for(j=1;j<=50;j++){ Inner loop


}
}
• The above loop will run for 100*50 iterations.
Program to
print tables
up to a
given
number.

Enter a number
4
The tables from 1 to 4
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
#include<stdio.h>
#include<conio.h> Program to
void main() display a
{
int i,j; pattern.
printf(“Displaying right angled triangle for 5
rows”);
for(i=1 ; i<=5 ; i++) {
for(j=1 ; j<=i ; j++)
printf(“* ”);
printf(“\n”);
}
}

Displaying right angled triangle for 5 rows


*
**
***
****
*****
Difference between while and do..while
while loop do..while loop
1. Condition is specified at the top 1. Condition is mentioned at the bottom
2. Body statements are executed when 2. Body statements are executed at least
the condition is satisfied once even if the expression value
evaluates to false
3. It is an entry controlled loop 3. It is an exit controlled loop
4.Syntax: 4.Syntax:
while (condition)
condition do
statement; {
statements;
}
while (condition);
condition
Jump statements
• You have learn that, the repetition of a loop is controlled by
the loop condition.
• C provides another way to control the loop, by using jump
statements.
• There are four jump statements:
Continue statement
• Continue statement is a jump statement. The
continue statement can be used only inside for
loop, while loop and do-while loop.
• Execution of these statement does not cause
an exit from the loop but it suspend the
execution of the loop for that iteration and
transfer control back to the loop for the next
iteration.
• Syntax:
continue;
continue statement
• In while and do…while loops, the continue
statement transfers the control to the loop condition.
• In for loop, the continue statement transfers the
control to the updating part.
continue statement
Program to
show the use
of continue
statement in
for loop

10 8 6 4 2
Using for loop
Using While Loop
goto
• Unconditionally transfer control.
• goto may be used for transferring control from one
place to another.
• The syntax is:
goto identifier;
Control is unconditionally transferred to the location of a
local label specified by identifier. For example,
Again:
...
goto Again;
• Defining a label
Label is defined following by the given syntax

label_name:
• label_name should be a valid identifier name.
: (colon) should be used after the label_name.
Two styles of ‘goto’ statement
We can use goto statement to transfer
program’s control from down to top (↑) and top
to down (↓).
Style 1 (Transferring the control from down to top)
label-name:
statement1;
statement2;
..
if(any-test-condition)
goto label-name;
Down to top
Style 2 (Transferring the control
from top to down)
// style 2
statements;
if(any-test-condition)
goto label-name;
statement1;
statement2;
label-name:
Other statements;
goto statement

n=10;

A:
n=10 printf(“%d “, n);
n = n -1;
A

Print
n
if (n>0)
goto A;
n = n -1

Output:
is n>0? True A

10 9 8 7 6 5 4 3 2 1
False
#include<stdio.h>
void main() Program to
{
int x; show goto
printf(“enter a number: ”);
scanf(“%d”,&x); statement.
if(x%2==0)
goto even;
else
goto odd;
even:
printf(“ %d is even”, x);
return;
odd:
printf(“%d is odd”, x);
}

enter a number: 18
18 is even
return statement
• Exits the function.
• return exits immediately from the currently
executing function to the calling routine,
optionally returning a value. The syntax is:
• return [expression];
• For example,
int sqr (int x){
return (x*x);
}
working
Points to remember
• for(;;)--- Infinite loop
• It is so important to remember that missing
condition makes a loop as infinite loop because for
loop treats no condition as true.
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;)
printf("\t%d",i++);
return 0;
}
#include<stdio.h>
int main()
{
int sum=0,i=1;
for(;i<=5;i++)
sum=sum+i;
printf("Sum of natural numbers from 1 to 5:
%d",sum);
return 0;
}
#include<stdio.h>
int main()
{
int i;
for(i=1;;i++)
printf("\t%d",i);
return 0;
}
Output:infinite
MCQs Link
• https://www.sanfoundry.com/c-interview-que
stions-answers/
• https://www.geeksforgeeks.org/c-multiple-ch
oice-questions/
• https://www.indiabix.com/c-programming/qu
estions-and-answers/
• http://www.tutorialspoint.com/cprogramming
/cprogramming_online_quiz.htm
• https://codingfox.com/7-4-for-loop-points-to-r
emember/
Predict the output of the program ?
#include<stdio.h>
int main()
{
if(printf("ABC"))
printf("True");
else
printf("False");
return 0;
}
a. ABC
b. ABCFalse
c.True
d. ABCTrue

You might also like