Final Exam Final Exam: Thursday Dec 13th, 2001 at 8:30 pm in SS-111, the regular classroom.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
CMSC 104, Version 9/011 The switch Statement Topics Multiple Selection switch Statement char Data Type and getchar( ) EOF constant Reading Section 4.7,
The ‘while’ loop ‘round and ‘round we go.
CMCS 104, Lecture 25 - REVIEW1 Review l Read textbook chapters l Read Lectures l General Programming Tips: ouse Top-Down Design ouse Incremental.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Final Review1 Final Exam l Final Exam: Thursday December 15, 2005 at 8:30 pm in room MP-008, the regular classroom. If you can not make it to the exam.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
UMBC CMSC 104 – Section 01, Fall 2016
Chapter 4 C Program Control Part I
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Functions, Part 2 of 2 Topics Functions That Return a Value
Variables and Arithmetic Operators in JavaScript
C Short Overview Lembit Jürimägi.
CMSC 104, Section 4 Richard Chang
Introduction to C Programming
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
The C “switch” Statement
Arrays, Part 1 of 2 Topics Definition of a Data Structure
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
CMSC 104, Section 4 Richard Chang
The C “switch” Statement
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Variables in C Topics Naming Variables Declaring Variables
Introduction to C Programming
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
The switch Statement Topics Multiple Selection switch Statement
The switch Statement Topics Multiple Selection switch Statement
The while Looping Structure
Introduction to C Topics Compilation Using the gcc Compiler
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Variables in C Topics Naming Variables Declaring Variables
The ‘while’ loop ‘round and ‘round we go.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Assignment Operators Topics Increment and Decrement Operators
UMBC CMSC 104 – Section 01, Fall 2016
Assignment Operators Topics Increment and Decrement Operators
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Variables in C Declaring , Naming, and Using Variables.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
Introduction to C Topics Compilation Using the gcc Compiler
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Variables in C Topics Naming Variables Declaring Variables
The switch Statement Topics Multiple Selection switch Statement
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
The while Looping Structure
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Variables in C Topics Naming Variables Declaring Variables
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to C Programming
Variables in C Topics Naming Variables Declaring Variables
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Assignment Operators Topics Increment and Decrement Operators
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Functions that return a value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

Final Exam Final Exam: Thursday Dec 13th, 2001 at 8:30 pm in SS-111, the regular classroom.

Using Variables You may declare variables in C. The declaration includes the data type you need. Examples of variable declarations: int meatballs ; float area ;

Declaring Variables When we declare a variable: space in memory is set aside to hold that data type That space is associated with the variable name Visualization of the declaration int meatballs ; meatballs FE07

