Summary of C: How To Program Sixth Edition by Deitel: Introduction To Computers, The Internet and The Web
Summary of C: How To Program Sixth Edition by Deitel: Introduction To Computers, The Internet and The Web
Kom
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
5. Arithmetic and logic unit (ALU) This section is in charge of calculation and usually is implemented as CPU in todays system. 6. Secondary storage unit This unit stores the data and information that is not actively required until they are needed sometimes.
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
C STANDARD LIBRARY
A program consists of several modules called functions. Existing functions that are available for programmers to use are in the C Standard Library. Using the librarysoftware reusabilityis greatly encouraged to avoid breaking the object-oriented programming, instead of creating functions from scratch and spending too much time in the process.
JAVA
Sun Microsystems in 1991 funded an internal corporate research project codenamed Green. The project resulted in the development of a C++-based language, created by James Gosling. They targeted the development of intelligent consumer electronic devices. Even though the project was in danger of cancellation back then, but the popularity of World Wide Web in 1993 has opened a new door for Java to add dynamic content (e.g., interactivity, animations and the like) to web pages. It was finally announced formally at an industry conference in May 1995.
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
was the development of the Pascal programming language by Professor Niklaus Wirth in 1971. Ada was developed under the sponsorship of the United States Department of Defense (DoD) during the 1970s and early 1980s. Ada provides multitasking. Although multithreading is not part of standard C, its available through various add-on libraries.
OBJECT TECHNOLOGY
Structured programming, realized in 1970 after a great depression in developing software was felt in 1960, leading to object-oriented programming in 1990. Object technology is a packaging scheme that helps us create meaningful software units. With the help of popular object-oriented programming languages, programmers can program in an object-oriented manner and thus resulted in significant productivity gains. For example, the time and money wasted to repeatedly make a software from scratch is far too great than if software reuse is applied. Moreover, software reuse can lead to a software which is more understandable, better organized and easier to maintain, modify and debug.
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
Phase 4: Linking C programs typically contain references to functions defined elsewhere. A linker links the object code with the code for the missing functions to produce an executable image. Phase 5: Loading Before a program can be executed, the program must first be placed in memory. This is done by the loader, which takes the executable image from disk and transfers it to memory. Phase 6: Execution The computer, under the control of its CPU, then executes the program.
HARDWARE TREND
Development in communication and computer technology is still going on strong. Every year, capacities of computers doubled, but strangely without any significant change on price. People pay lesser and lesser for the technology that ease their life, which is explained in Moores Law, by the person who first identifies it, Gordon Moore, cofounder of Intel. Whether its the amount of memory, secondary storage or processor speed, people pay less for significant development of computers, which truly leads to Information Revolution.
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
CHAPTER II
INTRODUCTION TO C PROGRAMMING
C PROGRAMMING
C language facilitates structured computer program design, which means it run in sequence, from the first line to the last. Comments, indicated by /* and ended with */ do not cause the computer to perform any action when the program is run. The lines and statements between the two signs are ignored by the C compiler. Comments can be used to help people who read the program to understand better about it. Another way to comment is to use // for single-line comment. Everything that is written after // will be regarded as comments. Lines beginning with # are processed by the preprocessor before the program is compiled. #include tells the preprocessor to include the contents of the other file. For example, #include <stdio.h> tells to include standard input/output header (<stdio.h>) in the program. This header contains information used by the compiler when compiling calls to standard input/output library functions such as printf. The function main is a part of every C program. Every program in C begins executing at the function main. Functions can return information, such as in
int main (void)
the keyword int to the left of main indicates that main returns an integer (whole number) value. To be noted, decimal points should be handled by data type float (called floating point numbers). When two integer values are divided, it results in integer division, which truncates any fractional part of the calculation. Therefore, to produce a floating-point calculation with integer values, temporary values that are floating-point numbers should be created with the unarytakes one operandcast operator. The cast operator is formed by placing parentheses around a data type name. Unary operators associate from right to left. Type double is a floating-point type much like float, but typically a variable of type double can store a value of much greater magnitude with greater precision than float. A left brace, {, begins the body of every function. A corresponding right brace ends each function. This pair of braces and the portion of the program between the braces is called a block. One of the actions instructed for the program to run is the printf. It is used to print on the screen the string stated and marked by the quotation marks. This is one example of printf:
printf( "Welcome to C!\n" );
The example is counted as one statement. Every statement must be ended by a statement terminator, which is semicolon (;). The backslash is called an escape sequence. Below is listed some common sequence.
6
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
Escape sequence \n \t \a \\ \
Description Newline. Position the cursor at the beginning of the next line. Horizontal tab. Move the cursor to the next tab stop. Alert. Sound the system bell. Backslash. Insert a backslash character in a string. Double quote. Insert a double-quote character in a string.
A variable is a location in memory where a value can be stored for use by a program. A variable name in C is any valid identifier. An identifier is a series of characters consisting of letters, digits and underscores ( _ ) that does not begin with a digit. In order for a variable to be used it has to be stated with a data type and a name after the left brace. C is case sensitive. When definitions are placed after executable statements, the program will not be able to recognize the statements. This condition is called as syntax error, compiled error, or compile-time error. If the error is fatal, it may cause the program to terminate prematurely, while a non-fatal one will still be able to allow the execution of the program, but might be with an incorrect result. A prompt is a message that requires specific action from the user. An example for a prompt is the statement to ask the user to input a certain value. After the user has input a certain value, the next action will be obtaining the input. In this case, scanf can be used. To be noted, whenever a value is stored to a memory, it will destroy the previous value that is previously there. But when the value is drawn out from the memory, it will still be there, and thus is a non-destructive process. The % is the format control string, indicates the type of data that should be input by the user. The %d conversion specifier indicates that the data should be an integer. The % in this context is treated as a special character that begins a conversion specifier. The second argument of scanf begins with an ampersand (&)called the address operator in C followed by the variable name. The ampersand tells scanf the location in memory at which the variable is stored. Most calculations are performed in assignment statements. There are several assignment operators, such as the = operator and the + operator. Both are binary operators. Function printf can use a format control string for some literal characters to be displayed and the conversion specifiers indicating place holders for data to output. After the conversion specifiers, we may specify the value that is to be printed. To print a certain number of digits to the right of a floating-point value, printf conversion specifier %.nf can be used, indicating that it will be displayed with n digits to the
7
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
right of the decimal point. If the %f conversion specifier is used (without specifying the precision), the default precision of 6 is used. When floating-point values are printed with precision, the printed value is rounded to the indicated number of decimal positions for display purposes. To end every main function, we use:
return 0;
When the return statement is used at the end of main, the value 0 indicates that the program has terminated successfully.
ARITHMETIC IN C
Arithmetic operators in C are binary operatorseach has two operands.
C operation Addition Subtraction Multiplication Division Remainder Arithmetic operator + * / % Algebraic expression f + 7 p c bm x / y or x y r mod s C expression f + 7 p c b * m x / y r % s
Parentheses for grouping sub expressions are used in C in the same manner as in algebraic expressions.
Operator(s) ( ) Operations(s) Parentheses Order of evalution (precedence) Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), theyre evaluated left to right. Evaluated second. If there are several, theyre evaluated left to right.
* / % + -
It is to be noted though, that unary operators such as unary + and unary - have precedence one level higher of multiplicative operators *, / and %.
ASSIGNMENT OPERATORS
8
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
C provides several assignment operators for abbreviating assignment expressions. Any statement of the form variable = variable operator expression; can be written in the form variable operator= expression;
The relational operators and equality operators all associate from left to right. The difference is that equality operators have a lower level of precedence than relational operators.
9
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
In writing C programs, it is allowed to use white-space characters (e.g. tabs, newlines and spaces) as it will not disturb the execution of the programs. However, splitting identifiers with white-space characters is not allowed. The order of association of operators usually goes from left to right, with an exception for assignment operator (=) which associates from right to left.
10
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
CHAPTER III
STRUCTURED PROGRAM DEVELOPMENT IN C
ALGORITHM, PSEUDOCODE AND FLOWCHART
In this book, it is encouraged that a person understands a problem completely before writing a program, as it will definitely help the most efficient approach on the programs structure. The term of what actions to be executed and the order of the actions is called algorithm. In a computer programming, specifying the order of actions is called program control. Pseudocode is a language that can be used to help specify the algorithm of a program. It is informal and not an actual computer programming language, but it can be converted to the desired programming language, such as the C language. Pseudocode takes form of everyday English. Other way is to use flowcharts, a structure of shapes that is connected by flowlines. In a flowchart, each shape represents an action in algorithm. The rectangle symbol (or action symbol) is used to indicate input/output operation and calculation. The beginning and the end of the flowchart is indicated by oval symbol with the writing Begin and End in it. If the flowchart contains only a portion of the whole algorithm, then it should be begun and ended by small circle symbols, instead of the oval symbols. This single-entry/single-exit control statement is the simplicity needed for efficient programming. The end of one statement can always be connected to the entry of another, which is called as controlstatement stacking. Then there is the diamond symbol (or decision symbol), which is used to contain a decision that is to be made. From these explanations of flowchart, it is clear that all programs contain of only three control structures, the sequence structure, the selection structure and the repetition structure1.
SELECTION STRUCTURE
The selection structure has three possible statements, they are the if selection statement (single-selection statement), the if...else statement (double-selection statement) and the switch statement (multiple-selection statement). The if selection statement runs if a condition is fulfilled and ignores the action if the condition is false. The expression specified by if statement can be either true or false, if a certain condition is met, then the action will be run. If the condition is false, then it will continue to end the statement. The if selection statement is a single-entry/single-exit structure. The other selection structure is the if...else statement (double-selection statement). It specifies a certain selection of actions to run depending on the true or false condition. If the condition is met, then it will run an action, but we could also set a certain
1
Bohm, C., and G. Jacopini, Flow Diagrams, Turing Machines, and Languages with Only Two Formation Rules, Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 336371.
11
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
action to be run when an expression turns out to be false. The if...else statement can be nested, which means another if...else statement can be placed after the initial if...else statement. Another way to write it in C is using the conditional operator (?:), which is a ternary operatorit takes three operands. A conditional expression is formed with the combination of conditional operator and the operands. The first operand is a condition, the second operand is the conditional expression when the condition is true, and the third operand is the conditional expression when the condition is false. The switch statement (multiple-selection statement) is the last selection structure. It can be used to specify many selection actions.
REPETITION STATEMENTS
One type of repetition statements is while. It is used to make a certain action is repeated when a condition remains true. When this statement executes, there will eventually be a time when the condition becomes false. That is the time when the program stops the repeating action and continues on to the next sequence. To set the repetition to definite number of times can be called as counter-controlled repetition. This means that the number of repetition is specified before the set of statements starts looping. Counter-controlled repetition requires: 1. The name of a control variable (or loop counter). 2. The initial value of the control variable. 3. The increment (or decrement) by which the control variable is modified each time through the loop. 4. The condition that tests for the final value of the control variable (i.e., whether looping should continue). Total is a variable used to accumulate the sum of values. If it is used before the value is initialized, it will still contain the garbage value from the previous value stored in the location. Thats why it is usually initialized to zero before a program starts. In a countercontrolled repetition, another variable is necessary to count the number of times the loop has been executing, which is called a counter. It is usually initialized as zero or one, depending on their use. The repetition statement that ends when the user input a certain value is called the sentinel-controlled repetition. This special value can be specified as signal value, dummy value or flag value. The sentinel value should be distinct from regular data items. This type of repetition is an indefinite repetition because the number of repetitions is not known before the loop begins executing. Top-down, stepwise refinement approach is helpful for developing well-structured programs. This approach first determines the top statement that conveys all the programs function. The next step will be dividing it into lines of tasks in order of the performance. This process is called refinement, and it continues until a well-structured program is formed.
12
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
CHAPTER IV
C PROGRAM CONTROL
for REPETITION STATEMENT
The for statement used for counter-controlled repetition can be written with this general format: for ( expression1; expression2; expression3 ) statement where expression1 initializes the loop-control variable, expression2 is the loop-continuation condition and expression3 increments or decrements the control variable. These expressions can all contain arithmetic expressions. The for statement can sometimes be written in while statement with this format: expression1; while ( expression2 ) { statement expression3; } These expressions often consists of comma-separated lists of expressions. The comma, as comma operators that guarantee that lists of expressions evaluate from left to right. Its primary use is to enable you to use multiple initialization and/or multiple increment expressions. The three expressions in the for statement are optional. If expression2 is omitted, an infinite loop will be created. One may omit expression1 if the control variable is initialized elsewhere in the program. expression3 may be omitted if the increment is calculated by statements in the body of the for statement or if no increment is needed. The increment expression in the for statement acts like a stand-alone C statement at the end of the body of the for. Function pow performs exponentiation. The function pow(x, y) calculates the value of x raised to the yth power. It takes two arguments of type double and returns a double value of variable y. To use this function, header <math.h> should be included.
CONVERSION SPECIFIER
To specify a certain value of data type, we need to use conversion specifier. A conversion specifier is written with % continued by a letter. There is a different conversion specifier for each data type that will be explained below:
Data type Integer (int) Character (char) Conversion specifier %d %c
13
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
Array of characters (char) Float (float) Double float (double) %s %f %f
We could use conversion specifier to align the value printed in the program. It is written in this general format: %x.yf. The x in the conversion specifier denotes the field width in which the value will be printed. A field width of x specifies that the value printed will appear in x print positions. The y specifies the precision (i.e., the number of decimal positions). To left justify a value in a field, place a - (minus sign) between the % and the field width.
14
T0016 Algorithm and Programming Home Game #1 Lecturer: Albertus Agung, S.Kom
LOGICAL OPERATORS
C provides some logical operators that can be used to combine simple conditions into a more complex condition. They are the && (logical AND), || (logical OR) and ! (logical NOT also called logical negation). The && logical operator requires all conditions specified to be true (nonzero) before the action is executed. Meanwhile, the || requires at least one condition to have nonzero value for the specified action is executed. So if there are two conditions combined with ||, one is false (have zero value) and one with nonzero value, then the action will be executed. The && has bigger precedence than ||. Both && and || associates from left to right. Another logical operator is the ! operator. This operator is used to reverse the meaning of a condition. Below will be stated the precedence and associativity of all operators introduced in this summary, top to bottom in decreasing order of precedence.
Operators ++ (postfix) - (postfix) + - ! ++ (prefix) - (prefix) * / % + < <= > >= == != && || ?: = += -= *= /= %= , Associativity Right to left Right to left Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right Type Postfix Unary Multiplicative Additive Relational Equality Logical AND Logical OR Conditional Assignment Comma
15