380 likes | 390 Views
Explore program flow concepts like loops and if statements with examples in C#.CS.31. Dive into waterfall metaphor and transform loops effectively. Get ready for Project 2/Homework Questions discussion.
E N D
CS 31 Discussion, Week 3 Faisal Alquaddoomi, faisal@cs.ucla.edu Office Hours: BH 2432, MW 4:30-6:30pm,F 12:30-1:30pm (today)
Agenda • Understanding program flow • the “Waterfall” metaphor • “If” statements review • Loops: While, Do-While, For • How to transform one into another • Project 2/Homework Questions • Time permitting: basic string operations • Even more time permitting: characters
Waterfall Metaphor • Imagine that your program is like a waterfall • water comes in through the top and can only take one path through your program • If statements are like “gates” that allow the water to only take one path and exclude other possible paths • This only applies to alternate paths at the same “level” as the if statement • We’ll demonstrate this with a few examples
A Familiar Example #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; if (true) { cout << "Path A was taken" << endl; } return 0; }
Extension: If-Else #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; if (true) { cout << "Path A was taken" << endl; } else { cout << “Path B was taken” << endl; } return 0; }
Multiple, Separate If-Else Statements int x = 32; if (x > 5) { cout << "Path A was taken" << endl; x = 16; } else { cout << “Path B was taken” << endl; } cout << “In between” << endl; if (x > 30) { cout << “The blue path" << endl; } else { cout << “The red path” << endl; }
Nested If Statements int x = 32; if (x > 10) { cout << "Path A was taken" << endl; x = 12; if (x < 50) { cout<< “Inner true path" << endl; } else { cout<< “Inner false path” << endl; } } else if (x < 1000) { cout << “Path B was taken” << endl; } cout << “At the end” << endl;
Inside a Nested If int x = 32; if (x > 10) { cout << "Path A was taken" << endl; x = 12; if (x < 50) { cout<< “Inner true path" << endl; } else { cout<< “Inner false path” << endl; } } else if (x < 1000) { cout << “Path B was taken” << endl; } cout << “At the end” << endl;
Loops • Think of these as “whirlpools” • Come in three flavors: While, Do-While, and For • They’re actually all equivalent to each other, as we’ll see later • Which one you decide to use is largely a matter of convenience
While Loops • The most basic type of loop • Much like an “If”, has a part that can be true or false (called the predicate) • If the predicate is true, the loop begins • if it’s false, the program skips over the loop • Unlike an If, when the program reaches the bottom of the loop, it jumps back to the top • If the predicate is still true, the loop continues • Otherwise, it skips to the bottom and continues
While Loop Flow, Part 1 int x = 1; while (x < 10) { cout << “x is: “ << x << endl; if (x > 8) { cout << “Almost there…”; } x = x + 1; } cout << “Done! x is ” << x << endl;
While Loop Flow, Part 2 int x = 1; while (x < 10) { cout << “x is: “ << x << endl; if (x > 8) { cout << “Almost there…”; } x = x + 1; } cout << “Done! x is ” << x << endl;
Do-While Loops • Exactly the same as a While loop, with one major difference: the predicate is checked when the loop ends, not when it starts • Once the program reaches the bottom of the loop, it checks the predicate • If it’s true, the loop jumps back to the top, just like a while, and starts running again • If it’s false, the loop ends and the program starts up below the do-while loop • Because the predicate is checked at the end, do-while loops always run at least once
Do-While Loop Flow, Part 1 int x = 1; do { cout << “x is: “ << x << endl; if (x > 8) { cout << “Almost there…”; } x = x + 1; } while (x < 10); // <- note the semicolon cout << “Done! x is ” << x << endl;
Do-While Loop Flow, Part 2 int x = 1; do { cout << “x is: “ << x << endl; if (x > 8) { cout << “Almost there…”; } x = x + 1; } while (x < 10);// <- note the semicolon cout << “Done! x is ” << x << endl;
While Loops Revisited int x = 1; while (x < 10) { cout << “x is: “ << x << endl; x = x + 1; } • To review, a while loop can have up to three parts: • The predicate (required) • A control variable (optional) • A change to the control variable(also optional)
For Loops, Part 1 • A For loop is just shorthand for a while loop with a control variable that gets changed int x = 1; while (x < 10) { cout << “x is: “ << x << endl; x = x + 1; }
For Loops, Part 2 • A For loop is just shorthand for a while loop with a control variable that gets changed • All the parts are still there, just written in a shorter form // int x = 1 for (int x = 1; x < 10; x = x + 1) { cout << “x is: “ << x << endl; // x = x + 1 }
String Basics • A string isa type of variable that holds a series of letters (e.g. a paragraph, a sentence, a word...) • Even just a single letter, but there’s a special type for just one letter, too • Seen in the project as clientName, where the client’s name is stored • Declaring and assigning to a string: string myName = “Faisal”;
Basic String Operations • Printing:cout << “My name: “ << myName << endl; • Reading:getline(cin, myName); • Getting the Number of Letters:string myFullName = “Faisal Alquaddoomi”; if (myFullName.size() >= 10)cout << “Your name is crazy long!”; • Note that this includes spaces, punctuation, etc.
More String Operations • Getting a Particular Letter by Position:string myLetters = “abcdefg”; for (inti = 0; i < myLetters.size(); i++)cout << myLetters[i] << “...”; • When using myLetters[i], what you get back is a type called a char • short for “character”, i.e. an individual letter • There are a few elementary operations for chars, but first…
What’s a Char, Exactly? • A char (again, short for “character”) is actually a small number • Computers “encode” letters as numbers, because at a hardware level computers only understand numbers • An “encoding” is just a table where every letter (in English, 26 of them) has a corresponding number • Technically, there’s an entry for each uppercase letter, each lowercase letter, punctuation, spaces…anything that can go in a string needs to have an entry in the table • The most widely accepted character encoding is ASCII, the American Standard Code for Information Interchange • To convert to ASCII, we take our letter (say, ‘A’), and look up the value for it in the ASCII table…
Looking up ‘A’ in ASCII • So, if we look up ‘A’, we find it has value 65 • Similarly, lowercase ‘a’ has the value 97 • There are a whole bunch of letters in the ASCII table that are “special” – you don’t need to worry about that • In code,char someChar = ‘a’;is exactly the same as sayingchar someChar = 97;
Some Char Operations • In all the following examples, ‘c’ is a char • isdigit(c): true if it’s a digit (e.g. 0 to 9), false otherwise • isalpha(c): true if it’s a letter, case-independent • islower(c): true if it’s lowercase (e.g. ato z) • isupper(c): true if it’s uppercase (e.g. A to Z) • tolower(c): returns a lowercase version of c if c is a letter, returns it verbatim otherwise • toupper(c): returns an uppercase version of c if c is a letter, returns it verbatim otherwise • You can make any of these yourself • e.g. (c >= ‘a’ && c <= ‘z’) is the same thing as islower(c)
Questions?Office Hours are immediately, downstairs in room 2432(from 12:30-1:30pm, but I’m usually there slightly longer)
Functions by Example #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; return 0; } • The code below should look very familiar by now • Let’s try to figure out what all the “magic” means…
Functions by Example, Part 2 #include <iostream> using namespace std; intmain() { cout << "Hello, world!" << endl; return 0; } • All functions have three parts, • A name • A return type • A list of parameters (main has no parameters)
Functions by Example, Part 2 #include <iostream> using namespace std; intmain(){ cout << "Hello, world!" << endl; return 0; } • The highlighted part below is the body of the function • When the function is “called”, the body starts running from the top
Multiple Functions #include <iostream> using namespace std; int sum(int x, int y) { int result = x + y; return result; } int main() { intfirstNum, secondNum; cout << “Enter two numbers: “ << endl; cin >> firstNum >> secondNum; cout << “Sum of the two is: “ << endl; cout << sum(firstNum, secondNum); return 0; }
Multiple Functions #include <iostream> using namespace std; intsum(int x, int y) { int result = x + y; return result; } int main() { intfirstNum, secondNum; cout << “Enter two numbers: “ << endl; cin >> firstNum >> secondNum; cout << “Sum of the two is: “ << endl; int answer = sum(firstNum, secondNum); cout << “Answer: “ << answer << endl; return 0; } Call from main() to sum()…
Multiple Functions #include <iostream> using namespace std; int sum(int x, int y) { int result = x + y; return result; } int main() { intfirstNum, secondNum; cout << “Enter two numbers: “ << endl; cin >> firstNum >> secondNum; cout << “Sum of the two is: “ << endl; intanswer= sum(firstNum, secondNum); cout << “Answer: “ << answer << endl; return 0; } …returns from sum() back to where we left off in main(), with a value
Functions Review • main() is a special function that gets called when your program starts • Besides that it’s a normal function • A function has a name, a return type, a parameter list, and a body • Like variables, functions must be declared before they’re used • We’ll go over techniques on how to fix that for program clarity later on
Functions Review, Part 2 • You call a function via myFunctionName(argument1, argument2) • myFunctionName is the name of your function • There must be one argument specified for each parameterthat the function takes • A function *must* return a value (with some exceptions) • What’s returned must be the same type as the function
The Exception: Void Functions #include <iostream> using namespace std; void sum(int x, int y) { int result = x + y; cout << “The sum is: ” << result; } int main() { intfirstNum, secondNum; cout << “Enter two numbers: “ << endl; cin >> firstNum >> secondNum; cout << “Sum of the two is: “ << endl; int answer = sum(firstNum, secondNum); cout << “Answer: “ << answer << endl; return 0; } Is there anything wrong with this picture?
Void Functions, Part 2 #include <iostream> using namespace std; void sum(int x, int y) { int result = x + y; cout << “The sum is: “ << result; } int main() { intfirstNum, secondNum; cout << “Enter two numbers: “ << endl; cin >> firstNum >> secondNum; cout << “Sum of the two is: “ << endl; int answer = sum(firstNum, secondNum); cout << “Answer: “ << answer << endl; return 0; } Yes; a void function has no type, so it can’t be used in expressions
Void Function Review • Void functions don’t pass back values, but they do have “side effects” • Printing things to the screen, for instance • Since void functions have no type, they can’t be used in expressions (including assignments) • They can, however, contain return statements • The return statements look like this:return; // note the lack of a value