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

03_PPS

This document covers control structures in C programming, including conditional statements (if, if-else, switch-case) and loops (for, while, do-while). It explains the usage of break and continue statements, as well as the goto statement for controlling program flow. Additionally, it provides examples of various control structures and their applications in problem-solving scenarios.
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)
8 views

03_PPS

This document covers control structures in C programming, including conditional statements (if, if-else, switch-case) and loops (for, while, do-while). It explains the usage of break and continue statements, as well as the goto statement for controlling program flow. Additionally, it provides examples of various control structures and their applications in problem-solving scenarios.
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/ 60

Programming for Problem Solving

(BE01000121)

UNIT: III Control Structures

Prof. Pinal Mistry


Information Technology Department
Mob: 8128138239
Email: [email protected]
Topic To Be Covered
◆ Conditional Statements: if, if-else, nested if-else, switch-case.

◆ Loops: for, while, do-while loops.

◆ Break and Continue Statements: Usage in loop control.


Conditional Statements

❏ 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:
1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:
❏ Break
❏ Continue
❏ Goto
❏ return
if statement
➔ The general form of a simple if statement is:
if(test expression)
{
statement-block;
}
Statement-x;

➔ The ‘statement-block’ may be a single statement or a group of statements.


➔ If the test expression is true, the statement-block will be executed; otherwise the
statement-block will be skipped and the execution will jump to the statement-x.
➔ Remember, when the condition is true both the statement-block and the statement-x
are executed in sequence.
// 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
if…else statement
➔ The if...else statement is an extension of the simple if statement. The general form is:
if(test expression)
{
True statement-block;
}
else
{
False statement-block;
}
Statement-x;

➔ If the test expression is true, then the true-block statement(s), immediately following
the if statements are executed; otherwise, the falseblock statement(s) are executed.
➔ In either case, either true-block or falseblock will be executed, not both.
➔ In both the cases, the control is transferred subsequently to the statement-x.
// C program to illustrate If…else statement

#include <stdio.h>

int main()
{
int i = 7;

if (i < 15)
{
printf("i is smaller than 15");
}
else
{
printf("i is greater than 15");
}
return 0;
}

