Introduction to Outline

#include II. Program 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) . 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 Preprocessor • Instruct compiler to perform some int x; Global Declaration transformation to file before compiling int main () { int y; Local Declaration • Example: #include 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 • 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 (_) • 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 • : 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 “A string” – preprocessor command, Name replaced by “String with newline \n char in it” Value in program “String with a double quote \” in it” – example: #define MAX_NUMBER 100

Constants (cont) Formatted Input/Output

• Memory constants • Input comes from files – declared similar to variables, type and name • Output sent to files – const added before declaration • Other objects treated like files: – Example: const float PI = 3.14159; – keyboard - standard input file (stdin) – Can be used as a variable, but one that cannot – monitor - standard output file (stdout) be changed • Generally send/retrieve characters to/from – Since the value cannot be changed, it must be initialized files

Formatted Output Formatted Output (cont)

• Command: printf - print formatted • Successive printf commands cause output to • Syntax: printf(Format String, Data List); be added to previous output – Format string any legal string • Ex. – Characters sent (in order) to screen printf(“Hi, how “); • Ex.: printf(“Welcome to\nCS 1621!\n”); printf(“is it going\nin 1621?”); causes prints Welcome to Hi, how is it going CS 1621! in 1621? to appear on monitor To the monitor

8 Field Specifications Field Specification Example

• Format string may contain one or more field printf(“%c %d %f\n”,’A’,35,4.5); specifications produces – Syntax: %[Flag][Width][Prec][Size]Code A 35 4.50000 – Codes: (varies on different computers) • c - data printed as character • d - data printed as integer • f - data printed as floating-point value Can have variables in place of literal constants – For each field specification, have one data (value of variable printed) value after format string, separated by commas

Width and Precision Width/Precision Example

• When printing numbers, generally use printf(“%5d%8.3f\n”,753,4.1678); width/precision to determine format produces – Width: how many character spaces to use in 753 4.168 printing the field (minimum, if more needed, values are right justified more used) If not enough characters in width, minimum – Precision: for floating point numbers, how many characters appear after the decimal point, number used width counts decimal point, number of digits use 1 width to indicate minimum number of chars after decimal, remainder before decimal should be used

Left Justification (Flags) Size Indicator

Put - after % to indicate value is left justified • Use hd for small integers printf(“%-5d%-8.3fX\n”,753,4.1678); produces • Use ld for long integers 753 4.168 X • Use Lf for long double For integers, put 0 after % to indicate should • Determines how value is treated pad with 0’s printf(“%05d”,753); produces 00753

9 Printf Notes Formatted Input

• Important to have one value for each field • Command: scanf - scan formatted specification • Syntax: scanf(Format String, Address List); – Format string a string with one or more field – some C versions allow you to give too few specifications values (garbage values are formatted and – Characters read from keyboard, stored in printed) variables • Values converted to proper type • scanf(“%c %d %f”,&cVar,&dVar,&fVar); – printf(“%c”,97); produces the character a on the attempts to read first a single character, then a whole number, then a floating point number screen from the keyboard

Formatted Input (cont) Formatted Input (cont)

• Generally only have field specifications and • More notes spaces in string – can use width in field specifications to indicate – any other character must be matched exactly max number of characters to read for number (user must type that char or chars) – computer will not read input until return typed – space characters indicate white-space is ignored – if not enough input on this line, next line read, – “white-space” - spaces, tabs, newlines (and line after, etc.) – %d and %f generally ignore leading white – inappropriate chars result in run-time errors (x space anyway (looking for numbers) when number expected) – %d and %f read until next non-number char – if end-of-file occurs while variable being read, reached an error occurs

Address Operator Scanf Rules

• & - address operator • Conversion process continues until • Put before a variable (as in &x) – end of file reached – maximum number of characters processed • Tells the computer to store the value read at – non-number char found number processed the location of the variable – an error is detected (inappropriate char) • More on address operators later • Field specification for each variable • Variable address for each field spec. • Any character other than whitespace must be matched exactly

10 Scanf Example Prompting for Input scanf(“%d%c %f”,&x,&c,&y); • Using output statements to inform the user and following typed: what information is needed: -543A printf(“Enter an integer: “); scanf(“%d”,&intToRead); 4.056 56 • Output statement provides a cue to the user: Enter an integer: user types here -543 stored in x, A stored in c, 4.056 stored in y, space and 56 still waiting (for next scanf)

11