《高级语言程序设计cha.ppt》由会员分享,可在线阅读,更多相关《高级语言程序设计cha.ppt(76页珍藏版)》请在三一办公上搜索。
1、A First Book of ANSI CFourth Edition,Chapter 2Getting Started in C Programming,A First Book of ANSI C,Fourth Edition,2,Objectives,Introduction to C ProgrammingProgramming StyleData TypesArithmetic Operations,A First Book of ANSI C,Fourth Edition,3,Objectives(continued),Variables and DeclarationsCase
2、 Study:Temperature ConversionCommon Programming and Compiler Errors,A First Book of ANSI C,Fourth Edition,4,Introduction to C Programming,A First Book of ANSI C,Fourth Edition,5,Introduction to C Programming(continued),C provides a comprehensive set of functionsStored in a set of files known as the
3、standard libraryThe standard library consists of 15 header files,A First Book of ANSI C,Fourth Edition,6,Introduction to C Programming(continued),A First Book of ANSI C,Fourth Edition,7,Introduction to C Programming(continued),A First Book of ANSI C,Fourth Edition,8,Identifiers,Identifiers in C cons
4、ist of three types:Reserved wordsStandard identifiersProgrammer-created identifiers,A First Book of ANSI C,Fourth Edition,9,Identifiers(continued),Reserved word:word that is predefined by the programming language for a special purpose and can only be used in a specified manner for its intended purpo
5、seAlso referred to as keywords in C,A First Book of ANSI C,Fourth Edition,10,Identifiers(continued),A First Book of ANSI C,Fourth Edition,11,Identifiers(continued),Standard identifiers:words predefined in CMost of the standard identifiers are the names of functions that are provided in the C standar
6、d libraryIt is good programming practice to use standard identifiers only for their intended purpose,A First Book of ANSI C,Fourth Edition,12,Identifiers(continued),A First Book of ANSI C,Fourth Edition,13,Identifiers(continued),Programmer-created identifiers:selected by the programmerAlso called pr
7、ogrammer-created names Used for naming data and functionsMust conform to Cs identifier rulesCan be any combination of letters,digits,or underscores(_)subject to the following rules:First character must be a letter or underscore(_)Only letters,digits,or underscores may follow the initial characterBla
8、nk spaces are not allowedCannot be a reserved word,A First Book of ANSI C,Fourth Edition,14,Identifiers(continued),Examples of invalid C programmer-created names:4ab7calculate totalwhileAll uppercase letters used to indicate a constantA function name must be followed by parentheses An identifier sho
9、uld be descriptive:degToRadians()Bad identifier choices:easy,duh,justDoIt C is a case-sensitive languageTOTAL,and total represent different identifiers,A First Book of ANSI C,Fourth Edition,15,The main()Function,A First Book of ANSI C,Fourth Edition,16,The main()Function(continued),Function header l
10、ine,Executable statements,A First Book of ANSI C,Fourth Edition,17,The printf()Function,printf()formats data and sends it to the standard system display device(i.e.,the monitor)Inputting data or messages to a function is called passing data to the functionprintf(Hello there world!);Syntax:set of rul
11、es for formulating statements that are“grammatically correct”for the languageMessages are known as strings in CA string of characters is surrounded by double quotesprintf(Hello there world!);,A First Book of ANSI C,Fourth Edition,18,The printf()Function(continued),Function arguments,A First Book of
12、ANSI C,Fourth Edition,19,The printf()Function(continued),Comment,Preprocessor command,Header file,Invoking or calling the printf()function,A First Book of ANSI C,Fourth Edition,20,The printf()Function(continued),Output is:Computers,computers everywhereas far as I can C,Newline escape sequence,A Firs
13、t Book of ANSI C,Fourth Edition,21,Programming Style:Indentation,Except for strings,function names,and reserved words,C ignores all white spaceWhite space:any combination of one or more blank spaces,tabs,or new linesIn standard form:A function name is placed,with the parentheses,on a line by itself
14、starting at the left-hand cornerThe opening brace follows on the next line,under the first letter of the function nameThe closing function brace is placed by itself at the start of the last line of the function,A First Book of ANSI C,Fourth Edition,22,Programming Style:Indentation(continued),Within
15、the function itself,all program statements are indented two spacesIndentation is another sign of good programming practice,especially if the same indentation is used for similar groups of statementsDont do this:intmain()printf(Hello there world!);return 0;,A First Book of ANSI C,Fourth Edition,23,Pr
16、ogramming Style:Comments,Comments help clarify what a program does,what a group of statements is meant to accomplish,etc.The symbols/*,with no white space between them,designate the start of a comment;the symbols*/designate the end of a comment/*this is a comment*/Comments can be placed anywhere wit
17、hin a program and have no effect on program executionUnder no circumstances may comments be nested/*this comment is/*always*/invalid*/,A First Book of ANSI C,Fourth Edition,24,Programming Style:Comments(continued),A First Book of ANSI C,Fourth Edition,25,Data Types,Data type:set of values and a set
18、of operations that can be applied to these valuesBuilt-in data type:is provided as an integral part of the language;also known as primitive type,A First Book of ANSI C,Fourth Edition,26,Data Types(continued),A First Book of ANSI C,Fourth Edition,27,Data Types(continued),A literal is an acceptable va
19、lue for a data typeAlso called a literal value or constant2,3.6,8.2,and Hello World!are literal values because they literally display their values,A First Book of ANSI C,Fourth Edition,28,Data Types(continued),A First Book of ANSI C,Fourth Edition,29,Integer Data Types,A First Book of ANSI C,Fourth
20、Edition,30,Integer Data Types(continued),int:whole numbers(integers)For example:0,-10,253,-26351Not allowed:commas,decimal points,special symbolschar:stores individual characters(ASCII)For example:A,$,b,!,A First Book of ANSI C,Fourth Edition,31,Integer Data Types(continued),A First Book of ANSI C,F
21、ourth Edition,32,Integer Data Types(continued),A First Book of ANSI C,Fourth Edition,33,Integer Data Types(continued),A First Book of ANSI C,Fourth Edition,34,Floating-Point Data Types,A floating-point value(real number)can be the number zero or any positive or negative number that contains a decima
22、l pointFor example:+10.625,5.,-6.2,3251.92,+2Not allowed:commas,decimal points,special symbolsfloat:single-precision numberdouble:double-precision numberStorage allocation for each data type depends on the compiler(use sizeof(),A First Book of ANSI C,Fourth Edition,35,Floating-Point Data Types(conti
23、nued),float literal is indicated by appending an f or Flong double is created by appending an l or L9.234 indicates a double literal9.234f indicates a float literal9.234L indicates a long double literal,A First Book of ANSI C,Fourth Edition,36,Floating-Point Data Types(continued),A First Book of ANS
24、I C,Fourth Edition,37,Exponential Notation,In numerical theory,the term precision typically refers to numerical accuracy,A First Book of ANSI C,Fourth Edition,38,Exponential Notation(continued),A First Book of ANSI C,Fourth Edition,39,Arithmetic Operations,Arithmetic operators:operators used for ari
25、thmetic operations:Addition+Subtraction-Multiplication*Division/Modulus Division%Binary operators require two operandsAn operand can be either a literal value or an identifier that has a value associated with it,A First Book of ANSI C,Fourth Edition,40,Arithmetic Operations(continued),A simple binar
26、y arithmetic expression consists of a binary arithmetic operator connecting two literal values in the form:literalValue operator literalValue3+712.62-9.8.08*12.212.6/2.Spaces around arithmetic operators are inserted for clarity and can be omitted without affecting the value of the expression,A First
27、 Book of ANSI C,Fourth Edition,41,Displaying Numerical Values,Arguments are separated with commasprintf(The total of 6 and 15 is%d,6+15);First argument of printf()must be a stringA string that includes a conversion control sequence,such as%d,is termed a control stringConversion control sequences are
28、 also called conversion specifications and format specifiersprintf()replaces a format specifier in its control string with the value of the next argumentIn this case,21,A First Book of ANSI C,Fourth Edition,42,Displaying Numerical Values(continued),printf(The total of 6 and 15 is%d,6+15);The total o
29、f 6 and 15 is 21printf(The sum of%f and%f is%f,12.2,15.754,12.2+15.754);The sum of 12.200000 and 15.754000 is 27.954000,A First Book of ANSI C,Fourth Edition,43,Displaying Numerical Values(continued),A First Book of ANSI C,Fourth Edition,44,Displaying Numerical Values(continued),A First Book of ANSI
30、 C,Fourth Edition,45,Displaying Numerical Values(continued),A First Book of ANSI C,Fourth Edition,46,Expression Types,Expression:any combination of operators and operands that can be evaluated to yield a valueInteger expression:contains only integer operands;the result is an integerFloating-point ex
31、pression:contains only floating-point operands;the result is a double-precisionIn a mixed-mode expression the data type of each operation is determined by the following rules:If both operands are integers,result is an integerIf one operand is real,result is double-precision,A First Book of ANSI C,Fo
32、urth Edition,47,Integer Division,15/2=7Integers cannot contain a fractional partRemainder is truncated%is the modulus or remainder operator9%4 is 117%3 is 214%2 is 0,A First Book of ANSI C,Fourth Edition,48,Negation,A unary operator is one that operates on a single operand,e.g.,negation(-)The minus
33、sign in front of a single numerical value negates(reverses the sign of)the number,A First Book of ANSI C,Fourth Edition,49,Negation(continued),A First Book of ANSI C,Fourth Edition,50,Operator Precedence and Associativity,Two binary arithmetic operator symbols must never be placed side by sideParent
34、heses may be used to form groupingsExpressions in parentheses are evaluated firstParentheses may be enclosed by other parenthesesParentheses cannot be used to indicate multiplication,A First Book of ANSI C,Fourth Edition,51,Operator Precedence and Associativity(continued),Three levels of precedence:
35、All negations are done firstMultiplication,division,and modulus operations are computed next;expressions containing more than one of these operators are evaluated from left to right as each operator is encounteredAddition and subtraction are computed last;expressions containing more than one additio
36、n or subtraction are evaluated from left to right as each operator is encountered,A First Book of ANSI C,Fourth Edition,52,Operator Precedence and Associativity(continued),Example:8+5*7%2*4=8+35%2*4=8+1*4=8+4=12,A First Book of ANSI C,Fourth Edition,53,Operator Precedence and Associativity(continued
37、),A First Book of ANSI C,Fourth Edition,54,Variables and Declarations,Variables are names given by programmers to computer storageVariable name usually limited to 255 charactersVariable names are case sensitive,A First Book of ANSI C,Fourth Edition,55,Variables and Declarations(continued),A First Bo
38、ok of ANSI C,Fourth Edition,56,Variables and Declarations(continued),num1=45;num2=12;total=num1+num2;,Assignment statements,A First Book of ANSI C,Fourth Edition,57,Variables and Declarations(continued),A First Book of ANSI C,Fourth Edition,58,Declaration Statements,Naming and specifying the data ty
39、pe that can be stored in each variable is accomplished using declaration statementsDeclaration statements within a function appear immediately after the opening brace of a functionfunction name()declaration statements;other statements;Definition statements define or tell the compiler how much memory
40、 is needed for data storage,A First Book of ANSI C,Fourth Edition,59,Declaration Statements(continued),A First Book of ANSI C,Fourth Edition,60,Declaration Statements(continued),A First Book of ANSI C,Fourth Edition,61,Declaration Statements(continued),A First Book of ANSI C,Fourth Edition,62,Declar
41、ation Statements(continued),A First Book of ANSI C,Fourth Edition,63,Declaration Statements(continued),You can omit the f and let the compiler convert the double precision value into a float value when the assignment is made,A First Book of ANSI C,Fourth Edition,64,Selecting Variable Names,Make vari
42、able names descriptiveLimit variable names to approximately 20 charactersStart the variable name with a letter,rather than an underscore(_)In a variable name consisting of several words,capitalize the first letter of each word after the first,A First Book of ANSI C,Fourth Edition,65,Selecting Variab
43、le Names(continued),Use variable names that indicate what the variable corresponds to,rather than how it is computedAdd qualifiers,such as Avg,Min,Max,and Sum to complete a variables name where appropriateUse single-letter variable names,such as i,j,and k,for loop indexes,A First Book of ANSI C,Four
44、th Edition,66,Initialization,Declaration statements can be used to store an initial value into declared variablesint numOne=15;When a declaration statement provides an initial value,the variable is said to be initializedLiterals,expressions using only literals such as 87.0+12 2,and expressions using
45、 literals and previously initialized variables can all be used as initializers within a declaration statement,A First Book of ANSI C,Fourth Edition,67,Case Study:Temperature Conversion,A friend of yours is going to Spain,where temperatures are reported using the Celsius temperature scale.She has ask
46、ed you to provide her with a list of temperatures in degrees Fahrenheit,and the equivalent temperature in degrees Celsius.The formula relating the two temperatures is Celsius=5/9(Fahrenheit 32).Initially,you are to write and test a program that correctly converts the Fahrenheit temperature of 75 deg
47、rees into its Celsius equivalent.,A First Book of ANSI C,Fourth Edition,68,Case Study:Temperature Conversion(continued),A First Book of ANSI C,Fourth Edition,69,Common Programming Errors,Omitting the parentheses,(),after mainOmitting or incorrectly typing the opening brace,that signifies the start o
48、f a function bodyOmitting or incorrectly typing the closing brace,that signifies the end of a functionMisspelling the name of a function;for example,typing print()instead of printf()Forgetting to close a string passed to printf()with a double quote symbol,A First Book of ANSI C,Fourth Edition,70,Com
49、mon Programming Errors(continued),Omitting the semicolon at the end of each executable statementForgetting to include n to indicate a new lineForgetting to declare all the variables used in a programStoring an incorrect data type in a declared variableUsing a variable in an expression before a value
50、 has been assigned to the variable,A First Book of ANSI C,Fourth Edition,71,Common Programming Errors(continued),Dividing integer values incorrectlyMixing data types in the same expression without clearly understanding the effect producedNot including the correct conversion control sequence in print