Full Transcript

C How to Program Ninth Edition Chapter 2 Intro to C Programming Copyright © 2021 Pearson Education, Inc. All Rights Reserved Objectives Write simple C programs. Use simple input and output statements. Use the fundamental data types. Learn computer memory concepts. Use arithmetic operators. Learn the...

C How to Program Ninth Edition Chapter 2 Intro to C Programming Copyright © 2021 Pearson Education, Inc. All Rights Reserved Objectives Write simple C programs. Use simple input and output statements. Use the fundamental data types. Learn computer memory concepts. Use arithmetic operators. Learn the precedence of arithmetic operators. Write simple decision-making statements. Begin focusing on secure C programming practices. Copyright © 2021 Pearson Education, Inc. All Rights Reserved Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers Loading… 2.4 Memory Concepts 2.5 Arithmetic in C 2.6 Decision Making: Equality and Relational Operators 2.7 Secure C Programming Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.1 Introduction Introduce C programming Presents several examples illustrating fundamental C features Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (1 of 15) 1. // fig02_01.c 2. // A first program in C. 3. #include 4. Loading… 5. // function main begins program execution 6. int main(void) { 7. 8. printf("Welcome to C!\n"); } // end function main OUTPUT: – Welcome to C! Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (2 of 15) Comments Begin with // Insert comments to document programs and improve program readability Comments do not cause the computer to perform actions Help other people read and understand your program Can also use multi-line comments – Everything between is a comment Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (3 of 15) #include Preprocessor Directive #include C preprocessor directive Preprocessor handles lines beginning with # before compilation This directive includes the contents of the standard input/output header () – Contains information the compiler uses to ensure that you correctly use standard input/output library functions such as printf Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (4 of 15) Blank Lines and White Space Blank lines, space characters and tab characters make programs easier to read Together, these are known as white space Generally ignored by the compiler Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (5 of 15) The main Function Begins execution of every C program Parentheses after main indicate that main is a function C programs consist of functions, one of which must be main Precede every function by a comment stating its purpose Functions can return information The keyword int to the left of main indicates that main “returns” an integer (whole number) value – for now simply mimic this Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (6 of 15) The main Function Functions can receive information – void in parentheses means main does not receive any information A left brace, {, begins each function’s body A corresponding right brace, }, ends each function’s body A program terminates upon reaching main’s closing right brace The braces form a block Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (7 of 15) An Output Statement string of Characters printf("Welcome to C!\n"); – “f” in printf stands for “formatted” Loading… Performs an action—displays the string in the quotes Str – A string is also called a character string, a message or a literal The entire line is called a statement Every statement ends with a semicolon statement terminator - Characters usually print as they appear between – Notice the characters \n were not displayed. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (8 of 15) Escape Sequences In a string, backslash (\) is an escape character Compiler combines a backslash with the next character to form an escape sequence \n means newline When printf encounters a newline in a string, it positions the output cursor to the beginning of the next line Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (9 of 15) Escape Sequence be can \n \t blank 4 or on 8 the a : line Space or Description characters 2 depends Moves the cursor to the beginning of the next line. Moves the cursor to the next horizontal tab stop. system \a Produces a sound or visible alert without changing the current cursor position. \\ Because the backslash has special meaning in a string, \\ is required to insert a backslash character in a string. \” Because strings are enclosed in double quotes, \” is required to insert a double-quote character in a string. - Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (10 of 15) The Linker and Executables When compiling a printf statement, the compiler merely provides space in the object program for a “call” to the function The compiler does not know where the library functions are— the linker does When the linker runs, it locates the library functions and inserts the proper calls to these functions in the object program Now the object program is complete and ready to execute The linked program is called an executable Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (11 of 15) Indentation Conventions Indent the entire body of each function one level of indentation within the braces that define the function’s body Emphasizes a program’s functional structure and helps make them easier to read Set an indentation convention and uniformly apply that convention Style guides often recommend using spaces rather than tabs Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (12 of 15) Using Multiple printfs Fig. 2.2 uses two statements to produce the same output as Fig. 2.1 Works because each printf resumes printing where the previous one finished Line 7 displays Welcome followed by a space (but no newline) Line 8’s printf begins printing immediately following the space Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (13 of 15) 1. 2. 3. // fig02_02.c // Printing on one line with two printf statements. #include 4. 5. // function main begins program execution 6. int main(void) { 7. printf("Welcome "); 8. printf("to C!\n"); 9. } // end function main OUTPUT: – Welcome to C! Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (14 of 15) Displaying Multiple Lines with a Single printf One printf can display several lines Each \n moves the output cursor to the beginning of the next line Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.2 A Simple C Program: Printing a Line of Text (15 of 15) 1. // fig02_03.c 2. // Printing multiple lines with a single printf. 3. #include 4. 5. // function main begins program execution 6. int main(void) { 7. 8. printf("Welcome\nto\nC!\n"); } // end function main OUTPUT: Welcome to C! Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (1 of 16) scanf standard library function obtains information from the user at the keyboard Next program obtains two integers, then computes their sum and displays the result Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (2 of 16) 1. // fig02_04.c 2. // Addition program. 3. #include 4. // function main begins program execution 5. int main(void) { 6. int integer1 = 0; // will hold first number user enters 7. int integer2 = 0; // will hold second number user enters 8. 9. printf("Enter first integer: "); // prompt 10. scanf("%d", &integer1); // read an integer 11. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (3 of 16) 1. printf("Enter second integer: "); // prompt 2. scanf("%d", &integer2); // read an integer 3. 4. int sum = 0; // variable in which sum will be stored 5. sum = integer1 + integer2; // assign total to sum 6. 7. 8. you argument have to this it is to write that clarify sum. L printf("Sum is %d\n", sum); // print sum & a - } // end function main 2 types of Print functions 1 :. Print that takes 2 Print. that talles a I argument arguments Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (4 of 16) OUTPUT: Enter first integer: 45 Enter second integer: 72 Sum is 117 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (5 of 16) Variables and Variable Definitions Lines 7 and 8 are definitions. The names integer1 and integer2 are variables— locations in memory where the program can store values for later use integer1 and integer2 have type int—they’ll hold whole-number integer values Lines 7 and 8 initialize each variable to 0 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (6 of 16) Define Variables Before They Are Used All variables must be defined with a name and a type before they can be used in a program You can place each variable definition anywhere in main before that variable’s first use in the code In general, you should define variables close to their first use Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (7 of 16) Identifiers and Case Sensitivity A variable name can be any valid identifier Each identifier may consist of letters, digits and underscores (_), but may not begin with a digit C is case sensitive, so a1 and A1 are different identifiers A variable name should start with a lowercase letter Choosing meaningful variable names helps make a program selfdocumenting Multiple-word variable names can make programs more readable – separate the words with underscores, as in total_commissions, or – run the words together and begin each subsequent word with a capital letter as in totalCommissions. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (8 of 16) Prompting Messages Line 10 displays "Enter first integer: " This message is called a prompt – tells user to take a specific action Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (9 of 16) The scanf Function and Formatted Inputs Line 11 uses scanf to obtain a value from the user Reads from the standard input, usually the keyboard The "%d" is the format control string — indicates the type of data the user should enter (an integer) Second argument begins with an ampersand (&) followed by the variable name – Tells scanf the location (or address) in memory of the variable – scanf stores the value the user enters at that memory location Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (10 of 16) Prompting for and Inputting the Second Integer Line 13 prompts the user to enter the second integer Line 14 obtains a value for variable integer2 from the user. Loading… Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (11 of 16) Defining the sum Variable Line 16 defines the int variable sum and initializes it to 0 before we use sum in line 17. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (12 of 16) Assignment Statement The assignment statement in line 17 calculates the total of integer1 and integer2, then assigns the result to variable sum using the assignment operator (=) Read as, “sum gets the value of the expression integer1 + integer2.” Most calculations are performed in assignments Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (13 of 16) Binary Operators The = operator and the + operator are binary operators— each has two operands Place spaces on either side of a binary operator to make the operator stand out and make the program more readable Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (14 of 16) Printing with a Format Control String The format control string "Sum is %d\n" in line 19 contains some literal characters to display ("Sum is ") and the conversion specification %d, which is a placeholder for an integer The sum is the value to insert in place of %d Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (15 of 16) Combining a Variable Definition and Assignment Statement You can initialize a variable in its definition For example, lines 16 and 17 can add the variables integer1 and integer2, then initialize the variable sum with the result: – int sum = integer1 + integer2; // assign total to sum Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.3 Another Simple C Program: Adding Two Integers (16 of 16) Calculations in printf Statements Actually, we do not need the variable sum, because we can perform the calculation in the printf statement Lines 16–19 can be replaced with – printf("Sum is %d\n", integer1 + integer2); Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.4 Memory Concepts (1 of 3) Every variable has a name, a type, a value and a location in the computer’s memory After placing 45 in integer1 When a value is placed in a memory location, it replaces the location’s previous value which is lost Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.4 Memory Concepts (2 of 3) After placing 72 in integer2 These locations are not necessarily adjacent in memory. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.4 Memory Concepts (3 of 3) After calculating sum of integer1 and integer2 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (1 of 9) Binary arithmetic operators C operation Arithmetic operator Algebraic expression C expression Addition + f+7 f+7 Subtraction Minus p minus c p minus c Multiplication * bm b asterisk m Division / x slash y or start fraction x over y end fraction x forward slash y Remainder % r mod s r percent sign s Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (2 of 9) Integer Division and the Remainder Operator Integer division yields an integer result – – evaluates to 1 evaluates to 3 Integer-only remainder operator, %, yields the remainder after integer division – yields 3 – yields 2 An attempt to divide by zero usually is undefined – Generally, a fatal error – Nonfatal errors allow programs to run to completion, often with incorrect results Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (3 of 9) Parentheses for Grouping Subexpressions Parentheses are used in C expressions in the same manner as in algebraic expressions Rules of Operator Precedence Generally the same as in algebra – Expressions grouped in parentheses evaluate first ▪ In nested parentheses, operators in the innermost pair of parentheses are applied first – *, / and % are applied next left-to-right – + and are evaluated next left-to-right – The assignment operator (=) is evaluated last. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (4 of 9) Algebra: C: Parentheses are required above Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (5 of 9) Algebra: C: Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (6 of 9) Algebra: C: Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (7 of 9) Second degree polynomial Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (8 of 9) In the second-degree polynomial, suppose a = 2, b = 3, c = 7 and x = 5 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.5 Arithmetic in C (9 of 9) Using Parentheses for Clarity Redundant parentheses can make an expression clearer – Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (1 of 13) Executable statements perform actions like calculations, input and output, or make decisions A condition is an expression that can be true or false This section introduces the if statement – Makes a decision based on a condition’s value – If true, the statement in the if statement’s body executes – Otherwise, it does not Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (2 of 13) Equality and Relational Operators Conditions are formed using the equality and relational operators Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (3 of 13) Relational operators Algebraic equality or relational operator C equality or relational operator Sample C condition Meaning of C condition > > x>y x is greater than y < < x number2) { printf("%d is greater than %d\n", number1, number2); } // end if 4. 5. 6. 7. if (number1 = number2) { printf("%d is greater than or equal to %d\n", number1, number2); } // end if } // end function main Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (8 of 13) OUTPUT 1: Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (9 of 13) OUTPUT 2: Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (10 of 13) OUTPUT 3: Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7 Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (11 of 13) Comparing Numbers Lines 16–18 compare number1’s and number2’s values for equality If the values are equal, line 17 displays a line of text indicating that Indenting each if statement’s body and placing blank lines above and below each if statement enhances program readability { begins the body of each if statement } ends each if statement’s body Any number of statements can be placed in an if statement’s body. Placing a semicolon immediately to the right of the right parenthesis after an if statement’s condition is a common error – The semicolon is treated as an empty statement that does not perform a task Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (12 of 13) Keywords Some words, such as int, if and void, are keywords or reserved words of the language and have special meaning to the compiler The following table contains the C keywords Do not use them as identifiers Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.6 Decision Making: Equality and Relational Operators (13 of 13) Keywords auto do goto signed unsigned break double if sizeof void case else int static volatile char enum long struct while const extern register switch continue float return typedef default for short union Keywords added in the C99 standard _Bool _Complex _Imaginary inline restrict Keywords added in the C11 standard _Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.7 Secure C Programming (1 of 2) Avoid Single-Argument printfs printf’s first argument is a format string, which it inspects for conversion specifications It then replaces each conversion specification with a subsequent argument’s value It tries to do this regardless of whether there is a subsequent argument to use Though the first printf argument typically is a string literal, it could be a variable containing a string that was input from a user In such cases, an attacker can craft a user-input format string with more conversion specifications than there are additional printf arguments. This exploit has been used by attackers to read memory that they should not be able to access. Copyright © 2021 Pearson Education, Inc. All Rights Reserved 2.7 Secure C Programming (2 of 2) Preventative measures – Use puts to output a string with a terminating \n – To display a string without a terminating newline character, use printf with two arguments—a "%s" format control string and the string to display. Copyright © 2021 Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials. Copyright © 2021 Pearson Education, Inc. All Rights Reserved