The C Programming - Lecture 24

Run Time Errors These errors occur during the execution of the programs though the program is free from syntax and logical errors. Some of the most common reasons for these errors are When you instruct your computer to divide a number by zero. When you instruct your computer to find logarithm of a negative number. When you instruct your computer to find the square root of a negative integer. Summary High level language is converted into computer understandable by a compiler. Compiler converts source code into computer understandable code C Programming is a way to program computers It has a syntax It has commands and structure C can not be learnt! It can be understood by implementing it!

ppt90 trang | Chia sẻ: thucuc2301 | Lượt xem: 590 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu The C Programming - Lecture 24, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
The C Programming Lecture 24Summary of Previous LectureProgramming in real life.IntroductionWhat is Problem Solving?Problem Solving process.AlgorithmHistoryWorking DefinitionExamplesAlgorithms to ProgramsSummary of Previous LectureComponents of AlgorithmsVariables and valuesInstructionsSequencesProceduresSelectionsRepetitionsDocumentationSoftware Development ProcessTop Down Algorithm DesignToday’s LectureAlgorithms and ProgramsA C programming languageHistory of CC, A High level languageHow to get started with C.Basic Structure of a C programData Storage and Data TypesVariables, Keywords, identifiers, AssignmentToday’s Lectureconstant variableprintf() and scanf() functions and usagePrecedence int and floatUnary operationsIncrement and decrement operationsToday’s LectureCommentsError and its TypesSummaryFrom Algorithms to ProgramsBoth are sets of instructions on how to do a taskAlgorithm: talking to humans, easy to understandin plain (English) languageProgram:talking to computer (compiler)can be regarded as a “formal expression” of an algorithmA C Programming LanguageFlexible language:Structured languageLow level activities possibleIt can produce lean and efficient codeWide availability on a variety of computersWidely used!History of CCPL Combined Programming Language (Barron et al., 1963)BCPL Basic CPL (Richards, 1969)B (Thompson, 1970)C K&R C (Ritchie, 1972)ANSI C American National Standards Institute C (X3J11, 1989)C99 (JTC1/SC22/WG14, ISO/IEC 9899, 1999)A High-Level LanguageCompilers and linkers translate a high level program into executable machine code.#include int main(){ printf(“Hello World”); return 0;}Source codeExecutable code 10100110 0111011000100110 0000000011111010 1111101001001110 1010011011100110 1001011011001110 0010111010100110 0100111011111010 0110011001001110 10000110etc...How to get started?Download Turbo C++ Version 3.0 a free software. it!Follow the step by step guide for your first program!Turbo C++ IDE Version 3Click New to open a program windowOpen a new window for writing a programOutput Message windowSet the Directories in Option MenuSet the output directory pathWrite your first program hereWrite your program here!Compile to find errorsCompile to check errorsNo Errors FoundExecute the program by Run optionRUN to executeSee output by pressing Ctrl+F5 Output of your first programBasic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: Pre Processor Directive include file in this program! stdio.h contains declaration of printf used in the programExample: Hello World Basic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: Program control is started from the main function. Example: Hello World Main Function = Main GateYou can enter the premises of the building through main gate! Similarly program control is entered through main function..!Basic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: int indicates that only an integer value can come out of this functionExample: Hello World Basic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: Curly braces mark the beginning and end of a block of instructions.Example: Hello World Basic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: Instruction (function call) to output “Hello World”. This will print Hello World on the output screenExample: Hello World Basic Structure of a C Program#include int main(){ printf(“Hello World”); return 0;}C Program: “Statements” (lines of instructions) always end with a semi-colon (;)Example: Hello World Where to store data?A data type is a representation of data that defines a size and valid range for data.Built-in types: char, int, floatType modifiers: long, short, constUser-defined types (arrays and records)What about “strings”?Strings are arrays of char (discussed later)Character RepresentationCharacters are stored as a small integerEach character has a unique integer equivalent specified by its position in the ASCII table (pronounced “as-key”)American Standard Code for Information InterchangeCharacter RepresentationThe ASCII values range from 0 to 127value 0: special character ’\0’ (a.k.a. NUL character)value 127: special character other special characters: ’\n’ ’\t’ ’\’’ ’\\’ etc.various “extended” sets from 128 to 255Remember: Variables This jarcan contain 10 cookies50 grams of sugar 3 slices of cakeetc.ValuesVariable Are containers for values – places to store values Example:VariableIs a logical name for a container (an actual piece of computer memory for values)Has a type associated with ittells the computer how to interpret the bitsMust be declared before use:int i; float result;int i=0; char initial=’K’;Variable Declaration: Examplesint myID;myIDVariableVariable Declaration: Examplesint myID;char myInitial = ’J’;Single “forward quotes” or apostrophe (’) rather than “back quotes” (‘)Variable Declaration: Examplesint myID;char myInitial = ’J’;01001010myInitialVariable Declaration: Examplesint myID;char myInitial = ’J’;char myInitial = 74 ;01001010myInitialVariable Declaration: Examplesfloat commission = 0.05;short int myHeight = 183; /* cm */long int mySalary = 100000000000000000000;long float chanceOfADate = 3e-500;double chanceOfA2ndDate = 1.5e-500;float commission = 0.05;short int myHeight = 183; /* cm */long int mySalary = 100000000000000000000;long float chanceOfADate = 3e-500;double chance_of_a_2nd_date = 1.5e-500;Variable Declaration: Examples“Keywords”Keyword...has a special meaning in C...is “case-sensitive”...cannot be used as variable namesExamples:int, char, long, main, float, double, const, while, for, if, else, return, break, case, switch, default, typedef, struct, etc. Variable Declaration: Examplesfloat commission = 0.05;short int myHeight = 183; /* cm */long int mySalary = 100000000000000000000;long float chanceOfADate = 3e-500;double chanceOfA2ndDate = 1.5e-500;“Identifiers”Identifier...is a series of characters consisting of letters, digits and underscores ( _) ...cannot begin with a digit...must not be a keyword...is “case-sensitive”Examples:sUmoFA, x1, y2, _my_ID_, Main (careful!)AssignmentPuts a specified value into a specified variableAssignment operator: = = ;not to be confused with ==Assignment: Examplesfloat x = 2.5 ;char ch ;int number ;ch = ’\n’ ;number = 4 + 5 ;/* current value of number is 9. */ number = number * 2;/* current value of number is now 18. */ AssignmentValue must have a type assignable to the variableValue may be automatically converted to fit the new containerExample:various.c#include /* Do various assignment statements */int main(){ int integer; char character; float floatingPoint; integer = 33; character = 33; floatingPoint = 33; integer = 'A'; character = 'A'; floatingPoint = 'A'; integer = 33.33; character = 33.33; floatingPoint = 33.33; integer = floatingPoint; floatingPoint = integer; return 0;} various.cConstant Variables...are variables that don’t vary...may not be assigned to....must be initializedconst float Pi = 3.14159;const int classSize = 100;Constant Variables: Examplesconst int myID = 192;myID = 666; /* Error! */const int passMark = 80;short char pAsSgRaDe = ’P’;const float pi = 3.1415926; /* oops */const double golden_ratio = 1.61803398874989;Converts an angle from degrees to radiansoutput “Enter angle in degrees”input angleInDegreesangleInRadians =  / 180 * angleInDegreesoutput angleInRadians#include /* Converts an angle in degrees to radians. */const float PI = 3.1415926;int main(){ float angleInDegs; float angleInRads; printf("Enter angle in degrees:"); scanf("%f", &angleInDegs); angleInRads = PI/180*angleInDegs; printf("%f\n", angleInRads); return 0;}Example: Constants Example: Constants “Global” constant variable“Local” variablesmore on this later...#include /* Converts an angle in degrees to radians. */const float PI = 3.1415926;int main(){ float angleInDegs; float angleInRads; printf("Enter angle in degrees: "); scanf("%f", &angleInDegs); angleInRads = PI/180*angleInDegs; printf("%f\n", angleInRads); return 0;}Example: Constants Print text on the screenscanf function gets values from user#include /* Converts an angle in degrees to radians. */const float PI = 3.1415926;int main(){ float angleInDegs; float angleInRads; printf("Enter angle in degrees: "); scanf("%f", &angleInDegs); angleInRads = PI/180*angleInDegs; printf("%f\n", angleInRads); return 0;}Example: Constants Result will be stored in angleInRads #include /* Converts an angle in degrees to radians. */const float PI = 3.1415926;int main(){ float angleInDegs; float angleInRads; printf("Enter angle in degrees: "); scanf("%f", &angleInDegs); angleInRads = PI/180*angleInDegs; printf("%f\n", angleInRads); return 0;}Example: Constants Will be printed on the screen#include /* Converts an angle in degrees to radians. */const float PI = 3.1415926;int main(){ float angleInDegs; float angleInRads; printf("Enter angle in degrees: "); scanf("%f", &angleInDegs); angleInRads = PI/180*angleInDegs; printf("%f\n", angleInRads); return 0;}printf() functionIn order to use printf(), function you need to include as #includeTo print an integer %d is used in printfFor exampleThis will print 9 on the output screenprintf() functionTo print a string on the screen %s is used in printf or simply type words with printf.For exampleThis will print Hello world! This is 9printf() functionTo print a floating point number %f is usedFor exampleThis will print 9.200000 on the screenprintf() functionFloating point with 2 digit precision, use %0.2f For exampleThis will print 9.20 on the screenscanf functionSame include directive is used,#includeUsed to get a value from user at run time.For example scanf(“%d”, &i);Will get an integer value in the variable i.Can get character, floating or integer value from the user.scanf exampleAsk user to enter a valuescans the valuePrints the user input value on the screenOutput of previous programWe have coveredTypeVariablesKeyword and IdentifiersAssignmentsConstant VariablesPrecedence in ExpressionsDefines the order in which an expression is evaluatedPrecedence in Expressions -- Example1 + 2 * 3 - 4 / 5 =B stands for brackets, O for Order (exponents), D for division, M for multiplication, A for addition, and S for subtraction.B.O.D.M.A.S.1 + (2 * 3) - (4 / 5) More on precedence*, /, % are at the same level of precedence +, - are at the same level of precedence For operators at the same “level”, left-to-right ordering is applied.2 + 3 – 1 = (2 + 3) – 1 = 42 – 3 + 1 = (2 – 3) + 1 = 02 * 3 / 4 = (2 * 3) / 4 = 6 / 42 / 3 * 4 = (2 / 3) * 4 = 0 * 4Precedence in Expressions – Example6.21 + 2 * 3 - 4 / 5 =1 + (2 * 3) - (4 / 5) Precedence in Expressions –Example..6.21 + 2 * 3 - 4 / 5 =1 + (2 * 3) - (4 / 5) Precedence in Expressions – Example..Integer division results in integer quotient1 + 2 * 3 - 4 / 5 =1 + (2 * 3) - (4 / 5) Precedence in Expressions – Example= 0D’oh1 + 2 * 3 - 4 / 5 =1 + (2 * 3) - (4 / 5) Precedence in Expressions ..71 + 2 * 3 - 4 / 5 =1 + (2 * 3) - (4 / 5) int and floatfloat is a “communicable” typeExample:1 + 2 * 3 - 4.0 / 5= 1 + (2 * 3) - (4.0 / 5)= 1 + 6 - 0.8= 6.2All integers are in Blackint and float – Example 2(1 + 2) * (3 - 4) / 5= ((1 + 2) * (3 - 4)) / 5= (3 * -1) / 5= -3 / 5= 0int and float – Example 2(1 + 2.0) * (3 - 4) / 5= ((1 + 2.0) * (3 - 4)) / 5= (3.0 * -1) / 5= -3.0 / 5= -0.6int and float – Example 3(1 + 2.0) * ((3 - 4) / 5) = (1 + 2.0) * (-1 / 5)= 3.0 * 0= 0.0Unary operatorsCalled unary because they require one operand.Example i = +1; /* + used as a unary operator */ j = -i; /* - used as a unary operator */The unary + operator does nothing, just emphasis that a numeric constant is positive.The unary – operator produces the negative of its operand.i=+1 is equal to i=i+1Increment and decrement operators++ is the increment operator i++;is equivalent to i = i + 1;-- is the decrement operator j--;is equivalent to j = j - 1;Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include /* Evaluate an expression */ Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include /* Evaluate an expression */ int main(){ return 0;}Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include /* Evaluate an expression */ int main(){ float result; return 0;}Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include /* Evaluate an expression */ int main(){ float result; result = 1 + 2 * 3 - 4 / 5; return 0;}Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output result#include /* Evaluate an expression */ int main(){ float result; result = 1 + 2 * 3 - 4 / 5; printf(“%f\n”, result); return 0;}Example -- Simple Expressions Evaluate an expressionset result to 1 + 2 * 3 - 4 / 5output resultOutput: 7.000000#include /* Evaluate an expression */ int main(){ float result; result = 1 + 2 * 3 - 4 / 5; printf(“%f\n”, result); return 0;}Example -- Simple Expressions CommentsEssential for documenting programsRun from a /* to the next */Examples:/* THIS IS A COMMENT *//* So is this *//*** ...and this.***/Comments ..Comments do not “nest”/* Comments start with a “/*” and end with a “*/” but they don’t nest! */Errors in C ProgramDo not get Fear of an Error!All good programmers started with lot of ErrorsUnderstand them and remove them!Types of ErrorsIn c program you may getSyntax errorLogical errorRun time errorsSyntax ErrorThese errors occur because of wrongly typed statements, which are not according to the syntax or grammatical rules of the language. For example, in C, if you don’t place a semi-colon after the statement (as shown below), it results in a syntax error. printf(“Hello,world”) Logical ErrorThese errors occur because of logically incorrect instructions in the program. Let us assume that in a 1000 line program, if there should be an instruction, which multiplies two numbers and is wrongly written to perform addition. This logically incorrect instruction may produce wrong results. Detecting such errors are difficult! Run Time ErrorsThese errors occur during the execution of the programs though the program is free from syntax and logical errors. Some of the most common reasons for these errors areWhen you instruct your computer to divide a number by zero. When you instruct your computer to find logarithm of a negative number. When you instruct your computer to find the square root of a negative integer. SummaryHigh level language is converted into computer understandable by a compiler.Compiler converts source code into computer understandable codeC Programming is a way to program computersIt has a syntaxIt has commands and structureC can not be learnt! It can be understood by implementing it!

Các file đính kèm theo tài liệu này:

  • pptlecture_24_199_2027002.ppt
Tài liệu liên quan