============================================================================ Faculty of Applied Science and Engineering, University of Toronto CSC181: Introduction to Computer Programming, Fall 2000 Tutorial Notes, Week 2 ============================================================================ ----------------- Summary of Topics ----------------- - A basic C program - Introduction to 'if' and 'while' ------- Example ------- The following program reads in 5 integers and returns the maximum of those integers: #include main() { int n = 0; int max = 0; int i = 0; scanf("%d", &max); i = 1; while (i != 5) { int temp = 0; scanf("%d", &temp); if (temp > max) { max = temp; } i++; } printf("maximum: %d", max); } ---------- Sample Run ---------- 5 2 8 3 9 1 maximum: 9 ---------------- 'if' and 'while' ---------------- Some notation: - expression A formula that evaluates to false (zero) or true (non-zero). - statement A single statement or a compound statement, i.e. a group of statements enclosed in braces. An if-statement is a "selection" statement, one that allows for conditional execution of statements. - The most basic form: if (expression) statement 'statement' is executed if 'expression' is true. - 'if' can be used in conjunction with 'else': if (expression) statement1 else statement2 If 'expression' is true, execute 'statement1', otherwise execute 'statement2'. - 'else' can be combined with 'if' to form 'else if': if (expression1) statement1 else if (expression2) statement2 If 'expression' is true, execute 'statement1'. Otherwise, if 'expression2' is true, execute 'statement2'. Refer to King, Section 5.2 for more details. A while-statement is an "iteration" statement, one that allows for repeated execution of statements. - The most basic form: while (expression) statement 'statement' is executed repeatedly as long as 'expression' is true. (If the 'expression' initially evaluates to false, then 'statement' will never be executed.) Refer to King, Section 6.1 for more details. --------- Exercises --------- 1. Write a program that reads in 2 integers x and y and prints all of the integers in between x and y (inclusive), one per line. 2. Write a program that reads in an integer and prints all of its divisors, one per line. (Hint: You will need the modulo operator, '%'; 'x % y' evaluates to the remainder from dividing x by y.) 3. Write a program that reads in 5 integers and prints how many times the number 4 occurs among those integers. 4. Write a program that reads in 5 integers and prints "There is at least one negative integer" if at least one of the integers is negative.