• No results found

loops.pdf

N/A
N/A
Protected

Academic year: 2020

Share "loops.pdf"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

1

Loops

¾

There are 3 major types of loops structures in C

¾

For loop

¾

While Loop

¾

Do-While Loop

2

For Loop

¾ It is often the case in programming that you want to do

something a fixed number of times. For loop is ideally suited for such cases.

¾ E.g. Printing numbers from 1 to 50

void main(void) Output:

{ count = 0

int count; clrscr(); count = 1

for (count =0; count<10; count ++) count = 2 printf(“Count = %d\n”, count); .

getch(); .

(2)

3

For loop Expression

for (initializing expression; test expression; increment /decrement expression)

Structure of for loop:

Initialize Expression: It is always executed as soon as the loop is entered. We can start at any number.

In the previous example we used count =0

Test Expression: If the test expression = true, body of loop will be executed. If the expression becomes false, loop will be

terminated and control will be passed to the statements following the loop.

Increment Expression: Increments the variable, each time the loop is executed.

Body of loop

¾ Following the keyword for and loop expression is the body of

the loop i.e. statement (statements) that will be executed each time round the loop.

¾ In for loop no semicolon between the loop expression and the

(3)

5

Operation of for loop

END Enter

Test

Body of Loop Initialize

Increment

False

True

for (count =0; count<10; count ++)

printf(“Count = %d\n”, count);

Keyword

Body of loop

Semicolon terminates entire statement

All this is a single C statement

6

Multiple Statements in for loop

¾ Two or more statements can also be used in body of loop.

void main(void) {

int count, total=0;

for (count =0; count<10; count ++) {

total = total + count;

printf(“Count = %d\n total = %d\n”, count, total); }

getch();

(4)

7

¾ The opening brace, the statements and the closing brace are all

treated as single C statement, called a “Compound Statement”or “block.”

¾ Each statement within the block is also a C statement and must

be terminated with semi colon in the usual way.

¾ Only 1 expression is allowed in the test expression unlike the

initialization and increment expression. Since a single condition must determine when the loop terminates.

ASCII Table Program

¾ In PC family, each of the numbers from 0 to 255 represent a

separate character.

¾ 0 – 31 Control codes (carriage return, tab, line feed)

¾ 32-127 usual printing characters

¾ 128-255 graphics and foreign language characters

void main(void) {

int n;

for ( n=1; n<256; n++)

printf(“%3d = %c \t”, n,n); getch();

(5)

9

¾ Printf() also uses a field width specifier of 3 so that each

number is printed in a box 3 characters wide, even if it has only 2 digits.

¾ This program prints both the character and its ASCII code. In

most languages this would require a separate conversion function to change number n into character whose ASCII value is n

¾ So format specifier can interpret the same variable in

different ways.

10

Nested for loop

¾ It is possible to nest one for loop inside another.

void main(void) {

int rows, cols; clrscr();

for ( rows=1; rows<6; rows++) {

for ( cols=1; cols<6; cols++)

printf(“%3d”, cols * rows);

} printf(“\n”);

getch();

} Output: 1 2 3 4 5

(6)

11

While Loop

void main(void)

{

int count=0;

int total = 0;

while (count <10)

{

total = total + count;

printf(“count= %d,total = %d\n”, count++, total);

}

getch();

}

While Loop

Output:

(7)

13

While Loop

Unexpected Condition:

¾

In situations where the number of iteration in a loop

are known in advance, while loops are actually less

appropriate. In this case for loop is a more natural

choice.

¾

While loop is used in situations where a loop may be

terminated unexpectedly by condition developing

within the loop.

14

Example

void main(void) {

int count=0;

printf(“Type in a phrase:”);

while (getche() != ‘\r’)

count++;

printf(“\n Character count is %d”, count); getch();

}

(8)

15

While Loop

¾ Here getche() function is used, that returns the value of the

character the instant it is typed. It also takes on or returns the value of character typed. So the function can be treated like a variable and compared with other variables or constants.

¾ So while loop will continue to be executed as long as it doesn't

encounter a ‘\r’. When it encounters it, loop will terminate and total number of characters typed will be printed out.

Operation of While Loop

END Start

Test

Body of Loop Initialize

Increment

False

(9)

17

ASCII Revisited

void main(void) {

char ch = ‘a’; while (ch != ‘\r’)

{

printf(“Enter a character:”); ch = getche();

printf(“\n the code for %c is %d\n”, ch,ch); }

getch(); }

Output: Enter a character: a The code for a is 97

18

ASCII Revisited

¾ Here we cant put the getche() in the while loop, as we want to

print a prompt to user before invoking it.

¾ It also shows that character variables can be interpreted as

(10)

19

Nested while loop

void main(void) {

int j; char ch = ‘a’;

for ( j=0; j<5; j++) {

printf(“\nType in a letter from ‘a’ to ‘e’:”);

while ((ch = getche()) != ‘d’)

{ printf(“\n Sorry %c is incorrect”,ch); printf(“\nTry Again”);

}

printf(“\nThats it”);

}

printf(“\nGame over”); getch();

}

Nested while loop

¾ You can play this game exactly 5 times, due to the outer loop

¾ Inner loop determines whether your guess is correct or not.

¾ Correct answer is always ‘d’ (unless you modify)

¾ Examine the statement:

while ( (ch = getche( ) ) != ‘d’ )

1. Function returns value

2. Value assigned to ch

3. Entire expression is given value of ch

4. Extra parenthesis to overcome precedence

(ch != ‘d’)

5. Expressions are compared

(11)

21

Nested while loop

¾ Reason for parenthesis is that precedence of relational operator

(!=) greater than the assignment operator (=)

¾ If parenthesis are not used i.e.

while (ch = (getche() != ‘d’)

is written, ch will now be set equal to result of true/false expression.

22

Mathematical while loop

void main(void) { long number = 1;

long answer = 1; while (number != 0)

{ printf(“\n enter a number”); scanf(“%d”, &number); answer = 1;

while (number >1)

answer = answer * number--; printf(“Factorial is %ld”\n”, answer); }

(12)

23

Mathematical while loop

¾ An example of while loop that calculates the factorial of a

number.

¾ Factorial of a number is = number multiplied by all numbers

smaller than itself.

¾ In the program, outer while recycle until a 0 value is entered.

¾ Inner loop uses decrement operator to reduce the “number” by

1 each time. When number = 1 loop terminates.

¾ Long integers are used because factorials grow rapidly and

would have exceeded the integer’s capacity of 32767.

¾ Long integers can hold 2,147,483,647 numbers.

Do-While Loop

Similar to while loop, difference is that the do loop test condition is evaluated after the loop is execute rather than before.

void main(void) {

int count=0; int total = 0;

do {

total = total + count;

printf(“count= %d,total = %d\n”, count++, total);

}

while (count <10)

(13)

25

Do-While Loop

¾ It has 2 keywords, doand while.

¾ Do keyword marks the beginning of loop, it has no other

function.

¾ While keyword marks the end of loop and contains the loop

expression.

¾ Terminated with a semi colon i.e. test condition in parenthesis

following while ends with a semi colon.

26

Operation of do-while Loop

Exit Enter Loop

Test Body of loop

Increment

False True

¾ upside down version of while

loop. Body of loop is first executed, then test condition is checked. If test condition is true, loop is repeated, if it is false, loop terminates.

¾ Body of loop will always be

(14)

27

void main(void) {

char ch;

do

{ printf(“\nType in a letter from ‘a’ to ‘e’:”);

while ((ch = getche()) != ‘c’)

{ printf(“\n Sorry %c is incorrect”,ch); printf(“\nTry Again”);

}

printf(“\nThats it”);

printf(“\nPlay again? (type ‘y’ or ‘n’):”); }

while (getche() = = ‘y’);

printf(“\nGame over. Thank you for playing”); getch();

}

It is assumed that you want atleast one game.

Summary

¾ For Loop:

¾ Frequently used where the loop will be traversed a fixed number of times.

¾ While Loop:

¾ Keeps repeating an action until an associated test condition returns false. Useful where programmer doesn't know in advance how many times loop will be executed.

¾ Do-While Loop:

References

Related documents

• After the initialize statement, the condition part of the loop will be executed if the condition becomes true then body of the loop will be executed otherwise the loop will

Optimal microgrid system design was addressed with the application of mathemat- ical optimization, specifically mixed integer linear programming. The problem consid- ered was

“You Stepped Out Of A Dream,” from the studio album, features Steve mixing it up on the brushes with a uniquely modern jazz approach in the context of a sax, bass, and

It is an exit-controlled loop statement (i.e., the body of the loop executed first and the test condition is evaluated for repetition of next time).. The body of loop may not

We implemented this using a Symmetrix VMAX 10K storage array together with an existing VNX5300 storage array to form a bi-directional disaster recovery solution.. We achieved this

On the other hand, operation (ii) is used to test whether the condition is true or false. If the condition is true, the program executes the body of the loop and then the value of

The positive impact of innovation cooperation on innovation activity suggests that the potential of innovation cooperation should be better exploited, especially in coun- tries that

A do-while loop is similar to a while loop except that it first executes the loop body and then checks the loop condition..