[go: up one dir, main page]

0% found this document useful (0 votes)
52 views25 pages

Construct 3 - Repetition / Looping by Prof. Elijah Omwenga October 2012

The document discusses different types of loops in C programming including for, while, do-while, and sentinel controlled loops. It provides examples of each loop type and explains how they work. It also discusses the break and continue statements that can be used to alter normal loop flow. Mathematical operators like addition, subtraction, multiplication, division, and modulus are also briefly explained.

Uploaded by

miller
Copyright
© Attribution Non-Commercial (BY-NC)
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)
52 views25 pages

Construct 3 - Repetition / Looping by Prof. Elijah Omwenga October 2012

The document discusses different types of loops in C programming including for, while, do-while, and sentinel controlled loops. It provides examples of each loop type and explains how they work. It also discusses the break and continue statements that can be used to alter normal loop flow. Mathematical operators like addition, subtraction, multiplication, division, and modulus are also briefly explained.

Uploaded by

miller
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 25

Lecture 6

Construct 3 Repetition / looping By Prof. Elijah Omwenga October 2012

Introduction to Looping Loops cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true.
When a condition becomes false, the loop ends and control is passed to the statements following the loop. If a loop continues forever, it is called an infinite loop. In looping, a sequence of statements is executed until some condition for the termination of the loop are satisfied.

A program loop therefore consists of two segments:


1.Control statement. 2.Body of the loop

The control statement sets certain conditions and then directs the repeated execution of the statements contained in the body of the loop.

There are three kinds of loops in C: the for loop, the while loop, and the do loop.

The for loop


The for loop is an entry controlled loop that provides a concise loop control. The general form of the loop is: for (initialisation; test condition; increment) { statement; statement; } // No semicolon here The execution of the for statement is done as, by firstly initialising the control variables using assignment statements such as i=0. the variables i is known as loop control variable.

The value of the control variable is tested using the test condition. See flowchart below:

The for loop


The body of the loop can contain one or multiple statements. The brace {} are used to group the multiple statements. However it is a good programming practice to use braces even if there is only one statement in the body of the loop.

The for loop

Test

False

Exit

True Body of loop

The for loop


The test condition is a relational expression, such as i<5 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
See the example

#include <stdio.h> void main() { int count, number, sum; double average; sum =0; for (count=0;count<5;count++) { printf ("Enter a number"); scanf("%d", &number); sum+=number; //sum=sum+number } average=(double)sum/count; printf("Sum is %d\n", sum); printf("The Average is %7.2lf\n", average);

The while loop


The test condition is evaluated first and if the condition is true, the body of the loop is executed zero or more times. After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.

This process of repeated execution of the body continues until the test condition finally become false. On exit, the program continues with the statement immediately after the body of the loop.

while loop
initialize count

Test

False

Exit

True True
Body of loop. Increment count

The general form of the while loop is: while (test-condition)

{ statement; statement; } // No semicolon here NB: The difference between while loop and the for loop is that the for loop does something a fixed number of times while the while loop can be used where the number of loops is not known.

#include <stdio.h> void main() { int count, number, sum; double average; sum =0; count=0; while (count<5) { printf ("Enter a number"); scanf("%d", &number); sum=sum+number; count++ } average=(double)sum/count; printf("Sum is %d\n", sum); printf("The Average is %7.2lf\n", average); }

The do .. while loop


Unlike the while loop in which a condition is tested before the loop is executed.
In do.. while (condition), the testing is done after the body of the loop is executed at least once.

This means that the execution is one or more times.


See the flowchart on the next slide...

Do while loop
initialize count
do { Body of loop. }

False Test True

Exit

The general form of the do loop is: do {

statement; statement;
} // No semicolon here

while (test-condition); // semi colons here On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again.

do while loop
This process continues as long as the condition is true.

When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test condition is evaluated at the bottom of the loop, the do . While construct provides an exit controlled loop and therefore the body of the loop is always executed at least once.

#include <stdio.h> void main() { int count, number, sum; double average; sum =0; count=0; do { printf ("Enter a number"); scanf("%d", &number); sum=sum+number; count++; } while (count<5); average=(double)sum/count; printf("Sum is %d\n", sum); printf("The Average is %7.2lf\n", average); }

Sentinel controlled loop

In a Sentinel-Controlled loop, a special value called a sentinel value is used to change the loop control expression from true to false.
For example, when reading data we may indicate the "end of data" by a special value, like -1 and 999. The control variable is called sentinel variable. A sentinel-Controlled loop is often called indefinite repetition loop because the number of repetitions is not known before the loop begins executing.

Sentinel controlled loop


#include <stdio.h> void main() { int number, count,sum; double average; sum =0;count=0; printf ("Enter a number "); scanf("%d", &number); while (number!=-1) { sum=sum+number;
}

printf ("Enter a number "); scanf("%d", &number); count++; } if (count>0) { average=(double)sum/count; printf("The Average is %7.2lf\n", average); } else printf("Sum is %d\n", sum);

Break and continue


Break and continue are used to alter the flow of control. Break is used to exit from a loop (for, while, or do) or a switch, passing control to the first statement outside the loop or switch. A break within a loop should always be protected within an if statement which provides the test to control the exit condition. Continue is similar to break but only works within loops where its effect is to force an immediate jump to the loop Boolean test. In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration. Like a break, continue should be protected by an if statement.

Break example: Prime number testing

Write your own program that tests if the given number is prime number.
#include <stdio.h> #include <math.h> void main() { int i, n, prime; prime=1; // prime is true printf("Input natural number :"); scanf("%d", &n); for( i=2; i<= n-1; i++) { if( n % i == 0 ) { prime =0; // prime is now false break; } }

if( prime ) printf("%d is prime number !\n", n); else printf("%d isnt a prime number! \n", n);
}

Prime numbers

To test if a number n is prime, we could loop through 2 to n - 1 and test whether each number divides exactly into n ((n % test) == 0). If any of them do, the number is not prime.
However, since by definition any number which is not prime can be divided by at least one other prime number, a more efficient way to do it is to test only the prime numbers less than n. Therefore, our program maintains a list of prime numbers already found, and uses that to test n.

Use of break and continue

Write a program that reads integers. If the given number is smaller than zero, program should print error message and stop reading numbers.
If the given number is bigger than 100, it should be skipped and program should read another number. All other numbers should be red and printed. Program must stop reading numbers when 0 or error shows up .

Break and continue


#include <stdio.h> void main() { int x; do { printf ("Input number :\n"); scanf("%d", &x ); if (x < 0) { printf("Not allowed value\n"); break; /* escapes the loop */ }

if (x > 100) { printf("Skipping the value\n"); continue; /* jumps to second iteration */ } printf ("Given number is : %d", x); } while (x != 0);
}

Mathematical Operators
Operator Name /Function Description The result of addition of two integers is an integer. The result of addition of a float and an integer is a float. A float plus a float results in a float The result of subtraction of two integers is an integer. The result of subtraction of a float and an integer is a float. A float minus a float results in a float Multiplication of two integers results in an integer. The result of multiplication of a float and an integer is a float. A float times a float results in a float

Addition

Subtraction

Multiplication

Division

modulus

Division of two integers results in an integer. Any remainder is lost. The result of division of a float and an integer is a float. A float divided by a float results in a float Acts on integers. Returns the remainder of an integer division

You might also like