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

Week-4 Control Statements

this is the soluction of week 4
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)
14 views

Week-4 Control Statements

this is the soluction of week 4
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/ 22

Weekk-3 Week-5

Week 4 - Control Statements

Week 4 - Control Statements


Control Statements
Conditional Statement in C
1. if Statement:
2. if-else Statement:
3. if-else if-else Statement:
4. switch Statement:
Nested conditional statements
Loop in C
1. for loop
2. while loop
3. do-while loop
Nested Loop
break, continue, goto statements
1. break Statement:
2. continue Statement:
3. goto Statement:
Control Statement Writing Format
1. Single-Line Statement Format:
2. Multi-Line Statement Format:

Control Statements
Conditional Statement in C
1. if Statement:
The if statement allows you to execute a block of code based on a condition. If the condition is
true, the code block is executed; otherwise, it's skipped.

Control Flow:
Syntax:

1 if (condition)
2 {
3 // Code to be executed if the condition is true
4 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 10;
6 if (x > 5)
7 {
8 printf("x is greater than 5\n");
9 }
10 return 0;
11 }

2. if-else Statement:
The if-else statement is used to execute if block of code when the if condition is true
otherwise else block will be execute.

Control flow:
Syntax:

1 if (condition)
2 {
3 // Code to be executed if the condition is true
4 }
5 else
6 {
7 // Code to be executed if the condition is false
8 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 3;
6 if (x > 5)
7 {
8 printf("x is greater than 5\n");
9 }
10 else
11 {
12 printf("x is not greater than 5\n");
13 }
14 return 0;
15 }
3. if-else if-else Statement:
The if-else if-else statement is used to check multiple conditions in sequence. It comes after
the initial if statement and is executed only if the previous conditions are false.

Control flow:

Syntax:

1
2 if (condition1)
3 {
4 // Code to be executed if condition1 is true
5 }
6 else if (condition2)
7 {
8 // Code to be executed if condition2 is true
9 }
10 else
11 {
12 // Code to be executed if none of the conditions are true
13 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 10;
6 if (x > 15)
7 {
8 printf("x is greater than 15\n");
9 }
10 else if (x > 5)
11 {
12 printf("x is greater than 5 but not greater than 15\n");
13 }
14 else
15 {
16 printf("x is not greater than 5\n");
17 }
18 return 0;
19 }

4. switch Statement:
The switch statement is a powerful control structure that allows you to select one of many code
blocks to be executed based on the value of an expression. It's especially useful when you have
multiple cases to handle and want to avoid using a series of if-else statements.

Control Flow:

Syntax:
1 switch (expression)
2 {
3 case value1:
4 // Code to be executed if expression is equal to value1
5 break;
6 case value2:
7 // Code to be executed if expression is equal to value2
8 break;
9 // ...
10 default:
11 // Code to be executed if none of the cases match
12 }

Here are some important points to note about the switch statement:

1. The switch statement evaluates the expression and then checks it against each case
label. It compares the expression with the value associated with each case . If a match is
found, the corresponding code block is executed. If no match is found, the code within the
default block (if present) is executed.

2. The break statement is crucial in each case . Without it, the execution will "fall through" to
the next case , and all subsequent code blocks will be executed until a break is encountered
or until the end of the switch statement. This behavior can be used intentionally in some
cases, but it's important to be aware of it.

3. The default case is optional. If none of the case values matches the expression , the code
block within the default case is executed.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int day = 2;
6 switch (day)
7 {
8 case 1:
9 printf("Monday\n");
10 break;
11 case 2:
12 printf("Tuesday\n");
13 break;
14 case 3:
15 printf("Wednesday\n");
16 break;
17 default:
18 printf("Other day\n");
19 }
20 return 0;
21 }
In this example, the switch statement evaluates the day variable, which is set to 2. Since day
matches the case 2 , "Tuesday" is printed. The break statements ensure that only the code block
corresponding to the matched case is executed.

If we had omitted the break statements, the program would continue to execute code for
all subsequent cases after matching the first one.

