Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
Loops and Conditionals; Functions and Procedures
in C++Computer Science Fundamentals II
Jim Fix
Spring 2020, Lecture 02-1, February 3rd, 2020
Announcements• Posted Homework 01 on Saturday, due Wednesday.
➡ Just a series of conditional and loop exercises.
➡ There's one std::string exercise; many "mod" and "div" ones.
• Posted a guide to installing C++.
➡ For Mac OS X (Xcode), Windows 10 (Ubuntu/WSL)
• CS Colloquium every Tuesday, 4:30-5:30 E314
➡ Tomorrow: Kevin Knight, UCLA expert on AI
Today
• Today, we'll continue basic C(++) programming:
➡ finish looking at loops and conditionals
➡ look at defining (helper) functions and procedures
• You can also check my (posted) grammar for C++.
GRAMMAR for a C programprogram ::= includes defs main main ::= int main(void) { block }
block ::= statements
statement ::= var-name = expression; var-dec g std::cout << outs ; std::cin >> var-name ; return expression ;conditional %loop %update %
If and While Statements➡ Python if statement:
if condition:body-when-true
➡ Python if-else statement: if condition:
body-when-true else:
body-when-false
➡ Python while loop: while condition:
body-when-true
➡ C++ if statement: if (condition) {
body-when-true }
➡ C++ if-else statement: if (condition) {
body-when-true } else {
body-when-false }
➡ C++ while loop: while (condition){
body-when-true }
• Mean essentially the same thing in the languages.
If and If-Else Statements• Just like in Python, you can use conditional statements to perform
execution of code blocks, driven by certain checks.
• There is an "if" statement if(condition-to-test) {
statements-to-execute-if-true }
• There is an "if-else" statement if(condition-to-test) {
statements-to-execute-if-true } else {
statements-to-execute-if-false }
• Note: no semicolon after the brace for these.
While Statement• Just like in Python, you can use loops to perform iteration, i.e. repeated execution
of a block of code until some condition no longer holds.
• Typically do this with a "while" loop: while (condition-to-test) {
statements-to-execute-when-true }
• This mimics the "infinite conditional": if(condition-to-test) {
statements-to-execute-if-true if (condition-to-test-again) {
same-statements-to-execute-again-if-true if (condition-to-test-again) {
same-statements-to-execute-again-if-true ...
}}
}
Example: guess.cc#include <iostream>#include <ctime> // For time()#include <cstdlib> // For srand() and rand()
int main() {
srand(time(0));
int number = (rand() % 100) + 1;
std::cout << "I've chosen a number from 1 to 100. "; std::cout << "Try to guess what it is.\n";
int guess; bool success = false;
while (!success) { ... // keep getting guesses and reporting their success }
std::cout << "Well done! "; std::cout << number << " was the number I chose.\n";
return 0;}
Example: guess.cc loop
int guess; bool success = false;
while (!success) { std::cin >> guess; if (guess < number) { std::cout << "That's too low. Try again.\n"; } else if (guess > number) { std::cout << "That's too high. Try again.\n"; } else { success = true; } }
"Cascading" if statements• They can end with just an "if"
if(condition-to-test) {statements-to-execute-if-true
} else if (some-other-test) {statements-to-execute-for-this-test
} else if...
} else if (...) {statements
}
• They can end with an "else" if(condition-to-test) {
statements-to-execute-if-true } else if...
} else {statements
}
Six Guess Version
int guess; bool success = false; int guesses = 0;
while (!success && guesses < 6) { std::cin >> guess; guesses = guesses + 1; if (guess < number) { std::cout << "That's too low. Try again.\n"; } else if (guess > number) { std::cout << "That's too high. Try again.\n"; } else { success = true; } }
Six Guess Version
int guess; bool success = false; int guesses = 0;
while (!success && guesses < 6) { std::cin >> guess; guesses = guesses + 1; if (guess < number) { std::cout << "That's too low. Try again.\n"; } else if (guess > number) { std::cout << "That's too high. Try again.\n"; } else { success = true; } }
Three kinds of loops• There is a "while" statement
while(condition-to-test) {statements-to-execute-when-true
}
• There is also a "do-while" statement!!!! do {
statements-to-execute-at-least once } while(condition-to-test);
• There is a "for" statement, sort of like Python's... for (initialization; theres-more-to-do; bump-to-next) {
statements-to-execute-on-one-thing }
countUp.cc using while#include <iostream>
int main() { int top; std::cout << "Enter the ending count: "; std::cin >> top;
int count = 0; while (count <= top) { std::cout << count << "\n"; count = count + 1; } std::cout << "Woo!\n";
return 0;}
countDown.cc using while#include <iostream>
int main() { int top; std::cout << "Enter the starting count: "; std::cin >> top;
int count = top; while (count > 0) { std::cout << count << "\n"; count = count - 1; } std::cout << "Woo!\n";
return 0;}
"for" loop• Anytime you have a loop like this
initial-statement while(condition-to-test) {
statements-to-execute-when-true update-statement
}
• You can write it like below
for(initial-statement ; condition-to-test; update-statement) {statements-to-execute-when-true
}
More C-like using for#include <iostream>
int main() { int top; std::cout << "Enter the ending count: "; std::cin >> top;
for (int count = 0; count <= top; count++) { std::cout << count << "\n"; } std::cout << "Woo!\n";
return 0;}
More C-like using for#include <iostream>
int main() { int top; std::cout << "Enter the ending count: "; std::cin >> top;
for (int count = 0; count <= top; count++) { std::cout << count << "\n"; } std::cout << "Woo!\n";
return 0;}
More C-like using for#include <iostream>
int main() { int top; std::cout << "Enter the starting count: "; std::cin >> top;
for (int count = top; count > 0; count--) { std::cout << count << "\n"; } std::cout << "Woo!\n";
return 0;}
More C-like using for#include <iostream>
int main() { int top; std::cout << "Enter the starting count: "; std::cin >> top;
for (int count = top; count > 0; count--) { std::cout << count << "\n"; } std::cout << "Woo!\n";
return 0;}
GRAMMAR for C statementsconditional ::= if (expression) {block}if (expression) {block} else {block}if (expression) {block} else if (expression) {block}if (expression) {block} else if (expression) {block} else {block}...
loop ::= while (expression) {block}do {block} while (expression);for (statement;expression;statement) {block}
update ::= var-name operation= expression ; var-name ++; // increment var-name --; // decrement
Modular Decomposition• Like in your Python programming, it is good style to break
up a program into smaller, testable code components
➡ It's good to define meaningful functions that compute some calculation and return some result.
➡ It's good to define meaningful procedures that perform some action (in Python: a function that returns None).
• In each case, we write them in a useful, general way: they take parameters that they compute with. abstraction ➡ We call functions to compute a result with some specific
arguments within an expression. ➡ We call procedures to perform some action with some
specific arguments as a statement line.
Example: temp.cc#include <iostream>
int getInt(std::string prompt, bool oneline) { std::cout << prompt << " "; if (!oneline) { std::cout << "\n"; } int response; std::cin >> response; return response;}
int fToC(int f) { return (f - 32) * 5 / 9;}
...
Example: temp.cc (cont'd)...
int cToF(int c) { return c * 9 / 5 + 32;}
void reportConversion(int amount, std::string scale, std::string toScale) { std::cout << "If in " << scale; std::cout << ", that would be " << amount; std::cout << " degrees " << toScale << ".\n";}
int main() { int t = getInt("Enter a temperature as an integer:",true); reportConversion(fToC(t),"fahrenheit","celsius"); reportConversion(cToF(t),"celsius","fahrenheit"); return 0;}
Anatomy of a C++ programa preamble of #include lines of "header files"
procedure or function definition
procedure or function definition
...
procedure or function definition
the definition of the main function
Example: temp.cc "anatomy"#include <iostream>
return-type fToC(parameter declarations) { function's body }
return-type cToF(parameter declarations) { function's body }
return-type getInt(parameter declarations) { function's body }
void reportConversion(param... dec...) { procedure's body }
int main() { body of the main function }
Anatomy of a function definition• Every function definition has
➡ the function's name ➡ the function's formal parameter variable declarations ➡ its body of statements, including a use of return ➡ the type of the value it returns
return-type function-name(parameter declarations) {Sequence of statements that form the body, including return.
}
• A parameter definition is of the form: type-name variable-name
• Recall these example type names: ➡ int, bool, char, std::string, double
• These are needed so the compiler can lay out space in memory reserved for storage of the bytes of data for each variable.
Functions from temp.cc
int getInt(std::string prompt, bool oneline) { std::cout << prompt << " "; if (!oneline) { std::cout << "\n"; } int response; std::cin >> response; return response;}
int fToC(int f) { return (f - 32) * 5 / 9;}
A procedure in temp.cc
void reportConversion(int amount, std::string scale, std::string toScale) { std::cout << "If in " << scale; std::cout << ", that would be " << amount; std::cout << " degrees " << toScale << ".\n";}
Procedures vs. Functions• A procedure is a callable "routine" that performs a series of
actions/calculations as statements, just like a function. • Unlike a function, procedures do not return a value. • Remember Python functions that always return the None value?
They're like those.
void procedure-name(parameter declarations) {Sequence of statements that form the body.
}
• Like a function, every procedure definition has ➡ the procedure's name ➡ the procedure's parameter variable declarations ➡ its body of statements, maybe the use of a return statement
• You give void as the return type, instead.
Example: guess6decomp.cc#include ...
void initialize() { ... }int randomInt(int low, int high) { ... }bool assessGuess(int guess, int target) { ... }void giveInstructions() { ... }void promptForGuess(int tries, int bound) { ... }bool playGame(int number, int bound) { ... }bool checkPlayAgain(void) { ... }
int main(void) { initialize(); do { int number = randomInt(1,100); giveInstructions(); bool theyWon = playGame(number,6); if (theyWon) { std::cout << "Well done! "; } else { std::cout << "Sorry, you are out of guesses...\n"; } std::cout << number << " was the number I chose.\n"; } while (checkPlayAgain());}
Example: guess6decomp.ccvoid initialize() { srand(time(0));}
int randomInt(int low, int high) { return (rand() % (high - low + 1)) + low;}
bool assessGuess(int guess, int target) { if (guess == target) return true;
if (guess < target) { std::cout << "That's too low. Try again.\n"; } else { std::cout << "That's too high. Try again.\n"; } return false;}
void giveInstructions() { std::cout << "I've chosen a number from 1 to 100. "; std::cout << "Try to guess what it is.\n";}...
Example: guess6decomp.cc...void promptForGuess(int tries, int bound) { if (tries == 0) { std::cout << "Enter a number: "; } else if (tries == bound-1) { std::cout << "This is your final guess. What's my number? "; } else { std::cout << "What's your next guess? "; }}
bool playGame(int number, int bound) { bool success = false; int tries = 0; do { promptForGuess(tries,bound); int guess; std::cin >> guess; tries = tries + 1; success = assessGuess(guess,number); } while (!success && tries < bound); return success;}...
Example: guess6decomp.cc...bool checkPlayAgain(void) { std::string answer; do { std::cout << "Would you like to play again [yes/no]? "; std::cin >> answer; } while ((answer != "yes") && (answer != "no")); return (answer == "yes");}
int main(void) { initialize(); do { int number = randomInt(1,100); giveInstructions(); bool theyWon = playGame(number,6); if (theyWon) { std::cout << "Well done! "; } else { std::cout << "Sorry, you are out of guesses...\n"; } std::cout << number << " was the number I chose.\n"; } while (checkPlayAgain());}
GRAMMAR for procedures/functionsprogram ::= includes defs main main ::= int main(void) { block }
def ::= proc-def | func-def proc-def ::= void name(type name, ...) {block}func-def ::= type name(type name, ...) {block}
statement ::= ... return; | return expression ;name(expression, ...)
expression ::= ... name(expression, ...)
Extending the C++ languageProcedures and functions allow you to extend the C language, making your own constructs • A function is like a programmer-defined expression. • A procedure is lika programmer-defined statement.
C++ also allows you to define your own data structures... • When we cover object-orientation in C++, classes will
let us define new data structures (new object types) as well as the operations on them (their methods)
Next up: arrays and structsLet's first look at two primitive C constructs for inventing data structures:
➡ C arrays: sequences of arbitrary size, all the same type ➡ C structs: ensembles of data items
• We'll pay careful attention to how they are laid out in memory.
• We'll introduce pointers and the address-of operator (&) to do that.