0% found this document useful (0 votes)
4 views20 pages

Unit2 Part2 Loops Jump Statements

This document provides comprehensive notes on loops and jump statements in C programming, detailing the definition, purpose, types, and examples of loops including for, while, and do-while loops. It also covers jump statements such as break, continue, and goto, explaining their syntax, use cases, and providing illustrative examples. The notes emphasize the efficiency of using loops to reduce code redundancy and improve program flow.

Uploaded by

rajputlakshya101
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)
4 views20 pages

Unit2 Part2 Loops Jump Statements

This document provides comprehensive notes on loops and jump statements in C programming, detailing the definition, purpose, types, and examples of loops including for, while, and do-while loops. It also covers jump statements such as break, continue, and goto, explaining their syntax, use cases, and providing illustrative examples. The notes emphasize the efficiency of using loops to reduce code redundancy and improve program flow.

Uploaded by

rajputlakshya101
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

UNIT 2 - PART 2: LOOPS AND JUMP

STATEMENTS
COMPREHENSIVE EXAM-READY STUDY
NOTES

17. LOOPS IN C PROGRAMMING


Definition
Loop: A control structure that executes a block of code multiple times based on a
condition. Loops allow us to write compact code and avoid repetition.

Purpose: - Execute same code multiple times - Save code and time - Access array
elements - Reduce redundancy

Why Do We Need Loops?


Without Loop (Inefficient):
void main() {
printf("Hello World\n");
printf("Hello World\n");
printf("Hello World\n");
printf("Hello World\n");
printf("Hello World\n");
}

With Loop (Efficient):


void main() {
for(int i = 0; i < 5; i++) {
printf("Hello World\n");
}
}

TYPES OF LOOPS IN C
C has 3 types of loops:
Loops in C
├── 1. for Loop (Entry-Controlled)
├── 2. while Loop (Entry-Controlled)
└── 3. do-while Loop (Exit-Controlled)

LOOP CLASSIFICATION
1. Entry-Controlled Loop (Pre-Check Loop)
Characteristics: - Condition checked BEFORE executing body - Body may not execute at
all if condition is false from start - Includes: for and while loops
Flow:
Check Condition → If TRUE → Execute Body → Check Again
↓ If FALSE
Exit Loop

2. Exit-Controlled Loop (Post-Check Loop)


Characteristics: - Condition checked AFTER executing body - Body ALWAYS executes
at least once even if condition is false - Includes: do-while loop
Flow:
Execute Body (First Time) → Check Condition → If TRUE → Go Back to Body
↓ If FALSE
Exit Loop

1. FOR LOOP
Definition
The for loop is an entry-controlled loop used to iterate statements a known number of
times. Most efficient when iteration count is predetermined.

When to Use For Loop


When number of iterations is KNOWN beforehand
Array/list traversal
Counter-based iterations
Pattern printing

Syntax
for (initialization; condition; increment/decrement) {
// Body of loop
statements;
}

Components:
1. Initialization: Sets initial value (executed once)
2. Condition: Checked before each iteration
3. Increment/Decrement: Executed after each iteration
4. Body: Code to execute repeatedly

Execution Flow
START

INITIALIZATION (done once)

CONDITION CHECK ← TRUE → EXECUTE BODY
↓ FALSE ↓
EXIT INCREMENT/DECREMENT
↑ ↓
└──── Go back to CONDITION CHECK

Examples
Example 1: Basic For Loop - Print 1 to 5

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

/* Output:
1
2
3
4
5
*/

Example 2: Print Table of 7

