0% found this document useful (0 votes)
44 views15 pages

CSE Chapter 7 Loops

Uploaded by

magnaff2
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)
44 views15 pages

CSE Chapter 7 Loops

Uploaded by

magnaff2
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/ 15

CSE Chapter 7 (Loops)

1. What is loop?

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

2. Kinds of loops.

= 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 at least once, irrespective of whether the
condition is true or false. do-while Loop is Exit Controlled loop.

Loop Type Description


for loop first Initializes, then condition check, then executes the body and at last,
the update is done.
while loop first Initializes, then condition checks, and then executes the body, and
updating can be inside the body.
do-while loop do-while first executes the body and then the condition check is 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.
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/condition: 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/increment/discriment: After execution of the loop body loop variable


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

// Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3...n are known as natural numbers


#include <stdio.h>

int main()

int num, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &num);

// for loop terminates when count exceeds num

for(count = 1; count <= num; ++count)

sum += count;

printf("Sum = %d", sum);

return 0;

The value entered by the user is stored in the variable num. Suppose, the user entered 10.

The count is initialized to 1 and the test expression is evaluated. Since the test expression
count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the
value of sum will equal to 1.

Then, the update statement ++count is executed and count will equal to 2. Again, the test
expression is evaluated. Since 2 is also less than 10, the test expression is evaluated to true
and the body of the for loop is executed. Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.

When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates.

Then, the value of sum is printed on the screen.

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.

#include <stdio.h>

