0% found this document useful (0 votes)
37 views5 pages

Understanding Loop Structures in C

This document discusses loops in C programming. It defines loops as groups of instructions that are repeatedly executed while a condition remains true. The three types of loops in C are while loops, do-while loops, and for loops. While and do-while loops check their condition at the beginning or end of each iteration. For loops allow the programmer to define an initialization, condition, and increment in one place. The document provides examples of each loop type and discusses nested loops. It also covers the break and continue statements, which alter normal loop execution. A set of exercises is provided to help students practice loops.

Uploaded by

semuty92
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)
37 views5 pages

Understanding Loop Structures in C

This document discusses loops in C programming. It defines loops as groups of instructions that are repeatedly executed while a condition remains true. The three types of loops in C are while loops, do-while loops, and for loops. While and do-while loops check their condition at the beginning or end of each iteration. For loops allow the programmer to define an initialization, condition, and increment in one place. The document provides examples of each loop type and discusses nested loops. It also covers the break and continue statements, which alter normal loop execution. A set of exercises is provided to help students practice loops.

Uploaded by

semuty92
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

LAB 5:

LOOPS

By the end of this section, students should be able to:

5.1

To know about repetition (looping) control structures.

To understand while, dowhile and for loop.

To know the function of break and continue statement in loop control structure

INTRODUCTION
A loop is a group of instructions the computer executes repeatedly while some loop-continuation

condition remains true. Also known as repetition structure, it repeatedly processes (a) program
instruction(s) until a condition is met. C has three types repetition, i.e. while, do-while, for and nested
[Link] while structure it allows for an action that has to be repeated while some condition remains true.
The dowhile repetition statement is similar to the while statement. In the while statement, the loopcontinuation condition is tested at the beginning of the loop before the body of the loop is performed. But
the dowhile statement tests the loop-continuation condition after the loop body is performed. In while,
there are two means of repetition i.e. Counter-controlled repetition and Sentinel-controlled repetition.
Counter-controlled repetition is sometimes called definite repetition because we know in advance exactly
how many times the loop will be executed. Sentinel-controlled repetition is sometimes called indefinite
repetition because its not known in advance how many times the loop will be executed.

The for repetition statement handles all the details of counter-controlled repetition. Nested for
loops consist of an outer loop with one or more inner loops. Each time the outer loop is repeated, the
inner loops are reentered, their loop control expressions are reevaluated and all required iteration are
performed. There are two types of statement related to loop, i.e. break and continue. break causes a loop
to terminate only the inner loop in nested loop. continue skips the remaining statements in the body of a
control statement and performs the next iteration of the loop (for while, for or dowhile statement).

5.2

GENERAL INFORMATION

5.2.1 Syntax
1) while
while(expression)
statement

E.g.
i = 0;
while (i<5)
{
printf(%d,i);
i = i++;
}

2) do while
do
statement
while(expression);

E.g.
i = 0;
do
{
printf(%d,i);
i = i++;
} while (i<5);

3) nested if else or else if

3) for
for ( expression1; expression2; expression3 )
statement

E.g.(1)
int i = 0;
for(i=0;i<5;i++)
{
printf(%d,i);
}

E.g.(2)
int i,j;
for(i=0,j=0;i<10&&j>0;i++,j0){
printf(i=%d\n,i);
printf(j=%d\n,j);

4) nested for
for ( expression1; expression2; expression3 )
statement
for ( expression1; expression2; expression3 )
statement

E.g.
int i,j;
for (i=1;i<=3;i++)
{
printf("Row %d :",i);
for (j=1;j<= 5;j++)
printf("%3d",j);
printf("\n");
}

5.3

EXERCISES

Short answer questions:


1. Loops
that
terminate
upon
scanning
a
called____________________________controlled loops.

special

input

value

2. Explain the difference between while loop and do while loop.

3. The syntax for for loop is: for (expression1; expression2; expression3).
Explain expression1, expression2, and expression3.

4. Is it true that below program display 29 lines output?


for(i = 0;i < 30;i = i + 1)
printf("%d\n", i);

are

5. If n=8, what is the output for below loop:


sum=0;
for(odd=1;odd<n;odd+=2)
sum=sum+odd;
printf(Sum of positive odd numbers less than %d is 5d.\n,n, sum);

