You are on page 1of 37

UNIT II -DECISION CONTROL STATEMENTS

Managing Input and Output operations, Decision Control Statements: Decision control
statements, Selection/conditional branching Statements: if, if-else, nested if, if-elif-else
statements. Basic loop Structures/Iterative statements: while loop, for loop, selecting
appropriate loop. Nested loops break and Continue statements.

Managing Input and Output operations:


I/O operations are helpful for a program to interact with users. C stdlib is the
standard C library for input-output operations. Two essential streams play their role
when dealing with input-output operations in C. These are:

1. Standard Input (stdin)


2. Standard Output (stdout)

Standard input or stdin is used for taking input from devices such as the keyboard
as a data stream. Standard output or stdout is used to give output to a device such as a
monitor. For I/O functionality, programmers must include the stdio header file within
the program.

Reading Characters in C:
The easiest and simplest of all I/O operations are taking a character as input by
reading that character from standard input (keyboard). getchar() function can be used
to read a single character. This function is an alternative to scanf() function.
Syntax:
var_name = getchar();
Example
#include<stdio.h>
void main()
{
char title;
title = getchar();
}

There is another function to do that task for files: getc() which is used to accept a
character from standard input.

Writing characters in C:
Similar to getchar(), there is another function that is used to write characters,
but one at a time. Syntax:
putchar(var_name);
Example:
#include<stdio.h>
void main()
{
char result = 'P';
putchar(result);
putchar('\n');
}

C Programming Input Output (I/O):


ANSI standard has defined many library functions for input and output in C
language. Functions printf() and scanf() are the most commonly used to display out
and take input respectively. Let us consider an example:

Output
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}

C Programming

Explanation of How this program works

∙ Every program starts from main() function.


∙ printf() is a library function to display output which only works if #include<stdio.h>is
included at the beginning.
∙ Here, stdio.h is a header file (standard input output header file) and #include is
command to paste the code from the header file when necessary. When compiler
encounters printf() function and doesn't find stdio.h header file, compiler shows
error.
∙ Code return 0; indicates the end of program. You can ignore this statement but, it is
good programming practice to use return 0;.

I/O of integers in C

Output
#include<stdio.h>
int main()
{
int c=5;
printf("Number=%d",c);
return 0;
}

Number=5

Inside quotation of printf() there, is a conversion format string "%d" (for integer). If
this conversion format string matches with remaining argument,i.e, c in this case, value
of c is displayed.
#include<stdio.h>
int main()
{
int c;
printf()("Enter a number\n");
scanf()("%d",&c);
printf()("Number=%d",c);
return 0;
}

Output
Enter a number
4
Number=4
The scanf() function is used to take input from user. In this program, the user is
asked a input and value is stored in variable c. Note the '&' sign before c. &c denotes
the address of c and value is stored in that address.

I/O of floats in C
#include <stdio.h>
int main(){
float a;
printf("Enter value: ");
scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d
return 0;
}

Output
Enter value: 23.45
Value=23.450000
Conversion format string "%f" is used for floats to take input and to display
floating value of a variable.

I/O of characters and ASCII code


#include <stdio.h>
int main(){
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0; }

Output
Enter character: g
You entered g.
Conversion format string "%c" is used in case of characters.

ASCII code
When character is typed in the above program, the character itself is not
recorded a numeric value(ASCII value) is stored. And when we displayed that value
by using "%c", that character is displayed.
#include <stdio.h>
int main(){
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.\n",var1); /* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
return 0;
}

Output
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.

You can display character if you know ASCII code only. This is shown by following
example.

Output
#include <stdio.h>
int main(){
int var1=69;
printf("Character of ASCII value 69: %c",var1);
return 0;
}

Character of ASCII value 69: E

The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII
value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.

Decision Control Statements


In any programming language, there is a need to perform different tasks based on the
condition. there must be a logic in place that checks the condition and if the condition returns
true it performs a task else it performs a different task Using decision control statements we can
control the flow of program in such a way so that it executes certain statements based on the
outcome of a condition (i.e. true or false).

