CSCE150A Computer Science & Engineering 150A Introduction Problem Solving Using Computers Language Elements

General Form Lecture 02 - Introduction To

Operators & Expressions

Formatting I/O Stephen Scott Running Programs (Adapted from Christopher M. Bourke)

Common Pitfalls

Fall 2009 1 / 77

[email protected] CSCE150A

Introduction C Language Elements Language Variable Declarations and Data Types Elements

General Form Executable Statements Operators & General Form of a C Program Expressions

Formatting Arithmetic Expressions I/O

Running Formatting Numbers in Program Output Programs Interactive Mode, Batch Mode, and Data Files Common Pitfalls Common Programming Errors

2 / 77 Overview of C Programming

CSCE150A

Introduction

Language Elements This chapter introduces C – a high-level developed General Form in 1972 by Dennis Ritchie at AT&T Bell Laboratories. Operators & Expressions This chapter describes the elements of a C program and the types of data Formatting I/O that can be processed by C. It also describes C statements for performing

Running computations, for entering data, and for displaying results. Programs

Common Pitfalls

3 / 77 C Language Elements

CSCE150A

Introduction Directives

Language Elements Syntax Displays for Preprocessor Directives Preprocessor Comments “int main()” Function Main Function Reserved Words Reserved Words Program Style Executable Statements Standard Identifiers Input/Output General Form User-Defined Identifiers Operators & Uppercase and Lowercase Letters Expressions

Formatting Program Style I/O

Running Programs

Common 4 / 77 Pitfalls Preprocessor Directives

CSCE150A

Introduction

Language The modifies the text of the C program before it is Elements passed to the . Preprocessor Comments Main Function Preprocessor directives are C program lines beginning with a # that Reserved Words Program Style provide instructions to the C preprocessor. Executable Statements Input/Output Preprocessor directives begins with a #, e.g. #include and #define. General Form Predefined libraries are useful functions and symbols that are Operators & Expressions predefined by the C language (standard libraries).

Formatting I/O

Running Programs

Common 5 / 77 Pitfalls #include and #define

CSCE150A

Introduction #include gives the program access to a library Language Elements Example: #include (standard input and output) has Preprocessor Comments definitions for input and output, such as printf and scanf. Main Function Reserved Words #define NAME value associates a constant Program Style Executable Statements Example: Input/Output General Form 1 #defineKMS_PER_MILE 1.609 Operators & 2 #definePI 3.14159 Expressions

Formatting I/O

Running Programs

Common 6 / 77 Pitfalls Comments

CSCE150A

Introduction Comments provide supplementary information making it easier for us to Language Elements understand the program, but comments are ignored by the C preprocessor Preprocessor Comments and compiler. Main Function Reserved Words Program Style - anything between them with be considered a comment, even Executable /**/ Statements Input/Output if they span multiple lines. General Form // - anything after this and before the end of the line is considered a Operators & Expressions comment.

Formatting I/O

Running Programs

Common 7 / 77 Pitfalls Function main

CSCE150A

The point at which a C program begins execution is the main Introduction

Language function: Elements Preprocessor 1 int main(void) Comments Main Function Reserved Words Program Style Every C program must have a main function. Executable Statements Input/Output The main function (and every other function) body has two parts: General Form Declarations - tell the compiler what memory cells are needed in the Operators & function Expressions Executable statements - (derived from the algorithm) are translated Formatting I/O into machine language and later executed

Running Programs

Common 8 / 77 Pitfalls Function main

CSCE150A

Introduction

Language Elements All C functions contain punctuation and special symbols Preprocessor Comments Punctuation - commas separate items in a list, semicolons appear at Main Function Reserved Words the end of each statement Program Style Executable Special symbols: *, =, {, }, etc. Statements Input/Output Curly braces mark the beginning and end of the body of every General Form function, including main

Operators & Expressions

Formatting I/O

Running Programs

Common 9 / 77 Pitfalls Reserved Words

CSCE150A

