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

CnotesUnit2

The document explains decision-making in C programming using if statements, including types like simple if, if-else, nested if-else, and else-if ladder. It also covers the switch statement for multi-way decisions and loops such as while, do-while, and for loops, along with control flow statements like goto, break, and continue. Key points and examples are provided to illustrate the usage of these constructs.

Uploaded by

hk9542863
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CnotesUnit2

The document explains decision-making in C programming using if statements, including types like simple if, if-else, nested if-else, and else-if ladder. It also covers the switch statement for multi-way decisions and loops such as while, do-while, and for loops, along with control flow statements like goto, break, and continue. Key points and examples are provided to illustrate the usage of these constructs.

Uploaded by

hk9542863
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Decision Making with if Statements in C

 Decision-making is an essential concept in programming that allows us to control the


flow of execution based on specific conditions.
 In C, decision-making statements enable the program to choose different paths based on
conditions.
 The if statement and its variations (if-else, nested if-else, and else-if ladder)
help us execute different code blocks depending on whether a condition is true (non-
zero) or false (zero).

2. Types of if Statements in C
There are four main types of if statements in C:

1. Simple if Statement
2. if-else Statement
3. Nested if-else Statement
4. else-if Ladder

3. Simple if Statement
Definition

 The simplest form of decision-making.


 Executes a block of code only if the condition is true.
 If the condition is false, the block is skipped.

Syntax
if (condition) {
// Code to execute if the condition is true
}

Syntax Explanation

 if: The keyword used for decision-making.


 condition: A logical expression that evaluates to true (non-zero) or false (zero).
 Curly Braces {}: Encloses the code block to execute if the condition is true. (Optional
for single statements)

Example
#include <stdio.h>
main() {
int num = 10;
if (num > 0) {
printf("Number is positive\n");
}

Explanation

 num > 0 is true (since 10 > 0).


 The code inside {} executes, and "Number is positive" is printed.

Output:

Number is positive

4. if-else Statement
Definition

 Extends the if statement to execute one block if the condition is true, and another if it
is false.

Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Example
#include <stdio.h>
main() {
int num = -5;
if (num >= 0) {
printf("Positive number\n");
} else {
printf("Negative number\n");
}

Explanation

 num >= 0 is false (since -5 >= 0 is false).


 The else block executes, printing "Negative number".
Output:

Negative number

5. Nested if-else Statement


Definition

 An if or if-else inside another if or else.


 Used for multiple level checks.

Syntax
if (condition1) {
if (condition2) {
// Code if both conditions are true
} else {
// Code if condition1 is true but condition2 is false
}
} else {
// Code if condition1 is false
}

Example
#include <stdio.h>
main() {
int num = 0;
if (num >= 0) {
if (num == 0) {
printf("Number is zero\n");
} else {
printf("Positive number\n");
}
} else {
printf("Negative number\n");
}

Explanation

 num >= 0 is true.


 Inside it, num == 0 is also true, so "Number is zero" is printed.

Output:

Number is zero
6. else-if Ladder
Definition

 Used when multiple conditions need to be checked one after another.


 If a condition is true, its corresponding block executes and the rest are skipped.

Syntax
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else if (condition3) {
// Code for condition3
} else {
// Code if none of the conditions are true
}

Example
#include <stdio.h>
main() {
int marks = 75;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 80) {
printf("Grade B\n");
} else if (marks >= 70) {
printf("Grade C\n");
} else {
printf("Grade D\n");
}

Explanation

 marks >= 90 is false.


 marks >= 80 is false.
 marks >= 70 is true, so "Grade C" is printed.

Output:

Grade C
Summary
Statement Type Purpose Executes When
Runs a block of code if a condition is
Simple if Condition is true
true
True → if block, False → else
if-else Runs one block if true, another if false
block
Nested if-else if-else inside another if-else One condition inside another
else-if Ladder Checks multiple conditions in sequence First true condition executes

8. Key Points to Remember


 Always use curly braces {} for multiple statements inside if, else, or else if.
 Conditions must evaluate to true (non-zero) or false (zero).
 The else block (if present) executes only if all conditions are false.
 Nested if statements should be properly indented for better readability.
 The else-if ladder executes only the first true condition and skips the rest.

Switch Statement in C
 The switch statement in C is a multi-way decision-making statement.
 It allows one variable to be tested against multiple possible values.
 It is an alternative to multiple if-else statements, making the code more readable and
efficient.

 The switch statement evaluates an expression and executes the block of code that
matches a specified case.
 If no cases match, an optional default case is executed.

Syntax
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
case value3:
// Code to execute if expression == value3
break;
default:
// Code to execute if no case matches
}
Syntax Explanation
 switch (expression):
o expression is evaluated first.
o It must be an integer, char, or enum (not float or string).
 case value:
o Each case represents a possible value for the expression.
o If expression matches value, the corresponding block executes.
 break;
o Stops execution after a case is matched.
o If missing, the execution falls through to the next case.
 default:
o Executes only if none of the cases match.
o It is optional but recommended.

Example 1: Basic switch Statement


#include <stdio.h>
main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Weekend\n");
}

Explanation

 day = 3, so case 3 executes.


 Since break; is present, execution stops after "Wednesday" is printed.
Output:

Wednesday

6. Example 2: switch Without break (Fall-through Behavior)


#include <stdio.h>
main() {
int num = 2;

switch (num) {
case 1:
printf("One\n");
case 2:
printf("Two\n");
case 3:
printf("Three\n");
default:
printf("Other\n");
}

Explanation

 num = 2, so case 2 executes.


 Since break is missing, execution falls through to the next cases.

Output:

Two
Three
Other

Example 3: switch with char


#include <stdio.h>
main() {
char grade = 'B';

switch (grade) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good\n");
break;
case 'C':
printf("Average\n");
break;
default:
printf("Fail\n");
}

return 0;
}

Output:

Good

switch vs if-else

Feature switch if-else


Data Type Works with int, char, enum Works with all data types
Multiple Efficient for checking a single variable
Can handle complex conditions
Conditions against multiple values
Becomes lengthy with multiple
Code Readability Cleaner and easier to read
conditions
No fall-through, each condition
Fall-through Executes next cases if break is missing
is separate

Loops in C
 Loops are control structures that repeat a block of code multiple times.
 They are used when we need to execute a set of statements multiple times with a
condition.
 Types of Loops in C:
1. while loop
2. do-while loop
3. for loop
4. Nested Loops (Loop inside another loop)

1. while Loop
Definition

 The while loop executes repeatedly as long as the given condition is true.
 If the condition becomes false, the loop terminates.

Syntax
while (condition) {
// Code to execute
}

Syntax Explanation

 while (condition): The loop runs as long as the condition is true.


 Inside {}, we write the statements that execute repeatedly.

Example
#include <stdio.h>
main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++; // Increment to prevent infinite loop
}
}

Output
1
2
3
4
5

2. do-while Loop
Definition

 Similar to while, but executes at least once, even if the condition is false.
 Condition is checked after executing the loop body.

Syntax
do {
// Code to execute
} while (condition);

Syntax Explanation

 The loop executes once first.


 Then, it checks the condition.
 If true, it repeats; if false, it stops.

Example
#include <stdio.h>
main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);

Output
1
2
3
4
5

Key Difference (while vs do-while)

Feature while loop do-while loop


Condition Checking Before executing the body After executing the body
Minimum Executions 0 times (if false at start) At least 1 time

4. for Loop
Definition

 The most commonly used loop, best for situations where the number of iterations is
known.
 It includes initialization, condition, and update in a single line.

Syntax
for (initialization; condition; update) {
// Code to execute
}

Syntax Explanation

 Initialization: Runs once before the loop starts.


 Condition: Checked before each iteration.
 Update: Runs after each iteration.

Example
#include <stdio.h>
main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}

Output
1
2
3
4
5

Comparison (while vs for)

Feature while loop for loop


Use Case When number of iterations is unknown When number of iterations is fixed
Syntax More flexible but longer Compact and easier to read

5. Nested Loops
Definition

 A loop inside another loop is called a nested loop.


 Used for working with multidimensional data (like matrices, patterns).

Syntax
for (initialization; condition; update) {
for (initialization; condition; update) {
// Inner loop code
}
}

Example: Printing a Star Pattern