6. Detect the error of below program? Correct the code so it displays all multiples of 4 from 0 to 100.
for mult4=0;
mult4<100;
mult4+=4;
printf(%d\n,mult4);
7. What is the output of below program:
j=10;
for(i=1;i<=5;++i){
printf(%d
%d\n,i,j);
j-=2;
}
8. How many lines the output of below program will display
for(i = 0; i < 5; i = i + 1)
for(j = 0; j < i; j = j + 1)
printf("%d %d\n", i, j);
9. What is displayed by the following program segments, assume m is 3, n is 5:
a. for (i=1,i<=n;++i){
for(j=0;j<1;++j){
printf((*);
}
printf(\n);
}
b. for (i=n,i>0;--i){
for(j=m;j>0;--j){
printf((*);
}
printf(\n);
}
10. What is the output of below program:
i=0;
while(i<=5) {
printf(%d %2d\n,i,10-i);
i=i+1;
}

11. What is displayed by this program fragment for an input of 8?


scanf(%d,&n);
ev=0;
while(ev<n) {
printf(%3d,ev);
ev=ev+2;
}
printf(\n);
12. Rewrite the following code segment as an equivalent segment that uses a for statement.
product = 1;
next = 1;
while (next <= m) {
product = product * next;
next = next + 1;
}
13. The following segment needs some revision. Insert braces where they are needed and correct
the errors:
count=0;
while(count<=5)
count+=1;
printf(Next number> );
scanf(%d,&next_num);
next_num+=sum;
printf(%d numbers were added;\n,count);
printf(their sum is %d.\n,sum);

14. Write a program that computes and displays the sum of collection of celcius temperature entered
at the terminal until a sentinel value of -100 is entered. Write pseudocode and draw the flowchart
of your program first.
15. Write a program using a loop to printout the following sequence including commas:

2, 4, 6, 8, 10, 12, 14, 16


16. Write a program to print output as below:

*
**
***
****
*****
******
Reference:
1. Deitel, Paul and Deitel, Harvey. 2010. C How To Program, Sixth Edition. Perason, 2010.
2. Hanly, Jeri R. and Koffman, Elliot B. 2010. Problem Solving and Program Design in C, Sixth
Edition. Pearson, 2010.
3. Cheng, H. Harry. 2010. C for engineers and scientists: An Interpretive Approach. McGrawHill, 2010.

Common questions

Powered by AI

Sentinel-controlled repetition is more beneficial in scenarios where input is processed until a particular stopping point is reached, such as processing input from a user until they enter a sentinel value indicating completion (e.g., '-1' to stop input acceptance). This approach is advantageous when the number of inputs is unpredictable, and the loop needs to run an indefinite number of times until an external signal (the sentinel) is detected . In contrast, counter-controlled repetition requires knowing the number of iterations beforehand, making it less flexible in cases of unpredictable input size .

Counter-controlled repetition in a 'for' loop is implemented by setting up loop expressions that manage the count explicitly. An example of such implementation is: `for (int i = 0; i < 5; i++) { printf("%d", i); }` . Here, `int i = 0` initializes the counter variable `i`. The condition `i < 5` checks whether the loop should continue, and `i++` incremetns the counter after each loop iteration. This encapsulation maintains control flow and allows iteration exactly five times, demonstrating precise counter-controlled repetition .

The 'while' loop can implement two types of repetition control: counter-controlled and sentinel-controlled. Counter-controlled repetition, known as definite repetition, occurs when the number of times the loop should execute is known before the loop is entered, utilizing a counter variable to track iterations . On the other hand, sentinel-controlled repetition, or indefinite repetition, is used when the number of iterations is not known in advance and depends on sentinel values signaling the end of the loop . This often involves reading input until a specific value is encountered, allowing flexibility in cases where input size or conditions vary .

The 'break' statement is used to exit a loop prematurely when a certain condition is met, terminating the loop's execution immediately. In nested loops, the 'break' statement only terminates the execution of the innermost loop where it is encountered, allowing the flow to continue with the next statement after this loop .

The fundamental difference between the 'while' and 'do-while' loop control structures lies in the point at which the loop-continuation condition is tested. In a 'while' loop, the condition is tested before the execution of the loop body, meaning if the condition is false initially, the loop body may not execute at all . Conversely, the 'do-while' loop tests the condition after the loop body is executed, ensuring that the loop body is executed at least once regardless of whether the condition is true or false initially .

The main reason for using a 'for' loop in counter-controlled repetition is its ability to encapsulate and clearly manage the loop's initialization, continuation condition, and increment/decrement process within a single line of code. The 'for' loop expressions are as follows: expression1 initializes the loop variable, expression2 is a condition check executed before each iteration, and expression3 updates the loop variable after each iteration . This concise structure makes the 'for' loop ideal for scenarios where the number of iterations is known in advance .

Nested loops expand the functionality of simple loop structures by enabling complex iteration patterns where the inner loops can execute completely for each iteration of the outer loop. This allows for operations on multi-dimensional data structures, such as matrices, where each element needs to be iterated over efficiently. With an outer loop controlling the rows and inner loops the columns or depth, nested loops facilitate comprehensive processing of structured data .

A programmer would prefer using a 'continue' statement within a loop in scenarios where certain iterations need to be skipped without terminating the entire loop execution. The 'continue' statement, when encountered, moves the control to the next iteration of the loop, bypassing any code remaining in the current loop iteration's body . This is particularly useful in filtering operations where some data processing conditions are met, rendering further operations redundant for the current step, while upcoming iterations should proceed unaffected .

A nested 'for' loop creates a rectangular grid pattern in output when both outer and inner loops iterate over integers. As each iteration of the outer loop triggers the entirety of the inner loop, for each increase in the outer loop's counter, the entire inner loop's range is executed afresh. For instance, a loop structure like `for (i=1;i<=3;i++) { for (j=1;j<=5;j++) printf("%3d",j); printf("\n"); }` would print a three-line pattern where each line contains values 1 through 5, precisely creating a 3x5 grid .

The given 'while' loop can be rewritten as a 'for' loop by integrating initialization, condition, and increment expressions directly into the loop construct. The equivalent 'for' loop is: `for (int product = 1, next = 1; next <= m; next++) { product = product * next; }` . This version retains the logical flow of the original loop but consolidates the iteration control within the 'for' loop syntax, streamlining the loop logic .

You might also like