Output:
i is smaller than 15
Nested if statement
➔ When a series of decisions are involved, we may have to use more than one if...else
statement in nested form as shown below::
if(test condition1)
{
if(test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
➔ If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test.
➔ If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2
will be evaluated and then the control is transferred to the statement-x.
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10) {
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
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 12 too
Else if ladder statement
➔ There is another way of putting if s together when multipath decisions are involved. A
multipath decision is a chain of if s in which the statement associated with each else is
an if . It takes the following general form:
if(condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
else if(condition-n)
Statement-n;
else
Default-statement;
statement-x;
➔ This construct is known as the else if
ladder.
➔ The conditions are evaluated from the
top (of the ladder), downwards.
➔ As soon as a true condition is found, the
statement associated with it is executed
and the control is transferred to the
statement-x (skipping the rest of the
ladder).
➔ When all the n conditions become false,
then the final else containing the
default-statement will be executed.
// C program to illustrate nested-if statement
#include <stdio.h>
void 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
switch-case statement
➔ We have seen that when one of the many alternatives is to be selected, we can use an
if statement to control the selection.
➔ However, the complexity of such a program increases dramatically when the number
of alternatives increases. The program becomes difficult to read and follow.
➔ At times, it may confuse even the person who designed it.
➔ Fortunately, C has a built-in multiway decision statement known as a switch.
➔ The switch statement tests the value of a given variable (or expression) against a list
of case values and when a match is found, a block of statements associated with that
case is executed.
➔ The general form of the switch statement is as shown below:
switch(expression)
{
case value1:
Block-1;
Break;

Case value2:
Block-2;
Break;

…..
…..

Default:
Default-block;
break;
}
Statement-x;
➔ The expression is an integer expression or characters.
➔ Value-1, value-2 ..... are constants or constant expressions (evaluable to an integral constant) and are known as case
labels .
➔ Each of these values should be unique within a switch statement.
➔ block-1, block-2 .... are statement lists and may contain zero or more statements.
➔ There is no need to put braces around these blocks.
➔ Note that case labels end with a colon (:)
➔ When the switch is executed, the value of the expression is successfully compared against the values value-1,
value-2,.... If a case is found whose value matches with the value of the expression, then the block of statements that
follows the case are executed.
➔ The break statement at the end of each block signals the end of a particular case and causes an exit from the switch
statement, transferring the control to the statement-x following the switch.
➔ The default is an optional case. When present, it will be executed if the value of the expression does not match with
any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x .
#include <stdio.h>
int main() { Output:
// Switch variable
int var = 1; Case 1 is Matched.

switch (var) {
case 1:
printf("Case 1 is Matched.");
break;

case 2:
printf("Case 2 is Matched.");
break;

case 3:
printf("Case 3 is Matched.");
break;

default:
printf("Default case is Matched.");
break;
}
return 0; }
THE ? : OPERATOR
➔ The C language has an unusual operator, useful for making two-way decisions.
➔ This operator is a combination of ? and :, and takes three operands.
➔ This operator is popularly known as the conditional operator .
➔ The general form of use of the conditional operator is as follows:
conditional expression ? expression1 : expression2
➔ The conditional expression is evaluated first. If the result is non-zero, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated
and its value is returned.
➔ For Example:
Goto Statement
➔ The goto statement in C allows the program to jump to some part of the code, giving you more control over its
execution.
➔ While it can be useful in certain situations, like error handling or exiting complex loops, it’s generally not
recommended because it can make the code harder to read and maintain.
➔ The goto requires a label in order to identify the place where the branch is to be made. A label is any valid
variable name, and must be followed by a colon. The label is placed immediately before the statement where
the control is to be transferred.
➔ The general forms of goto and label statements are shown below:
➔ The label : can be anywhere in the program either before or after the goto label; statement.
➔ During running of a program when a statement like
goto begin; is met,
the flow of control will jump to the statement immediately following the label begin :
This happens unconditionally

➔ Note that a goto breaks the normal sequential execution of the program.
➔ If the label: is before the statement goto label ; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump .
➔ On the other hand, if the label: is placed after the goto label ; some statements will be skipped and the jump is
known as a forward jump.
➔ Example:
#include <stdio.h>

int main() { In this program, a predefined value is assigned to n.


int n = 0;
If n equals 0, the program jumps to the jump_here label
// If the number is zero, jump to using the goto statement.
// jump_here label If n is non-zero, the program prints the value.
if (n == 0)
goto jump_here; The goto statement is used to control the flow by jumping
to a specific part of the program.
// This will be skipped
printf("You entered: %d\n", n);

jump_here:
printf("Exiting the program.\n");
return 0;
}

Output:
Exiting the program.
➔ Example: Check Even or Odd Number
#include <stdio.h>

int main() {
int n = 26;
if (n % 2 == 0)
// jump to even
goto even;
else
// Jump to odd
goto odd;

even:
printf("%d is even", n);
return 0;

odd:
printf("%d is odd", n);
return 0;
}
Output:
26 is even
➔ Example: Prints numbers from 1 to 10
#include <stdio.h>

int main(){

int n = 1;

// Label here
label:
printf("%d ", n);
n++;
if (n <= 10)

// jumb back to the label


goto label;
return 0;
}

Output:
1 2 3 4 5 6 7 8 9 10
Program 1: Find the Minimum of Two Numbers
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a < b)
{
printf("%d is the minimum number.\n", a);
} else if (b < a)
{
printf("%d is the minimum number.\n", b);
} else
{
printf("Both numbers are equal.\n");
} return 0; }
Program 2: Check Divisibility by 3 and 5
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 3 == 0 && num % 5 == 0) {
printf("The number is divisible by both 3 and 5.\n");
} else if (num % 3 == 0) {
printf("The number is divisible by 3.\n");
} else if (num % 5 == 0) {
printf("The number is divisible by 5.\n");
} else {
printf("The number is not divisible by 3 or 5.\n");
}
return 0;
}
Program 3: Check Whether a Character is a Vowel or Consonant

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
printf("%c is a vowel.\n", ch);
} else {
printf("%c is a consonant.\n", ch);
}
return 0;
}
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.
❏ A loop in C consists of two parts, a body of a loop and a control statement. The control statement is a
combination of some conditions that direct the body of the loop to execute until the specified condition
becomes false.
❏ Types of Loops in C:
❏ Depending upon the position of a control statement in a program, looping statement in C is classified into two
types:

1. Entry controlled loop

2. Exit controlled loop


Entry Controlled Loop Exit Controlled Loop
➔ In the entry-controlled loop, the control conditions ➔ In the case of an exit-controlled loop, the test is

are tested before the start of the loop execution. performed at the end of the body of the loop and

➔ If the conditions are not satisfied, then the body of therefore the body is executed unconditionally for

the loop will not be executed. the first time.

➔ Also known as the pre-test Loop. ➔ Also known as the post-test Loop.
➔ The control conditions must be well defined and specified otherwise the loop will execute an infinite number
of times. The loop that does not stop executing and processes the statements number of times is called as an
infinite loop. An infinite loop is also called as an “Endless loop.”
➔ Following are some characteristics of an infinite loop:
◆ No termination condition is specified.
◆ The specified conditions never meet.
➔ The specified condition determines whether to execute the loop body or not.
➔ ‘C’ programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop


