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 /* printf, scanf definitions */ #define KMS_PER_MILE /* 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); } preprocessor directive standard header file comment constant reserved word standard identifier comment 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.) Reserved WordMeaning int integer; indicates that the main function returns an integer value void indicates that the main function receives no data from the operating system double indicates that the memory cells store real numbers return returns control from the main function to the operating system
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.) Invalid identifierReason invalid 1Letter begin with a number double reserved word int reserved word TWO*FOUR character * not allowed joe’s character ‘ not allowed
12 C language elements (cont.) User-defined identifiers 1.An identifier must consist only of letters, digits, and underscores 2.An identifier cannot begin with a digit 3.A C reserved word cannot be used as an identifier 4.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 Reserved Words Standard Identifiers User-Defined Identifiers int, void, double, return printf, scanf KMS_PER_MILE, main, miles, kms
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 THAN s or bagel If more than 2 or more words, the underscore character (_) will be better dollars_per_hour THAN dollarsperhour
15 C language elements (cont.) Choose identifiers long enough to convey the meaning, but not too long lbs_per_sq_in THAN pounds_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 declarations and 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: to int can be used in arithmetic operations: add, subtract, multiply, and divide; also in comparing two integers Examples: , 435, +15, 125, 32767
18 Data type double It used to represent real numbers Examples: , , 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 10 5 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 places to the right” If the exponent is negative it means “move the decimal point places to the left”
19 Data type double (cont.) Valid double ConstantsInvalid double Constants e-04 (value is ) 2.345e2 (value is 234.5) 1.15e-3 (value is ) 12e+5 (value is ) 150 (no decimal point).12345e (missing exponent) 15e-0.3 (0.3 is invalid exponent) 12.5e.3 (.3 is invalid exponent) 34, (comma is not allowed)
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 Valid double ConstantsInvalid double Constants e-04 (value is ) 2.345e2 (value is 234.5) 1.15e-3 (value is ) 12e+5 (value is ) 150 (no decimal point).12345e (missing exponent) 15e-0.3 (0.3 is invalid exponent) 12.5e.3 (.3 is invalid exponent) 34, (comma is not allowed)
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 miles kms machine language miles-to-kms conversion program memory ? ? miles kms machine language miles-to-kms conversion program memory
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/Output operations 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 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 format string print list
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 PlaceholderVariable TypeFunction Use %c %d %f %lf char int double printf/scanf printf scanf
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. 1 st new line 2 nd 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 does rather 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 Arithmeti c Operator MeaningExamples +-*/%+-*/% addition subtraction multiplication division remainder is is – 2 is – 2.0 is * 2 is * 2.0 is / 2.0 is / 2 is 2 5 % 2 is 1
44 Arithmetic expressions (cont.) Result of integer division 3 / 15 = 018 / 3 = 6 15 / 3 = 516 / - 3 varies 16 / 3 = 50 / 4 = 0 17 / 3 = 54 / 0 is undefined
45 Arithmetic expressions (cont.) Result of % operation 3 % 5 = 35 % 3 = 2 4 % 5 = 45 % 4 = 1 5 % 5 = 015 % 5 = 0 6 % 5 = 115 % 6 = 3 7 % 5 = 215 % -7 varies 8 % 5 = 315 % 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 * equals (299 / 100) * (299 % 100) equals 2 *
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 with multiple 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 for evaluating 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).
51 Rules for evaluating expressions (cont.) x y z a b c d can be written in a more readable form using parentheses: (x y z) (a b) (c d) The formula for the area of a circle a = r 2 can be written in C as area = PI radius radius; where the constant macro PI =
52 Rules for evaluating expressions (cont.) z (a b 2) w -y containing type int only.
53 Writing mathematical formulas in C Always specify multiplication explicitly by using the operator * where needed (formulas 1 and 4) Use parentheses when required to control the order of operator evaluation (formulas 3 and 4) Two arithmetic operators can be written in succession if the second is a unary operator (formula 5) Mathematical Formula C Expression 1.b 2 – 4ac 2.a + b – c a –(b + c) b * b – 4 * a * c a + b – c (a + b) / (c + d) 1 / (1 + x * x) a * –(b + c)
54 Case study: evaluating a collection of coins It demonstrates the manipulation of type int data (using / and %) and type char data Problem Your local bank branch has many customers who save their change and periodically bring it in for deposit. Write a program to interact with their customers and determine the value of a collection of coins. Analysis To solve this problem, you need to get the count of each type of coin (quarters, dimes, nickels, pennies) from a customer. From those counts, you can determine the total value of the coins in cents. Once you have that figure, you can do an integer division using 100 as the divisor to get the dollar value; the remainder of this division will be the leftover change. In the data requirements, list the total value in cents ( total_cents ) as a program variable, because it is needed as part of the computation process but is not a required problem output. To personalize the interaction, get each customer’s initials before getting the coin counts.
55 Case study: evaluating a collection of coins (cont.) Data requirements Problem inputs char first, middle, last /* a customer’s initials */ int quarters /* the count of quarters */ int dimes /* the count of dimes */ int nickels /* the count of nickels */ int pennies /* the count of pennies */ Problem outputs int dollars /* value in dollars */ int change /* leftover change */ Additional program variables int total_cents /* total value in cents */
56 Case study: evaluating a collection of coins (cont.) Design Initial algorithm 1.Get and display the customer;s initials 2.Get the count of each kind of coin 3.Compute the total value in cents 4.Find the value in dollars and change 5.Display the value in dollars and change Step 3 and 4 may need refinement. Their refinement are: Step 3 Refinement 3.1 Find the equivalent value of each kind of coin in pennies and add these values Step 4 Refinement 4.1 dollars in the integer quotient of total_cents and change is the integer remainder of total_cents and 100 Implementation The program is shown in the following
57 Case study: evaluating a collection of coins (cont.) /* * Determines the value of a collection of coins */ #include int main(void) { char first, middle, last; /* input – 3 initials */ int pennies, nickels; /* input – count of each coin type */ int dimes, quarters; /* input – count of each coin type */ int change; /* output – change amount */ int dollars; /* output – dollar amount */ int total_cents; /* total cents */ /* Get and display the customer’s initials */ printf(“Type in 3 initials and press return> ”); scanf(“%c%c%c”, &first, &middle, &last); printf(“Hello %c%c%c, let’s see what your coins are worth.\n”, first, middle, last);
58 Case study: evaluating a collection of coins (cont.) /* Get the count of each kind of coin */ printf(“Number of quarters> ”); scanf(“%d”, &quarters); printf(“Number of dimes > ”); scanf(“%d”, &dimes); printf(“Number of nickels > ”); scanf(“%d”, &nickles); printf(“Number of pennies > ”); scanf(“%d”, &pennies); /* Compute the total value in cents */ total_cents = 25 * quarters + 10 * dimes + 5 nickles + pennies; /* Find the value in dollars and change */ dollars = total_cents / 100; change = total_cents % 100; /* Display the value in dollars and change */ printf(“\nYour coins are worth %d dollars and %d cents.\n”, dollars, change); return(0); }
59 Case study: evaluating a collection of coins (cont.) Type in 3 initials and press return> BMC Hello BMC, let’s see what your coins are worth. Number of quarters> 8 Number of dimes > 20 Number of nickels > 30 Number of pennies > 77 Your coins are worth 6 dollars and 27 cents.
60 Formatting value of type int Simply add a number between the % and the d of the %d placeholder in the printf format string Field width The number of columns used to display a value ValueFormatDisplayed Output ValueFormatDisplayed Output 234 %4d %5d %6d %1d %4d %5d %6d %1d -234
61 Formatting value of type double It must indicate both the total field width needed and the number of decimal places desired The form of the format string placeholder is %n.mf where n is a number representing the total field width, and m is the desired number of decimal places Displaying x using format string placeholder %6.2f Value of x Displayed Output Value of xDisplayed Output
62 Formatting value of type double (cont.) ValueForma t Displayed Output ValueFormatDisplayed Output %5.2f %3.2f %5.3f %4.2f %8.3f %.3f %4.2f %5.1f %8.5f %4.2f %8.5f %.4f
63 Interactive mode, batch mode, and data files Interactive mode A mode of program execution in which the user responds to prompts by entering (typing in) data E.g. our previous program Batch mode A mode of program execution in which the program scans its data from a previously prepared data file Input redirection E.g. In the UNIX and MS-DOS OS, program take its input from file mydata instead of from the keyboard by placing the symbols <mydata at command prompt metric <mydata
64 Batch version program /* * Converts distance in miles to kilometers */ #include /* printf, scanf definitions */ #define KMS_PER_MILE /* conversion constant */ int main(void) { double miles, /* input – distance in miles */ kms; /* output – distance in kilometers */ /* Get and echo the distance in miles */ scanf(”%lf”, &miles); printf(“The distance in miles is %.2f.\n”, miles); /* Convert the distance to kilometers */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers */ printf(“That equals %.2f kilometers.\n”, kms); return (0); } The distance in miles is That equals kilometers.
65 Echo prints vs Prompts scanf(“%lf”, &miles); It gets a value for miles from the first (and only) line of the data file. Because the program input comes from a data file, there’s no need to precede with a prompting message. Instead we use printf(“The distance in miles is %.2f.\n”, miles); This statement echo prints or displays the value just stored in miles and provides a record of the data manipulated by the program Output redirection Redirect program output to a disk file instead of to the screen E.g. In the UNIX and MS-DOS OS, program put its output to file myoutput by placing the symbols >myoutput at command prompt metric >myoutput For input and output file, it will be better to use the command line metric myoutput
66 Program with Named Files /* * Converts distance in miles to kilometers */ #include /* printf, scanf, fprint, fscanf, fopen, fclose definitions */ #define KMS_PER_MILE /* conversion constant */ int main(void) { double miles, /* input – distance in miles */ kms; /* output – distance in kilometers */ FILE *inp, /* pointer to input file */ *outp; /* pointer to output file */ /* Open the input and output files */ inp = fopen(”c:distance.dat”, “r”); outp = fopen(“c:distance.out”, “w”); /* Get and echo the distance in miles */ fscanf(inp, ”%lf”, &miles); fprintf(outp, “The distance in miles is %.2f.\n”, miles); /* Convert the distance to kilometers */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers */ fprintf(outp, “That equals %.2f kilometers.\n”, kms); /* Close files */ fclose(inp); fclose(outp); return (0); } Contents of input file distance.dat Contents of output file distance.out The distance in miles is That equals kilometers.
67 Common programming errors Murphy’s Law: “If something can go wrong, it will” Debugging – correcting error from a program According to computer folklore, computer pioneer Dr. Grace Murray Hopper diagnosed the first hardware error caused by a large insect found inside a computer component)
68 Syntax errors The violation of the C grammar rules, detected during program translation (compilation) Examples: Missing semicolon at the end of the variable declaration (in line 271) Undeclared variable miles (detected in lines 275 & 278) Last comment is not closed because of blank in * / close-comment sequence (in line 280)
69 Syntax errors (cont.) 221 /* Converts distance in miles to kilometers */ #include /* printf, scanf definitions */ 266 #define KMS_PER_MILE /* conversion constant */ int 269 main(void) 270 { 271double kms /* Get the distance in miles */ 274printf(“Enter the distance in miles> ”); ***** Semicolon added at the end of the previous source line 275 scanf(“%lf”, &miles); ***** Identifier “miles” is not declared within this scope ***** Invalid operand of address-of operator /* Convert the distance to kilometers */ 278kms = KMS_PER_MILE * miles; ***** Identifier “miles” is not declared within this scope /* Display the distance in kilometers * / 281printf(“That equals %f kilometers.\n”, kms); return (0); 284 } ***** Unexpected end-of-file encountered in a comment ***** “}” inserted before end-of-file
70 Run-Time errors An attempt to perform an invalid operation, detected during program execution Occurs when the program directs the computer to perform an illegal operation, such as dividing a number by zero If it occur the computer will stop executing your program and will display a diagnostic message that indicates the line where there error was detected
71 Run-Time errors (cont.) 111 #include int 264 main(void) 265 { 266int first, second; 267double temp, ans; printf(“Enter two integers> ”); 270 scanf(“%d%d”, &first, &second); 271 temp = second / first; 272 ans = first / temp; 273printf(“The result is %.3f\n”, ans); return (0); 276 } Enter two integers? 14 3 Arithmetic fault, divide by zero at line 272 of routine main
72 Undetected errors It leads to incorrect result It has to predict the results your program should produce and verify that the actual output is correct A very common source of incorrect results in C programs is the input of a mixture of character and numeric data scanf ’s different of the %c placeholder on the one hand, and of the %d and %lf to the other scanf first skips any blanks and carriage returns in the input when a numeric value is scanned, but, scanf skips nothing when it scans a character unless the %c placeholder preceded by a blank
73 Undetected errors (cont.) Revised start of main function for Coin Evaluation int main(void) { char first, middle, last; /* input – 3 initials */ int pennies, nickels; /* input – count of each coin type */ int dimes, quarters; /* input – count of each coin type */ int change; /* output – change amount */ int dollars; /* output – dollar amount */ int total_cents; /* total cents */ int year; /* current year */ /* Get the current year */ printf(“Enter the current year and press return> ”); scanf(“%d”, &year); /* Get the program user’s initials */ printf(“Type in 3 initials and press return> ”); scanf(“%c%c%c”, &first, &middle, &last); printf(“Hello %c%c%c, let’s check your coins’ value in %d.\n”, first, middle, last, year);
74 Undetected errors (cont.) If the user types in 2005 and then the letters BMC, we would expect the second call to printf to display: Hello BMC, let’s check your coins’ value in Instead, it displays the message: Hello BM, let’s check your coins’ value in 2005.
75 Undetected errors (cont.) Why? Let’s see the status of memory The value of year is correct, but the three characters stored are not ‘ B ’, ‘ M ’, “ C ’, but ‘ \n ’, ‘ B ’, and ‘ M ’. The ‘ \n ’ in first is the character that results from the user pressing the key after entering the number 2005 The scan of 2005 stopped at this character, so it was the first character processed by the statement scanf(“%c%c%c”, &first, &middle, &last); Because the letter C was not yet scanned, it will be scanned during the next scanf call. This will lead to further problems. By the following code, scanf will skip spaces (including carriage returns) before scanning a character scanf(“ %c%c%c”, &first, &middle, &last);
76 Logic errors An error caused by following an incorrect algorithm Usually logic error do not cause run-time errors and do not display error messages difficult to detect! The only sign of a logic error may be incorrect program output You can detect it by testing the program thoroughly, comparing its output to calculated results You can prevent it by carefully desk checking the algorithm and the program before you type it in Debugging can be time consuming plan your program solutions carefully and desk check them to eliminate bugs early
77 Logic errors on a program #include int main(void) { int first, second, sum; printf(“Enter two integers> ”); scanf(“%d%d”, first, second); /* ERROR! Should be &first, &second */ sum = first + second; printf(“%d + %d = %d\n”, first, second, sum); return (0); } Enter two integers> =