CSCE150A CSCE150A Computer Science & Engineering 150A Language Elements Introduction Problem Solving Using Computers Introduction Language Language Variable Declarations and Data Types Elements Elements

General Form Lecture 02 - Introduction To C General Form Executable Statements Operators & Operators & General Form of a C Program Expressions Expressions Formatting Formatting Arithmetic Expressions I/O Stephen Scott I/O Formatting Numbers in Program Output Running (Adapted from Christopher M. Bourke) Running Programs Programs Interactive Mode, Batch Mode, and Data Files Common Common Pitfalls Pitfalls Common Programming Errors

Fall 2009 1 / 77 2 / 77

[email protected]

Overview of C Programming C Language Elements

CSCE150A CSCE150A

Introduction Introduction Preprocessor Directives Language Language Syntax Displays for Preprocessor Directives Elements This chapter introduces C – a high-level programming language developed Elements Preprocessor General Form in 1972 by Dennis Ritchie at AT&T Bell Laboratories. Comments “int main()” Function Main Function Operators & Reserved Words Expressions Reserved Words This chapter describes the elements of a C program and the types of data Program Style Executable Formatting that can be processed by C. It also describes C statements for performing Statements Standard Identifiers I/O Input/Output Running computations, for entering data, and for displaying results. General Form User-Defined Identifiers Programs Operators & Uppercase and Lowercase Letters Common Expressions Pitfalls Formatting Program Style I/O

Running Programs

Common 3 / 77 4 / 77 Pitfalls

Preprocessor Directives #include and #define

CSCE150A CSCE150A

Introduction Introduction #include gives the program access to a The C preprocessor modifies the text of the C program before it is Language Language #include Elements passed to the compiler. Elements Example: (standard input and output) has Preprocessor Preprocessor Comments Comments definitions for input and output, such as printf and scanf. Main Function Preprocessor directives are C program lines beginning with a # that Main Function Reserved Words Reserved Words #define NAME value associates a constant Program Style provide instructions to the C preprocessor. Program Style Executable Executable Statements Statements Example: Input/Output Preprocessor directives begins with a #, e.g. #include and #define. Input/Output General Form Predefined libraries are useful functions and symbols that are General Form 1 #defineKMS_PER_MILE 1.609 Operators & Operators & 2 #definePI 3.14159 Expressions predefined by the C language (standard libraries). Expressions

Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 5 / 77 6 / 77 Pitfalls Pitfalls Comments Function main

CSCE150A CSCE150A

The point at which a C program begins execution is the main Introduction Comments provide supplementary information making it easier for us to Introduction Language Language function: Elements understand the program, but comments are ignored by the C preprocessor Elements Preprocessor Preprocessor 1 int main(void) Comments and compiler. Comments Main Function Main Function Reserved Words Reserved Words Program Style Program Style Executable /**/ - anything between them with be considered a comment, even Executable Every C program must have a main function. Statements Statements Input/Output if they span multiple lines. Input/Output The main function (and every other function) body has two parts: General Form // - anything after this and before the end of the line is considered a General Form Declarations - tell the compiler what memory cells are needed in the Operators & Operators & function Expressions comment. Expressions Executable statements - (derived from the algorithm) are translated Formatting Formatting I/O I/O into machine language and later executed

Running Running Programs Programs

Common Common 7 / 77 8 / 77 Pitfalls Pitfalls

Function main Reserved Words

CSCE150A CSCE150A

Introduction Introduction A word that has special meaning in C. E.g.: Language Language int - Indicates that the main function (or any other function) returns Elements All C functions contain punctuation and special symbols Elements Preprocessor Preprocessor an integer value, or that a memory cell will store an integer value Comments Punctuation - commas separate items in a list, semicolons appear at Comments double Main Function Main Function - Indicates that a function returns a real number or that a Reserved Words the end of each statement Reserved Words memory cell will store a real number Program Style Program Style Executable Special symbols: *, =, {, }, etc. Executable Statements Statements Always lower case Input/Output Curly braces mark the beginning and end of the body of every Input/Output General Form function, including main General Form Can not be used for other purposes Operators & Operators & Appendix E has a full listing of reserved words (ex: Expressions Expressions

Formatting Formatting double, int, if, else, void, return etc.) I/O I/O

Running Running Programs Programs

Common Common 9 / 77 10 / 77 Pitfalls Pitfalls

Standard Identifiers User-Defined Identifiers

CSCE150A CSCE150A

We choose our own identifiers to name memory cells that will hold data Introduction Introduction and program results and to name operations (functions) that we define Language Standard identifiers have a special meaning in C (assigned by Language Elements Elements (more on this in Chapter 3) Preprocessor standard libraries). Preprocessor Comments Comments Main Function Standard identifiers can be redefined and used by the programmer for Main Function [a-zA-Z] [0-9] Reserved Words Reserved Words An identifier must consist only of letters , digits , Program Style other purposes Program Style Executable Executable and . Statements Not recommended If you redefine a standard identifier; C will no Statements Input/Output Input/Output longer be able to use it for its original purpose. An identifier cannot begin with a digit (and shouldn’t begin with an General Form General Form ). Operators & Examples: input/output functions printf, scanf Operators & Expressions Expressions A C reserved word cannot be used as an identifier. Formatting Formatting I/O I/O An identifier defined in a C should not be redefined.