While Loop
➔ The simplest of all the looping structures in C is the while statement.
➔ The basic format of the while statement is

while(test_condition)
{
Body of loop
}

➔ The while is an entry-controlled loop statement.


➔ The test-condition is evaluated and if the condition is true , then the body of the loop is executed.
➔ After execution of the body, the test-condition is once again evaluated and if it is true, the body is executed once again.
This process of repeated execution of the body continues until the test-condition finally becomes false and the control is
transferred out of the loop.
➔ On exit, the program continues with the statement immediately after the body of the loop.
➔ The body of the loop may have one or more statements. The braces are needed only if the body contains two or more
statements. However, it is a good practice to use braces even if the body has only one statement.
➔ Example:

#include <stdio.h>

int main() {
int i = 1;
// Condition for the loop
while (i <= 5)
{
printf("PPS\n");
// Increment i after each iteration
i++;
Output:
}
return 0; PPS
PPS
} PPS
PPS
PPS
➔ Example: Calculate the Sum of First N Natural Numbers

#include <stdio.h>
int main() {
int sum = 0, i = 1;
while (i <= 10) {
// Add the current value of i to sum
sum += i;
// Increment i
i++;
}
printf("%d", sum);
Output:
return 0;
} 55
Do…while Loop
➔ While loop makes a test of condition before the loop is executed. Therefore, the body of the loop may not be executed
at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the
body of the loop before the test is performed. Such situations can be handled with the help of the do statement.
➔ The basic format of the do…while statement is

do
{
Body of loop
}
while(test-condition);

➔ The do…while is an exit-controlled loop statement.


➔ On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the
test-condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of
the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop
will be terminated and the control goes to the statement that appears immediately after the while statement.
➔ Example:

#include <stdio.h>

void main() {
int i = 1;
do
{
printf("PPS\n");
// Increment i after each iteration
i++;
}
while(i<=5); // Condition for the loop
Output:

PPS
} PPS
PPS
PPS
PPS
➔ Example:

#include <stdio.h>
void main() {
int number;
// Prompt the user for input
do
{
printf("Enter a number (negative number to quit): ");
scanf("%d", &number);
// If the number is not negative, print it
if (number >= 0) {
printf("You entered: %d\n", number);
}
}
while (number >= 0); // Continue until a negative number is entered
printf("Program terminated.\n");
}
for Loop
➔ The for loop is another entry-controlled loop that provides a more concise loop control structure.
➔ The general form of the for loop is

for(initialization ; test-condition ; increment or decrement)


{
Body of loop
}

➔ The execution of the for statement is as follows:


➔ Initialization of the control variables is done first, using assignment statements such as i = 1 and count = 0. The
variables i and count are known as loop-control variables.
➔ The value of the control variable is tested using the test-condition. The test-condition is a relational expression, such as
i < 10 or i > 0, that determines when the loop will exit. If the condition is true , the body of the loop is executed;
otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
➔ When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last
statement in the loop. Now, the control variable is incremented or decremented using an assignment statement, such
as i = i+1 or i = i – 1, and the new value of the control variable is again tested to see whether it satisfies the loop
condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the
control variable fails to satisfy the test-condition.

Example: C program using a for loop to print the numbers from 1 to 10:
#include <stdio.h>

int main() {
// Using a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++)
{
printf("%d\n", i);
}

return 0;
}
➔ When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last
statement in the loop. Now, the control variable is incremented or decremented using an assignment statement, such
as i = i+1 or i = i – 1, and the new value of the control variable is again tested to see whether it satisfies the loop
condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the
control variable fails to satisfy the test-condition.

Example: C program using a for loop to print the numbers from 1 to 10:
#include <stdio.h>

int main() {
// Using a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++)
{
printf("%d\n", i);
}

return 0;
}
➔ Example: calculate and print the squares of numbers from 1 to 5

#include <stdio.h>

int main() {
// Loop through numbers from 1 to 5
for (int num = 1; num <= 5; num++)
{
int square = num * num; // Calculate the square of the number
printf("The square of %d is %d\n", num, square); // Print the result
}

// End of program
printf("Program has finished calculating squares.\n");

return 0;
}
● Additional Features of for Loop
1. The for loop in C has several capabilities that are not found in other loop constructs. For example, more than one
variable can be initialized at a time in the for statement. The statements

p=1;

For (n=0;n<17;n++)

Can be rewritten as

for (p=1, n=0; n<17; n++)

2. Like the initialization section, the increment section may also have more than one part.
3. The third feature is that the test-condition may have any compound relation and the testing need not be limited only to
the loop control variable.

