0% found this document useful (0 votes)
9 views

PPS Unit 3-Notes

The document provides an overview of control statements in C programming, focusing on conditional branching and iterations. It details various types of control statements including decision-making statements (if, if-else), selection statements (switch-case), iteration statements (for, while), and jump statements (break, continue, goto). Additionally, it explains the syntax and usage of these statements with examples to illustrate their functionality in programming.

Uploaded by

aryankondekar15
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)
9 views

PPS Unit 3-Notes

The document provides an overview of control statements in C programming, focusing on conditional branching and iterations. It details various types of control statements including decision-making statements (if, if-else), selection statements (switch-case), iteration statements (for, while), and jump statements (break, continue, goto). Additionally, it explains the syntax and usage of these statements with examples to illustrate their functionality in programming.

Uploaded by

aryankondekar15
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/ 30

1

Subject : Programming for Problem Solving


Unit-III - (Conditional Branching and Iterations)
Control Statements in C
Control statements enable us to specify the flow of program control — that is,
the order in which the instructions in a program must be executed. They make it
possible to make decisions, to perform tasks repeatedly or to jump from one
section of code to another.
Types of Control Statements
There are four types of control statements in C:
1. Decision making statements (if, if-else)
2. Selection statements (switch-case)
3. Iteration statements (for, while, do-while)
4. Jump statements (break, continue, goto)

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.

Need of Conditional Statements


• There come situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next.
• Similar situations arise in programming also where we need to make some
decisions and based on these decisions we will execute the next block of
code.
o For example, in C if x occurs then execute y else execute z. There can
also be multiple conditions like in C if x occurs then execute p, else if
condition y occurs execute q, else execute r.
o This condition of C else-if is one of the many ways of importing
multiple conditions.

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
2

4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:
• break
• continue
• goto
• return
So start discussing each of them one by one.

1. if in C
The if-else statement is used to carry out a logical test and then take one of twopossible
actions depending on the outcome of the test (ie, whether the outcome is trueor false).
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)
{
// 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

Flow Diagram of if Statement


3

Example of if in C
// C program to illustrate If statement

#include <stdio.h>

int main()

int i = 10;

if (i > 15)

printf("10 is greater than 15");

printf("I am Not in if");

Output
I am Not in if
As the condition present in the if statement is false. So, the block below the if
statement is not executed.

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
}
4

Flowchart of if-else Statement

Flow Diagram of if else

Example of if-else
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) {
printf("i is smaller than 15");
}
else {
printf("i is greater than 15");
}
return 0;

Output
5

i is greater than 15
The block of code following the else statement is executed as the condition present
in the if statement is false.

Another Example:
int time = 20;
if (time < 18)
{
printf("Good day.");
} else
{
printf("Good evening.");
}
// Outputs "Good evening."

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)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

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)
6

printf("i is smaller than 12 too\n");


else
printf("i is greater than 15");

}
}
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


7

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

Another Example
int time = 22;
if (time < 10)
{
printf("Good morning.");
} else if (time < 18)
{
printf("Good day.");
} else if (time < 21)
{
printf("Good evening.");
} else
{
printf("Good Neight.");
}

// Outputs "Good evening."

Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next
condition, in the else if statement, is also false, so we move on to the else condition
since condition1 and condition2 is both false - and print to the screen "Good evening".
8

However, if the time was 14, our program would print "Good day."

5. 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

Flowchart of switch in C
9

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break statement breaks out of the switch block and stops the execution
• The default statement is optional, and specifies some code to run if there is no case match

The example below uses the weekday number to calculate the weekday name:

Example
#include<stdio.h>
Int main()
{
int day = 4;
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
Return (0);
}

// Outputs "Thursday" (day 4)

The break Keyword


When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
10

A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;

switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}

// Outputs "Looking forward to the Weekend"

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

6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar
to the if-else statement. It is also known as the ternary operator as it works on three
operands. It is often used to replace simple if else statements:
11

Syntax of Conditional Operator


(condition) ? [true_statements] : [false_statements];
Flowchart of Conditional Operator

Flow Diagram of Conditional Operator

Example
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");

Example of Conditional Operator


// C Program to illustrate the use of conditional operator
#include <stdio.h>
// driver code
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);
12

// changing the value of flag


flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);
return 0;
}

Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25

Another Example if-else


int myNum = 5;

if (myNum % 2 == 0)
{
printf("%d is even.\n", myNum);
}
else
{
printf("%d is odd.\n", myNum);
}

7. Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the
functions in a program. They support four types of jump statements:

A) break
This loop control statement is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop iterations stop there,
and control returns from the loop immediately to the first statement after the loop.

Syntax of break
break;
Basically, break statements are used in situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on
some condition.
13

Example of break
// C program to illustrate

// to show usage of break

// statement
#include <stdio.h>
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
}
}
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
14

int n = 6;
// key to be searched
int key = 3;
// Calling function to find the key
findElement(arr, n, key);
return 0;
}

Output
Element found at position: 3

B) continue
• This loop control statement is just like the break statement.
The continue statement is opposite to that of the break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop.
• As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the
loop, the code inside the loop following the continue statement will be
skipped and the next iteration of the loop will begin.
Syntax of continue
continue;

Example of continue
// C program to explain the use of continue statement
#include <stdio.h>
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++)
{
// If i is equals to 6, continue to next iteration without printing
if (i == 6)
continue;
else
// otherwise print the value of i
printf("%d ", i);
}
return 0;
}

Output
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C, it will be local to that if/else block only. You
can use global variables inside the if/else block. If the name of the variable you
15

created in if/else is as same as any global variable then priority will be given to the
`local variable`.

#include <stdio.h>

int main()

int gfg = 0; // local variable for main

