Você está na página 1de 13

Introduc)on

to Programming
REPETITION while loops

Control of Flow
SEQUENCE SELECTION - if, if else REPETITION while, do while, for

Repe))on
Repe))on also known as itera)on, and as Looping Some)mes when wri)ng a program we want to repeat an ac)on several )mes: Input several numbers Add up a list of numbers Output several messages

Repe))on xed number of )mes


If we know exactly how many .mes the statements occur then we might do this by wri)ng the statements several )mes prinO(input persons age); scanf(%d, &input1); prinO(input persons age); scanf(%d, &input2); prinO(input persons age); scanf(%d, &input3);

Repe))on xed number of )mes


Instead of repeatedly wri)ng the same statements our program, it can be more ecient to repeat them REPEAT 3 TIMES { OUTPUT Input your age INPUT age}

Repe))on xed number of )mes while


We can implement repe))on using the while construct while (<condi)on is true>) { repeat these statements } When the condi)on becomes false the repe))on stops

Repe))on xed number of )mes while


int count=1; while ( count <= 10) {prinO(input persons age); scanf(%d, &age); count++; } Can anyone see a problem with this program?

Repe))on indeterminate number of )mes


number = 1; WHILE (number > 0 ) { OUTPUT Input your age INPUT age OUTPUT Input a posi)ve number to con)nue INPUT number }

Repe))on indeterminate number of )mes in C


int number = 1; while (number > 0 ) { prinO( Input your age); scanf(%d, &age); prinO (Input a posi)ve number to con)nue); scanf(%d, &number); }

Repe))on xed number of )mes


while loops con)nue to loop while some condi)on is true, and stops when the condi)on becomes false . while (condi)on) { do this} int age = 10; while (age < 18) { prin>(You cant drive); age++; } //what is the output?

C program
#include <stdio.h> void main() {int age = 10; while (age < 18) { prinO(You cant drive); prinO (You are aged , %d &age); age++; } prinO(You are 18 now so you can drive); }

#include <stdio.h> void main() { int input; Int PIN = 1234; Int yes =1; while(yes == 1) { prin>(please enter your PIN number); scanf(%d, &input); if (input == PIN) { prin>( Your PIN number was correct, you can access your bank account); } else { prin>(Your PIN number was INCORRECT, you cannot access your account); } prin>(Enter 1 to try again, and 0 to exit); scanf(%d, &yes); } }

#include <stdio.h> void main() { int input; Int PIN = 1234; Int yes =1; while(yes == 1) { prin>(please enter your PIN number); scanf(%d, &input); if (input == PIN) { prin>( Your PIN number was correct, you can access your bank account); yes = 0; } else { prin>(Your PIN number was INCORRECT, you cannot access your account); prin>(Enter 1 to try again, and 0 to exit); scanf(%d, &yes); } }

Você também pode gostar