Selection/conditional branching Statements:


Many programs require a logical test to be carried out at some particular point.
Based on the condition, some actions will be carried out. This is known as Branching.
There are various branching statements available in C Language. They are,
∙ Simple-if
∙ if..else
∙ Nested if
∙ if..else..if ladder
∙ switch case

1. Simple if
if statement is the most simple decision-making statement. If condition is true,
given statements will be executed. If condition is not true i.e., false, given statements
will not be executed.

Syntax
if(condition)
{
Statements;
}

Flowchart Program
if
condition

True

Statements

Next Statement

False
Output
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("\nEnter the number");
scanf("%d",&n);
if(n>0)
printf("\nNumber is Positive");
getch();
}

Enter the number: 6


Number is Positive

Enter the number: -7

2. if else statement
If condition is true, some set of statements will be executed. If condition
is not true i.e., false, another set of statements will be executed.
Syntax
if(condition)
{
Statement1;
}
else
{
Statement2;
}

Here, if condition is true, statement1 is executed and if condition is


false, statement2 is executed.

Flowchart Program
Statement1

True False
if
condition
?

Statement2

Next Statement

Write a C Program to find whether the given number is Odd or Even number,
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("\nEnter the number");
scanf("%d",&n);
if(n%2==0)
printf(“%d is Even Number");
else
printf(“%d is Odd Number”);
getch();
}
Output
Enter the number: 6
6 is Even Number

Enter the number: 7


7 is Odd Number

3. Nested if statement
If one or more statements are embedded within the if statement, it is
known as Nested if statement.
Syntax
if(condition1)
{
if(condition2)

Statement1; else
Statement2; }
else
{
Statement3;
}

Flowchart

False if (cond1)
?
True

True False if
Statement1

Next Statement
Program
Statement3
e
cond2
?

Statement2

Write a C Program to find greatest of 3 numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\nEnter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“%d is great",a);
else
printf(“%d is grear”,c);
}
else
{
Output
if(b>c)
printf(“%d is great”,b);
else
printf(“%d is great”,c);
}
getch();
}

Enter 3 number: 6 2 1
6 is great

Enter the number: 2 6 8


8 is great

4. if-else-if ladder statement


This control structure is clear and easier format. Nested-if statement is
quite complex when there are more than three alternatives. But if-else-if ladder
can work clearly with many alternative conditions.
Syntax
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
else
default statement;

Flowchart

True
Statement1
If
Condition
1
?

True
False

False
If

Statement2
Condition
2
?

True

If
Condition 3

?
False

Statement3 Default
stmt

Next Statement
Program
Write a C Program to print the student grade based on the mark
limit. Note: As per Anna University mark system, mark and its
respective grade is given below
Mark Range Grade Condition Applicable for this control
structure

91-100 S Mark>90

81-90 A Mark>80

71-80 B Mark>70

61-70 C Mark>60

57-60 D Mark>56

50-56 E Mark>=50

Below 50 Fail Mark<50

Output
#include<stdio.h>
#include<conio.h>
void main()
{
int mark;
clrscr();
printf("\nEnter the mark:");
scanf("%d",&mark);
if(mark>90)
printf("S Grade");
else if(mark>80)
printf("A Grade");
else if(mark>70)
printf("B Grade");
else if(mark>60)
printf("C Grade");
else if(mark>56)
printf("D Grade");
else if(mark>=50)
printf("E Grade");
else
printf("Fail Mark");
getch();
}

Enter the mark: 85


A Grade

Enter the mark: 50


E Grade

Enter the mark: 45


Fail Mark

Switch statement
Switch statement is a multiple branching statement. Switch statement
allows user to make a decision from a number of choices. Selection is based on
the current value of expression which is included in the switch statement.