Running Running Programs Programs

Common Common 11 / 77 12 / 77 Pitfalls Pitfalls Preprocessor Directives Reserved Words Variables Special Symbols Punctuation

User-Defined Identifiers Program Style

CSCE150A CSCE150A Examples: letter_1, Inches, KMS_PER_MILE Introduction Some compilers will only see the first 31 characters Introduction Language Language Elements Uppercase and lowercase are different Elements Preprocessor Preprocessor A program that “looks good” is easier to read and understand than one Comments (Variable, variable, VARIABLE are all different) Comments Main Function Main Function that is sloppy (i.e. good spacing, well-named identifiers). Reserved Words Choosing identifer names: Reserved Words Program Style Program Style Executable Executable In industry, programmers spend considerably more time on program Statements Choose names that mean something Statements Input/Output Should be easy to read and understand Input/Output maintenance than they do on its original design or coding. General Form Shorten only if possible General Form Operators & Operators & Expressions Don’t use Big, big, and BIG as they are easy to confuse Expressions Formatting Formatting I/O Identifiers using all-caps are usually used for preprocessor-defined I/O

Running constants (#define) Running Programs Programs

Common Common 13 / 77 14 / 77 Pitfalls Pitfalls

Style Tips Style Tips Rigorous Comments Naming Conventions

CSCE150A CSCE150A

Introduction Introduction The number of comments in your program doesn’t affect its speed or Language Language Give your variables meaningful names (identifiers) Elements size. Elements Preprocessor Preprocessor Comments Comments x,y may be good if you’re dealing with coordinates, but bad in Main Function Always best to include as much documentation as possible in the Main Function Reserved Words Reserved Words general. Program Style form of comments. Program Style Executable Executable myVariable, aVariable, anInteger, etc are bad: they do not Statements Begin each program or function with a full explanation of its inputs, Statements Input/Output Input/Output describe the purpose of the variable. General Form outputs, and how it works. General Form tempInt,PI, numberOfStudents are good because they do. Operators & Operators & Expressions Include comments as necessary throughout the program Expressions

Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 15 / 77 16 / 77 Pitfalls Pitfalls

Style Tips CamelCaseNotation Anatomy of a Program

CSCE150A CSCE150A

1 /* Old School C convention: separate compound words with underscores 2 * Converts distances from miles to kilometers. Comments Introduction Introduction 3 */ 4 #include /* printf, scanf definitions*/ Language number_of_students, interest_rate, max_value, etc. Language 5 #define KMS_PER_MILE 1.609 Elements Elements 6 7 int ma in(vo id) Preprocessor Underscore (shift-hyphen) is inconvenient Preprocessor Comments Comments 8 { Main Function Main Function 9 double miles , kilometers ; Reserved Words Solution: camelCaseNotation - connect compound words with Reserved Words 10 printf("How many miles do you have?"); Program Style Program Style 11 Executable upper-case letters. Executable 12 scanf("%lf",&miles); Statements Statements 13 Input/Output Example: numberOfStudents, interestRate, maxValue, etc. Input/Output 14 kilometers= miles* 1.609; General Form General Form 15 printf("You have%f kilometers\n", kilometers); Much easier to shift-capitalize 16 Operators & Operators & 17 return 0; Expressions Much more readable Expressions 18 } Formatting Formatting I/O Ubiquitous outside of programming: MasterCard, PetsMart, etc. I/O Running Running Programs Programs

Common Common 17 / 77 18 / 77 Pitfalls Pitfalls Comments Comments Preprocessor Directives Reserved Words Variables Variables Special Symbols Special Symbols Punctuation Punctuation

Comments Comments Preprocessor Directives Preprocessor Directives Reserved Words Reserved Words Variables Special Symbols Punctuation Punctuation

Comments Preprocessor Directives Reserved Words Variables Special Symbols

Anatomy of a Program Anatomy of a Program

CSCE150A CSCE150A

1 /* 1 /* 2 * Converts distances from miles to kilometers. 2 * Converts distances from miles to kilometers. Introduction 3 */ Introduction 3 */ 4 #include /* printf, scanf definitions*/ Preprocessor Directives 4 #include /* printf, scanf definitions*/ Language 5 #define KMS_PER_MILE 1.609 Language 5 #define KMS_PER_MILE 1.609 Elements 6 Elements 6 Reserved Words Preprocessor 7 int ma in(vo id) Preprocessor 7 int ma in(vo id) Comments 8 { Comments 8 { Main Function 9 double miles , kilometers ; Main Function 9 double miles , kilometers ; Reserved Words 10 printf("How many miles do you have?"); Reserved Words 10 printf("How many miles do you have?"); Program Style 11 Program Style 11 Executable 12 scanf("%lf",&miles); Executable 12 scanf("%lf",&miles); Statements 13 Statements 13 Input/Output 14 kilometers= miles* 1.609; Input/Output 14 kilometers= miles* 1.609; General Form 15 printf("You have%f kilometers\n", kilometers); General Form 15 printf("You have%f kilometers\n", kilometers); 16 16 Operators & 17 return 0; Operators & 17 return 0; Expressions 18 } Expressions 18 }

Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 18 / 77 18 / 77 Pitfalls Pitfalls

Anatomy of a Program Anatomy of a Program

CSCE150A CSCE150A

1 /* 1 /* 2 * Converts distances from miles to kilometers. 2 * Converts distances from miles to kilometers. Introduction 3 */ Introduction 3 */ 4 #include /* printf, scanf definitions*/ 4 #include /* printf, scanf definitions*/ Language 5 #define KMS_PER_MILE 1.609 Language 5 #define KMS_PER_MILE 1.609 Elements 6 Elements 6 Preprocessor 7 int ma in(vo id) Preprocessor 7 int ma in(vo id) { { Comments 8 Variables Comments 8 Main Function 9 double miles , kilometers ; Main Function 9 double miles , kilometers ; Reserved Words 10 printf("How many miles do you have?"); Reserved Words 10 printf("How many miles do you have?"); Special Symbols Program Style 11 Program Style 11 Executable 12 scanf("%lf",&miles); Executable 12 scanf("%lf",&miles); Statements 13 Statements 13 Input/Output 14 kilometers= miles* 1.609; Input/Output 14 kilometers= miles* 1.609; General Form 15 printf("You have%f kilometers\n", kilometers); General Form 15 printf("You have%f kilometers\n", kilometers); 16 16 Operators & 17 return 0; Operators & 17 return 0; Expressions 18 } Expressions 18 }

Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 18 / 77 18 / 77 Pitfalls Pitfalls

Anatomy of a Program Anatomy of a Program

CSCE150A CSCE150A

1 /* /* 2 * Converts distances from miles to kilometers. * Converts distances from miles to kilometers. */ standard header file comment Introduction 3 */ Introduction #include /* printf, scanf definitions */ 4 #include /* printf, scanf definitions*/ prepocessor #define KMS_PER_MILE 1.609 /* conversion constant */ Language 5 #define KMS_PER_MILE 1.609 Language constant int Elements 6 Elements reserved word 7 int ma in(vo id) main(void) Preprocessor Preprocessor { 8 { Comments Comments double miles, /* distance in miles */ Main Function 9 double miles , kilometers ; Main Function variable kms; /* equivalent distance in kilometers */ Reserved Words 10 printf("How many miles do you have?"); Reserved Words Program Style 11 Program Style /* Get the distance in miles */ comment Executable 12 scanf("%lf",&miles); Executable printf("Enter the distance in miles> "); Statements Punctuation Statements standard 13 identifier scanf("%lf", &miles); Input/Output 14 kilometers= miles* 1.609; Input/Output /* Conver the distance to kilometers. */ General Form 15 printf("You have%f kilometers\n", kilometers); General Form 16 kms = KMS_PER_MILE * miles; special Operators & 17 return 0; Operators & 18 } /* Display the distance in kilometers. */ Expressions Expressions printf("That equals %f kilometers.\n", kms); Formatting Formatting return(0); reserved punctuation I/O I/O word } Running Running special symbol Programs Programs

Common Common 18 / 77 19 / 77 Pitfalls Pitfalls Variable Declarations and Data Types Variables Declarations

CSCE150A CSCE150A

Introduction Introduction Variables - a name associated with memory cells Language Language (miles, kilometers) that store a program’s input data. The value Elements Elements Preprocessor Preprocessor of this memory cell can be changed. Comments Comments Main Function Variable Declaration Main Function Variable declarations - statements that communicate to the compiler Reserved Words Reserved Words Program Style Data Types Program Style that names of variables in the program and the kind of information Executable Executable Statements Statements stored in each variable. Input/Output Input/Output Example: double miles, kms; General Form General Form Each declaration begins with a unique identifier to indicate the type of Operators & Operators & Expressions Expressions data Formatting Formatting Every variable used must be declared before it can be used I/O I/O

Running Running Programs Programs

Common Common 20 / 77 21 / 77 Pitfalls Pitfalls

Data Types Data Types Integers

CSCE150A CSCE150A

Introduction Introduction Integers are whole numbers, negative and positive Data Types: a set of values and a set of operations that can be used Language Language Elements on those values. Elements Declaration: int Preprocessor Preprocessor Comments In other words, it is a classification of a particular type of Comments The ANSI C standard requires integers be at least 16 bits: in the Main Function Main Function Reserved Words information. Reserved Words range 32767 to 32767 Program Style Program Style − Executable Integers int Executable Statements Statements One bit for the sign and 15 for the number Input/Output Doubles double Input/Output General Form Characters char General Form Modern standard that int types are 32 bits. Range: 31 31 Operators & Operators & 2 = 2, 147, 483, 648 to 2, 147, 483, 648 = 2 Expressions The idea is to give semantic meaning to 0s and 1s. Expressions − − Newer systems are 64-bit. What range does this give? Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 22 / 77 23 / 77 Pitfalls Pitfalls

Data Types Data Types Doubles Characters

CSCE150A CSCE150A

Introduction Introduction Language Doubles are decimal numbers, negative and positive Language char: an individual character values with single quotes around it. Elements Elements Preprocessor Example: 0.5, 3.14159265, 5, 8.33 Preprocessor Comments Comments Example: a letter, a digit, or a special symbol Main Function Main Function Reserved Words Declaration: double Reserved Words Example: ’a’,’B’,’*’,’!’ Program Style Program Style Executable Executable Statements On most systems, doubles are 8 bytes = 64 bits Statements You can treat each character as a number: see Appendix A Input/Output Precision is finite: cannot fully represent irrationals π, 1 , etc. Input/Output General Form 3 General Form The ASCII standard assigns number (0 thru 255) to each character:

Operators & An approximation only, but 15–16 digits of precision Operators & A is 65, many are non-printable control characters Expressions Expressions

Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 24 / 77 25 / 77 Pitfalls Pitfalls Executable Statements Assignment Statements

CSCE150A CSCE150A

Introduction Introduction Assignment statements - stores a value or a computational result in a Language Language Elements Assignment Statements Elements variable Preprocessor Preprocessor Comments Input/Output Operations and Functions Comments Used to perform most arithmetic operations in a program. Main Function Main Function Reserved Words Reserved Words Form: variable= expression; Program Style printf Function Program Style Executable Executable kms= KMS_PER_MILE* miles; Statements Statements Input/Output scanf Function Input/Output General Form return Statement General Form The assignment statement above assigns a value to the variable kms. The Operators & Operators & Expressions Expressions value assigned is the result of the multiplication of the constant macro Formatting Formatting KMS_PER_MILE (1.609) by the variable miles I/O I/O

Running Running Programs Programs

Common Common 26 / 77 27 / 77 Pitfalls Pitfalls

Memory of Program Assignments Continued

CSCE150A CSCE150A Memory In C, the symbol = is the assignment operator. Introduction miles miles Introduction Read as “becomes”, “gets”, or “takes the value of” rather than Language ? 10.00 Language Elements Elements “equals” Preprocessor Preprocessor Comments type double Comments In C, == tests equality. Main Function kms kms Main Function Reserved Words Reserved Words Program Style Program Style Examples: Executable ? 16.09 Executable Statements Statements Input/Output Input/Output 1 inta,b,c; General Form KMS_PER_MILE KMS_PER_MILE General Form 2 b = 10; Operators & 1.609 1.609 Operators & Expressions constant Expressions 3 a = 15; Formatting Formatting I/O I/O 4 c=a+b; Figure: Memory Running Running Programs Programs

Common Common 28 / 77 29 / 77 Pitfalls Pitfalls

Assignments Misconception Input/Output Operations and Functions

CSCE150A CSCE150A Input operation - data transfer from the outside world into memory.

Introduction In C you can write: Introduction Output operation - An instruction that displays program results to

Language sum= sum+ item; or Language the program user or sends results to a file or device Elements a=a + 1; Elements Preprocessor Preprocessor input/output functions - special program units that do all Comments Comments Main Function These are not algebraic expressions Main Function input/output operations. Common I/O functions found in the Reserved Words Reserved Words Program Style Program Style Standard Input/Output Library: stdio.h Executable This does not imply that 0 = 1 Executable Statements Statements Input/Output Meaning: a is to be given the value that a had before plus one Input/Output Function call - in C, a function call is used to call or activate a General Form General Form Common programming practice function. Operators & Operators & Expressions Instructs the computer to add the current value of sum to the value Expressions Analogous to ordering food from a restaurant. You (the calling Formatting of item then store the result into the variable sum. Formatting routine) do not know all of the ingredients and procedures for the I/O I/O food, but the called routine (the restaurant) provides all of this for Running Running Programs Programs you. Common Common 30 / 77 31 / 77 Pitfalls Pitfalls Output Function: printf Function Place Holder

CSCE150A Included in the stdio.h library. CSCE150A

Introduction functions arguments Introduction A placeholder always begins with the symbol %. Note the newline escape Language Language sequence \n. Format strings can have multiple placeholders. Elements Elements Preprocessor function name place holder new line Preprocessor Comments Comments Main Function Main Function Reserved Words Reserved Words Placeholder Variable Type Function Use Program Style Program Style Executable Executable %c char printf, scanf Statements Statements Input/Output printf("That equals %f kilometers.\n", kms); Input/Output %d int printf, scanf General Form General Form %f double printf only Operators & Operators & %lf double scanf only Expressions Expressions

Formatting formatting print list Formatting I/O I/O Running Figure: Parts of the printf function Running Programs Programs

Common Common 32 / 77 33 / 77 Pitfalls Pitfalls

Displaying Prompts Input Function: scanf

CSCE150A CSCE150A functions arguments

Introduction Introduction function name place holder

Language When input data is needed in an interactive program, you should use the Language Elements printf function to display a prompting message, or prompt, that tells Elements Preprocessor Preprocessor Comments the program user what data to enter. Comments Main Function Main Function scanf("%lf", &kms); Reserved Words Reserved Words Program Style printf("Do you have any questions?"); Program Style Executable Executable Statements Statements Input/Output or Input/Output variable list General Form General Form formatting Operators & printf("Enter the number of items>"); Operators & Expressions Expressions Figure: Parts of the scanf function Formatting Formatting I/O I/O

Running Running Programs Programs In general, do not put extra characters in the format string Common Common 34 / 77 35 / 77 Be sure to use the ampersand, & with scanf!!! Pitfalls Pitfalls

Return Statement Program Example

CSCE150A CSCE150A

1 #include Introduction Introduction 2 Language Language 3 int main(void){ Elements return 0; Elements 4 char first, last; Preprocessor Preprocessor Comments Comments 5 Main Function This statement returns a 0 to the operating system to signify that the Main Function 6 printf("Enter your first and last initials"); Reserved Words Reserved Words Program Style program ended in a correct position. It does not mean the program did Program Style 7 scanf("%c%c",&first,&last); Executable Executable Statements what it was supposed to do. It only means there were no runtime errors. Statements 8 Input/Output Input/Output There still may have been logical errors. 9 printf("Hello%c.%c. How are you?\n", first, last); General Form General Form 10 Operators & Operators & 11 return 0; Expressions Expressions 12 } Formatting Formatting I/O I/O

Running Running Programs Programs

Common Common 36 / 77 37 / 77 Pitfalls Pitfalls General Form of a C Program General Form of a C Program

CSCE150A CSCE150A

Introduction Introduction 1 proprocessor directives Language Programs begin with preprocessor directives that provide information Language 2 Elements Elements about functions from standard libraries and definitions of necessary 3 main function heading{ General Form program constants. General Form Operators & Operators & 4 Expressions #include and #define Expressions 5 declarations Formatting Next is the main function. Formatting I/O I/O 6

Running Inside the main function are the declarations and executable Running 7 executable statements Programs statements. Programs 8 } Common Common Pitfalls Pitfalls

38 / 77 39 / 77

Program Style - Spaces in Programs Comments in Programs

CSCE150A The compiler ignores extra blanks between words and symbols, but you CSCE150A may insert space to improve the readability and style of a program. Use comments to do Program Documentation, to help others read and Introduction Introduction understand the program. You should always leave a blank space after a comma and before and Language Language Elements after operators such as , , and =. Elements ∗ − The start of the program should consist of a comment that includes General Form Indent the body of the main function, as well as between any other General Form the programmer’s name, date of current version, and brief description Operators & curly brackets. Operators & Expressions Expressions of what the program does. Formatting 1 int main(void){ Formatting I/O I/O Include comments for each variable and each major step in the 2 { Running Running program. Programs 3 { Programs For any function, make comments to briefly describe the input to the Common 4 {} Common Pitfalls 5 }// End Level2 Pitfalls function, the output of the function, and the use of the function. 6 }/* End Level1*/ 7 return 0; Comments cannot be nested! 8 }// end main

40 / 77 41 / 77

Comments in Programs Arithmetic Expressions

CSCE150A CSCE150A

Style: Introduction Introduction Language 1 /* Language Operators / and % (Read mod or remainder) Elements 2 * Multiple line comments are good Elements General Form General Form Data Type of Expression 3 * for describing functions. Operators & Operators & Mixed-Type Assignment Statement Expressions 4 */ Expressions Formatting 5 Formatting Type Conversion through Cast I/O I/O Expressions with Multiple Operators Running 6 /* This/* isNOT*/ ok.*/ Running Programs 7 Programs Writing Mathematical Formulas in C Common Common Pitfalls 8 /*// ok.*/ Pitfalls

42 / 77 43 / 77 1 51 % 2 1 → 2 100 % 4 0 2 100 % 4 0 → → 3 101 % 31 8 3 101 % 31 8 → →

Arithmetic Expressions Arithmetic Expressions

CSCE150A CSCE150A

Operator Meaning Examples Introduction Introduction + addition 5 + 2 is 7 Language To solve most programming problems, you will need to write Language Elements Elements 5.0 + 2.0 is 7.0 arithmetic expressions that manipulate type int and double data. General Form General Form subtraction 5 2 is 3 Operators & Most operators manipulate two operands, which may be constants, Operators & − − Expressions Expressions 5.0 2.0 is 3.0 variables, or other arithmetic expressions. − Formatting Formatting * multiplication 5 * 2 is 10 I/O +, -, *, / can be used with integers or doubles I/O 5.0 * 2.0 is 10.0 Running Running Programs % can be used only with integers to find the remainder. Programs / division 5 / 2 is 2 Common Common 5.0 / 2.0 is 2.5 Pitfalls Pitfalls % remainder 5 % 2 is 1

44 / 77 45 / 77

Division Remainder Operator

CSCE150A CSCE150A

When applied to two positive integers Introduction Introduction The remainder operator (%) returns the integer remainder of the result of Language The division operator (/) computes the integer part of the result of Language Elements dividing its first operand by its second. Elements dividing its first operand by its second. General Form Example: the result of 7 / 2 is 3 General Form Operators & C only allows the answer to have the same accuracy as the operands. Operators & Similar to integer division, except instead of outputting integral Expressions If both operands are integers, the result will be an integer. Expressions portion, outputs remainder. Formatting Formatting I/O If one or both operands are double, the answer will be a double. I/O The operand % can give different answers when the second operand is Running Running negative. Programs Different C implementations differ on integer division with negative Programs Common numbers (which way they’ll truncate) Common As with division, % is undefined when the second operand is 0. Pitfalls Pitfalls / is undefined when the second operand is 0: 0.4 / 0 = ?

46 / 77 47 / 77

Remainder Operator Remainder Operator Exercise Exercise

CSCE150A CSCE150A Problem Problem Introduction What are the results of the following operations? Introduction What are the results of the following operations? Language Language Elements 1 51 % 2 Elements 1 51 % 2 General Form General Form 2 100 % 4 2 100 % 4 Operators & Operators & Expressions 3 101 % 31 Expressions 3 101 % 31 Formatting Formatting I/O I/O

Running Running 1 51 % 2 1 Programs Programs → Common Common Pitfalls Pitfalls

48 / 77 48 / 77 3 101 % 31 8 →

Remainder Operator Remainder Operator Exercise Exercise

CSCE150A CSCE150A Problem Problem Introduction What are the results of the following operations? Introduction What are the results of the following operations? Language Language Elements 1 51 % 2 Elements 1 51 % 2 General Form General Form 2 100 % 4 2 100 % 4 Operators & Operators & Expressions 3 101 % 31 Expressions 3 101 % 31 Formatting Formatting I/O I/O

Running 1 51 % 2 1 Running 1 51 % 2 1 Programs → Programs → Common 2 100 % 4 0 Common 2 100 % 4 0 Pitfalls → Pitfalls → 3 101 % 31 8 →

48 / 77 48 / 77

Data Type of an Expression Type Conversion through Type Casting

CSCE150A CSCE150A The data type of each variable must be specified in its declaration, but Introduction how does C determine the data type of an expression? Introduction Language Language Elements The data type of an expression depends on the type(s) of its Elements C is flexible enough to allow the programmer to convert the type of an General Form General Form operand(s). If both are of type int, then result is of type int. If expression by placing the desired type in parentheses before the Operators & Operators & Expressions either one or both is of type double, then result is of type double. Expressions expression, an operation called a type cast. Formatting An expression that has operands of both int and double is a Formatting I/O I/O Example: (double)5 / 2 results in 2.5, not 2 as seen previously. Running mixed-type expression, and will be typed as double. Running Programs Programs Common For a mixed-type assignment, be aware that the expression is evaluated Common Pitfalls Pitfalls first, and then the result is converted to the correct type. E.g. if y is double, then y=5/2 gets 2.0, not 2.5

49 / 77 50 / 77

Expressions with Multiple Operators Rules for Evaluating Expressions

CSCE150A CSCE150A 1 Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from Introduction Introduction the inside out, with the innermost expression evaluated first. Language In expressions, we often have multiple operators Language Elements Elements 2 Operator precedence rule: Operators in the same expression are Equations may not evaluate as we wish them to: General Form General Form evaluated in a fixed order (see Table 1 in your book) Operators & Is x/y z the same as (x/y) z or x/(y z)? Operators & Expressions ∗ ∗ ∗ Expressions Unary Operators +,- Unary operators take only one operand: -5, +3, -3.1415, etc. Formatting Formatting Binary Operators *,/,% I/O Binary operators take two operands: I/O Binary Arithmetic +,- Running 3 + 4, 7 / 5, 2 * 6, 4 % 3, etc. Running Programs Programs 3 Associativity rule: Common Common Pitfalls Pitfalls Unary operators in the same subexpression and at the same precedence level are evaluated right to left. Binary operators in the same subexpression and at the same precedence level are evaluated left to right.

51 / 77 52 / 77 1 x = -90 (why not 10?) − 2 y = 13 2 y = 13 3 z = -20 3 z = -20

3 z = -20

Exercise Exercise

CSCE150A CSCE150A Problem Problem Introduction What are the results of the following expressions: Introduction What are the results of the following expressions: Language Language Elements 1 x = -15 * 4 / 2 * 3; Elements 1 x = -15 * 4 / 2 * 3; General Form 2 y = 5 + 2 * 4; General Form 2 y = 5 + 2 * 4; Operators & Operators & Expressions 3 z = 4 - 5 * 2 - 4 + -10; Expressions 3 z = 4 - 5 * 2 - 4 + -10; Formatting Formatting I/O I/O

Running Running Programs Programs 1 x = -90 (why not 10?) − Common Common Pitfalls Pitfalls

53 / 77 53 / 77

Exercise Exercise

CSCE150A CSCE150A Problem Problem Introduction What are the results of the following expressions: Introduction What are the results of the following expressions: Language Language Elements 1 x = -15 * 4 / 2 * 3; Elements 1 x = -15 * 4 / 2 * 3; General Form 2 y = 5 + 2 * 4; General Form 2 y = 5 + 2 * 4; Operators & Operators & Expressions 3 z = 4 - 5 * 2 - 4 + -10; Expressions 3 z = 4 - 5 * 2 - 4 + -10; Formatting Formatting I/O I/O

Running Running Programs 1 x = -90 (why not 10?) Programs 1 x = -90 (why not 10?) − − Common 2 y = 13 Common 2 y = 13 Pitfalls Pitfalls 3 z = -20

53 / 77 53 / 77

Writing Mathematical Formulas in C Make Expressions Unambiguous Pitfalls

CSCE150A CSCE150A

Introduction Introduction

Language Language Common misconception: Mathematical Formulas in algebra and in C are Elements Elements not the same. General Form x = (-15 * 4) / (2 * 3); General Form Operators & Operators & Algebra: multiplication is implied: xy Expressions Even if unnecessary, add parentheses to improve readability Expressions Formatting Formatting C: Operations must be explicit: x*y I/O I/O Algebra: division is written a+b Running Running c+d Programs Programs C: Cannot use such conveniences, must write (a+b)/(c+d) Common Common Pitfalls Pitfalls

54 / 77 55 / 77 Formatting Numbers in Program Output Formatting Integer Types

CSCE150A CSCE150A

Introduction Introduction Recall the placeholder in printf/scanf for integers: %d Language Language Elements Elements By default, the complete integer value is output with no leading General Form Formatting Values of Type int General Form space Operators & Operators & Expressions Formatting Values of Type double Expressions You can insert a number to specify the minimum number of columns Formatting Program Style Formatting to be printed: %nd I/O I/O If n is less than the number of digits: no effect Running Running Programs Programs Otherwise, leading blank spaces are inserted before the number so Common Common Pitfalls Pitfalls that n columns are printed

56 / 77 57 / 77

Formatting Integer Types Example Formatting Values of Type double

CSCE150A CSCE150A

Introduction 1 intx = 2345; Introduction Recall the placeholder for doubles: %f Language 2 printf("%6d\n",x); Language Elements Elements Must specify both the total number of columns as well as the 3 printf("%2d\n",x); General Form General Form precision (number of decimal digits) Operators & Operators & Format: %n.mf Expressions Expressions n is the field width (minimum number of columns to be printed Formatting Result: Formatting I/O I/O including the decimal) 2345 Running 1 Running m is the number of digits after the decimal to be printed (may end up Programs 2 2345 Programs being padded with zeros Common Common Pitfalls Pitfalls May or may not define both n, m.

58 / 77 59 / 77

Formatting Values of Type double Programming Tip Example Man pages

CSCE150A CSCE150A

1 double pi = 3.141592; Introduction 2 printf("%.2f\n",pi); Introduction On a UNIX system like cse, the command man (short for manual) Language Language Elements 3 printf("%6.2f\n",pi); Elements can be used to read documentation on standard library functions. General Form 4 printf("%15.10f\n",pi); General Form Example: :prompt> man printf gives a detailed description on Operators & Operators & Expressions Expressions printf Formatting Result: Formatting Contains additional information: how to print leading zeros instead I/O I/O of blanks, etc. Running 1 3.14 Running Programs 2 3.14 Programs Can also look at web-based resources, and Kernighan and Ritchie’s Common Common Pitfalls 3 3.1415920000 Pitfalls reference book

60 / 77 61 / 77 Interactive Mode, Batch Mode, and Data Files Definitions

CSCE150A CSCE150A

Introduction Introduction

Language Language Elements Input Redirection Elements General Form General Form Active mode - the program user interacts with the program and types

Operators & Program Style Operators & in data while the program is running. Expressions Expressions Output Redirection Batch mode - the program scans its data from a data file prepared Formatting Formatting I/O Program-Controlled Input and Output Files I/O beforehand instead of interacting with its user. Running Running Programs Programs

Common Common Pitfalls Pitfalls

62 / 77 63 / 77

Input Redirection

CSCE150A CSCE150A Recall the mile-to-kilometer program. 1 #include Introduction Recall miles-to-kilometers conversion program: active mode Introduction 2 int main(void) Language prompted user for input Language { Elements Elements 3 4 double miles, kilometers; General Form If expected formatting of input/output is known, you can put it in a General Form 5 printf("How many miles do you have?"); Operators & plain text file and use input/output redirection on the command line Operators & Expressions Expressions 6 7 scanf("%lf",&miles); Formatting Example: Formatting I/O I/O 8 9 kilometers= miles * 1.609; Running prompt:> conversion< mydata Running Programs Programs 10 printf("You have%f kilometers\n",kilometers); Common where mydata is a plain text file containing a single double-formatted Common 11 Pitfalls Pitfalls 12 return 0; number. 13 }

64 / 77 65 / 77

Echo Prints vs. Prompts Program-Controlled Input and Output Files

CSCE150A CSCE150A

Introduction scanf gets a value for miles from the first (and only) line of the data Introduction As an alternative to input/output redirection, C allows a program to

Language file Language explicitly name a file from which the program will take input and a file to Elements Elements If we will only run the program in batch mode, there is no need for which the program will send output. The steps needed to do this are: General Form General Form the prompting message Operators & Operators & 1 Include stdio.h Expressions We do need to output the answer, though: Expressions Formatting Formatting 2 Declare a variable of type FILE *. I/O printf("The distance in miles is %.2f.\n",miles); I/O 3 Running Running Open the file for reading, writing or both. Programs However, we can also redirect the output to a file: Programs 4 Read/write to/from the file. Common prompt:> conversion< mydata> result.txt Common Pitfalls Pitfalls It’s enough to echo only the number: printf("%.2f.\n",miles); 5 Close the file.

66 / 77 67 / 77 Program Example File Input/Output Common Programming Errors

CSCE150A 1 #include CSCE150A 2 #define KMS_PER_MILE 1.609 3 Introduction 4 int main(void){ Introduction

Language 5 double kms, miles; Language Elements 6 FILE*inp,*outp; Elements Syntax Errors General Form 7 General Form

Operators & 8 inp= fopen("distance.dat","r"); Operators & Run-Time Errors Expressions Expressions 9 outp= fopen("distance.out","w"); Undetected Errors Formatting 10 fscanf(inp,"%lf",&miles); Formatting I/O 11 fprintf(outp,"The distance in miles is %.2f.\n", miles); I/O Logic Errors Running 12 Running Programs Programs 13 kms=KMS_PER_MILES* miles; Common Common Pitfalls 14 fprintf(outp,"That equals %.2f kilometers.\n", miles); Pitfalls 15 fclose(inp); 16 fclose(outp); 17 return 0; 18 } 68 / 77 69 / 77

Errors Syntax Errors

CSCE150A CSCE150A

A syntax error occurs when your code violates one or more grammar rules Bugs - Errors in a programs code. Introduction Introduction of C and is detected by the compiler at it attempts to translate your Language Debugging - Finding and removing errors in the program. Language Elements Elements program. If a statement has a syntax error, it cannot be translated and

General Form When the compiler detects an error, it will output an error message. General Form your program will not be compiled.

Operators & May be difficult to interpret Operators & Expressions May be misleading Expressions Common syntax errors: Formatting Formatting I/O Three types of errors I/O Missing semicolon Running Syntax error Running Programs Run-time error Programs Undeclared variable Common Common Pitfalls Undetected error Pitfalls Last comment is not closed Logic error A grouping character not closed (’(’, ’ ’, ’[’) {

70 / 77 71 / 77

Run-Time Errors Undetected Errors

CSCE150A CSCE150A

Introduction Detected and displayed by the computer during the execution of a Introduction

Language program Language Elements Elements Code was correct and logical, executed fine, but led to incorrect Occurs when the program directs the computer to perform an illegal General Form General Form results. Operators & operation. Example: dividing a number by zero or opening a file that Operators & Expressions does not exist Expressions Essential that you test your program on known correct input/outputs. Formatting Formatting I/O When a run-time error occurs, the computer will stop executing your I/O Common formatting errors with scanf/printf: keep in mind the Running program Running correct placeholders and syntax. Programs Programs

Common May display a useful (or not) error message Common Pitfalls Pitfalls Segmentation fault, core dump, bus error, etc.

72 / 77 73 / 77 Logic Errors Questions

CSCE150A CSCE150A

Introduction Introduction Language Logic errors occur when a program follows a faulty algorithm. Language Elements Elements

General Form Usually do not cause run-time errors and do not display error General Form Operators & messages—difficult to detect Operators & Questions? Expressions Expressions

Formatting Must rigorously test your program with various inputs/outputs Formatting I/O I/O Pre-planning your algorithm with pseudocode or flow charts will also Running Running Programs help you avoid logic errors Programs Common Common Pitfalls Pitfalls

74 / 77 75 / 77

Exercise Exercise: Answer

CSCE150A Debug the following program: CSCE150A 1 /* 2 * Calculate and display the sum of two input values 1 /* 3 */ Introduction 2 * Calculate and display the difference of two input values Introduction 4 #include 3 */ Language Language 5 Elements 4 #include Elements 6 int main(void) General Form 5 General Form 7 { Operators & 6 int main(void) Operators & 8 inta,b;/* inputs*/ Expressions 7 { Expressions 9 int sum;/* sum of inputs*/ Formatting 8 inta,b;/* inputs Formatting 10 printf("Input the first number:"); I/O I/O 9 integer sum;/* sum of inputs*/ 11 scanf("%d",&a); Running 10 printf("Input the first number:%d",&A); Running Programs Programs 12 printf("Input the second number:"); 11 printf("Input the second number:"); 13 scanf("%d",&b); Common Common Pitfalls 12 scanf("%d",b); Pitfalls 14 sum=a+b; 13 a+b= sum; 15 printf("%d+%d=%d\n",a,b, sum); 14 printf("%d+%d=%d\n",a;b, sum); 16 return 0; 15 return 0; 17 }

76 / 77 77 / 77