Repeatedy ask if user wants cake until user says yes or yeah. How would you implement this?→
Stepping Through Cake
Let's make an assumption that the user enters "no" first, and then "yeah" second.
answer is set to no by default
condition is true, answer (no) is not 'yes' or 'yeah'
answer is set to user input of 'no'
condition is true, answer (no) is not 'yes' or 'yeah'
answer is set to user input of 'yes'
condition is false, answer != 'yeah' is now false!
have some cake is printed
Accumulating Values
Write a program that will: →
continually ask the user for a number (forever)
add that number to a running total
print out the running total
Potential Solution for Accumulating Values
A Difficult One…
Write a program that continually asks the user for numbers, and asks them if they'd like to keep going. In the end, it should output the average of all of the numbers entered→
Some Hints, Please?
Let's try keeping track of multiple variables:
a user's answer to whether or not the program should continue
the total (sum) of the numbers that a user has entered
the count of numbers input
An Average Solution
Increment / Decrement
We've used the following syntax to increment or decrement a variable
Slightly tedious…
Increment / Decrement Continued
There's some syntactic sugar that makes doing this less verbose: use += or -=
n += 1 is the same as n = n + 1
n -= 1 is the same as n = n - 1
More Syntactic Sugar
This works for other operators too. What does this code print out? →
What About Strings?
Also works with strings…. What does this code print out? →
Other Exercises
count the number of digits in an int
repeatedly use integer division
…until the original number becomes 0
keep count of divisions
continually add exclamation points to a word
ask for a word
ask for x number of exclamation points
print out resulting word and exclamation points
continue asking for another word and exclamation points