DOC PREVIEW
UW CSE 303 - Lecture Notes

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

10/19/20091David Notkin  Autumn 2009  CSE303 Lecture 9Dictionary.com, "c," in The American Heritage® Abbreviations Dictionary, Third Edition. Source location: Houghton Mifflin Company, 2005. http://dictionary.reference.com/browse/c. Available: http://dictionary.reference.com. Accessed: October 19, 2009.Today• Some C leftovers from Friday• Primitive data types: integers, real numbers, characters, Boolean• Functions• Arrays• Strings (briefly)CSE303 Au09 2Mostly the same as Java• Variables– can be used without being initialized (!)– must be declared at the start of a function or block (changed in C99)• for loops– variable cannot be declared in the loop header• if/else statements, while and do/while loops– there is no boolean type (changed in C99)– any type of value can be used as a test– 0 means false, every other number means true• Parameters / returns– C has certain features for values vs. references ("pointers")Very different from Java• Strings– very clunky to use in C; arrays of characters– are not objects; do not contain methods (external string functions)• I/O to/from console and files– no Scanner; must use input functions such as scanf– console I/O different than file I/O• Errors and exceptions– C has no try/catch and does not represent errors as objects– errors are usually returned as integer error codes from functions– crashes are mostly called "segmentation faults" and are not of much direct utility in figuring out what is wrongAlso very different• Arrays– are just bare contiguous blocks of memory– have no methods and do not know their own length (!)• Objects– C doesn't have them– closest similar feature: struct (a set of fields; no methods)• Memory management– most memory that you consume, you must explicitly free afterward• API and provided libraries– C doesn't have very many, compared to Java– you must write many things yourself (even data structures)printf continued• A placeholder can specify the parameter's width or precision:– %8d an integer, 8 characters wide, right-aligned– %-8d an integer, 8 characters wide, left-aligned– %.4f a real number, 4 digits after decimal– %6.2f a real number, 6 total characters wide, 2 after decimal• Examples:int age = 45;double gpa = 1.2345678;printf("%8d %7.3f\n", age, gpa);printf("%8.2f %.1f %10.5f", gpa, gpa, gpa);10/19/20092scanf• scanf("format string", variables);• uses same syntax for formatted strings, placeholders as printf• Must precede each variable with an & (address-of operator)int x;int y;printf("Type your x and y values: ");scanf("%d %d", &x, &y);function descriptionscanfreads formatted input from consolescanf continued• scanf returns the number of values successfully read: can be examined to see whether the reading was successful• if # of variables listed doesn't match # of format placeholders– too many variables: later ones ignored– too few variables: program crashes!Practice exercise [if you want]• Write a C program that makes change:– prompts the user for an amount of money– reports the number of pennies, nickels, dimes, quarters, and dollars• ExampleAmount of money? 17.93Pennies : 2Nickels : 1Dimes : 1Quarters: 3Dollars : 17Primitive numeric types– integer types: char (1B), short (2B), int (4B), long (8B)– real numbers:float (4B), double (8B)– modifiers: short, long, signed, unsigned (non-negative)type bytes range of values printfchar10 to 255%cshort int2-32,768 to 32,767%hiunsigned short int20 to 65,535%huint4-2,147,483,648 to 2,147,483,647%d, %iunsigned int40 to 4,294,967,295%ulong long int8-9e18 to 9e18 - 1%llifloat4approx. 10-45to 1038%fdouble8approx. 10-324to 10308%lflong double12A lot!%Lfconst variables• const type name = expression;– declares a variable whose value cannot be changed• Example:const double MAX_GPA = 4.0;...MAX_GPA = 4.5; // grade inflation! (error)– The compiler will issue this warning:warning: assignment of read-only variable 'MAX_GPA'Boolean type#include <stdbool.h>...bool b = false;• C doesn't actually have a Boolean type (anything can be a test)• including stdbool.h gives a pseudo-Boolean type bool (C99)– false is really a macro alias for 0– true is really a macro alias for 110/19/20093Anything wrong hereif (x < y == true) {...}bool b2 = x < 10;CSE303 Au09 13Quintessential C bugint x;printf("Please type your age: ");scanf("%d", &x);if (x = 18) {printf("You can now vote!\n");}Defining a functionreturnType name(type name, ..., type name) {statements;}• Exampleint sumTo(int max) {int sum = 0;int i;for (i = 1; i <= max; i++) {sum += i;}return sum;}Problem: function ordering• You cannot call a function that has not been declared (defined) yetint main(void) {int sum = sumTo(100);printf("The sum is %i\n", sum);return 0;}// sumTo is not declared until hereint sumTo(int max) {...}• Solution : Reverse the order of function definition, or ...Array usage• type name[size] = {value, value, ..., value};– allocates an array and fills it with pre-defined element values– if fewer values are given than the size, the rest are filled with 0• name[index] = expression; // set an elementint primes[6] = {2, 3, 5, 6, 11, 13};primes[3] = 7;int allZeros[1000] = {0}; // 1000 zerosMulti-dimensional arrays• type name[rows][columns];– creates a two-dimensional array of given sizes, full of garbage data• type name[rows][columns] = {{values}, ..., {values}};– allocates a 2D array and fills it with pre-defined element valuesint grid[10][10];int matrix[3][5] = {{10, 5, -3, 17, 82},{ 9, 0, 0, 8, -7},{32, 20, 1, 0, 14}};10/19/20094Exercise• Write a complete C program that outputs the first 16 Fibonacci numbers in reverse order, 8 numbers per line, 6 spaces per number.987 610 377 233 144 89 55 3421 13 8 5 3 2 1 1Arrays as parameters• Arrays do not know their own size; they are just memory chunks – harder than in Javaint sumAll(int a[]);int main(void) {int numbers[5] = {7, 4, 3, 15, 2};int sum = sumAll(numbers);return 0;}int sumAll(int a[]) {int i, sum = 0;for (i = 0; i < ... ???}Solution 1: declare size• Declare a function with the array's exact sizeint sumAll(int a[5]);int main(void) {int numbers[5] = {7, 4, 3, 15, 2};int sum = sumAll(numbers);return 0;}int sumAll(int a[5]) {int i, sum = 0;for (i = 0; i < 5; i++) {sum += i;}return sum;}Solution 2: pass size• Pass the array's size as a


View Full Document

UW CSE 303 - Lecture Notes

Documents in this Course
Profiling

Profiling

11 pages

Profiling

Profiling

22 pages

Profiling

Profiling

11 pages

Testing

Testing

12 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?