200 likes | 210 Views
Learn about switch statements, loops, and control flow in programming. Understand when to use while loops, for loops, and nested loops. Master the basics of programming with real-world examples and explanations. Improve your coding skills today!
E N D
Switch - A cleaner if/else-if • Long strings of if/else if/else if/else is difficult to read • A switch statement is a more compact ways of stating: “Only one of these blocks of statements should be executed. We choose which statement depending on the value of an expression” • default is analogous to the finalelse • Always have a default case! • Syntax: switch( expr ) { case VALUE_1: stmts; break; case VALUE_2: stmts; break; default: stmts; break; } Note: you can only switch on int (or char) data types!
Loops • Loops execute a block of curly-brace-enclosed statements (or a single statement) repeatedly • How do we know when to stop? When a certain condition evaluates to false. • Variables can change value in the body of a loop • “Like functions, loops take code that has been generalized and execute it many times” • Note: Two nested loops are very different from two sequential loops! while( contExpr ) { stmts; updateStmt; } for(initStmt; contExpr; updateStmt ) { stmts; }
Loops: while vs. for • Recommended usages • For-loops are great for: • When you know how many times you want to execute the statements (ie – counting) • Iterating through lists (we’ll see more of this in the future) • Ease of reading (all the code is in one place) • For loops are not-so-great for: • Executing until a condition changes (waiting for a sentinal) • While-loops are great for: • Executing the statements depends on a condition
int userNumber; /*** First type of loop: iterate until a certain condition has been met (ie -- until the user enters 0) ***/ printf("Enter 0 to quit\n"); while( userNumber != 0 ) { printf("Enter a number:”); scanf("%d", &userNumber); } int numTimes = 0; int userNumber; /*** Second type of loop: do a set of statements a number of times. Here, this number is known at compile-time */ printf("This loop prompts you for 10 numbers\n”); while( numTimes < 10 ) { printf("Enter a number:”); scanf("%d", &userNumber); numTimes = numTimes + 1; } Loops: while vs. for
int i, j; i = 1; while(i < 10){ printf(“%d ”, i); i = i + 1; j = -1; while(j > -10){ printf(“%d ”, j); j = j – 1; } printf(“\n”); } printf(“i is %d, j is %d”, i, j); int i, j; i = 1; while(i < 10){ printf(“%d ”, i); i = i + 1; } j = -1; while(j > -10){ printf(“%d ”, j); j = j – 1; } printf(“\n”); printf(“i is %d, j is %d”, i, j); Nested vs Sequential Loops
Control Flow • Loops • Repeatedly executes the same block of statements. Execution resumes at the first statement following the loop. • Switch • (May) jump to and execute a selected block of statements, then exits. Execution resumes at the first statement following the switch. • If/else-if • Check the first ‘if’ and all subsequent ‘if’s (linearly) until a match is found. Executes that selected block of statements, then exits the entire if/else-if group of statements. Execution resumes at the first statement following the if/else-if’s
Control Flow: A Real-World Example Does this sound familiar? warning C4715: not all control paths return a value What’s wrong with this code? int i; if(someCondition) { … i = someFunc(); } else if(anotherCondition) { … i = anotherFunc(); } else if(aThirdCondition) { … i = aThirdFunc(); } /* Very important calculation with i here*/
A recipe is a sequence of instructions which must be executed in order Ever tried baking a cake without breaking the eggs first? A recipe may have a list of ingredients A recipe may have a final product E.g. a recipe for a birthday cake produces a cake (duh!) The recipe tells you what to do - but you don’t actually bake a cake until someone asks you to A function is a series of statements executed in sequential order A function has a list of parameters, which may be void A function has a return value, which may also be void A function defines behavior - but isn’t actually executed until it is called Cooking with Functions
A recipe refers to ingredients in ways that may not match the particular ingredients you actually use. E.g. - a recipe may tell you to mix “flour” and “sugar” together, but that’s not the same as when you physically mix SoftaSilk flour with C&H granulated sugar When one recipe calls for another, the entirety of the other recipe is finished before the first recipe can continue Ever tried frosting a cake before baking the layers? Arguments are the actual data that a function is given. Parameters are names a function uses to refer to the arguments, but they are not one and the same When one function calls another, the entirety of the other function is executed before the caller continues execution Cooking with Functions (cont)
Returning and void • When a function returns, it ceases execution and control returns to its caller • The caller resumes execution at the point where the function was called • A function returns a value to its caller • The type of the returned value is the return type of the function • A function whose return type is void does not return a value • A function which takes a void parameter list is called with no arguments at all
Function Details Functions, like variables, must be either: • Declared before being used (prototyped, then defined after main) OR • “Initialized” at the point of declaration (defined before main)
int calculateDiscriminant(int a, int b, int c); Return type Function name Parameters Function Syntax • A function declaration/prototype consists of: • Return type • Function name • List of parameters (not arguments) in parentheses • Function parameters must specify the name and the type • Functions that take no parameters must have the keyword void in place of the parameter list • A function call is the actual invocation/execution of the function. It consists of : • Function name • List of arguments (not parameters) in parentheses • Must match the function parameters in number, type, and order • Arguments can be any expression of the appropriate type • Arguments passed to a function do not include a type • Functions with void parameters are called with empty parentheses: ()
Function Definition int calculateDiscriminant(int a, int b, int c) { int result; result = b*b - 4*a*c; return result; } Function Calls int discr; int first, second, third; discr = calculateDiscriminant(1, 2, 3); printf(“The answer is %d”, calculateDiscriminant(1, 2, 3)); discr = calculateDiscriminant(first, second*2, third-second); Using and Definining Functions
Local Variables and Scope • Local variables • Variables declared inside a function are local – they may have the same name as other variables in other functions, but changing a local variable does not change variables by the same name in other functions • More cooking analogies: • The “flour” you used when baking a cake is not the same “flour” used to make Play-doh • Parameters && Arguments • The values of arguments are copied or substituted into your functions’ parameters • Again, changes to local variables don’t affect the caller’s arguments (yet)
What’s really happening … • Every function needs memory/storage for each of its variables. Collectively, the memory reserved for allfunctions is called the stack, or call stack. • This storage, located in main memory (“RAM”), is a series of numbered addresses and the associated storage space -- basically an array of memory locations. • Variable names allow you to access data at these locations. By attaching a symbolic name (ie -- variable name) to each location, you eliminate the need to remember each variable’s address. • Together, the data/variables for a particular function call are located in a stack frame, or activation record. int aFunc(int x, int y) { double a, b; char c; /* etc */ return 2*x; } Address c (4112) b (4108) a (4104) Memory location y (4100) Variable Name x (4096)
What’s really happening … (cont) c • Parameters and return values are passed by copy • Generally, variables and parameters in one frame are inaccessible from another • Once the function finished execution, that portion of the stack is reclaimed and the values there are no longer available int aFunc(int x, int y) { double a, b; char c; /* etc */ return 2*x; } int main(void) { char c = ‘h’; int x = 7; x = aFunc(1, 2); x = aFunc(2, 3); return 0; } b aFunc’svariables/stack frame a y x x main’svariables/stack frame c ‘h’
The Call Stack • If main() called a(), which called b() , which called c(), you were told: • main() is “paused” in order to execute a(), which is in turn “paused” for b(). • After each function’s execution, however, control would return to the calling function, and continue executing. But nothing in the caller is changed • This is behavior implemented with a call stack
The Call Stack (cont) c’svariables/stack frame • In the call stack, stack frames or activation records are “pushed” on top of each other • This is why we can have local variables! The names of the variables are unique to that stack frame • The currently active function has its stack frame/activation record on the top of the stack i i b’svariables/stack frame j x a’svariables/stack frame y main’svariables/stack frame ‘h’ c x
The Call Stack (cont) • In the call stack, allocation of stack frames and the variables inside of them is done automatically for you, by the compiler. • The memory for these variables is thus called “automatic” • Memory on the stack is sometimes called “local”, as well • But this is very limiting!! • If memory usage must be known at compile-time, then the size of the stack frame (and therefore arrays) must also be known at compile time! • Solution: allocate memory at runtime • Random trivia: • Really old Macs didn’t used to have dynamic memory. Programmers just allocated a bunch of memory (ie -- really big arrays) on the stack and hoped they didn’t overflow the stack/array
Reminders • Unofficial office hours after section in this room • Official office hours: Mon 3:30-4:20, MGH 450 • Random trivia: • 15 cr. == $1,254 per quarter (in-state tuition) • CSE 142 == $334.40 • Each office hour == $7.60 • If you haven’t visited office hours yet, you’ve wasted $30.40 so far! • Si hoc legere scis nimium eruditionis habes • Hw 2b due this Sunday, Apr 22