Naming Conventions (continued) Use all uppercase for symbolic constants ( #define ) Example: PI (#define PI 3.14159 ) Function names follow the same rules as variables

Case Sensitive C is case sensitive It matters whether something is upper or lower case Example: area is different than Area which is different than AREA

More Variables Predefined types in C Integers Floating point int, long int, short int Floating point float, double Characters char

Keywords in C auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

Which Are Legal Identifiers ? AREA area_under_the_curve 3D num45 Last-Chance #values x_yt3 pi num$ %done lucky***

Arithmetic Operators Name Operator Example Addition + num1 + num2 Subtraction - initial - spent Multiplication * fathoms * 6 Division / sum / count Modulus % m % n

Modulus % The expression m % n yields the remainder after m is divided by n. Modulus is an integer operation. - Both operands MUST be integers. Examples : 17 % 5 = 2 6 % 3 = 0 9 % 2 = 1 5 % 8 = 5

Integer Division If both operands of a division expression are integers, you get an integer answer. The fractional portion is thrown away. Examples : 17 / 5 = 3 4 / 3 = 1 35 / 9 = 3 Division where one operand is a floating point number will produce a floating point answer. Automatic promotion.

Arithmetic Operators Rules of Operator Precedence Operator(s) Precedence & Associativity ( ) Evaluated first. If nested - innermost first. If on same level - left to right. * / % Evaluated second. If many, they are evaluated left to right + - Evaluated third. If there are several, evaluated left to right. = Evaluated last, right to left.

Relational Operators < less than > greater than < = less than or equal to > = grater than or equal to = = is equal to != is not equal to Relational expressions evaluate to the int value 1 (True) or the int value 0 (False) All of these operators are called binary operators because they take two expressions as operands

True or False Arithmetic expressions also evaluate to true of false. Any expression that has a zero value is false. ( 0 ) is False Any expression that has a non-zero value is true. ( 1 ) is True

Structured Programming All programs can be written in terms of only 3 control structures The sequence structure Unless otherwise directed, the statements are executed in the order in which they are written. The selection structure Used to choose among alternative courses of action The repetitive structure Allows that an action is to be repeated while some condition remains true.

A Selection Structure the if statement if ( condition is “true” ) { statement(s) } if ( value = = 0 ) printf (“The value you entered was zero\n”);

Example of if - else if ( value = = 0 ) { printf (“The value you entered was zero\n”); } else printf (“You didn’t enter a zero\n”);

Example if ( value = = 0 ) { printf (“The value you entered was zero\n”); } else if ( value < 0 ) printf (“%d is negative.\n”, value); else printf (“%d is positive.\n”, value);

Gotcha int a = 2; if (a = 1) { printf (“ a is one \n”); } else if (a == 2) printf (“ a is two \n ”); else printf (“ The vaue of a is %d \n”, a);

Our example while loop children = 10 ; cookies = 1024 ; while ( children > 0 ) { children = children - 1; cookies = cookies / 2 ; }

Using a Sentinel Value We could let the user keep entering the grades and when he’s done enter some special value that signals us that he’s done. This special signal value is called a sentinel value. We have to make sure that the value we choose as the sentinel isn’t a legal grade. (ie. can’t use 0 as the sentinel )

The Priming Read When we use a sentinel value to contol a while loop, we have to get the first value from the user before we encounter the loop so that it will be tested and the loop can be entered. This is known as a priming read. We have to give significant thought to the initialization of variables, the sentinel value and getting into the loop.

Pseudocode for Using a Sentinel to End a while Loop’s Execution Initialize total to 0 Initialize counter to 0 Get the first grade from the user While the grade != the sentinel value Add grade to total Add 1 to counter Get the next grade (could be sentinel) average = total / counter Print the average

The cast operator ( ) We can use a cast operator to create a temporary value of the desired type, to be used in a calculation. Does NOT change the variable’s type or how it is stored. Is only good for the statement it’s in. Often used to avoid integer division. Used anytime we want to temporarily change a type for a calculation.

Using a Sentinel (continued) while (grade != -1) { total = total + grade ; counter = counter + 1 ; printf (“Enter grade, -1 to end : “); scanf (“%d”, &grade); } average = ( float ) total / counter ; printf (“The average was %.2f\n”, average) ;

Increment and Decrement Operators The Increment Operator ++ The Decrement Operator -- Precedence - lower than (), but higher than * / and % Associativity - right to left Increment and decrement operators can only be applied to variables, NOT to constants or expressions

Post-Increment Operator The position of the ++ determines WHEN the value is incremented. If the ++ is after the variable then the incrementing is done last. int amount, count; count = 3; amount = 2 * count++; amount gets the value of 2 * 3 or 6 and then 1 gets added to count So after executing the last line, amount is 6 and count is 4.

Pre-Increment Operator If the ++ is before the variable then the incrementing is done first. int amount, count; count = 3; amount = 2 * ++count; 1 gets added to count first, then amount gets the value of 2 * 4 or 8 So after executing the last line, amount is 8 and count is 4.

Decrement Operator If we want to subtract one from a variable, we can say: count = count - 1; Programs can often contain statements that decrement variables, so to save on typing, C provides these shortcuts : count- - ; OR - - count; They do the same thing. Either of these statements change the value of count by subtracting one from it.

The for loop Repetitive Structure The for loop handles details of the counter-controlled loop automatically The initialization of the the loop control variable, termination conditional test and modification are handled in for loop structure for ( i = 1; i < 11; i++) { initialization modification } test

A for loop that counts from 0 to 10 for (i = 0; i < 11 ; i++) { printf (“%d”, i); } printf (“\n”);

do-while example do { printf (“Enter a positive number: “); scanf (“%d”, &num); if (num < = 0) printf (“ \n That is not positive, try again \n ”); } } while (num <= 0);