printf("Before if-else block %d\n", gfg);

if (1) {

int gfg = 100; // new local variable of if block

printf("if block %d\n", gfg);

printf("After if block %d", gfg);

return 0;

Output
Before if-else block 0
if block 100
After if block 0

C) goto
The goto statement in C also referred to as the unconditional jump statement can be
used to jump from one point to another within a function.

Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement
marked as a label. Here, a label is a user-defined identifier that indicates the target
statement. The statement immediately followed after ‘label:’ is the destination
statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the
above syntax.
16

Examples of goto
// C program to print numbers from 1 to 10 using goto statement
#include <stdio.h>
// function to print numbers from 1 to 10
int main()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10

D) return
• The return in C returns the flow of the execution to the function from where it
is called.
• This statement does not mandatorily need any conditional statements.
• As soon as the statement is executed, the flow of the program stops
immediately and returns the control from where it was called.
• The return statement may or may not return anything for a void function, but
for a non-void function, a return value must be returned.
Flowchart of return

Flow Diagram of return

Syntax of return
return [expression];
17

Example of return
// C code to illustrate return statement
#include <stdio.h>
// non-void return type function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}
// returns void function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}

Output
The sum is 20
18

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.

// C program to illustrate need of loops


#include <stdio.h>
int main()
{
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

There are mainly two types of loops in C Programming:

1. Entry Controlled loops: In Entry controlled loops the test condition


is checked before entering the main body of the loop. For Loop and
While Loop is Entry-controlled loops.

2. Exit Controlled loops: In Exit controlled loops the test condition is


evaluated at the end of the loop body. The loop body will execute
atleast once, irrespective of whether the condition is true or false. do-
while Loop is Exit Controlled loop.
19

Loop Type Description

first Initializes, then condition check, then executes the body


for loop
and at last, the update is done.

while first Initializes, then condition checks, and then executes the
loop body, and updating can be inside the body.

do-while do-while first executes the body and then the condition check is
loop done.

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) //for(int i=1; i<=10; i++) 11
{ {
// printf(“Hello…”);
// body of for loop }
//
}
20

Example:
int n=15;
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}

-In for loop, a loop variable is used to control the loop.


-Firstly we initialize the loop variable with some value, then check its test
condition.
-If the statement is true then control will move to the body and the body of for
loop will be executed.
-Steps will be repeated till the exit condition becomes true.
If the test condition will be false then it will stop.
• Initialization Expression: In this expression, we assign a loop variable
or loop counter to some value. for example: int i=1;

• Test Expression: In this expression, test conditions are performed.


If the condition evaluates to true then the loop body will be executed and
then an update of the loop variable is done.
If the test expression becomes false then the control will exit from the
loop. for example, i<=9;

• Update Expression: After execution of the loop body, loop variable is


updated by some value it could be incremented, decremented, multiplied,
or divided by any value.
21

for loop - Flow Chart:

Example

// C program to illustrate for loop


#include <stdio.h>
int main()
{
int i = 0;

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


{
printf( "Hello World\n");
}
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
22

Hello World
Hello World

Another example :
Write a C program to create table for first 10 natural numbers;

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; int i=1;
while (test_expression) while(i<5)
{ {
// body of the while loop printf(“hello”);
i++; //i=i+1
}
update_expression;
}
23

Flow Diagram for while loop:

// C program to illustrate while loop


#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");

// update expression
i++;
}
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
24

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);
25

// 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++;

} while (i < 1); // Test expression

return 0;
}

Output
Hello World

Above program will evaluate (i<1) as false since i = 2. But still, as it


is a do-while loop the body will be executed once.

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":
26

Example
int i, j;
// Outer loop
for (i = 1; i <= 2; ++i)
{
printf("Outer: %d\n", i); // Executes 2 times

// Inner loop
for (j = 1; j <= 3; ++j)
{
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}

Example
int number = 2;
int i;

// Print the multiplication table for the number 2


for (i = 1; i <= 10; i++)
{
if (i==5)
continue;
printf("%d x %d = %d\n", number, i, number * i);
}

return 0;

Loop Control Statements


Loop control statements in C programming are used to
change execution from its normal sequence.

Name Description

the break statement is used to terminate the


break switch and loop statement. It transfers the
statement execution to the statement immediately
following the loop or switch.
27

Name Description

continue statement skips the remainder body


continue
and immediately resets its condition before
statement
reiterating it.

goto goto statement transfers the control to the


statement labeled statement.

C Break and Continue


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);
}

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++)


28

{
if (i == 4)
continue;
printf("%d\n", i);
}

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example
int i = 0;

while (i < 10) {


if (i == 4) {
break;
}
printf("%d\n", i);
i++;
}

Continue Example
int i = 0;

while (i < 10)


{
if (i == 4)
{
i++;
continue;
}
printf("%d\n", i);
i++;
}

Infinite Loop
An infinite loop is executed when the test expression never
becomes false and the body of the loop is executed
repeatedly. A program is stuck in an Infinite loop when the
condition is always true. Mostly this is an error that can be
resolved by using Loop Control statements.
Using for loop:
29

// C program to demonstrate infinite


// loops using for loop
#include <stdio.h>
int main ()
{
int i;

// This is an infinite for loop


// as the condition expression
// is blank
for ( ; ; )
{
printf("This loop will run forever.\n");
}

return 0;
}

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

Using While loop:


// C program to demonstrate infinite loop using while loop
#include <stdio.h>

int main()
{
while (1)
printf("This loop will run forever.\n");
return 0;
}

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
30

Using the do-while loop:


// C program to demonstrate infinite loop using do-while loop
#include <stdio.h>
int main()
{
do
{
printf("This loop will run forever.\n");
} while (1);

return 0;
}

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

You might also like