The switch statement is a clean and efficient way to handle multiple conditions, especially when
you have a lot of cases to consider, making your code more readable and maintainable.

Nested conditional statements


Nested conditional statements in C refer to the use of one or more conditional statements (such
as if , else if , or else ) inside another conditional statement. They allow for more complex
decision-making within your code, enabling you to evaluate multiple conditions in a hierarchical
manner. Here are some short notes on nested conditional statements along with examples:

1. Structure: In nested conditional statements, you have one or more conditional statements
inside another conditional statement. The inner conditionals are entirely contained within the
body of the outer conditional.

2. Execution: The outer conditional statement is evaluated first. Depending on its result, the
code inside the corresponding block is executed. Within each block, you may have additional
conditional statements to further refine the decision-making process.

3. Example 1: Nested if Statements:

1 #include <stdio.h>
2
3 int main()
4 {
5 int age = 25;
6 int hasID = 1;
7 int hasTicket = 0;
8
9 if (age >= 18)
10 {
11 if (hasID)
12 {
13 printf("You can enter the event.\n");
14 }
15 else
16 {
17 printf("You need an ID to enter.\n");
18 }
19 }
20 else
21 {
22 printf("You are too young to enter.\n");
23 }
24
25 return 0;
26 }
In this example, nested if statements are used to determine if a person can enter an event.
The outer if checks the age, and the inner if checks for an ID.
4. Use Cases:

Nested conditional statements are helpful when you need to evaluate multiple
conditions in a hierarchical manner.

They are used to handle more complex decision-making logic, especially when different
conditions need to be checked one after another.

5. Example 2: Nested if-else Statements:

1 #include <stdio.h>
2
3 int main() {
4 int num = 15;
5
6 if (num > 0)
7 {
8 printf("The number is positive.\n");
9 }
10 else if (num < 0)
11 {
12 printf("The number is negative.\n");
13 }
14 else
15 {
16 printf("The number is zero.\n");
17 }
18
19 return 0;
20 }

In this example, nested if-else statements are used to determine whether a number is
positive, negative, or zero.

6. Proper Indentation: To enhance code readability, it's crucial to use proper indentation when
working with nested conditional statements. Each level of indentation should reflect the
nesting level of the conditionals.

Nested conditional statements allow for more complex and structured decision-making within
your code. Proper organization, indentation, and comments (where necessary) are essential to
maintain code clarity and readability in such cases.

Loop in C
1. for loop
A for loop in C is a control structure used for repetitive execution of a block of code. It is
particularly useful when you know in advance how many times you want a certain set of
instructions to be repeated. The for loop is made up of three parts: initialization, condition, and
increment/decrement, each separated by a semicolon.

Control Flow:
Syntax:

The basic structure of a for loop is as follows:

1 for (initialization; condition; update(increment/decrement))


2 {
3 // Code to be executed repeatedly as long as the condition is true
4 }

Here are detailed notes on the for loop in C along with examples:

1. Initialization: The initialization part is executed only once at the beginning of the loop. It is
typically used to initialize loop control variables. This is where you set the starting value for
the loop.

2. Condition: The condition is a Boolean expression that is evaluated before each iteration of
the loop. If the condition is true, the loop continues; if it's false, the loop terminates.

3. Increment/Decrement: The increment/decrement part is executed at the end of each loop


iteration, just before the condition is checked again. It is typically used to modify the loop
control variable, progressing toward the loop termination condition.

Example 1: Counting from 1 to 5


1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 5; i++)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, the loop initializes i to 1, checks if i is less than or equal to 5, and increments i
by 1 in each iteration. The loop continues to execute until i is no longer less than or equal to 5.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true. You can have multiple statements in the
loop body, and they are executed sequentially.

Example 2: Sum of First 10 Natural Numbers

1 #include <stdio.h>
2
3 int main() {
4 int sum = 0;
5 for (int i = 1; i <= 10; i++)
6 {
7 sum += i; // Equivalent to: sum = sum + i;
8 }
9 printf("Sum of the first 10 natural numbers: %d\n", sum);
10 return 0;
11 }

