
Introduction to C Outline #include <stdio.h> II. Program Basics A. Program skeleton preprocessor directives int main () global declarations { functions local declarations printf(“Welcome to CS 1621!\n”); statements } B. Comments and Documentation C. Names (identifiers) reserved words Outline (cont) Outline (cont) II. Program Basics (cont) II. Program Basics (cont) D. Variable declarations F. Formatted input/output 1. Memory allocation 1. Files 2. Printf (monitor output) 2. Atomic types a. format strings void, int, float, char field specifications E. Constants b. data list 1. literal 3. Scanf (keyboard input) a. format strings 2. defined b. address list 3. memory 4. Prompting for Input History of C C Program Structure 1960: ALGOL (ALGOrithmic Language) Preprocessor Directives • Program defined by: – global declarations 1967: BCPL (Basic Combined Programming Global Declarations – function definitions Language) Function Definitions • May contain preprocessor 1970: B programming language (typeless) int main () { directives 1972: C: BCPL plus B with types Local Declarations • Always has one function 1978: Kernighan + Ritchie standard for C Statements named main, may contain others 1989: ANSI standard for C } 1 Parts of a Program Preprocessor Directives • Begin with # #include <stdio.h> Preprocessor Directive • Instruct compiler to perform some int x; Global Declaration transformation to file before compiling int main () { int y; Local Declaration • Example: #include <stdio.h> Function printf("Enter x and y: "); – add the header file stdio.h to this file scanf(&x,&y); Statements – .h for header file printf("Sum is %d\n",x+y); } – stdio.h defines useful input/output functions Declarations Functions • Global • Consists of header and body – visible throughout program – header: int main () – describes data used throughout program – body: contained between { and } • Local • starts with location declarations – visible within function • followed by series of statements – describes data used only in function • More than one function may be defined • Functions are called (invoked) - more later Main Function Comments • Every program has one function main • Text between /* and */ • Header for main: int main () • Used to “document” the code for the human • Program is the sequence of statements reader between the { } following main • Ignored by compiler (not part of program) • Statements are executed one at a time from • Have to be careful the one immediately following to main to – comments may cover multiple lines the one before the } – ends as soon as */ encountered (so no internal comments - /* An /* internal */ comment */) 2 Comment Example Documentation #include <stdio.h> • Global - start of program, outlines overall /* This comment covers solution, may include structure chart * multiple lines • Module - when using separate files, * in the program. indication of what each file solves */ • Function - inputs, return values, and logic int main () /* The main header */ { used in defining function /* No local declarations */ • Add documentation for key (tough to understand) comments printf(“Too many comments\n”); • Names of variables - should be chosen to be } /* end of main */ meaningful, make program readable Syntax of C Identifier • Rules that define C language • Names used for objects in C – Specify which tokens are valid • Rules for identifiers in C: – Also indicate the expected order of tokens – first char alphabetic [a-z,A-Z] or underscore (_) • Some types of tokens: – has only alphabetic, digit, underscore chars – reserved words: include printf int ... – first 31 characters are significant – identifiers: x y ... – cannot duplicate a reserved word – literal constants: 5 ‘a’ 5.0 ... – case (upper/lower) matters – punctuation: { } ; < > # /* */ Reserved Words Valid/Invalid Identifiers • Identifiers that already have meaning in C Valid Invalid sum 7of9 • Examples: c4_5 x-name – include, main, printf, scanf, if, else, … A_NUMBER name with spaces – more as we cover C language longnamewithmanychars 1234a TRUE int _split_name AXYZ& 3 Program Execution Variables • Global declarations set up • Named memory location • Function main executed • Variables declared in global or local – local declarations set up declaration sections – each statement in statement section executed • Syntax: Type Name; • executed in order (first to last) • Examples: • changes made by one statement affect later statements int sum; float avg; char dummy; Variable Type Variable Name • Indicates how much memory to set aside for • Legal identifier the variable • Not a reserved word • Also determines how that space will be • Must be unique: interpreted – not used before • Basic types: char, int, float – variable names in functions (local declarations) – specify amount of space (bytes) to set aside considered to be qualified by function name – what can be stored in that space – variable x in function main is different from x – what operations can be performed on those vars in function f1 Multiple Variable Declarations Variable Initialization • Can create multiple variables of the same • Giving a variable an initial value type in one statement: • Variables not necessarily initialized when int x, y, z; declared (value is unpredictable - garbage) is a shorthand for • Can initialize in declaration: int x; • Syntax: Type Name = Value; int y; • Example: int z; int x = 0; - stylistically, the latter is often preferable 4 Initialization Values Multiple Declaration Initialization • Literal constant (token representing a value, • Can provide one value for variables like 5 representing the integer 5) initialized in one statement: • An expression (operation that calculates a int x, y, z = 0; value) • Each variable declared and then initialized • Function call with the value • The value, however specified, must be of the correct type Type Standard Types • Set of possible values • Atomic types (cannot be broken down) – defines size, how values stored, interpreted – void • Operations that can be performed on those – char possible values – int • Data types are associated with objects in C – float, double (variables, functions, etc.) • Derived types – composed of other types Literal Constants Void Type • Sequences of characters (tokens) that • Type name: void correspond to values from that type • Possible values: none -35 is the integer -35 • Operations: none 3.14159 is the floating pointer number 3.14159 • Useful as a placeholder ‘A’ is the character A • Can be used to initialize variables 5 Integer Type Integer Types/Values • Type name: Type Bytes Bits Min Val Max Val – int – short int short int 2 16 -32768 32767 – long int int 4 32 -2147483648 2147483647 • Possible values: whole numbers (within given ranges) as in 5, -35, 401 long int 4 32 -2147483648 2147483647 • Operations: arithmetic (addition, subtraction, multiplication, …), and others Why Limited? Two’s Complement • With a fixed number of bits, only a certain Integers: number of possible patterns positive number: 0, number in binary • 16 bits, 65,536 possible patterns 97 in binary 1*64 + 1*32 + 1*1 (1100001) – 32768 negative numbers pad with leading zeroes (0 00000001100001) - 16 bits zero: 0, all zeroes – 1 zero negative number: 1, (inverse of number + 1) – 32767 positive numbers -97 (1, 111111110011110 + 1) • Overflow: attempt to store a value to large 1 111111110011111 in a variable (40000 in short int) Unsigned Integers Integer Literal Constants • Type: unsigned int Syntax: • No negative values 1 or more digits • unsigned int: Optional leading sign (+ or -) – possible values: 0 to 65536 Optional l or L at the end for long • Representation: binary number Optional u or U for unsigned Examples: 5, -35, 401, 4010L, -350L, 2000UL 6 Floating-Point Type Floating-Point Representation • Type names: • float: 4 bytes, 32 bits – float • double: 8 bytes, 64 bits – double • long double: 10 bytes, 80 bits – long double • Representation: • Possible values: floating point numbers, 5.0 – magnitude (some number of bits) plus exponent -3.5, 4.01 (remainder of bits) • Operations: arithmetic (addition, – 3.26 * 10^4 for 32600.0 subtraction, multiplication, …), and others Floating-Point Limitations Floating-Point Literals • Maximum, minimum exponents • Syntax: – Zero or more digits, decimal point, then zero or – maximum possible value (largest positive more digits (at least one digit) magnitude, largest positive exponent) – Whole numbers also treated as float – minimum value (largest negative magnitude, – Optional sign at start largest positive exponent) – Can be followed by e and whole number (to – can have overflow, and underflow represent exponent) – f or F at end for float • Magnitude limited – l or L at end for long double – cannot differentiate between values such as • Examples: 5, .5, 0.5, -1.0, 2.1e+3, 5.1f 1.00000000 and 1.00000001 Character Type Character Literals • Type name: char • Single key stroke between quote char ‘ • Possible values: keys that can be typed at • Examples: ‘A’, ‘a’, ‘b’, ‘1’, ‘@’ the keyboard • Some special chars: • Representation: each character assigned a value (ASCII values), 8 bits – ‘\0’ - null char – A - binary number 65 – ‘\t’ - tab char – a - binary number 97 – ‘\n’ - newline char – b - binary number 98 – ‘\’’ - single quote char – 2 - binary number 50 – ‘\\’ - backslash char 7 String Literals Constants • No string type (more later) • Literal constants - tokens representing • Contained between double quote chars (“) values from type • Examples: • Defined constants “” - null string – syntax: #define Name Value
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages11 Page
-
File Size-