for vs while use a for loop when your program “knows” exactly how many times to loop use a while loop when there is a condition that will terminate your loop

Nested for loops How many times is the ‘if’ statement executed? for (i = 1; i < 5; i++) { for (j = 1; j < 3; j+) if (j % 2 = = 0) printf (“O”); } else printf (“X”); printf (“\n”); How many times is the ‘if’ statement executed? What is the output ??

The char data type The char data type holds a single character char ch; The char is held as a one-byte integer in memory. The ASCII code is what is actually stored, so we can use them as characters or integers, depending on our purpose Use scanf (“%c”, &ch); to input 1 char

Character Example #include <stdio.h> main ( ) { char ch; printf (“Enter a character: “); scanf (“%c”, &ch); printf (“The value of %c is %d.\n”, ch, ch); } If the user entered an A the output would be The value of A is 65.

The getchar ( ) function We can also use the getchar() function that is found in the stdio library The getchar ( ) function reads one charcter from stdin and returns that character (value) The value can then be stored in either a char variable or an integer variable

getchar () example #include <stdio.h> main ( ) { char grade; printf (“Enter a letter grade: “); grade = getchar ( ); printf (“\nThe grade you entered was %c.\n”, grade); }

switch example switch (day) { case 0: printf (“Sunday\n”); break; case 1: printf (“Monday\n”); case 2: printf (“Tuesday\n”); case 3: printf (“Wednesday\n”); case 4: printf (“Thursday\n”); case 5: printf (“Friday\n”); case 6: printf (“Saturday\n”); default: printf (“Error -- unexpected value for day\”); }

break The last statement of each ‘case’ in the switch should be (99 % of the time) break; The break causes program control to jump to the right brace of the switch Without the break, the code flows into the next case. This is almost never what you want.

#define EOF getchar( ) is usually used to get characters from a file until the “end of file” is reached The value used to indicate the end of file varies from system to system. It is “system dependent”. But, regardless of the system we’re using, there is a #define in stdio library for EOF

Logical Operators Logical operators are used for combining condition && is AND if ( (x > 5) && (y < 6) ) || is OR if ( (z == 0) || (x > 10) ) ! is NOT if (! (bob >42) )

Example of || if (grade == ‘D’ || grade == ‘F’) { printf (“See you next semester!\n”); }

Operator Precedence & Associativity ( ) left to right/inside-out ++ -- ! + (unary) - (unary) (type) right to left * / % left to right + (addition) - (subtraction) left to right < <= > >= left ot right == != left to right && left to right || left to right = += -= *= /= %= right to left , (comma) right to left

Examining PrintMessage #include <stdio.h> void PrintMessage (void); function Prototype main ( ) { PrintMessage ( ); function call } void PrintMessage (void) function header printf (“A message for you:\n\n”); function printf (“Have a Nice Day!\n”); body

Another version of PrintMessage void PrintMessage (int counter); main ( ) { int num; printf (“Enter an integer: “); scanf (“%d”, &num); PrintMessage (num); one argument matches the one } of type int formal parameter of type int void PrintMessage (int counter) int i; for (i = 0; i < counter; i++) printf (“Have a nice day\n\n”); }

Using AverageTwo #include <stdio.h> float AverageTwo (int num1, int num2); main ( ) { float average; int num1 = 5, num2 = 8; average = AverageTwo (num1, num2); printf (“The average of %d and %d is %f\n”, num1, num2, average); } float AverageTwo (int num1, int num2) float average; Promoted to float average = (num1 + num2) / 2.0; return average;

Local Variables Functions only “see” their own local variable. This includes main ( ) The variables that are passed to the function are matched with the formal parameters in the order they are passed The parameters are declarations of local variables. The values passed are assigned to those variables Other local variables can be declared within the function