Syntax
Flowchart
switch(choice)
{
case 1:
block1;
break;
case 2:
block2;
break;
case 3:
block3;
break;
.
case n:
blockn;
break;
default:
default statement; }

switch
choice

case 1 case 2 case 3 case n default

Block1 break
Block2 break
Block3 break
Block4 break
Default Block break

Exit
Program

Write a C Program to print the student grade based on the mark limit.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,choice;
clrscr();

Output
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\n1.Add\n2.Subtract\n3.Multiply\n4.Divide"); printf("\nEnter the
choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Sum is %d",a+b);
break;
case 2:
printf("Difference is %d",a-b);
break;
case 3:
printf("Product is %d",a*b);
break;
case 4:
printf("Quotient is %d",a/b);
break;
default:
printf("Invalid choice");
}
getch();
}

Enter 2 numbers: 10 5
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 1
15
Enter choice: 2
5
Enter choice: 3
50
Enter choice: 4
2

Looping Statement/Iterative statements:


A loop is defined as a block of statement which is repeatedly executed for
certain number of times. A group of instructions executed until some logical condition
is satisfied. It is known as looping. Looping process include 3 main actions.

1. Initialization of condition variable


2. Test the conditional variable for execution
3. Incrementing or updating the condition variable
The test may be either to determine whether the loop has been repeated for
specified number of times or to exit for the loop.

Various Looping statements are,


∙ while
∙ do-while
∙ for

1. while loop
The simplest form of looping structure in C language is the while statement. It
is also called an Entry Controlled Loop. In while loop, condition is evaluated first if
condition is true, body of the loop will be executed. If condition is false, body of the
loop will be skipped from execution.

Syntax
while(condition)
{
body of loop
}

Flowchart

Entry

Test
condition ?
True
False Next statement (if any)

Body of the loop


Program
1. Write a C Program to print 0 to 10
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0; //initialization
clrscr();
while(i<=10) //Test condition
{
printf("%d\n",i);
i=i+1; //increment
}
getch();
}

Output
0
1
2
3
4
5
6
7
8
9
10

2. Write a C Program to print 10 to 0


Output
#include<stdio.h>
#include<conio.h>
void main()
{
int i=10; //initialization
clrscr();
while(i>=0) //Test condition
{
printf("%d\t",i);
i=i-1; //decrement
}
getch();
}

10 9 8 7 6 5 4 3 2 1 0

3. Write a C Program to print even number upto 20 (i.e., 2 4 6 8 10..... 20)

Output
#include<stdio.h>
#include<conio.h>
void main()
{
int i=2; //initialization
clrscr();
while(i<=20) //Test condition
{
printf("%d\t",i);
i=i+2; //increment
}
getch();
}

2 4 6 8 10 12 14 16 18 20

2. do - while loop
Do-while loop is also called an Exit Controlled Loop. In do-while loop,
body of the loop will be executed once first, later if condition is true, body of
the loop will be executed repeatedly until condition fails. If condition is false,
body of the loop will be executed only once.

Syntax
do
{
body of loop
} while(condition);

Note: condition statement in do-while loop should be terminated with semicolon


(;) compulsorily.

Flowchart

Entry

Body of the loop


Program
True Test
condition
?
False
Next
statement

1. Write a C Program to print 0 to 10


#include<stdio.h>
#include<conio.h>
void main()
{
int i=0; //initialization
clrscr();
do
{
printf("%d\t",i);
i=i+1; //increment

} while(i<=10); //Test condition


getch();
}

Output
0 1 2 3 4 5 6 7 8 9 10

2. Write a C Program to print odd numbers upto 20


Output
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1; //initialization
clrscr();
do
{
printf("%d\t",i);
i=i+2; //increment

} while(i<20); //Test condition


getch();
}

1 3 5 7 9 11 13 15 17 19

Difference between while and do-while loop


S.No while loop do-while loop

1 Entry Controlled Loop. Exit Controlled Loop.

2 Condition is evaluated first. Condition is evaluated at end.