In this example, the for loop calculates the sum of the first 10 natural numbers by iteratively
adding each number to the sum variable.

Termination: The for loop continues to execute as long as the condition is true. When the
condition becomes false, the loop terminates, and program control moves to the code following
the loop.

Example 3: Printing Numbers in Reverse

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 10; i >= 1; i--)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, the for loop counts down from 10 to 1, printing the numbers in reverse order.
Infinite Loops: Be cautious when using for loops to avoid infinite loops, where the condition
never becomes false. This can lead to a program that never terminates.

Example 4: Infinite Loop (Avoid This)

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 5;)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, variable i is not updating to reach till termination condition, the loop will never
terminate because i is always 1.

2. while loop
A "while loop" in C is a control structure used for repetitive execution of a block of code as long as
a certain condition is true. It is particularly useful when you don't know in advance how many
times the loop should execute and want to keep executing as long as a specific condition holds.

Control Flow:
Syntax:

The basic structure of a while loop is as follows:

1 while (condition)
2 {
3 // Code to be executed repeatedly as long as the condition is true
4 }

Here are detailed notes on the while loop in C along with examples:

Condition: The loop begins by evaluating the condition . If the condition is true, the code inside
the loop's body is executed. If the condition is false, the loop terminates, and program control
moves to the code following the loop.

Example 1: Counting from 1 to 5

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6 while (i <= 5)
7 {
8 printf("%d\n", i);
9 i++;
10 }
11 return 0;
12 }

In this example, the while loop starts with i set to 1 and checks if i is less than or equal to 5. As
long as this condition is true, the loop body is executed.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true. You can have multiple statements in the
loop body, and they are executed sequentially.

Example 2: Sum of Numbers

1 #include <stdio.h>
2
3 int main()
4 {
5 int sum = 0;
6 int number;
7 printf("Enter numbers (enter 0 to stop): ");
8 scanf("%d", &number);
9 while (number != 0)
10 {
11 sum += number;
12 scanf("%d", &number);
13 }
14 printf("Sum: %d\n", sum);
15 return 0;
16 }

In this example, the while loop reads numbers from the user and calculates their sum. The loop
continues until the user enters 0.

Infinite Loops: Be cautious when using while loops to avoid infinite loops, where the condition
never becomes false. This can lead to a program that never terminates.

Example 3: Infinite Loop (Avoid This)

1 #include <stdio.h>
2
3 int main()
4 {
5 while(1)
6 {
7 printf("This is an infinite loop.\n");
8 }
9 return 0;
10 }

In this example, the loop's condition is always true ( 1 is always true), and the loop will continue
indefinitely. It should be avoided or have a termination condition inside the loop.

Termination Condition: A while loop should have a well-defined termination condition to


ensure that it eventually ends. Without a termination condition, the loop will run indefinitely.

Example 4: Termination Condition

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 10;
6 while (i > 0)
7 {
8 printf("%d\n", i);
9 i--;
10 }
11 return 0;
12 }

In this example, the loop continues as long as i is greater than 0. It decrements i in each
iteration, ensuring the loop will eventually terminate.
3. do-while loop
A do-while loop in C is a control structure used for repetitive execution of a block of code as long
as a certain condition is true, similar to the "while loop." However, the key difference is that the
"do-while loop" guarantees that the code inside the loop is executed at least once, even if the
condition is initially false.

Control flow:

Syntax:

The basic structure of a do-while loop is as follows:

1 do
2 {
3 // Code to be executed repeatedly
4 } while (condition);

Here are detailed notes on the do-while loop in C along with examples:

Execution: In a do-while loop, the code inside the loop is executed first, and then the condition
is checked. If the condition is true, the loop continues; if it's false, the loop terminates.

Example 1: Counting from 1 to 5


1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6 do
7 {
8 printf("%d\n", i);
9 i++;
10 } while (i <= 5);
11 return 0;
12 }