Data Types and Conversion Specifiers Data Type printf scanf conversion conversion float %f %f double %f %lf long double %Lf %Lf int %d %d long int %ld %ld unsigned int %u %u unsigned long int %lu %lu short int %hd %hd char %c %c

Commonly Used Header Files header file Contains function prototypes for <stdio.h> the standard input/output library functions & information used by them <math.h> the math library functions <stdlib.h> the conversion of number to text, text to number, memory allocation, random numbers and other utility functions <time.h> maninpulating time and date <ctype.h> functions that test characters for certain properties and that can convert case others see page 159 of text

Manipulating what rand() returns Since rand() returns unsigned integers in a large range, we often have to manipulate the return value to suit our purposes Suppose we want only random numbers in the range from 0 to 5 num = rand () % 6 How about 1 to 6? num = 1 + rand( ) % 6; How about 5 to 20? num = 5 + rand ( ) % 16;

srand ( ) and rand ( ) The pseudo-random number generator needs an unsigned int as it’s seed Although it produces what appear to be random numbers, if we use the same seed, we get the same sequence of random numbers To get different random numbers each time we run our program, we have to give a different seed each time

Array Declarations int array [5] ; This declaration sets aside a chunk of memory that’s big enough to hold 5 integers. It does not initialize those memory locations to 0 or any other value. Initializing an array may be done with an array initializer, as in : int array [5] = { 5, 2, 6, 9, 3 } ; array 5 2 6 9 3 0 1 2 3 4

Indexing Array Elements Values of individual elements can be found by indexing into the array. In our example, array [0] is equal to 5 and array [3] is equal to 9. The integer in square brackets is called the subscript. The subscript could also be an expression that evaluates to an integer. In our example, array is the name of the array.

Filling Arrays Since many arrays are quite large, using an array initializer is impractical. Large arrays are often filled using a for loop. for ( i = 0; i < 100; i++) { rolls [ i ] = 0 ; } would set every element of the 100 element array, rolls, to 0.

Using #define for array sizes #define SSIZE 39 #define GSIZE 5 main ( ) { int score [SSIZE] , gradeCounter [GSIZE] ; } We often use the #define to give the sizes of arrays.

Arrays and Pointers The array name alone (without [ ] ) is just a variable that contains the starting address of the block of memory where the array is held. A pointer is just a variable that holds an address. So the array name alone is a pointer to the array. Pointers have types. If an array is an array of ints, then the name of that array has the type pointer to int or int pointer.

Passing Arrays to Functions The function prototype : void FillArray ( int array[ ], int numElems); The function definition header: void FillArray ( int array[ ], int numElems) The function call: FillArray ( array, SIZE); Notice that we are passing only the name of the array (an address) and that we aren’t returning anything (the function is void)

Passing an Array to a Function Example #include <stdio.h> #define SIZE 4 void FillArray (int array[ ], int numElems) ; main ( ) { int array [SIZE]; FillArray ( array, SIZE); /* Print the elements of the array */ for ( i = 0; i < SIZE; i++) printf (array[%d] = %d\n”, i, array[ i ] ); } /******************************************* FillArray is a function that will fill each element of any integer array passed to it with a value that is the same as that element’s subscript. *******************************************/ void FillArray (int array[ ], int numElems) { int i; for ( i = 0; i < numElems; i++) array [i] = i; } array[0] = 0 array[1] = 1 array[2] = 2 array[3] = 3 output

Passing Arrays to Functions If an individual element of an array such as temper[3] is passed to a function, it is passed by value not address. So the array is not modified. Not like when &temper[0] or temper is passed. Example on page 230 of text.

Multiple Subscripted Arrays A common use of multiple subscripted arrays is to represent tables of values consisting of information arranged in rows + columns. For example: a [ 2 ] [ 3 ] row column

Multiple Subscripted Arrays void printArray ( int a [ ] [ 3 ] , int SIZE_R , int SIZE_C ) { …… ….. } When we receive a single-subscripted array as an argument to a function, the array brackets are empty in the functions parameter list. The first subscript of a multiple-subscripted array is not required either, but all subsequent subscripts are required