What is break
?:
break
will terminate a loop or exit a switch
Why use break
?:
- allows you to stop the loop/switch if an error or irregular condition is detected
How to use break
?:
- Things to note:
- there are no arguments
What is break
?:
break
will terminate a loop or exit a switchWhy use break
?:
How to use break
?:
Simple break Example:
This program shows how to use a break
statement:
break Example with Nested Loops:
This program shows what happens when using a break
statement within a nested loop:
break
only exits inner loopbreak
within the outer loop is needed to exit the outer loop as wellWhat is continue
?:
continue
allows you to bypass the remainder of the current iteration of a loopWhy use continue
?:
continue
allows the loop to continue on to the next iterationbreak
, in contrast, will exit the loop entirelyHow to use continue
?:
continue Example:
This program shows how to use a continue
statement:
What is goto
?:
goto
allows you to jump to different sections of your programgoto
is a carry-over from older programming languagesWhy use goto
?:
goto
unless absolutely necessary because goto
program flow is hard to followgoto
:
if
/else
break
continue
goto
might be to break out of jump out of a doubly nested loop
if - break
statementsHow to use goto
?:
goto
statementThis program shows how to use goto
out_of_both_loops
statements are still executed when the program exits out of both loops without the goto
statementWhat is return
?:
return
causes the program logic to return to the point from which the function was calledreturn
optionally returns information to the point from which the function was calledWhy use return
?:
main
function, then the program will endHow to use return
?:
return
does not need to return an expression, e.g. expression is optionalThis program shows how to use return
printf
statement (You are out of both loops
) is never executed because the program just endsmain
function typically returns 0
to the operating system that calls the main
function
Update this program to implement a switch
using goto
Write a program that allows the user to input a positive integer. The program will count from 1 up till the positive number. For numbers that are divisible by 3, print out Fizz
instead of the number. For numbers that are divisible by 5, print out Buzz
instead of the number. For numbers that are divisible by 3 and 5, print out FizzBuzz
instead of the number. Try to use the continue
statement or the goto
statement to accomplish this.
For example:
Please enter the max number to count to: [user enters in 31] 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31