In this example, the do-while loop starts with i set to 1. The code inside the loop body is
executed at least once before the condition is checked.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true, similar to the "while loop."

Example 2: Sum of Numbers

1 #include <stdio.h>
2
3 int main()
4 {
5 int sum = 0;
6 int number;
7 do
8 {
9 printf("Enter a number (enter 0 to stop): ");
10 scanf("%d", &number);
11 sum += number;
12 } while (number != 0);
13 printf("Sum: %d\n", sum);
14 return 0;
15 }

In this example, the do-while loop reads numbers from the user and calculates their sum. The
loop continues until the user enters 0.

Infinite Loops: Just like in the "while loop," be cautious when using do-while loops to avoid
infinite loops. Make sure the termination condition is eventually met to prevent indefinite
execution.

Example 3: Infinite Loop (Avoid This)


1 #include <stdio.h>
2
3 int main()
4 {
5 do
6 {
7 printf("This is an infinite loop.\n");
8 } while (1);
9 return 0;
10 }

In this example, the loop's condition is always true ( 1 is always true), and the loop will continue
indefinitely. It should be avoided or have a termination condition inside the loop.

Termination Condition: A do-while loop should have a well-defined termination condition to


ensure that it eventually ends. Without a termination condition, the loop may run indefinitely.

Example 4: Termination Condition

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 10;
6 do
7 {
8 printf("%d\n", i);
9 i--;
10 } while (i > 0);
11 return 0;
12 }

In this example, the loop continues as long as i is greater than 0, ensuring that it will eventually
terminate.

Use Cases: do-while loops are useful when you want to ensure that a block of code is executed
at least once, even if the initial condition is false. It is also beneficial when you need to repeatedly
prompt the user for input until a specific condition is met.

Nested Loop
Nested loops in C refer to the use of one or more loops inside another loop. These nested loops
are particularly useful when you need to handle more complex patterns, multi-dimensional data
structures, or situations that require multiple levels of iteration. Here are some short notes on
nested loops along with examples:

1. Structure: In nested loops, you have one loop (e.g., for , while , or do-while ) inside
another loop. The inner loop is entirely contained within the body of the outer loop.

2. Execution: The outer loop executes the inner loop repeatedly as long as its condition
remains true. Each iteration of the outer loop triggers multiple iterations of the inner loop.
3. Example 1: Printing a Rectangle Pattern (Using Nested for Loops):

1 #include <stdio.h>
2
3 int main()
4 {
5 int rows = 4;
6 int columns = 6;
7
8 for (int i = 1; i <= rows; i++)
9 {
10 for (int j = 1; j <= columns; j++)
11 {
12 printf("* ");
13 }
14 printf("\n");
15 }
16
17 return 0;
18 }

In this example, nested for loops are used to print a rectangle pattern of asterisks. The
outer loop controls the number of rows, and the inner loop controls the number of asterisks
in each row.

4. Use Cases:

Nested loops are helpful for handling multi-dimensional data structures like matrices,
arrays, or tables.

They are used to traverse and manipulate two-dimensional or multi-dimensional arrays.

Nested loops are commonly used to create patterns, such as triangles, rectangles, and
more complex shapes.

5. Example 2: Multiplication Table (Using Nested for Loops):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 for (int j = 1; j <= 10; j++)
8 {
9 printf("%3d ", i * j);
10 }
11 printf("\n");
12 }
13
14 return 0;
15 }

In this example, nested for loops are used to create a multiplication table from 1 to 10. The
outer loop controls the multiplicand ( i ), and the inner loop controls the multiplier ( j ).
6. Proper Indentation: To enhance code readability, it's crucial to use proper indentation when
working with nested loops. Each level of indentation should reflect the nesting level of the
loop.

Nested loops allow for more intricate and structured control over iterations, especially when
dealing with multi-dimensional data or complex patterns. Proper organization and indentation are
essential to maintain code clarity and readability in such cases.

break, continue, goto statements


1. break Statement:

Purpose: The break statement is used to exit a loop prematurely, even if the loop's
condition is still true. It is often used to break out of loops based on specific conditions.

Usage: In a loop, when the break statement is encountered, the loop is terminated, and the
program control moves to the statement immediately following the loop.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 if (i == 5)
8 {
9 break; // Exit the loop when i is 5
10 }
11 printf("%d ", i);
12 }
13 return 0;
14 }

In this example, the loop terminates early when i equals 5, and the program control moves to the
statement after the loop.

2. continue Statement:

Purpose: The continue statement is used to skip the current iteration of a loop and
immediately proceed to the next iteration. It is often used to bypass specific actions within a
loop for certain conditions.

Usage: When a continue statement is encountered in a loop, the current iteration is


skipped, and the loop proceeds with the next iteration.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 if (i % 2 == 0)
8 {
9 continue; // Skip even numbers
10 }
11 printf("%d ", i);
12 }
13 return 0;
14 }

In this example, the continue statement is used to skip even numbers ( i % 2 == 0 ), resulting in
the printing of only odd numbers.

3. goto Statement:

Purpose: The goto statement is used to transfer program control to a specific labeled
statement within the same function. It provides a way to create non-linear control flow in
your code.

Usage: You use the goto statement with a label and a colon. When the goto statement is
encountered, program control jumps to the labeled statement.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6
7 start: // Label
8 if (i <= 10)
9 {
10 printf("%d ", i);
11 i++;
12 goto start; // Jump to the 'start' label
13 }
14
15 return 0;
16 }

In this example, the goto statement is used to create a loop-like structure. It jumps back to the
start label as long as the condition is true.

Caution: The use of goto is discouraged in modern programming practices because it can lead to
complex and hard-to-maintain code. It's generally considered a best practice to use structured
control flow constructs like for , while , and if whenever possible.
Control Statement Writing Format
1. Single-Line Statement Format:
Definition:

In the single-line statement format, control statements are written on a single line without
enclosing the block of code within curly braces {} .

This format is typically used when you have a single statement to execute based on a
condition or iteration.

It is concise and suitable for simple, one-liner statements.

Syntax:

1 if (condition) statement;

Example 1 (Single-Line if statement):

1 #include <stdio.h>
2 int main()
3 {
4 int num = 10;
5 if (num > 0) printf("Number is positive\n");
6 return 0;
7 }

Example 2 (Single-Line for loop):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 0; i < 5; i++) printf("%d ", i);
6 return 0;
7 }

Use Cases:

This format is suitable for simple and concise code where only one statement needs to be
executed.

It is useful when code brevity is a priority.

Pros:

Compact and space-efficient.

Suitable for straightforward and short statements within control structures.

Reduces visual clutter when dealing with short statements.

Cons:

Less readable for complex logic or code with multiple statements.

Not suitable for organizing and grouping extensive code sections.


2. Multi-Line Statement Format:
Definition:

In the multi-line statement format, control statements are enclosed within curly braces {} to
represent a block of code.

This format is used for complex logic or code sections that include multiple statements.

It enhances code readability and maintainability by providing a structured way to group


multiple statements.

Syntax:

1 if (condition)
2 {
3 statement1;
4 statement2;
5 // ...
6 }

Example 1 (Multi-Line if statement):

1 #include <stdio.h>
2
3 int main()
4 {
5 int num = 10;
6 if (num > 0)
7 {
8 printf("Number is positive\n");
9 printf("This is a multi-line statement.\n");
10 }
11 return 0;
12 }

Example 2 (Multi-Line for loop):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 0; i < 5; i++)
6 {
7 printf("%d ", i);
8 printf("This is a multi-line statement.\n");
9 }
10 return 0;
11 }

Use Cases:
This format is essential for organizing and grouping multiple statements, especially in
complex logic.

It enhances code readability and maintainability for code with extensive logic or multiple
statements.

Pros:

Provides a structured way to group and organize multiple statements.

Improves code readability for complex logic.

Cons:

Takes up more space in the source code compared to single-line blocks.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy