UNIT II
2.1 Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These
decision-making statements in programming languages decide the direction of the flow of
program execution.
Types of Conditional Statements in C:
Following are the decision-making statements available in C:
1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
1. if in C
The if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statements is executed otherwise not.
==Syntax of if Statement
if(condition) //(1<10) // true
{
e than 10 thas why corn is true “)printf(“1 is leas
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement
will consider the first immediately below statement to be inside its block.
Flowchart of if Statement
Example of if in C
#include <stdio.h>
int main()
{ // curly bractes
int i = 20;
// condition
if (i > 15) //
{ . ////////////// /////condition
oprintf("20 is greater than 15 cond is true ");
}
Output:
I am Not in if
2. if-else in C
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else when the
condition is false? Here comes the C else statement. We can use the else statement with
the if statement to execute a block of code when the condition is false. The if-else
statement consists of two blocks, one for false expression and one for true expression.
Syntax of if else in C
if (condition) /
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
#include <stdio.h>
int main()
{
int i = 20;
if (i< 15) {
printf("i is greater than 15");
}
else
{
printf(" statement is false");
}
return 0;
}
Output
i is greater than 15
3. Nested if-else in C:
A nested if in C is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, C allow us to nested if statements within
if statements, i.e, we can place an if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
if (condition1) //{
/* code to be executed if condition1 is true */
if (condition2) {
/* code to be executed if condition2 is true */
} else {
/* code to be executed if condition2 is false */
}
} else {
/* code to be executed if condition1 is false */
}
Flowchart of Nested if-else
Example of Nested if-else:
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
if (i == 20) {
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}
Output
i is smaller than 15
i is smaller than 12 too
4. if-else-if Ladder in C:
The if else if statements are used when the user has to decide among multiple options. The C 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 C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.
if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder
Example of if-else-if Ladder
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Output
i is 20
6. switch Statement in C:
The switch case statement is an alternative to the if else if ladder that can be used to execute
the conditional code based on the value of the variable specified in the switch statement. The
switch block consists of cases to be executed based on the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate
any other data type.
Flowchart of switch:
Example of switch Statement
// C Program to illustrate the use of switch statement
#include <stdio.h>
int main()
{
// variable to be used in switch statement
int var = 2;
// declaring switch cases
switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}
Output
Case 2 is executed
#include <stdio.h>
int main()
{
int a;
printf("Enter number of the month you want to see\n");
scanf("%d",&a);
switch(a)
{
case 1:
printf("JANUARY");
break;
case 2:
printf("FEBRUARY");
break;
case 3:
printf("MARCH");
break;
case 4:
printf("APRIL");
break;
case 5:
printf("MAY");
break;
case 6:
printf("JUNE");
break;
case 7:
printf("JULY");
break;
case 8:
printf("AUGUST");
break;
case 9:
printf("SEPTEMBER");
break;
case 10:
printf("OCTOBER");
break;
case 11:
printf("NOVEMBER");
break;
case 12:
printf("DECEMBER");
break;
default:
printf("A YEAR HAS ONLY 12 MONTHS...");
}
}
C – Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple
times without repetition of code.
for Loop :
for loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to
perform n number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//int a=0;
int a;
a=1
// body of for loop
//
}
Example:
#include <stdio.h>
int main() {
// int i;
//0 1234
for ( int i = 0; i < 20 ;i++) {
printf("%d\n", i);
}
return 0;
}
/ Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when count exceeds num
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is terminated on the
basis of the test condition. If the test condition will become false then it will break from the
while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body
will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
// C program to illustrate
// do-while loop
#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
do
{
// loop body
printf( "Hello World\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0;
}
Output
Hello World
1. Nested for Loop
Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the
equivalent flow diagram for nested ‘for’ loops:
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}
Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out"
of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the for loop when i is equal to 4:
Example
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d\n", i);
}
output:
0
1
2
3
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.
This example skips the value of 4:
Example
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}
C
go to statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the
program control to a predefined label. The goto statment can be used to repeat some part of the code for a
particular condition. It can also be used to break the multiple loops which can't be done by using a single break
statement. However, using goto is avoided these days since it makes the program less readable and
complicated.
Syntax:
label:
//some part of the code;
goto label;
Example:
#include <stdio.h>
int main (){
int n = 0;
if (n = = 0)
goto end;
printf("The number is: %d", n);
end:
printf ("End of program");
return 0;
}
2)
Int main()
for(i=1;i<10;i++)
For(j=1;j<I;j++)
Printf(“%d”,j);
//If(j==6)
//Goto out;
Printf(“\n);
//Out:
Return 0;
exit() in C
The C exit() function is a standard library function used to terminate the calling
process. When exit() is called, any open file descriptors belonging to the process
are closed and any children of the process are inherited by process 1, init, and the
process parent is sent a SIGCHLD signal.
It is defined inside the <stdlib.h> header file.
Exit :The exit function in c is defined under the stdlib. h header file is used to terminate the function
currently running. The fuction also terminates all the programs which are running, flushes all the
file buffers, closes all the stream and deletes all the temporary files
Difference between For, While and Do-While Loop in
Programming:
do-while
Feature for Loop while Loop Loop
for (initialization;
condition; while do { } while
Syntax
increment/decrement) (condition) { } (condition);
{}
Declared
outside the Declared
Declared within the
loop; should outside the
loop structure and
Initialization be done loop
executed once at the
explicitly structure
beginning.
before the
loop.
Checked Checked
Checked before each after each
Condition before each
iteration. iteration.
iteration.
Executed
Executed inside the
inside the loop; needs
Executed after each
Update loop; needs to to be
iteration.
be handled handled
explicitly. explicitly.
Useful
Useful when when the
the number of loop block
Suitable for a known must be
iterations is
number of iterations executed at
Use Cases not known in
or when looping over least once,
advance or
ranges. regardless
based on a
condition. of the initial
condition.
Scope
Scope extends
extends beyond the
Initialization
Limited to the loop beyond the loop; needs
and Update
body. loop; needs to to be
Scope
be handled handled
explicitly. explicitly.
DIFF BETWEEN WHILE AND DO WHILE
1 While the loop is an entry The do-while loop is an
. control loop because exit control loop because
firstly, the condition is in this, first of all, the body
checked, then the loop's of the loop is executed
body is executed. then the condition is
checked true or false.
2 The statement of while The statement of the
. loop may not be executed do-while loop must be
at all. executed at least once.
3 The while loop terminates As long as the condition is
. when the condition true, the compiler keeps
becomes false. executing the loop in the
do-while loop.
4 In a while loop, the test In a do-while loop, the
. condition variable must variable of test condition
be initialized first to check Initialized in the loop also.
the test condition in the
loop.
5 In a while loop, at the end In this, at the end of the
. of the condition, there is condition, there is a
no semicolon. semicolon.
Syntax: Syntax:
while (condition) while (condition);
6 While loop is not used for It is mostly used for
. creating menu-driven creating menu-driven
programs. programs because at
least one time; the loop is
executed whether the
condition is true or false.
7 In a while loop, the In a do-while loop,
. number of executions irrespective of the
depends on the condition condition mentioned, a
defined in the while minimum of 1 execution
block. occurs.
8 Syntax of while loop: Syntax of do-while loop:
.
while (condition) do
{ {
Block of statements; statements;
} }
Statement-x; while (condition);
Statement-x;
9 Program of while loop: Program of do-while loop:
.
Program of while loop: #include
#include
#include Void main()
#include {
Void main() int i;
{ clrscr();
int i; i = 1;
clrscr(); do
i = 1; {
while(i<=10) printf("hello");
{ i = i + 1;
printf("hello"); }
i = i + 1; while(i<=10);
} getch();
getch(); }
}