int main() {

int i = 1; // Initialize the counter variable


// While loop to print numbers from 1 to 10

while (i <= 10) {

printf("%d\n", i); // Print the current value of i

i++; // Increment the counter variable

return 0; // Indicate that the program ended successfully

Explanation:

1. Header File: #include <stdio.h> is included to use the printf function for output.
2. Main Function: The main function is the entry point of the program.
3. Counter Initialization: int i = 1; initializes the counter variable i to 1.
4. While Loop: while (i <= 10) checks if i is less than or equal to 10.
o Inside the loop, printf("%d\n", i); prints the current value of i.
o i++; increments the counter variable i by 1.
5. Return Statement: return 0; indicates that the program finished successfully.

When you run this program, it will output the numbers from 1 to 10, each on a new line.

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.
#include <stdio.h>

int main() {

int i = 1; // Initialize the counter variable

// Do-while loop to print numbers from 1 to 10

do {

printf("%d\n", i); // Print the current value of i

i++; // Increment the counter variable

} while (i <= 10); // Continue the loop as long as i is less than or equal to 10

return 0; // Indicate that the program ended successfully

Explanation:
1. Header File: #include <stdio.h> is included to use the printf function for output.
2. Main Function: The main function is the entry point of the program.
3. Counter Initialization: int i = 1; initializes the counter variable i to 1.
4. Do-While Loop:
o The do block contains the code to be executed. In this case, it prints the current value of
i and then increments i.
o The while (i <= 10); condition is checked after the execution of the loop body. The
loop continues to execute as long as i is less than or equal to 10.
5. Return Statement: return 0; indicates that the program finished successfully.

The do-while loop guarantees that the loop body is executed at least once, even if the condition
is false initially. In this program, however, the loop will execute 10 times, printing the numbers
from 1 to 10.

Loop Control Statements


Loop control statements in C programming are used to change execution from
its normal sequence.
Name Description
break statement the break statement is used to terminate the switch and loop statement. It
transfers the execution to the statement immediately following the loop
or switch.
continue continue statement skips the remainder body and immediately resets its
statement condition before reiterating it.
goto statement goto statement transfers the control to the labeled statement.

Break Statement

jumping

The break in C is a loop control statement that 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.
Break with Simple loops

Consider the situation where we want to search for an element in an array. To do this, use a
loop to traverse the array starting from the first index and compare the array elements with
the given key.

Example:

#include <stdio.h>

int main() {

int n, key, i;

int found = 0; // Variable to keep track if the key is found

// Input the size of the array

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

int arr[n]; // Declare the array with size n


// Input array elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Input the key to search

printf("Enter the element to search for: ");

scanf("%d", &key);

// Linear search for the key in the array

for (i = 0; i < n; i++) {

if (arr[i] == key) {

printf("Element %d found at index %d.\n", key, i);

found = 1; // Key is found

break; // Exit the loop since we found the key

// If the key was not found

if (!found) {

printf("Element %d not found in the array.\n", key);

return 0; // Indicate that the program ended successfully

}
Continue Statement in C++

Skipping

C continue statement is a loop control statement that forces the program control to execute
the next iteration of the loop. As a result, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.

Example: Consider the situation when you need to write a program that prints numbers from
1 to 10 but not 4. It is specified that you have to do this using loop and only one loop is
allowed to use. Here comes the usage of the continue statement. What we can do here is we
can run a loop from 1 to 10 and every time we have to compare the value of the iterator with
4. If it is equal to 4 we will use the continue statement to continue to the next iteration
without printing anything otherwise we will print the value.

Continue Statement with for Loop

If continue is used in a for loop, the control flow jumps to the test expression after skipping
the current iteration.

#include <stdio.h>

int main() {

int i;

// Use a for loop to print numbers from 1 to 10


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

// Skip the number 4

if (i == 4) {

continue; // Skip the rest of the loop iteration for i = 4

// Print the current value of i

printf("%d\n", i);

return 0; // Indicate that the program ended successfully

Explanation:

1. Header File: #include <stdio.h> is included to use the printf function for output.
2. Main Function: The main function is the entry point of the program.
3. For Loop:
o for (i = 1; i <= 10; i++) initializes i to 1 and increments it until i is greater
than 10.
o Inside the loop, the if (i == 4) condition checks if the current value of i is 4.
o If i is 4, the continue; statement skips the rest of the current loop iteration and
moves to the next iteration.
o If i is not 4, printf("%d\n", i); prints the current value of i.
4. Return Statement: return 0; indicates that the program ended successfully.

This program will output numbers from 1 to 10, but it will skip printing the number 4.

Continue Statement with While Loop

With continue, the current iteration of the loop is skipped, and control flow resumes in the
next iteration of while loop.
#include <stdio.h>

int main() {
int i = 1; // Initialize the counter variable

// Use a while loop to print numbers from 1 to 10


while (i <= 10) {
i++; // Increment the counter variable before breaking
if (i == 4) {

continue; // Skip the rest of the current loop iteration and move to the next
iteration
}
printf("%d\n", i); // Print the current number
i++; // Increment the counter variable
}

return 0; // Indicate that the program ended successfully


}

Explanation:

1. Header File: #include <stdio.h> is included to use the printf function for output.
2. Main Function: The main function is the entry point of the program.
3. Counter Initialization: int i = 1; initializes the counter variable i to 1.
4. While Loop:
o while (i <= 10) continues the loop as long as i is less than or equal to 10.
o Inside the loop, if (i == 4) checks if the current value of i is 4.
▪ If i is 4, i++ increments the counter to avoid an infinite loop, and continue;
skips the rest of the current loop iteration, which effectively avoids printing the
number 4.
o If i is not 4, printf("%d\n", i); prints the current value of i.
o i++ increments the counter variable to proceed to the next number.
5. Return Statement: return 0; indicates that the program finished successfully.

In this program, the continue statement is used to skip the number 4 while allowing the loop to
continue printing the remaining numbers. The break statement is not necessary in this case, but
if it were to be used, it would typically break out of the loop entirely, which is not required for
this specific task.

Continue Statement with do-while Loop


In do-while loop, the condition is checked after executing the loop body. When a
continue statement is encountered in the do-while loop, the control jumps directly to the
condition checking for the next loop, and the remaining code in the loop body is skipped.

#include <stdio.h>

int main() {
int i = 1; // Initialize the counter variable

// Use a do-while loop to print numbers from 1 to 10


do {
i++; // Increment the counter variable before continuing
if (i == 4) {

continue; // Skip the rest of the loop iteration for i = 4


}
printf("%d\n", i); // Print the current number
i++; // Increment the counter variable
} while (i <= 10); // Continue the loop as long as i is less than or equal to 10

return 0; // Indicate that the program ended successfully


}

Explanation:

1. Header File: #include <stdio.h> is included to use the printf function for output.
2. Main Function: The main function is the entry point of the program.
3. Counter Initialization: int i = 1; initializes the counter variable i to 1.
4. Do-While Loop:
o do { ... } while (i <= 10); ensures that the loop executes at least once and
continues as long as i is less than or equal to 10.
o Inside the loop, if (i == 4) checks if the current value of i is 4.
▪ If i is 4, i++ increments the counter to avoid an infinite loop, and continue;
skips the rest of the current loop iteration, which effectively avoids printing the
number 4.
o If i is not 4, printf("%d\n", i); prints the current value of i.
o i++ increments the counter variable to proceed to the next number.
5. Return Statement: return 0; indicates that the program finished successfully.

In this program, the continue statement is used to skip the iteration of the loop where the
number 4 would be printed, allowing the loop to continue with the next iteration and print all
other numbers from 1 to 10.

You might also like