3 Body of the loop is executed only if the Body of the loop is executed at least once
test condition is true. even if the condition fails.

4 Syntax Syntax

while(condition) do
{ {
body of loop body of loop
} } while(condition);
5 Example Example

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int i=6; int i=6;
clrscr(); clrscr();
while(i<5) do
{ {
printf("Welcome"); printf("Welcome");
} }while(i<5);
printf("\nHave a Nice day"); printf("\nHave a Nice day");
getch(); getch();
} }

Output Output

Have a Nice day Welcome


Have a Nice day

3. for loop
If the programmer knows how many times the statement will repeat,
then for loop is used. for loop is most commonly and properly used loop in C
Language. It allows specifying three important actions of loop in single line.

Syntax
for(initialization;test_condition;increment/decrement) {
body of loop
}

Note: Here all three actions (i.e., initialization, test condition and
increment/decrement) are performed in single line within for loop. Each action
is separated using semicolon (;).

Flowchart
Intialization

Test condition
?

True

Body of the loop

Increment/decrement
FalseNext statement

Above flowchart represents the actual execution procedure of for loop.


Generally user represent for loop in larger program as follows.

for (i=0; i<=10; i++)

True

Body of loop
False

Program
1. Write a C Program to print 0 to 10 using for loop
Output
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<=10;i++)
{
printf("%d\t",i);
}
getch();
}

0 1 2 3 4 5 6 7 8 9 10

2. Write a C Program to print even number upto 100 (i.e., 2 4 6 8 10..... 100)

Output
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=2;i<=100;i+=2)
{
printf("%d\t",i);
}
getch();
}

2 4 6 8 10 12 14 16 ............... 100

Unconditional Statements
There are few unconditional statements used in C Language. They are
∙ goto statement
∙ break
∙ continue

1. goto statement
It transfers the control from one point to another point without checking
any condition. Goto statement is used to move from one position to another
position in the program unconditionally.

Syntax
goto label;
.....
.....
label:
statements of label

Program
1. Write a C Program to print student result using goto statement.
Output
#include<stdio.h>
#include<conio.h>
void main()
{
int mark;
clrscr();
printf("Enter mark:");
scanf("%d",&mark);
if(mark>50)
goto result;
else
printf("\nFail Mark");
result:
printf("\nPass Mark");
getch();
}

Enter mark: 86
Pass Mark

Enter mark: 35
Fail Mark

2. break statement
Break statement is used to terminate or stop the loop. It is used to jump
out of the loop instantly without waiting to get back to the conditional test. It is
often used in switch statement. Break statement can be used in all looping
structures.

Syntax
break;

Program
1. Write a C Program to illustrate purpose of break statement
#include<stdio.h>
#include<conio.h>
void main()
{
int i,limit;
clrscr();
printf("\nEnter limit from 1 to 100");
scanf("%d",&limit);
for(i=1;i<=100;i++)
{
printf("%d\t",i);
if(i==limit)
break; //loop terminates when i value reaches given limit
}
getch();
}

In the above program, for loop is set from 1 to 100. By default loop
works up to 100. Usage of break statement, terminates the loop when user limit
is reached.

Output
Enter limit from 1 to 100: 5
12345

Enter limit from 1 to 100: 2


12

Enter limit from 1 to 100: 15


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

3. continue statement
Continue statement is used to continue next iteration of the loop
statement. It skip the statement given below it and continue loop for the next
condition.
Syntax
continue;

Program
1. Write a C Program to illustrate purpose of break statement
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("Even Numbers:\n");
for(i=1;i<20;i++)
{
if(i%2!=0)
continue; //skip statement below and continue loop
printf("%d\t",i);
}
getch();
}

In the above program, for loop is set from 1 to 20. Usage of continue
statement, skip the [printf("%d\t",i);] for odd numbers, because of condition
[i%2!=0].
i i%2 Condition Result Respective action
(i%2 !=0)

1 1%2 = 1 1 != 0 True Skip 1

2 2%2 = 0 0 != 0 False Print 2

3 3%2 = 1 1 != 0 True Skip 3

4 4%2 = 0 0 != 0 False Print 4

5 5%2 = 1 1 != 0 True Skip 5

6 6%2 = 0 0 != 0 False Print 6

7 7%2 = 1 1 != 0 True Skip 7

8 8%2 = 0 0 != 0 False Print 8

9 9%2 = 1 1 != 0 True Skip 9

10 10%2 = 0 0 != 0 False Print 10


Output

Nested Loops:
Even Number
2 4 6 8 10 12 14 16 18

A nested loop means a loop statement inside another loop statement. That is
why nested loops are also called “loop inside loops“. We can define any number of
loops inside another loop.

Nested for loop


Nested for loop refers to any type of loop that is defined inside a ‘for’ loop.
Syntax:
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}
// C program to print elements of Three-Dimensional Array
// with the help of nested for loop
#include <stdio.h>
int main()
{
// initializing the 3-D array
int arr[2][3][2]
= { { { 0, 6 }, { 1, 7 }, { 2, 8 } },
{ { 3, 9 }, { 4, 10 }, { 5, 11 } } };

// Printing values of 3-D array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at arr[%i][%i][%i] = %d\n",
i, j, k, arr[i][j][k]);
}
}
}
return 0;
}

Output
Element at arr[0][0][0] = 0
Element at arr[0][0][1] = 6
Element at arr[0][1][0] = 1
Element at arr[0][1][1] = 7
Element at arr[0][2][0] = 2
Element at arr[0][2][1] = 8
Element at arr[1][0][0] = 3
Element at arr[1][0][1] = 9
Element at arr[1][1][0] = 4
Element at arr[1][1][1] = 10
Element at arr[1][2][0] = 5
Element at arr[1][2][1] = 11
Nested while Loop
A nested while loop refers to any type of loop that is defined
inside a ‘while’ loop. Syntax:
while(condition) {
while(condition) {
// statement of inside loop
}
// statement of outer loop
}
Example: Print Pattern using nested while loops
// C program to print pattern using nested while loops
#include <stdio.h>
int main()
{
int end = 5;
printf("Pattern Printing using Nested While loop");
int i = 1;
while (i <= end) {
printf("\n");
int j = 1;
while (j <= i) {
printf("%d ", j);
j = j + 1;
}
i = i + 1;
}
return 0;
}

Output
Pattern Printing using Nested While loop
1
12
123
1234
12345
Nested do-while Loop
A nested do-while loop refers to any type of loop that is defined inside
a do-while loop. Syntax:
do{
do{
// statement of inside loop
}while(condition);
// statement of outer loop
}while(condition);
Example: Below program uses a nested for loop to print all prime factors of a number.
Output:
// C Program to print all prime factors
// of a number using nested loop
#include <math.h>
#include <stdio.h>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}

// This condition is to handle the case when n


// is a prime number greater than 2
if (n > 2)
printf("%d ", n);
}
/* Driver program to test above function */
int main()
{
int n = 315;
primeFactors(n);
return 0;
}

3357

Break Inside Nested Loops

Whenever we use a break statement inside the nested loops it breaks the
innermost loop and program control is inside the outer loop.
// C program to show working of break statement
// inside nested for loops
#include <stdio.h>
int main()
{
int i = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {

// This inner loop will break when i==3


if (i == 3) {
break;
}
printf("* ");
}
printf("\n");
}
return 0;
}

Output
***
***
***

***
Continue Inside Nested loops
Whenever we use a continue statement inside the nested loops it skips
the iteration of the innermost loop only. The outer loop remains unaffected.
// C program to show working of continue statement
// inside nested for loops
#include <stdio.h>
int main()
{
int i = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
// This inner loop will skip when j==2
if (j==2) {
continue;
}
printf("%d ",j);
}
printf("\n");
}
return 0;
}

You might also like