#include <stdio.h>
main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 5; j++) {
printf("* ");
}
printf("\n"); // Newline after inner loop
}
return 0;
}
Output
* * * * *
* * * * *
* * * * *

Explanation

 Outer loop (i) runs 3 times (rows).


 Inner loop (j) runs 5 times per outer loop iteration (columns).

6. Summary Table
Loop Type When to Use Execution Condition
When condition-based looping is
while Runs while the condition is true
needed
When the loop must execute at least
do-while Executes first, then checks condition
once
When the number of iterations is
for Executes until condition is false
fixed
Nested When working with tables, Each inner loop completes for every outer
Loops matrices, patterns loop iteration

Key Points to Remember


🔹 Use while when the number of iterations is unknown.
🔹 Use do-while when the loop must execute at least once.
🔹 Use for when the number of iterations is known in advance.
🔹 Nested loops are useful for multidimensional problems but can be inefficient if deeply
nested.

Jumps in Loops – goto, break, and continue in C


 In C, jump statements are used to alter the flow of execution in loops and functions.
 The main jump statements in C are:
1. goto – Transfers control to a labeled statement.
2. break – Exits the loop or switch statement.
3. continue – Skips the remaining statements of the current iteration and moves to
the next iteration.

1. goto Statement
Definition
 The goto statement jumps to a labeled statement in the program.
 It can transfer control forward or backward within the same function.
 Not recommended as it makes code harder to read (considered bad practice).

Syntax
goto label;
...
label:
// Code to execute

Syntax Explanation

 goto label; moves the control to label: in the program.


 label: is a user-defined name followed by a colon (:).

Example
#include <stdio.h>
main() {
int num = 1;

if (num == 1)
goto jump; // Jump to label

printf("This will not execute\n");

jump:
printf("Jumped to this label!\n");

Output
Jumped to this label!

2. break Statement
Definition

 The break statement is used to terminate a loop or switch case immediately.


 When break is encountered inside a loop, the loop stops execution and control moves to
the statement after the loop.

Syntax
break;
Syntax Explanation

 break; immediately exits the loop and resumes execution after the loop block.

Example: Stopping a loop when a condition is met


#include <stdio.h>
main() {
for (int i = 1; i <= 5; i++) {
if (i == 3)
break; // Exit loop when i = 3
printf("%d\n", i);
}
}

Output
CopyEdit
1
2

 Loop breaks when i == 3, so numbers 3, 4, 5 are not printed.

3. continue Statement
Definition

 The continue statement skips the remaining code inside the loop for the current
iteration and moves to the next iteration.
 Unlike break, it does not exit the loop but simply skips the rest of the current
iteration.

Syntax
continue;

Syntax Explanation

 When continue; is encountered, the remaining statements in the current iteration are
skipped, and the loop moves to the next iteration.

Example: Skipping a specific iteration


#include <stdio.h>
main() {
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // Skip printing when i = 3
printf("%d\n", i);
}
return 0;
}

Output

1
2
4
5

 Iteration with i == 3 is skipped, but the loop continues normally.

5. Difference Between break and continue


Feature break continue
Effect on Stops execution of the loop Skips the current iteration, continues with
loop completely the next
Exits loop? Yes No
Where to
To terminate a loop early To skip specific iterations
use?

Example Comparing break and continue


#include <stdio.h>
int main() {
printf("Using break:\n");
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
printf("%d ", i);
}

printf("\nUsing continue:\n");
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf("%d ", i);
}

return 0;
}

Output
Using break:
1 2

Using continue:
1 2 4 5

 break exits the loop when i == 3.


 continue skips iteration i == 3 but continues the loop.

6. Summary Table
Jump
Function Effect on Execution Use Case
Statement
goto
Jumps to a labeled Unconditionally jumps to another Avoid unless necessary
statement part of the code (bad practice)
break Exits the loop or Stops loop execution completely When we need to exit
switch early
continue
Skips the current Moves to next iteration, skipping When we need to skip
iteration remaining statements certain iterations

7. Key Points to Remember


✅ Use break when you want to exit a loop early.
✅ Use continue when you want to skip an iteration but keep looping.
✅ Avoid goto whenever possible (can make code confusing).
✅ Never forget to use proper conditions with break and continue to prevent infinite loops.

You might also like