#include<stdio.h>
int main() {
int num = 7;
for(int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}

/* Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70
*/

Example 3: Sum of First 10 Numbers

#include<stdio.h>
int main() {
int sum = 0;
for(int i = 1; i <= 10; i++) {
sum = sum + i;
}
printf("Sum: %d\n", sum);
return 0;
}

/* Output:
Sum: 55
*/

For Loop Variations

Reverse Loop

for(int i = 5; i >= 1; i--) {


printf("%d\n", i);
}
// Output: 5 4 3 2 1

Skip Values (Increment by 2)


for(int i = 1; i <= 10; i += 2) {
printf("%d\n", i);
}
// Output: 1 3 5 7 9

Multiple Initializations

for(int i = 1, j = 10; i <= 5; i++, j--) {


printf("i=%d, j=%d\n", i, j);
}

2. WHILE LOOP
Definition
The while loop is an entry-controlled loop used to iterate when the number of iterations
is NOT KNOWN. Condition is checked first.

When to Use While Loop


When iteration count is UNKNOWN
User input validation
Data processing until condition met
Event-driven loops

Syntax
initialization;
while (condition) {
// Body of loop
statements;
increment/decrement;
}

Execution Flow
INITIALIZATION

CONDITION CHECK ← TRUE → EXECUTE BODY
↓ FALSE ↓
EXIT INCREMENT/DECREMENT
↑ ↓
└─── Go back to CONDITION CHECK

Examples

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

/* Output:
1
2
3
4
5
*/

Example 2: Input Validation

#include<stdio.h>
int main() {
int age;
while(age < 0 || age > 120) {
printf("Enter valid age: ");
scanf("%d", &age);
}
printf("Valid age: %d\n", age);
return 0;
}

Example 3: Sum Until Negative

#include<stdio.h>
int main() {
int num, sum = 0;
printf("Enter numbers (negative to stop): ");

while(num >= 0) {
scanf("%d", &num);
if(num >= 0)
sum += num;
}
printf("Sum: %d\n", sum);
return 0;
}

3. DO-WHILE LOOP
Definition
The do-while loop is an exit-controlled loop that executes body at least once even if
condition is false. Condition is checked after execution.

Key Difference from While


while: Body may NOT execute if condition is false
do-while: Body ALWAYS executes at least once

When to Use Do-While Loop


Body must execute at least once
Menu-driven programs
User interaction loops
Input validation with retry

Syntax
initialization;
do {
// Body of loop
statements;
increment/decrement;
} while (condition);

Note: Semicolon after while is MANDATORY

Execution Flow
INITIALIZATION

EXECUTE BODY (First Time - Unconditional)

CONDITION CHECK
├─ TRUE → Go back to EXECUTE BODY
└─ FALSE → EXIT

Examples

Example 1: Print 1 to 5

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

/* Output:
1
2
3
4
5
*/

Example 2: Menu-Driven Program


#include<stdio.h>
int main() {
int choice;
do {
printf("\n1. Play\n2. Settings\n3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch(choice) {
case 1: printf("Playing...\n"); break;
case 2: printf("Settings...\n"); break;
case 3: printf("Exiting...\n"); break;
default: printf("Invalid choice\n");
}
} while(choice != 3);
return 0;
}

Example 3: Do-While vs While

// While Loop - Body may not execute


int a = 10;
while(a < 5) {
printf("Inside while\n"); // NOT executed
a++;
}

// Do-While Loop - Body executes at least once


int b = 10;
do {
printf("Inside do-while\n"); // EXECUTED ONCE
b++;
} while(b < 5);

WHILE vs DO-WHILE COMPARISON TABLE


Feature While Loop Do-While Loop
Type Entry-Controlled Exit-Controlled
Condition Check Before executing body After executing body
Minimum 0 (may not execute) 1 (always executes at least once)
Executions
When to Use When pre-check needed When post-check needed
Syntax while(condition) { } do { } while(condition);
Semicolon Not after while Mandatory after while

FOR vs WHILE LOOP


Feature For Loop While Loop
Use Case Known iterations Unknown iterations
Example Print 1 to 10 Read until -1 entered
Initialization Inside for() Before while()
Increment Inside for() In loop body
Best For Counters, arrays User input, conditions
INFINITE/INDEFINITE LOOPS
Definition
A loop that never terminates because the condition always remains true or is never
checked.

When Condition Never Becomes False


// Infinite for loop
for(int i = 1; i >= 1; i++) {
printf("i = %d\n", i); // i always increases, always >= 1
}

// Infinite while loop


while(1) {
printf("Infinite loop\n");
}

// Infinite do-while
do {
printf("Infinite loop\n");
} while(1);

When to Use Infinite Loops


1. Operating Systems - Run continuously until user shuts down
2. Server Applications - Accept requests until administrator stops
3. Games - Accept user input until player exits
4. Menu-Driven Programs - Continue until exit option selected

Breaking Infinite Loop


while(1) {
printf("Enter 0 to exit: ");
int input;
scanf("%d", &input);

if(input == 0) {
break; // Exit loop
}
}

NESTED LOOPS
Definition
Nested loops are loops inside loops. One loop becomes the body of another loop.

Why Use Nested Loops?


Access 2D arrays/matrices
Print patterns
Multiple iterations needed
Combinations and permutations

Types of Nested Loops


Nested For Loops

for (init1; condition1; increment1) {


for (init2; condition2; increment2) {
statements; // Inner loop body
}
}

Nested While Loops

while (condition1) {
while (condition2) {
statements; // Inner loop body
}
}

Nested Do-While Loops

do {
do {
statements; // Inner loop body
} while (condition2);
} while (condition1);

Nested Loop Examples

Example 1: Multiplication Table (1 to 5, 1 to 5)

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

/* Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
*/

Example 2: Star Pattern


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

/* Output:
*
**
***
****
*****
*/

Example 3: Number Pattern

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

/* Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/

18. JUMP STATEMENTS


Jump statements alter the normal flow of program execution.
Jump Statements
├── 1. break
├── 2. continue
├── 3. goto
└── 4. return

BREAK STATEMENT
Definition
The break statement terminates (exits) the loop or switch statement immediately and
transfers control to the statement after the loop/switch.

Syntax
loop or switch {
...
if (condition)
break;
...
}
// Next statement after loop/switch

When to Use Break


1. When iteration count is unknown
2. Terminate loop based on condition
3. Exit switch case

Examples

Example 1: Break in For Loop

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

/* Output:
0
1
2
3
4
5
Came outside of loop
*/

Example 2: Search in Array

#include<stdio.h>
int main() {
int arr[] = {1, 5, 3, 8, 2, 9};
int search = 8, found = 0;

for(int i = 0; i < 6; i++) {


if(arr[i] == search) {
found = 1;
break; // Element found, exit
}
}

if(found)
printf("Element found\n");
else
printf("Element not found\n");

return 0;
}
Example 3: Break in Nested Loops

#include<stdio.h>
int main() {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
if(j == 2)
break; // Breaks inner loop only
printf("i=%d, j=%d\n", i, j);
}
}
return 0;
}

