A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

IF E ITERAÇÃO WHILE Dilvan Moreira (baseado no livro Big Java e T. Munzner)

Apresentações semelhantes


Apresentação em tema: "IF E ITERAÇÃO WHILE Dilvan Moreira (baseado no livro Big Java e T. Munzner)"— Transcrição da apresentação:

1 IF E ITERAÇÃO WHILE Dilvan Moreira (baseado no livro Big Java e T. Munzner)

2 Lembrando: Operadores Relacionais  Testam dois valores (operandos)  Operadores  == igual retorna vaerdadeiro se igual, falso se não nota: não confundir com =  != diferente retorna verdadeiro se diferente, falso se igual  < menor que  <= menor ou igual que  > maior que  >= maior ou igual que

3 Lembrando: Operadores Lógicos  Modo de combinar relultados de operadores relacionais num teste único  AND, OR, e NOT  em termos matemáticos  Operadores  && AND lógico  || OR lógico  ! NOT lógico

4 Objetivos  Ser capaz de programar usando if e switch  Ser capaz de programar com laços (loops) while, for e do  Entender loops aninhados

5 Sintaxe do If  Sintaxe  Palavra reservada if  seguida de expressão booleana entre parenteses  seguida de comando if (x == y) printf("x equals y! ");  Resultado  se expressão booleana é verdadeira, comando é executado  se não, execução pula comando

6 Sintaxe do If-Else  Opção do else:  palavra reservada else  seguida por comando if (x == y) printf("x equals y!"); else printf("x is not equal to y!");  Resultado  se expressão booleana é verdadeira, primeiro comando é executado  se não, segundo comando é executado

7 Uso de Blocos de Comandos  Quando se quer executar mais de um comando, baseado numa condição  Substitui um comando por muitos dentro de {} if (x == y) { printf("x equals y!"); printf("I'm happy"); } else { printf("x is not equal to y"); printf("I'm depressed"); printf("How about you?"); }

8 Sintaxe do Switch  Usado para seguir caminhos diferentes baseado num valor switch (finalMark) { case 4: printf("You get an A"); break; case 3: printf("You get a B"); break; case 2: printf("You get a C"); break; default: printf("See you next year"); }

9 Sintaxe do Switch  Expressão deve ser integer, char switch (finalMark) { case 4: printf("You get an A"); break; case 3: printf("You get a B"); break; case 2: printf("You get a C"); break; default: printf("See you next year");

10 Sintaxe do Switch  Os valores do case não podem ser variáveis switch (finalMark) { case 4: printf("You get an A"); break; case 3: printf("You get a B"); break; case 2: printf("You get a C"); break; default: printf("See you next year"); }

11 Sintaxe do Switch  O comando default é opcional switch (finalMark) { case 4: printf("You get an A"); break; case 3: printf("You get a B"); break; case 2: printf("You get a C"); break; default: printf("See you next year"); }

12 Sintaxe do Switch  Comandos break são muito importantes switch (finalMark) { case 4: printf("You get an A"); break; case 3: printf("You get a B"); break; case 2: printf("You get a C"); break; default: printf("See you next year");

13 Repetição, Interação, Loops  Computadores são bons em realizar a mesma tarefas muitas vezes  Loops (laços) permitem operações repetitivas em programas  Loops acontecem na vida real também:

14 Subindo Escadas  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step. ...and so on...

15 Comando While while (expressão booleana) corpo  A forma mais simples de loop em C  Corpo do loop  um comando  um bloco de comandos {usando chaves}  Fluxo de controle  corpo executado se expressão é verdadeira  expressão booleana é reavaliada  se continua verdadeira, corpo é executado novamente  repete a execução do corpo enquanto expressão for verdadeira

16 If Versus While boolean expression statement true como if funciona false

17 If Versus While boolean expression statement true como if funciona boolean expression statement truefalse como while funciona false

18 If Versus While-Fluxograma boolean expression statement true como if funciona boolean expression statement truefalse como while funciona false

19 If Versus While boolean expression statement true como if funciona boolean expression statement truefalse como while funciona false  Como a expressão muda de verdadeiro para falso?

20 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  comando while

21 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  expressão booleana

22 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  corpo do comando while  o que vai ser repetido

23 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  programa continua aqui quando condição fica falsa

24 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  trace o que acontece quando executado

25 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } limit 3

26 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } limit 3 counter 1

27 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } counter <= limit? sim limit 3 counter 1

28 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } "The square of 1 is 1" aparece no monitor counter <= limit? sim limit 3 counter 1

29 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } limit 3 counter 2

30 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } counter <= limit? sim limit 3 counter 2

31 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } "The square of 2 is 4" aparece no monitor counter <= limit? sim limit 3 counter 2

32 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } limit 3 counter 3

33 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } counter <= limit? sim limit 3 counter 3

34 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } "The square of 3 is 9" aparece no monitor counter <= limit? sim limit 3 counter 3

35 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } limit 3 counter 4

36 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } counter <= limit? NÃO! limit 3 counter 4

37 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; } “End of demonstration" mostrado no monitor counter <= limit? NÃO! limit 3 counter 4

38 Comparando com Subir a Escada  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step.  Am I at the top of the stairs?  No.  Climb up one step. ...and so on...

39 Comparando com Subir a Escada while (I’m not at the top of the stairs) { Climb up one step }  Subir uma escada é um loop while!

40 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter >= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  mudando condição de parada

41 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter >= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  mudando condição de parada: Corpo nunca executa

42 Usando o comando while int main () { int limit = 3; int counter = 1; while (counter <= counter) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  mudando a condição: fica sempre verdadeiro

43 Cuidado: Loop Infinito int main () { int limit = 3; int counter = 1; while (counter <= counter) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 1; } printf("End of demonstration\n"); return 0; }  se sempre verdadeiro, loop nunca termina

44 Cuidado: Loop Infinito int main () { int limit = 3; int counter = 1; while (counter <= limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter - 1; } printf("End of demonstration\n"); return 0; }  condição de terminação OK, incremento incorreto

45 Cuidado: Loop Infinito int main () { int limit = 9; int counter = 0; while (counter != limit) { printf("The square of %d is %d”, counter, counter * counter); counter = counter + 2; } printf("End of demonstration\n"); return 0; }  programa nunca satisfaz condição de parada

46 Exercício  Ler o número de matricula de um aluno e as suas duas notas A e B, e após calcular a média ponderada entre estas notas (A tem peso 1 e B tem peso 2). Verifique se a nota digitada é valida, caso seja inválida, repita a leitura. Repetir este procedimento para uma turma composta por oito alunos, usando o comando While. Exemplo de tela de saída: Entre com o numero do aluno: 235 Entre com o grau A: 5.0 Entre com o grau B: 6.0 O aluno numero 235 tem uma media: 5.66 Entre com o nome do aluno: 335 Entre com o grau A: 12.5 Nota invalida! Entre com o grau A: 2.5...

47 Perguntas?


Carregar ppt "IF E ITERAÇÃO WHILE Dilvan Moreira (baseado no livro Big Java e T. Munzner)"

Apresentações semelhantes


Anúncios Google