1. Switch Function
a. Executes one or more of several options
i. int i;
printf(“dame un numero positive: “);
1. The switch program will read the input, and try to match it to a
specific case. For example, if the input is 1, the “case 1” is
matched and the statement for that case is executed. If no case is
matched, it will resort to the default case.
2. The “break” function tells the program to terminate the switch
function once a case is matched. Without it, the function will
execute all statements after the one that is matched. For example,
if the input was two, the function would execute both the “case 2”
and the “default” statement. This incidence is called “fall-through.”
b. This function works only on “int” and “char” value types, not double or float.
2. Conditional (? :)
a. Format: expression1 ? expression2 : expression 3
i. if expression 1 is:
1. true, then expression 2 is evaluated.
2. false, then expression 3 is evaluated.
ii. The conditional can also be used in a “printf” function. For example:
1. printf(n%2 ? “odd” : “even”);
2. printf(“You have %d item%s.”, n, (n == 1) ? “ “ :
b. Its precedence is lower than that of regular operators (=, -, *, /, %, …) c. Multiple conditionals will be associated form right to left. For example:
i. c1 ? v1 : c2 ? v2 : v0; becomes c1 ? v1 : (c2 ? v2 :
1. Means that if c1, then v1, otherwise if c2, then v2, otherwise v0.
3. Conditional vs If-Else
a. Often interchangeable, but the conditional is more concise. However,
conditionals only work with integers and characters.
b. “If-Else” function is often more versatile, because it can fit many statements
within one function.
a. With loops, a code segment can be executed repeatedly
b. Each loop execution is an iteration, and will execute as long as the expression is
c. Three types of loops:
i. Format: while(expression) statement;
1. if true, then the statement is executed, and repeats until the
expression becomes false.
ii. int n, i = 1
printf( “Number of lines: “);
while (i <= n)
1. This function will ask for a number of lines (n). If the incremented
integer (i) is less than or equal to “n”, it will print out the current
line number, and then increment the integer (i) by 1. When the
integer becomes greater than “n”, then the function stops
iii. Ex: Prompt user for a positive integer, repeat while user complies. When
input is non-positive, output the average of all previous (positive)