The loop uses a compound test condition with the counter variable i and sentinel variable sum . The loop is executed as long
as both the conditions i < 20 and sum < 100 are true. The sum is evaluated inside the loop.
➔ Comparison of the Three Loops
Nesting of for Loop
➔ Nesting of loops, that is, one for statement within another for statement, is allowed in C. For example, two loops can be
nested as follows:

for ( initialization; condition; increment )


{

for ( initialization; condition; increment )


{

// statement of inside loop


}

// statement of outer loop


}

The nesting may continue up to any desired level. The loops should be properly indented so as to enable the reader to easily
determine which statements are contained within each for statement.
Example: Multiplication Table Using Nested for Loops

#include <stdio.h>
int main() {
int i, j;
// Outer loop for rows
for (i = 1; i <= 10; i++) {
// Inner loop for columns
for (j = 1; j <= 10; j++) {
// Print the product of i and j 1 2 3 4 5 6 7 8 9 10
printf("%d\t", i * j);
} 2 4 6 8 10 12 14 16 18 20
// Move to the next line after each row is printed 3 6 9 12 15 18 21 24 27 30
printf("\n"); 4 8 12 16 20 24 28 32 36 40
}
5 10 15 20 25 30 35 40 45 50
return 0; 6 12 18 24 30 36 42 48 54 60
}
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Example: Star Pattern
*
#include <stdio.h> **
***
int main() {
int i, j; ****
int n = 5; // Number of rows *****
// Outer loop for the number of rows
for (i = 1; i <= n; i++) {
// Inner loop for printing stars in each row
for (j = 1; j <= i; j++) {
printf("* ");
}
// Move to the next line after printing stars in one row
printf("\n");
}
return 0;
}
Example: Star Pattern
*
#include <stdio.h> ***
int main() { *****
int i, j, k; *******
int n = 5; // Number of rows
*********
// Outer loop for the number of rows
for (i = 1; i <= n; i++) {
// Print spaces for alignment
for (j = i; j < n; j++) {
printf(" ");
}
// Print stars
for (k = 1; k <= (2 * i - 1); k++) {
printf("*");
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Example: Number Pattern
1
#include <stdio.h> 12
int main() { 123
int i, j; 1234
int n = 5; // Number of rows 12345
// Outer loop for the number of rows
for (i = 1; i <= n; i++) {
// Inner loop to print numbers
for (j = 1; j <= i; j++) {
printf("%d ", j);
}
// Move to the next line after printing numbers in one row
printf("\n");
}
return 0;
}
Example: Alphabet Pattern A
AB
#include <stdio.h>
ABC
int main() { ABCD
int i, j; ABCDE
int n = 5; // Number of rows
// Outer loop for the number of rows
for (i = 1; i <= n; i++) {
// Inner loop to print letters
for (j = 1; j <= i; j++) {
printf("%c ", 'A' + j - 1); // Printing characters starting from 'A'
}
// Move to the next line after printing letters in one row
printf("\n");
}
return 0;
}
➔ Entry Controlled Loop Vs Exit Controlled Loop

Parameter Entry Control Exit Control

Flow of loop The condition is tested at the beginning of the Loop The condition is tested at the end of the Loop after the loop
before the loop body executes. body is executed at least once.

The number of times the loop The loop body may not be run if the condition is false. The loop body runs at least once, even if the condition is false.
is executed

Example loops While Loop, For loop are some popular Entry Do-while is usually used as Exit Controlled Loop.
Controlled Loops.

Efficiency Since the condition is tested at the beginning of the Exit-controlled loops consistently execute the loop body at least
Loop, the loop body's code can be skipped if it is false. once, which can be less efficient if the condition is false.

Application It is mostly used when we know how many iterations are It is used when the loop body’s code needs to be executed at
required and the loop condition is always met. least once.
Break Statement in Loop:

➔ The break statement ends the loop immediately when it is encountered.


➔ Its syntax is:
break;
➔ The break statement is almost always used with if...else statement inside the loop.
Example 1: break statement
#include <stdio.h>

int main() {
int i;
double number, sum = 0.0;

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


printf("Enter n%d: ", i);
scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Continue Statement in Loop:

➔ The continue statement skips the current iteration of the loop and continues with the
next iteration.
➔ Its syntax is:
continue;
➔ The continue statement is almost always used with the if...else statement.
Example 1: Continue statement

#include <stdio.h>

int main() {
int i;
double number, sum = 0.0;

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


printf("Enter n%d: ", i);
scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Break Vs Continue Statement

break continue

The break statement terminates the loop and brings the The continue statement terminates only the current iteration and
program control out of the loop. continues with the next iterations.

The syntax is: break; The syntax is: continue;

The break can also be used in switch case. Continue can only be used in loops.

You might also like