/* Output:
i=1, j=1
i=2, j=1
i=3, j=1
*/

Note: Break exits only the innermost loop, not outer loops.

CONTINUE STATEMENT
Definition
The continue statement skips the current iteration and passes control to the beginning
of the loop for the next iteration.

Syntax
loop {
...
if (condition)
continue;
// Remaining code skipped, goes to next iteration
...
}

When to Use Continue


Skip specific iterations based on condition
Avoid nested if-else
Process selective data

Examples

Example 1: Skip Even Numbers


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

/* Output:
1
3
5
7
9
*/

Example 2: Skip Value 5

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

/* Output:
1
2
3
4
6
7
8
9
10
*/

Example 3: Continue in While Loop

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

/* Output:
1
2
4
5
*/
BREAK vs CONTINUE
Feature Break Continue
Action Exits loop completely Skips current iteration
Control Goes After loop Beginning of loop
Example Find element, exit Skip value, process rest
Iterations Stops all remaining Continues remaining

GOTO STATEMENT
Definition
The goto statement is a jump statement that transfers control to a labeled statement.
Creates an unconditional jump.

Syntax
label:
statements;

goto label; // Jump back to label

When to Use Goto


Break out of multiple nested loops
Menu systems (though not recommended)
Error handling (rarely)

Warning:Modern programming avoids goto as it makes code hard to follow. Use


break/continue instead.

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

loop:
printf("%d\n", x);
x++;

if(x <= 5)
goto loop; // Jump to 'loop' label

return 0;
}

/* Output:
1
2
3
4
5
*/
19. SWITCH-CASE STATEMENT
Definition
Switch-case is a control statement used to execute one block from multiple choices
based on the value of an expression.

Advantages Over If-Else Ladder


More readable
Cleaner code
Faster for multiple choices
Better for menu-driven programs

Syntax
switch (expression) {
case constant1:
statements;
break;
case constant2:
statements;
break;
case constant3:
statements;
break;
default:
statements; // Executed if no case matches
}

Rules for Switch-Case


1. Expression Type: Must be int or char (not float)
2. Case Values: Must be constants (not variables)
3. Unique Cases: No duplicate case values
4. Case Labels End: Always with colon :
5. Default: Optional (but recommended)
6. Break Statement: Recommended to prevent fallthrough

Valid and Invalid Switch Expressions

Valid Invalid
switch(x) switch(x+y)
switch(a) switch(2.5)
switch(ch) switch(func())
switch(1+2) switch(f) (f is float)

Valid and Invalid Cases

Valid Invalid
case 1: case 1.5:
case 'A': case x: (x is variable)
case 10: case 1, 2, 3:
case 'a': case x+1:
Execution Flow
SWITCH (expr) evaluated

COMPARE with cases
├─ Match found → Execute case block → CHECK BREAK
│ ├─ YES: Exit switch
│ └─ NO: Continue to next case
(Fallthrough)
└─ No match → Execute DEFAULT block → Exit switch

Examples

Example 1: Simple Switch

#include<stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);

switch(number) {
case 10:
printf("Number is 10\n");
break;
case 50:
printf("Number is 50\n");
break;
case 100:
printf("Number is 100\n");
break;
default:
printf("Number is not 10, 50, or 100\n");
}

return 0;
}

/* Test Cases:
Input: 10 → Output: Number is 10
Input: 50 → Output: Number is 50
Input: 75 → Output: Number is not 10, 50, or 100
*/

Example 2: Vowel Checker


#include<stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);

switch(ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel\n", ch);
break;
default:
printf("%c is not a vowel\n", ch);
}

return 0;
}

/* Output:
Input: a → Output: a is a vowel
Input: b → Output: b is not a vowel
*/

Example 3: Calculator Using Switch

#include<stdio.h>
int main() {
int a, b, choice;

printf("Enter two numbers: ");


scanf("%d %d", &a, &b);

printf("\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n");


printf("Enter choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Sum: %d\n", a + b);
break;
case 2:
printf("Difference: %d\n", a - b);
break;
case 3:
printf("Product: %d\n", a * b);
break;
case 4:
if(b != 0)
printf("Division: %d\n", a / b);
else
printf("Cannot divide by zero\n");
break;
default:
printf("Invalid choice\n");
}

return 0;
}

Example 4: Day of Week


#include<stdio.h>
int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);

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;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day number\n");
}

return 0;
}

FALLTHROUGH IN SWITCH (Important for


Exams)
What is Fallthrough?
When a case matches but no break is found, execution continues to the next case. This is
called fallthrough.

Example: Without Break (Fallthrough)


#include<stdio.h>
int main() {
int number = 10;

switch(number) {
case 10:
printf("number is 10\n");
// NO BREAK - falls through
case 50:
printf("number is 50\n");
case 100:
printf("number is 100\n");
default:
printf("number is not 10, 50, or 100\n");
}

return 0;
}

/* Output:
number is 10
number is 50
number is 100
number is not 10, 50, or 100

Explanation: After case 10 matched, all remaining cases executed!


*/

Example: With Break (Correct)


#include<stdio.h>
int main() {
int number = 10;

switch(number) {
case 10:
printf("number is 10\n");
break; // Exit after this case
case 50:
printf("number is 50\n");
break;
case 100:
printf("number is 100\n");
break;
default:
printf("number is not 10, 50, or 100\n");
}

return 0;
}

/* Output:
number is 10

Explanation: Break exits switch after matching case.


*/

Intentional Fallthrough (Rare)


switch(grade) {
case 'A':
case 'B':
printf("Good Grade\n");
break;
case 'C':
printf("Average Grade\n");
break;
case 'D':
case 'F':
printf("Poor Grade\n");
break;
}

EXAM PREPARATION SUMMARY (Part 2)


Key Concepts
1. Loops: Execute code multiple times
2. For Loop: Known iterations
3. While Loop: Unknown iterations, entry-controlled
4. Do-While: Always executes at least once, exit-controlled
5. Nested Loops: Loop inside loop
6. Break: Exit loop/switch
7. Continue: Skip iteration
8. Goto: Jump to label (avoid)
9. Switch-Case: Multiple choices based on value
10. Fallthrough: Continue to next case without break

Quick Reference Table

Loop Type Entry/Exit When to Use Min Executions


for Entry Known count 0
while Entry Unknown count 0
do-while Exit At least once 1

Common Exam Questions


MCQ: - Difference between while and do-while? (Execution check) - What does break
do? (Exits loop) - What does continue do? (Skips iteration) - Output of fallthrough switch?
(All cases execute)

8-Mark: - Explain all 3 loop types with examples - Write nested loop program - Switch vs
if-else comparison

12-Mark: - Complete loop classification with flowcharts - Nested loop patterns - Switch-
case programs (calculator, day finder, etc.)

END OF UNIT 2 PART 2 STUDY NOTES - LOOPS AND JUMP STATEMENTS

You might also like