1 / 77

Pengantar C/C++

Pengantar C/C++. Outline. C overview C language elements Variable declarations and data types Executable statements General form of a C program Arithmetic expressions. C overview. C is a high-level programming language Developed in 1972 By Dennis Ritchie at AT&T Bell Laboratories

lara-mays
Download Presentation

Pengantar C/C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pengantar C/C++

  2. Outline • C overview • C language elements • Variable declarations and data types • Executable statements • General form of a C program • Arithmetic expressions

  3. C overview • C is a high-level programming language • Developed in 1972 • By Dennis Ritchie at AT&T Bell Laboratories • From two previous programming languages, BCPL and B • Used to develop UNIX • Used to write modern operating systems • Hardware independent (portable) • By late 1970s C had evolved to “Traditional C”

  4. C overview (cont.) • Standardization • Many slight variations of C existed, and were incompatible • Committee formed to create a “unambiguous, machine-independent” definition • Standard created in 1989, updated in 1999

  5. C language elements • Preprocessor • A system program that modifies a C program prior to its compilation • Preprocessor directive • A C program line beginning with # that provides an instruction to the preprocessor • Library • A collection of useful functions and symbols that may be accessed by a program

  6. C language elements (cont.) • Constant macro • A name that is replaced by a particular constant value before the program is sent to the compiler • Comment • Text beginning with /* and ending with */ that provides supplementary information but is ignored by the preprocessor and compiler

  7. C language elements (cont.) /* * Converts distance in miles to kilometers */ #include <stdio.h> /* printf, scanf definitions */ #define KMS_PER_MILE 1.609 /* conversion constant */ int main(void) { double miles, /* input – distance in miles */ kms; /* output – distance in kilometers */ /* Get the distance in miles */ printf(“Enter the distance in miles> ”); scanf(”%lf”, &miles); /* Convert the distance to kilometers */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers */ printf(“That equals %f kilometers.\n”, kms); return (0); } standard header file comment preprocessor directive constant reserved word comment standard identifier special symbol reserved word punctuation special symbol

  8. C language elements (cont.) • Function main int main(void) • Declarations • A part of a program that tell the compiler the names of memory cells in a program • Executable statements • Program lines that are converted to machine language instructions and executed by the computer • Reserved word • A word that has special meaning in C

  9. C language elements (cont.)

  10. C language elements (cont.) • Standard identifier • A word having special meaning but one that a programmer may redefine (but redefinition is not recommended!) • Example: • printf • scanf

  11. C language elements (cont.)

  12. C language elements (cont.) • User-defined identifiers • An identifier must consist only of letters, digits, and underscores • An identifier cannot begin with a digit • A C reserved word cannot be used as an identifier • An identifier defined in a C standard library should not be redefined • Examples: letter_1, letter_2, inches, cent, CENT_PER_INCH, Hello, variable • Only first 31 characters taking into account

  13. C language elements (cont.) per_capita_meat_consumption_in_1980 per_capita_meat_consumption_in_1995 • The two identifiers would be viewed as identical by a C compiler • C compiler considers uppercase and lowercase usage significantly different

  14. C language elements (cont.) • Program style • “looks good” is easier to read and understand • Programmers spend considerably more time on program maintenance (updating, modifying) than they do on its original design or coding • Meaningful name for a user-defined identifier  easy to understand • salary to store a person’s salary THANs or bagel • If more than 2 or more words, the underscore character (_) will be better  dollars_per_hourTHANdollarsperhour

  15. C language elements (cont.) • Choose identifiers long enough to convey the meaning, but not too long • lbs_per_sq_inTHANpounds_per_square_inch • Don’t choose names that are similar to each other • Avoid selecting 2 names that are different only in their use of uppercase and lowercase letters, such as LARGE and large • Not to user 2 names that differ only in the presence or absence of an underscore, such as xcoord and x_coord

  16. Variable declarationsand data types • Variable • A name associated with a memory cell whose value can change • Variable declarations • Statements that communicate to the compiler the names of variables in the program and the kind of information stored in each variable • Data types • A set of values and operations that can be performed on those values

  17. Data type int • In mathematics, integers are whole numbers • The int data type is used to represent integers in C • ANSI C specifies the range: -32767 to 32767 • int can be used in arithmetic operations: add, subtract, multiply, and divide; also in comparing two integers • Examples: -10500, 435, +15, 125, 32767

  18. Data type double • It used to represent real numbers • Examples: 3.14159, 0.0005, 150.0 • double can be used in arithmetic operations: add, subtract, multiply, and divide; also in comparing them • Scientific notation can be used for very large or very small values • Example: 1.23E5 = 1.23e5 = 1.23  105 • So, in C scientific notation we read the letter e or E as “times 10 to the power” • If the exponent is positive it means “move the decimal point <the value> places to the right” • If the exponent is negative it means “move the decimal point <the value> places to the left”

  19. Data type double (cont.)

  20. Data type double (cont.) • Data type double is an abstraction for the real numbers because it does not include them all • Some real numbers are too large or too small, and some real numbers cannot be represented precisely because of the finite size of a memory cell

  21. Data type char • It used to represent an individual character value - a letter, a digit, or a special symbol • Each type char value is enclosed in apostrophes (single quotes) • Examples: ‘A’ ‘z’ ‘2’ ‘9’ ‘*’ ‘:’ ‘”’ ‘ ‘ • You can store a character in a type char variable and compare character data. • C allows you to perform arithmetic operations on type char data, but is has to be care

  22. Executable statements • Programs in memory Before execution After execution of a Program of a Program memory memory machine language miles-to-kms conversion program machine language miles-to-kms conversion program miles miles ? 10.00 kms kms ? 16.09

  23. Assignment statements • Instruction that stores a value or a computational result in a variable • Example: kms = KMS_PER_MILE * miles; • In C the symbol = is the assignment operator. Read is as “becomes,” “gets,” or “takes the value of” rather than “equals” because it is not equivalent to the “equal sign” of mathematics.

  24. Assignment statements (cont.) kms = KMS_PER_MILE * miles;

  25. Assignment statements (cont.) sum = sum + item;

  26. Assignment statements (cont.) • If x and new_x are type double variables, the statement new_x = x; copies the value of variable x into variable new_x. The statement new_x = -x; instructs the computer to get the value of x, negate that value, and store the result in new_x

  27. Input/Outputoperations and functions • Input operation • An instruction that copies data from an input device into memory • Output operation • An instruction that displays information stored in memory • The most common I/O functions are supplied as part of the C standard I/O library #include <stdio.h> • Function call • A C function that performs an input or output operation

  28. The printf function printf(“That equals %f kilometers.\n”, kms); • Function argument • Enclosed in parentheses following the function name; provides information needed by the functions • Format string • In a call to printf, a string of characters enclosed in quotes (“), which specifies the form of the output line function name function arguments print list format string

  29. The printf function (cont.) • Print list • In a call to printf, the variables or expressions whose values are displayed • Placeholder • Symbol beginning with % in format string that indicates where to display the output value

  30. The printf function (cont.) • Newline escape sequence • The character sequence \n, which is used in a format string to terminate an output line • Multiple placeholders • If the print list of a printf call has several variables, the format string should contain the same number of placeholders. • C matches variables with placeholders in left-to-right order

  31. The printf function (cont.) • If letter_1, letter_2, and letter_3 are type char variables and age is type int, the printf call printf(“Hi %c%c%c – your age is %d\n”, letter_1, letter_2, letter_3, age); displays a line such as Hi EBK – your age is 35

  32. More about \n • Cursor • A moving place marker that indicates the next position on the screen where information will be displayed • Example printf(“Here is the first line\n”); printf(“\nand this is the second.\n”); It produces 2 lines of text with a blank line in between: Here is the first line and this is the second. 1st new line 2nd new line

  33. More about \n (cont.) printf(“This sentence appears \non two lines. \n”); • The character after the \n appear on a new output line: This sentence appears on two lines. new line

  34. Displaying Prompts • Prompt (Prompting message) • A message displayed to indicate what data to enter and in what form printf(“Enter the distance in miles> ”); scanf(“%lf”, &miles); • It displays a prompt for square meters (a numeric value).

  35. The scanf function scanf(“%lf”, &miles); • It calls function scanf to copy data into the variable miles • It copies the data from the standard input device, usually is the keyboard the computer will attempt to store in miles whatever data the program user types at the keyboard • The format string “%lf” consists of a single placeholder for number, as an input

  36. The scanf function (cont.) • Notice that in a call to scanf, the name of each variable that is to be given a value is preceded by the & character • the & is the C address-of operator  tells the scanf function where to find each variable into which it is to store a new value • If the & were omitted scanf only know a variable’s current value, not its location in memory, so scanf would unable to store a new value in the variable • Example: Scanning data line BOB

  37. The return statement return(0); • It transfers control from the program to the operating system • The value 0 is considered the result of function main’s execution, and it indicates that your program executed without error

  38. General form of a C program preprocessor directives main function heading { declarations executable statements }

  39. Program style • Spaces in program • The consistent and careful use of blank spaces can improve the style of a program • A blank space is required between consecutive words in a program line • The compiler ignores extra blanks between words and symbols  insert space to improve the readability and style of a program • Leave a blank space after a comma and before and after operators, e.g., *, /, +, -, = • Indent the body of the main function and insert blank lines between sections of the program • But it’s wrong  / * and * /, also MAX ITEMS

  40. Comments in programs • Programmers make a program easier to understand by using comments to describe the purpose of the program, the use of identifiers, and the purpose of each program step  part of program documentation • Program documentation • Information (comments) that enhances the readability of a program double miles, /* input – distance in miles */ kms; /* output – distance in kilometers */ We document most variables in this way

  41. Program style –using comment • Header section • The programmer’s name • The date of the current version • A brief description of what the program does /* * Programmer: Ucup Date completed: Sep 12, 2005 * Instructor: Irfan Class: CI1301 * * Calculates and displays the area and circumference * of a circle */

  42. Program style –using comment (cont.) • Before you implement each step in the initial algorithm, you should write a comment that summarizes the purpose of the algorithm step • This comment should describe what the step doesrather than simply restate the step in English /* Convert the distance to kilometers. */ kms = KMS_PER_MILE * miles; is more descriptive and hence preferable to /* Multiply KMS_PER_MILE by miles and store result in kms. */ kms = KMS_PER_MILE * miles;

  43. Arithmetic expressions

  44. Arithmetic expressions (cont.) • Result of integer division 3 / 15 = 0 18 / 3 = 6 15 / 3 = 5 16 / - 3 varies 16 / 3 = 5 0 / 4 = 0 17 / 3 = 5 4 / 0 is undefined

  45. Arithmetic expressions (cont.) • Result of % operation 3 % 5 = 3 5 % 3 = 2 4 % 5 = 4 5 % 4 = 1 5 % 5 = 0 15 % 5 = 0 6 % 5 = 1 15 % 6 = 3 7 % 5 = 2 15 % -7 varies 8 % 5 = 3 15 % 0 is undefined

  46. Arithmetic expressions (cont.) • The formula m equals (m / n) * n + (m % n) • Examples: 7 equals (7 / 2) * 2 + (7 % 2) equals 3 * 2 + 1 299 equals (299 / 100) * 100 + (299 % 100) equals 2 * 100 + 99

  47. Data type of an expression ace + bandage • is type int if both ace and bandage are type int; otherwise, it’s type double • It’s as an example of the general form ace arithmetic_operator bandage • Mixed-type expression • An expression with operands of different types • The data type of such a mixed-type expression will be double

  48. Mixed-type assignment statement • Mixed-type assignment • The expression being evaluated and the variable to which it is assigned have different data types • Example: m = 3; n = 2; p = 2.0; x = m / p; y = m / n; x = 9  0.5; n = 9  0.5;

  49. Expressions withmultiple operators • Unary operator • An operator with one operand • Examples: • negation () and plus () operators • x =  y; p =  x  y; • Binary operator • An operator with two operands • When  and  are used to represent addition and subtraction, they are binary operators • x = y  z; z = y  x;

  50. Rules forevaluating expressions • Parentheses rule • All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expression evaluated first. • Operator precedence rule • Operators in the same expression are evaluated in the following order • Unary ,  first • , , % next • Binary ,  last • Association rule • Unary operators in the same subexpression and at the same precedence level (such as  and ) are evaluated right to left (right associativity). Binary operators in the same subexpression and at the same precedence level (such as  and ) are evaluated left to right (left associativity).

More Related