Introduction A word that has special meaning in C. E.g.: Language int - Indicates that the main function (or any other function) returns Elements Preprocessor an integer value, or that a memory cell will store an integer value Comments - Indicates that a function returns a real number or that a Main Function double Reserved Words memory cell will store a real number Program Style Executable Statements Always lower case Input/Output General Form Can not be used for other purposes Operators & Appendix E has a full listing of reserved words (ex: Expressions

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

Running Programs

Common 10 / 77 Pitfalls Standard Identifiers

CSCE150A

Introduction

Language Standard identifiers have a special meaning in C (assigned by Elements Preprocessor standard libraries). Comments Main Function Standard identifiers can be redefined and used by the programmer for Reserved Words Program Style other purposes Executable Statements Not recommended If you redefine a standard identifier; C will no Input/Output longer be able to use it for its original purpose. General Form

Operators & Examples: input/output functions printf, scanf Expressions

Formatting I/O

Running Programs

Common 11 / 77 Pitfalls User-Defined Identifiers

CSCE150A

We choose our own identifiers to name memory cells that will hold data Introduction and program results and to name operations (functions) that we define Language Elements (more on this in Chapter 3) Preprocessor Comments Main Function An identifier must consist only of letters , digits , Reserved Words [a-zA-Z] [0-9] Program Style Executable and underscores. Statements Input/Output An identifier cannot begin with a digit (and shouldn’t begin with an General Form underscore). Operators & Expressions A C cannot be used as an identifier. Formatting I/O An identifier defined in a C standard library should not be redefined.

Running Programs

Common 12 / 77 Pitfalls User-Defined Identifiers

CSCE150A Examples: letter_1, Inches, KMS_PER_MILE Introduction Some will only see the first 31 characters Language Elements Uppercase and lowercase are different Preprocessor Comments (Variable, variable, VARIABLE are all different) Main Function Reserved Words Choosing identifer names: Program Style Executable Statements Choose names that mean something Input/Output Should be easy to read and understand General Form Shorten only if possible Operators & Expressions Don’t use Big, big, and BIG as they are easy to confuse Formatting I/O Identifiers using all-caps are usually used for preprocessor-defined

Running constants (#define) Programs

Common 13 / 77 Pitfalls Program Style

CSCE150A

Introduction

Language Elements Preprocessor A program that “looks good” is easier to read and understand than one Comments Main Function that is sloppy (i.e. good spacing, well-named identifiers). Reserved Words Program Style Executable In industry, programmers spend considerably more time on program Statements Input/Output maintenance than they do on its original design or coding. General Form

Operators & Expressions

Formatting I/O

Running Programs

Common 14 / 77 Pitfalls Style Tips Rigorous Comments

CSCE150A

Introduction

Language The number of comments in your program doesn’t affect its speed or Elements size. Preprocessor Comments Main Function Always best to include as much documentation as possible in the Reserved Words Program Style form of comments. Executable Statements Input/Output Begin each program or function with a full explanation of its inputs, General Form outputs, and how it works.

Operators & Expressions Include comments as necessary throughout the program

Formatting I/O

Running Programs

Common 15 / 77 Pitfalls Style Tips Naming Conventions

CSCE150A

Introduction Language Give your variables meaningful names (identifiers) Elements Preprocessor Comments x,y may be good if you’re dealing with coordinates, but bad in Main Function Reserved Words general. Program Style Executable myVariable, aVariable, anInteger, etc are bad: they do not Statements Input/Output describe the purpose of the variable. General Form tempInt,PI, numberOfStudents are good because they do. Operators & Expressions

Formatting I/O

Running Programs

Common 16 / 77 Pitfalls Style Tips CamelCaseNotation

CSCE150A

Old School C convention: separate compound words with underscores Introduction

Language number_of_students, interest_rate, max_value, etc. Elements Preprocessor Underscore (shift-hyphen) is inconvenient Comments Main Function Solution: camelCaseNotation - connect compound words with Reserved Words Program Style upper-case letters. Executable Statements Input/Output Example: numberOfStudents, interestRate, maxValue, etc. General Form Much easier to shift-capitalize Operators & Expressions Much more readable Formatting I/O Ubiquitous outside of programming: MasterCard, PetsMart, etc. Running Programs

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

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

Common 18 / 77 Pitfalls Comments

Reserved Words Variables Special Symbols Punctuation

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

Common 18 / 77 Pitfalls Comments Preprocessor Directives

Variables Special Symbols Punctuation

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

Common 18 / 77 Pitfalls Comments Preprocessor Directives Reserved Words

Special Symbols Punctuation

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

Common 18 / 77 Pitfalls Comments Preprocessor Directives Reserved Words Variables

Punctuation

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

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

Anatomy of a Program

CSCE150A

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

Formatting I/O

Running Programs

Common 18 / 77 Pitfalls Anatomy of a Program

CSCE150A

/* * Converts distances from miles to kilometers. */ standard header file comment Introduction prepocessor #include /* printf, scanf definitions */ directive #define KMS_PER_MILE 1.609 /* conversion constant */ Language Elements constant int main(void) reserved word Preprocessor { Comments double miles, /* distance in miles */ Main Function variable kms; /* equivalent distance in kilometers */ Reserved Words Program Style /* Get the distance in miles */ comment Executable printf("Enter the distance in miles> "); Statements standard identifier scanf("%lf", &miles); Input/Output /* Conver the distance to kilometers. */ General Form kms = KMS_PER_MILE * miles; special symbol Operators & /* Display the distance in kilometers. */ Expressions printf("That equals %f kilometers.\n", kms); Formatting return(0); reserved punctuation I/O word } Running special symbol Programs

Common 19 / 77 Pitfalls Variable Declarations and Data Types

CSCE150A

Introduction

Language Elements Preprocessor Comments Main Function Variable Declaration Reserved Words Program Style Data Types Executable Statements Input/Output General Form

Operators & Expressions

Formatting I/O

Running Programs

Common 20 / 77 Pitfalls Variables Declarations

CSCE150A

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

Running Programs

Common 21 / 77 Pitfalls Data Types

CSCE150A

Introduction Data Types: a set of values and a set of operations that can be used Language Elements on those values. Preprocessor Comments In other words, it is a classification of a particular type of Main Function Reserved Words information. Program Style Executable Integers Statements int Input/Output Doubles double General Form Characters char Operators & Expressions The idea is to give semantic meaning to 0s and 1s.

Formatting I/O

Running Programs

Common 22 / 77 Pitfalls Data Types Integers

CSCE150A

Introduction Integers are whole numbers, negative and positive Language Elements Declaration: int Preprocessor Comments The ANSI C standard requires integers be at least 16 bits: in the Main Function Reserved Words range −32767 to 32767 Program Style Executable Statements One bit for the sign and 15 for the number Input/Output General Form Modern standard that int types are 32 bits. Range: 31 31 Operators & −2 = −2, 147, 483, 648 to 2, 147, 483, 648 = 2 Expressions Newer systems are 64-bit. What range does this give? Formatting I/O

Running Programs

Common 23 / 77 Pitfalls Data Types Doubles

CSCE150A

Introduction Language Doubles are decimal numbers, negative and positive Elements Preprocessor Example: 0.5, 3.14159265, 5, 8.33 Comments Main Function Reserved Words Declaration: double Program Style Executable Statements On most systems, doubles are 8 bytes = 64 bits Input/Output Precision is finite: cannot fully represent irrationals π, 1 , etc. General Form 3

Operators & An approximation only, but 15–16 digits of precision Expressions

Formatting I/O

Running Programs

Common 24 / 77 Pitfalls Data Types Characters

CSCE150A

Introduction Language char: an individual character values with single quotes around it. Elements Preprocessor Example: a letter, a digit, or a special symbol Comments Main Function Reserved Words Example: ’a’,’B’,’*’,’!’ Program Style Executable Statements You can treat each character as a number: see Appendix A Input/Output General Form The ASCII standard assigns number (0 thru 255) to each character:

Operators & A is 65, many are non-printable control characters Expressions

Formatting I/O

Running Programs

Common 25 / 77 Pitfalls Executable Statements

CSCE150A

Introduction

Language Elements Assignment Statements Preprocessor Comments Input/Output Operations and Functions Main Function Reserved Words Program Style printf Function Executable Statements Input/Output scanf Function General Form return Statement Operators & Expressions

Formatting I/O

Running Programs

Common 26 / 77 Pitfalls Assignment Statements

CSCE150A

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

Running Programs

Common 27 / 77 Pitfalls Memory of Program

CSCE150A Memory

Introduction miles miles

Language Elements ? 10.00 Preprocessor Comments type double Main Function kms kms Reserved Words Program Style Executable ? 16.09 Statements Input/Output General Form KMS_PER_MILE KMS_PER_MILE

Operators & Expressions constant 1.609 1.609

Formatting I/O Figure: Memory Running Programs

Common 28 / 77 Pitfalls Assignments Continued

CSCE150A

In C, the symbol = is the assignment operator. Introduction Read as “becomes”, “gets”, or “takes the value of” rather than Language Elements “equals” Preprocessor Comments In C, tests equality. Main Function == Reserved Words Program Style Examples: Executable Statements Input/Output 1 inta,b,c; General Form

Operators & 2 b = 10; Expressions 3 a = 15; Formatting I/O 4 c=a+b;

Running Programs

Common 29 / 77 Pitfalls Assignments Misconception

CSCE150A

Introduction In C you can write:

Language sum= sum+ item; or Elements Preprocessor a=a + 1; Comments Main Function These are not algebraic expressions Reserved Words Program Style Executable This does not imply that 0 = 1 Statements Input/Output Meaning: a is to be given the value that a had before plus one General Form Common programming practice Operators & Expressions Instructs the computer to add the current value of sum to the value Formatting I/O of item then store the result into the variable sum.

Running Programs

Common 30 / 77 Pitfalls Input/Output Operations and Functions

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

Introduction Output operation - An instruction that displays program results to

Language the program user or sends results to a file or device Elements Preprocessor input/output functions - special program units that do all Comments Main Function input/output operations. Common I/O functions found in the Reserved Words Program Style Standard Input/Output Library: stdio.h Executable Statements Input/Output Function call - in C, a function call is used to call or activate a General Form function. Operators & Expressions Analogous to ordering food from a restaurant. You (the calling

Formatting routine) do not know all of the ingredients and procedures for the I/O food, but the called routine (the restaurant) provides all of this for Running Programs you. Common 31 / 77 Pitfalls Output Function: printf Function

CSCE150A Included in the stdio.h library.

Introduction functions arguments Language Elements Preprocessor function name place holder new line Comments Main Function Reserved Words Program Style Executable Statements Input/Output printf("That equals %f kilometers.\n", kms); General Form

Operators & Expressions

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

Common 32 / 77 Pitfalls Place Holder

CSCE150A

Introduction A placeholder always begins with the symbol %. Note the newline escape Language sequence \n. Format strings can have multiple placeholders. Elements Preprocessor Comments Main Function Reserved Words Placeholder Variable Type Function Use Program Style Executable %c char printf, scanf Statements Input/Output % int printf, scanf General Form %f double printf only Operators & %lf double scanf only Expressions

Formatting I/O

Running Programs

Common 33 / 77 Pitfalls Displaying Prompts

CSCE150A

Introduction

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

Formatting I/O

Running Programs

Common 34 / 77 Pitfalls Input Function: scanf

CSCE150A functions arguments

Introduction function name place holder

Language Elements Preprocessor Comments Main Function scanf("%lf", &kms); Reserved Words Program Style Executable Statements Input/Output variable list General Form formatting Operators & Expressions Figure: Parts of the scanf function Formatting I/O

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

CSCE150A

Introduction

Language Elements return 0; Preprocessor Comments Main Function This statement returns a 0 to the operating system to signify that the Reserved Words Program Style program ended in a correct position. It does not mean the program did Executable Statements what it was supposed to do. It only means there were no runtime errors. Input/Output General Form There still may have been logical errors.

Operators & Expressions

Formatting I/O

Running Programs

Common 36 / 77 Pitfalls Program Example

CSCE150A

1 #include Introduction 2 Language 3 int main(void){ Elements 4 char first, last; Preprocessor Comments 5 Main Function 6 printf("Enter your first and last initials"); Reserved Words Program Style 7 scanf("%c%c",&first,&last); Executable Statements 8 Input/Output 9 printf("Hello%c.%c. How are you?\n", first, last); General Form 10 Operators & 11 return 0; Expressions 12 } Formatting I/O

Running Programs

Common 37 / 77 Pitfalls General Form of a C Program

CSCE150A

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

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

38 / 77 General Form of a C Program

CSCE150A

Introduction 1 proprocessor directives Language 2 Elements 3 main function heading{ General Form 4 Operators & Expressions 5 declarations Formatting I/O 6

Running 7 executable statements Programs 8 } Common Pitfalls

39 / 77 Program Style - Spaces in Programs

CSCE150A The compiler ignores extra blanks between words and symbols, but you may insert space to improve the readability and style of a program.

Introduction You should always leave a blank space after a comma and before and Language Elements after operators such as ∗, −, and =. General Form Indent the body of the main function, as well as between any other Operators & Expressions curly brackets. Formatting 1 int main(void){ I/O 2 { Running Programs 3 {

Common 4 {} Pitfalls 5 }// End Level2 6 }/* End Level1*/ 7 return 0; 8 }// end main

40 / 77 Comments in Programs

CSCE150A Use comments to do Program Documentation, to help others read and Introduction understand the program. Language Elements The start of the program should consist of a comment that includes General Form the programmer’s name, date of current version, and brief description Operators & Expressions of what the program does. Formatting I/O Include comments for each variable and each major step in the

Running program. Programs For any function, make comments to briefly describe the input to the Common Pitfalls function, the output of the function, and the use of the function. Comments cannot be nested!

41 / 77 Comments in Programs

CSCE150A

Style: Introduction Language 1 /* Elements 2 * Multiple line comments are good General Form 3 * for describing functions. Operators & Expressions 4 */ Formatting 5 I/O

Running 6 /* This/* isNOT*/ ok.*/ Programs 7 Common Pitfalls 8 /*// ok.*/

42 / 77 Arithmetic Expressions

CSCE150A

Introduction Language Operators / and % (Read mod or remainder) Elements

General Form Data Type of Expression Operators & Mixed-Type Assignment Statement Expressions

Formatting Type Conversion through Cast I/O Expressions with Multiple Operators Running Programs Writing Mathematical Formulas in C Common Pitfalls

43 / 77 Arithmetic Expressions

CSCE150A

Introduction Language To solve most programming problems, you will need to write Elements

General Form arithmetic expressions that manipulate type int and double data. Operators & Most operators manipulate two operands, which may be constants, Expressions variables, or other arithmetic expressions. Formatting I/O +, -, *, / can be used with integers or doubles Running Programs % can be used only with integers to find the remainder. Common Pitfalls

44 / 77 Arithmetic Expressions

CSCE150A

Operator Meaning Examples Introduction

Language + addition 5 + 2 is 7 Elements 5.0 + 2.0 is 7.0 General Form − subtraction 5 − 2 is 3 Operators & Expressions 5.0 − 2.0 is 3.0

Formatting * multiplication 5 * 2 is 10 I/O 5.0 * 2.0 is 10.0 Running Programs / division 5 / 2 is 2 Common 5.0 / 2.0 is 2.5 Pitfalls % remainder 5 % 2 is 1

45 / 77 Division

CSCE150A

When applied to two positive integers Introduction The division operator (/) computes the integer part of the result of Language Elements dividing its first operand by its second. General Form Example: the result of 7 / 2 is 3 Operators & C only allows the answer to have the same accuracy as the operands. Expressions If both operands are integers, the result will be an integer. Formatting I/O If one or both operands are double, the answer will be a double. Running Programs Different C implementations differ on integer division with negative

Common numbers (which way they’ll truncate) Pitfalls / is undefined when the second operand is 0: 0.4 / 0 = ?

46 / 77 Remainder Operator

CSCE150A

Introduction The remainder operator (%) returns the integer remainder of the result of Language Elements dividing its first operand by its second.

General Form

Operators & Similar to integer division, except instead of outputting integral Expressions portion, outputs remainder. Formatting I/O The operand % can give different answers when the second operand is Running negative. Programs

Common As with division, % is undefined when the second operand is 0. Pitfalls

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

Remainder Operator Exercise

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

Running Programs

Common Pitfalls

48 / 77 2 100 % 4 → 0 3 101 % 31 → 8

Remainder Operator Exercise

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

Running 1 Programs 51 % 2 → 1

Common Pitfalls

48 / 77 3 101 % 31 → 8

Remainder Operator Exercise

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

Running 1 Programs 51 % 2 → 1 Common 2 100 % 4 → 0 Pitfalls

48 / 77 Remainder Operator Exercise

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

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

48 / 77 Data Type of an Expression

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? Language Elements The data type of an expression depends on the type(s) of its General Form operand(s). If both are of type int, then result is of type int. If Operators & Expressions either one or both is of type double, then result is of type double. Formatting An expression that has operands of both int and double is a I/O

Running mixed-type expression, and will be typed as double. Programs Common For a mixed-type assignment, be aware that the expression is evaluated 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 Type Conversion through Type Casting

CSCE150A

Introduction

Language Elements C is flexible enough to allow the programmer to convert the type of an General Form expression by placing the desired type in parentheses before the Operators & Expressions expression, an operation called a type cast. Formatting I/O Example: (double)5 / 2 results in 2.5, not 2 as seen previously. Running Programs

Common Pitfalls

50 / 77 Expressions with Multiple Operators

CSCE150A

Introduction

Language Elements In expressions, we often have multiple operators

General Form Equations may not evaluate as we wish them to:

Operators & Is x/y ∗ z the same as (x/y) ∗ z or x/(y ∗ z)? Expressions Unary operators take only one operand: -5, +3, -3.1415, etc. Formatting I/O Binary operators take two operands: Running Programs 3 + 4, 7 / 5, 2 * 6, 4 % 3, etc.

Common Pitfalls

51 / 77 Rules for Evaluating Expressions

CSCE150A 1 Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from Introduction the inside out, with the innermost expression evaluated first. Language Elements 2 Operator precedence rule: Operators in the same expression are General Form evaluated in a fixed order (see Table 1 in your book) Operators & Expressions Unary Operators +,- Formatting Binary Operators *,/,% I/O Binary Arithmetic +,- Running Programs 3 Associativity rule: Common 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.

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

Exercise

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

Running Programs

Common Pitfalls

53 / 77 2 y = 13 3 z = -20

Exercise

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

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

Common Pitfalls

53 / 77 3 z = -20

Exercise

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

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

Common 2 Pitfalls y = 13

53 / 77 Exercise

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

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

Common 2 Pitfalls y = 13 3 z = -20

53 / 77 Make Expressions Unambiguous

CSCE150A

Introduction

Language Elements General Form x = (-15 * 4) / (2 * 3); Operators & Expressions Even if unnecessary, add parentheses to improve readability Formatting I/O

Running Programs

Common Pitfalls

54 / 77 Writing Mathematical Formulas in C Pitfalls

CSCE150A

Introduction

Language Common misconception: Mathematical Formulas in algebra and in C are Elements not the same. General Form Operators & Algebra: multiplication is implied: xy Expressions

Formatting C: Operations must be explicit: x*y I/O Algebra: division is written a+b Running c+d Programs C: Cannot use such conveniences, must write (a+b)/(c+d) Common Pitfalls

55 / 77 Formatting Numbers in Program Output

CSCE150A

Introduction

Language Elements General Form Formatting Values of Type int Operators & Expressions Formatting Values of Type double Formatting Program Style I/O

Running Programs

Common Pitfalls

56 / 77 Formatting Integer Types

CSCE150A

Introduction Recall the placeholder in printf/scanf for integers: %d Language Elements By default, the complete integer value is output with no leading General Form space Operators & Expressions You can insert a number to specify the minimum number of columns

Formatting to be printed: %nd I/O If n is less than the number of digits: no effect Running Programs Otherwise, leading blank spaces are inserted before the number so Common Pitfalls that n columns are printed

57 / 77 Formatting Integer Types Example

CSCE150A

Introduction 1 intx = 2345; Language 2 printf("%6d\n",x); Elements 3 General Form printf("%2d\n",x);

Operators & Expressions

Formatting Result: I/O

Running 1 2345 Programs 2 2345 Common Pitfalls

58 / 77 Formatting Values of Type double

CSCE150A

Introduction Recall the placeholder for doubles: %f Language Elements Must specify both the total number of columns as well as the

General Form precision (number of decimal digits) Operators & Format: %n.mf Expressions n is the field width (minimum number of columns to be printed Formatting I/O including the decimal) Running m is the number of digits after the decimal to be printed (may end up Programs being padded with zeros Common Pitfalls May or may not define both n, m.

59 / 77 Formatting Values of Type double Example

CSCE150A

1 double pi = 3.141592; Introduction 2 printf("%.2f\n",pi); Language Elements 3 printf("%6.2f\n",pi);

General Form 4 printf("%15.10f\n",pi);

Operators & Expressions

Formatting Result: I/O

Running 1 3.14 Programs 2 3.14 Common Pitfalls 3 3.1415920000

60 / 77 Programming Tip Man pages

CSCE150A

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

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

CSCE150A

Introduction

Language Elements Input Redirection General Form

Operators & Program Style Expressions Output Redirection Formatting I/O Program-Controlled Input and Output Files Running Programs

Common Pitfalls

62 / 77 Definitions

CSCE150A

Introduction

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

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

Common Pitfalls

63 / 77 Input Redirection

CSCE150A

Introduction Recall miles-to-kilometers conversion program: active mode Language prompted user for input Elements

General Form If expected formatting of input/output is known, you can put it in a

Operators & plain text file and use input/output redirection on the command line Expressions

Formatting Example: I/O

Running Programs prompt:> conversion< mydata

Common Pitfalls where mydata is a plain text file containing a single double-formatted number.

64 / 77 CSCE150A Recall the mile-to-kilometer program. 1 #include Introduction 2 int main(void) Language 3 Elements { 4 double miles, kilometers; General Form 5 printf("How many miles do you have?"); Operators & Expressions 6 7 scanf("%lf",&miles); Formatting I/O 8

Running 9 kilometers= miles * 1.609; Programs 10 printf("You have%f kilometers\n",kilometers); Common 11 Pitfalls 12 return 0; 13 }

65 / 77 Echo Prints vs. Prompts

CSCE150A

Introduction scanf gets a value for miles from the first (and only) line of the data

Language file Elements If we will only run the program in batch mode, there is no need for General Form

Operators & the prompting message Expressions We do need to output the answer, though: Formatting I/O printf("The distance in miles is %.2f.\n",miles); Running Programs However, we can also redirect the output to a file:

Common prompt:> conversion< mydata> result.txt Pitfalls It’s enough to echo only the number: printf("%.2f.\n",miles);

66 / 77 Program-Controlled Input and Output Files

CSCE150A

Introduction As an alternative to input/output redirection, C allows a program to

Language explicitly name a file from which the program will take input and a file to Elements which the program will send output. The steps needed to do this are: General Form

Operators & 1 Expressions Include stdio.h Formatting 2 Declare a variable of type FILE *. I/O 3 Running Open the file for reading, writing or both. Programs 4 Read/write to/from the file. Common Pitfalls 5 Close the file.

67 / 77 Program Example File Input/Output

CSCE150A 1 #include 2 #define KMS_PER_MILE 1.609 3

Introduction 4 int main(void){

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

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

CSCE150A

Introduction

Language Elements Syntax Errors General Form

Operators & Run-Time Errors Expressions Undetected Errors Formatting I/O Logic Errors Running Programs

Common Pitfalls

69 / 77 Errors

CSCE150A

Introduction Bugs - Errors in a programs code. Language Debugging - Finding and removing errors in the program. Elements

General Form When the compiler detects an error, it will output an error message.

Operators & May be difficult to interpret Expressions May be misleading Formatting I/O Three types of errors

Running Syntax error Programs Run-time error Common Pitfalls Undetected error Logic error

70 / 77 Syntax Errors

CSCE150A

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

General Form your program will not be compiled.

Operators & Expressions Common syntax errors:

Formatting I/O Missing semicolon Running Programs Undeclared variable

Common Pitfalls Last comment is not closed A grouping character not closed (’(’, ’{’, ’[’)

71 / 77 Run-Time Errors

CSCE150A

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

Language program Elements Occurs when the program directs the computer to perform an illegal General Form

Operators & operation. Example: dividing a number by zero or opening a file that Expressions does not exist Formatting I/O When a run-time error occurs, the computer will stop executing your Running program Programs

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

72 / 77 Undetected Errors

CSCE150A

Introduction

Language Elements Code was correct and logical, executed fine, but led to incorrect General Form results. Operators & Expressions Essential that you test your program on known correct input/outputs. Formatting I/O Common formatting errors with scanf/printf: keep in mind the

Running correct placeholders and syntax. Programs

Common Pitfalls

73 / 77 Logic Errors

CSCE150A

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

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

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

74 / 77 Questions

CSCE150A

Introduction

Language Elements

General Form Operators & Questions? Expressions

Formatting I/O

Running Programs

Common Pitfalls

75 / 77 Exercise

CSCE150A Debug the following program: 1 /*

Introduction 2 * Calculate and display the difference of two input values 3 */ Language Elements 4 #include General Form 5

Operators & 6 int main(void) Expressions 7 { Formatting 8 inta,b;/* inputs I/O 9 integer sum;/* sum of inputs*/ Running 10 printf("Input the first number:%d",&A); Programs 11 printf("Input the second number:"); Common Pitfalls 12 scanf("%d",b); 13 a+b= sum; 14 printf("%d+%d=%d\n",a;b, sum); 15 return 0;

76 / 77 Exercise: Answer

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

77 / 77