Chapter 1 Introduction to C Programming REV00 REV00 Chapter 1 Introduction to C Programming DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.1 Introduction We will learn the C programming language Learn structured programming and proper programming techniques. This course is appropriate for technically oriented people with little or no programming experience. Experienced programmers who want a deep and rigorous treatment of the language DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.2 History of C C Evolved by Ritchie from two previous. programming languages, BCPL and B Used to develop UNIX. Now, most operating systems written with C or C++. Hardware independent (portable). By late 1970's C had evolved to "Traditional C“. Standard created in 1989, updated in 1999 DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.3 Identifiers In C the names of variables, functions, labels and various others user defined items are called identifiers. The length of these identifiers can vary from one to several character The first character must be a letter or an underscore, and subsequent characters must be either letters, digits, or underscores. Use meaningful identifiers Be consistent DDC1123 PENGATURCARAAN I (C)
1.3.1 Correct and Incorrect Identifiers names REV00 1.3.1 Correct and Incorrect Identifiers names Correct Incorrect count 1count test123 Hi!there High_balance High…balance Total_score Total+score DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.4 Basic Data Types Data is information that maybe manipulated by computer A binary digit, or a bit is the smallest item of data Type Size (bytes) char 1 int 2 or 4 float 4 double 8 DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.5 Declaring Variables Declaration: int a = 10; Type Name Value 10 a Memory location DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 1.6 Constants Constant refer to fixed values that the program may not alter. Constant can be any of the basic data types. Declaration: #define PI 3.142; Keyword Value Name DDC1123 PENGATURCARAAN I (C)
1.7 Formatted Input/Output REV00 1.7 Formatted Input/Output Standard Output with printf( ) Syntax: printf ("Hello World!"); or printf ("Number: %d", a); Hello World! output Number: 10 output DDC1123 PENGATURCARAAN I (C)
1.7 Formatted Input/Output REV00 1.7 Formatted Input/Output Format specifiers: printf ("Number: %d", a); %d is a format specifier that indicates the data should be of type integer. DDC1123 PENGATURCARAAN I (C)
1.7 Formatted Input/Output REV00 1.7 Formatted Input/Output Standard Input with scanf( ) Syntax: scanf ("%d", &a); Input a Memory location DDC1123 PENGATURCARAAN I (C)
Chapter 2 Structure of a C Program REV00 Chapter 2 Structure of a C Program DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 2.1 Expression Operators, constants, functions and variable are the constituents of expressions. An expression in C is any combination of this elements. Most of the expression follow the general rules of algebra. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 2.2 Operators & Expressions Arithmetic type Arithmetic operator Addition + Subtraction - Multiplication * Division / Modulus % DDC1123 PENGATURCARAAN I (C)
2.3 Precedence and Associativity REV00 2.3 Precedence and Associativity Operator(s) Precedence & Associativity ( ) Evaluated first. If nested (embedded), innermost first. If on same level, left to right. * / % Evaluated second. If there are several, evaluated left to right. + - Evaluated third. If there are several, evaluated left to right. = Evaluated last, right to left. DDC1123 PENGATURCARAAN I (C)
2.4 Evaluating Expression REV00 2.4 Evaluating Expression Operator Precedence Order of Evaluation () [] -> . 1 Left to right ! ++ -- + - * & sizeof(type) 2 Right to Left * / % 3 + - 4 << >> 5 < <= > >= 6 == != 7 DDC1123 PENGATURCARAAN I (C)
2.4 Evaluating Expression REV00 2.4 Evaluating Expression Operator Precedence Order of Evaluation & 8 Left to right ^ 9 | 10 && 11 12 ?: 13 Right to Left = += *= /= &= 14 ^= |= <<= >>= ' 15 DDC1123 PENGATURCARAAN I (C)
2.5 Mixed Type Expression (Conversion) REV00 2.5 Mixed Type Expression (Conversion) When constant and varibles of different types are mixed in an expression, they are all converted to the same type The compiler converts all operands up to the type of the largest operand is called type promotion. First all char and short int values are automatically elevated to int ( integral promotion). Once this step has been completed, all other conversions are done operation by operation. DDC1123 PENGATURCARAAN I (C)
2.5 Mixed Type Expression (Conversion) REV00 2.5 Mixed Type Expression (Conversion) If operand is… Then 2nd converted… Long double Double Unsigned long Long Unsigned int Float DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 2.6 Statement All programs can be broken down into 3 controls Sequence – handled automatically by compiler Selection – if, if/else or switch Repetition – while, do/while or for Can only be combined in two ways Nesting (rule 3) Stacking (rule 2) Any selection can be rewritten as an if statement, and any repetition can be rewritten as a while statement DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 Chapter 3 Functions DDC1123 PENGATURCARAAN I (C)
3.1 Designing Structured Programs REV00 3.1 Designing Structured Programs Structured programming is a problem solving strategy and a programming methodology that includes the following guidelines: The program uses only the sequence, selection, and repetition control structures. The flow of control in the program should be as simple as possible. The construction of a program embodies top-down design. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 3.1 Designing Structured Programs Involves repeatedly decomposing a problem into smaller problems Eventually leads to a collection of small problems or tasks each of which can be easily coded The function construct in C is used to write code for these small, simple problems. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 3.2 Functions A C program is made up of one or more functions, one of which is main( ). Execution always begins with main( ), no matter where it is placed in the program. By convention, main( ) is located before all other functions. When program control encounters a function name, the function is called (invoked). Program control passes to the function. The function is executed. Control is passed back to the calling function. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 3.2 Functions Standard library functions Collection of functions for performing useful operation ( mostly written by computer vendors ) Functions such as printf and scanf are standard library functions DDC1123 PENGATURCARAAN I (C)
3.3 User Defined Functions REV00 3.3 User Defined Functions Declarations: returnType functionName ( parametetList ) { declarations statements } Header Body Example void printGreeting ( void ) { printf ("Hello World!"); } DDC1123 PENGATURCARAAN I (C)
3.3 User Defined Functions REV00 3.3 User Defined Functions Declarations: returnType functionName ( parametetList ) Functions must be declared before they are called Function prototype DDC1123 PENGATURCARAAN I (C)
3.4 Standard Library Functions REV00 3.4 Standard Library Functions Collection of functions for performing useful operation ( mostly written by computer vendors ). Functions such as printf, scanf,and getchar and are standard library functions. Programmers can write their own functions. C function names follow the same naming rules as C variables. DDC1123 PENGATURCARAAN I (C)
3.4 Standard Library Functions REV00 3.4 Standard Library Functions Informs the compiler that there will be a function defined later that: returns this type has this name takes these arguments void printMessage (void) ; Needed because the function call is made before the definition -- the compiler uses it to see if the call is made properly DDC1123 PENGATURCARAAN I (C)
3.4 Standard Library Functions REV00 3.4 Standard Library Functions Passes program control to the function Must match the prototype in name, number of arguments, and types of arguments void printMessage (void) ; int main ( ) same name no arguments { printMessage ( ) ; return 0 ; } DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 3.5 Scope File scope Identifier defined outside function, known in all functions Used for global variables, function definitions, function prototypes Function scope Can only be referenced inside a function body Used only for labels (start:, case: , etc.) DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 3.5 Scope Block scope Identifier declared inside a block Block scope begins at declaration, ends at right brace Used for variables, function parameters (local variables of function) Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block Function prototype scope Used for identifiers in parameter list DDC1123 PENGATURCARAAN I (C)
Chapter 4 Selection Making Decision REV00 Chapter 4 Selection Making Decision DDC1123 PENGATURCARAAN I (C)
4.1 Logical Data and Operator REV00 4.1 Logical Data and Operator Sometimes we need to test multiple conditions in order to make a decision. Logical operators are used for combining simple conditions to make complex conditions. && is AND if ( x > 5 && y < 6 ) || is OR if ( z == 0 || x > 10 ) ! is NOT if (! (bob > 42) ) DDC1123 PENGATURCARAAN I (C)
4.1 Logical Data and Operator REV00 4.1 Logical Data and Operator && ( logical AND ) Returns true if both conditions are true || ( logical OR ) Returns true if either of its conditions are true ! ( logical NOT, logical negation ) Reverses the truth/falsity of its condition Unary operator, has one operand Useful as conditions in loops Expression Result true && false false true || false true !false true DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 4.2 Two Way Selection C supports two selection statement: If and Swicth. if-else statement if (conditional_expression) { statement 1; } else { statement 2; } DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 4.3 Multiway Seletion Nested if-else statements Syntax: If (conditional_expression1) statement 1; else if (conditional_expression2) statement 2; else defaultStatement; DDC1123 PENGATURCARAAN I (C)
4.4 More Standard Library Function REV00 4.4 More Standard Library Function rand( ) A function in C standard library Generates an integer between 0 and RAND_MAX srand( ) srand seeds function rand to produce a different sequence of random numbers for each execution of a program rand generates pseudo-random numbers DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 4.5 A Menu Program if ( value == 0 ) { printf (“The value you entered was zero.\n”) ; } else if ( value < 0 ) printf (“%d is negative.\n”, value) ; else printf (“%d is positive.\n”, value) ; DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 Chapter 5 Repetition DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 5.1 Concept of a Loop In C looping allow a set of instruction to be repeatedly executed until a certain condition is reached. This condition may be predetermined(as in for loop) or open ended (as in while and do-while loop). DDC1123 PENGATURCARAAN I (C)
5.2 Pre Test and Post Test Loop REV00 5.2 Pre Test and Post Test Loop C program has some constructs that can be used to define controlled loops(repetition) on a program block. A program block that is executed repeatedly by a repetition statement is called loop body. There are two types of repetition statement: Pretest statements Posttest statements DDC1123 PENGATURCARAAN I (C)
5.2 Pre Test and Post Test Loop REV00 5.2 Pre Test and Post Test Loop A pretest repetition statement computers a value for its accociated predicate before entering the loop body and will execute the loop body as long as the predicate is true. predicate Loop body true false DDC1123 PENGATURCARAAN I (C)
5.2 Pre Test and Post Test Loop REV00 5.2 Pre Test and Post Test Loop A posttest repetition statement first executes the loop body and then computers the predicate. If the predicate is true, the loop body is executed again; otherwise the repetition terminates. true predicate Loop body false DDC1123 PENGATURCARAAN I (C)
5.3 Initializing and Updating REV00 5.3 Initializing and Updating DDC1123 PENGATURCARAAN I (C)
5.4 Event Controlled and Counter Controlled REV00 5.4 Event Controlled and Counter Controlled If it is known in advance exactly how many times a loop will execute, it is known as a counter-controlled loop. int i = 1 ; while ( i <= 10 ) { printf(“i = %d\n”, i) ; i = i + 1 ; } DDC1123 PENGATURCARAAN I (C)
5.4 Event Controlled and Counter Controlled REV00 5.4 Event Controlled and Counter Controlled If it is NOT known in advance exactly how many times a loop will execute, it is known as an event-controlled loop. sum = 0 ; printf(“Enter an integer value: “) ; scanf(“%d”, &value) ; while ( value != -1) { sum = sum + value ; printf(“Enter another value: “) ; } DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 5.5 Loops in C #include <stdio.h> int main () { int i = 1 ; initialization of loop control variable /* count from 1 to 100 */ while ( i < 101 ) test of loop termination condition printf (“%d “, i) ; i = i + 1 ; modification of loop control } variable return 0 ; } DDC1123 PENGATURCARAAN I (C)
5.6 Others Statement related to looping REV00 5.6 Others Statement related to looping The break statement can be used in while, do-while, and for loops to cause premature exit of the loop. The continue statement can be used in while, do-while, and for loops. It causes the remaining statements in the body of the loop to be skipped for the current iteration of the loop. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 5.7 Recursive – Factorial Recursive functions Function that calls itself Can only solve a base case Divides up problem into What it can do What it cannot do - resembles original problem (Launches a new copy of itself (recursion) step) Eventually base case gets solved Gets plugged in, works its way up and solves whole problem DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 5.7 Recursive – Factorial Example: factorial: 5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3! ... Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6; DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 6.0 Text File DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 6.1 Concepts of a file Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data Storage of data in variables and arrays is only temporary DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 6.1 Concept of a file Data Hierarchy: Bit - smallest data item (Value of 0 or 1) Byte - 8 bits (Used to store a character) - Decimal digits, letters, and special symbols Field - group of characters conveying meaning Record - group of related fields - Represented by a struct or a class DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 6.2 File and Stream C views each file as a sequence of bytes File ends with the end-of-file marker Or, file ends at a specified byte Stream created when a file is opened Provide communication channel between files and programs Opening a file returns a pointer to a FILE structure DDC1123 PENGATURCARAAN I (C)
6.3 Input/Output Functions REV00 6.3 Input/Output Functions Output Function ( printf( ) ) Precise output formatting is the conversion specifications: flags, field widths, precisions, etc. Can perform rounding, aligning columns, right/left justification, inserting literal characters, exponential format, hexadecimal format, and fixed width and precision DDC1123 PENGATURCARAAN I (C)
6.3 Input/Output Functions REV00 6.3 Input/Output Functions Format printf( format-control-string, other-arguments ); Format control string: describes output format. Other-arguments: correspond to each conversion specification in format-control-string. Each specification begins with a percent sign(%), ends with conversion specifier DDC1123 PENGATURCARAAN I (C)
6.3 Input/Output Functions REV00 6.3 Input/Output Functions Input Function ( Scanf( ) ) Input formatting Capabilities Input all types of data Input specific characters Skip specific characters Format scanf(format-control-string, other-arguments); DDC1123 PENGATURCARAAN I (C)
6.3 Input/Output Functions REV00 6.3 Input/Output Functions Format-control-string Describes formats of inputs Other-arguments Pointers to variables where input will be stored Can include field widths to read a specific number of characters from the stream DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 Chapter 7 Array DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.1 Concepts Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name Position number Format: arrayname[ position number ] First element at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n – 1 ] DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.2 Using Arrays in C Initializers int n[ 4 ] = { 2, 4, 6, 8 }; If not enough initializers, rightmost elements become 0 int n[ 4 ] = { 0 } All elements 0 If too many a syntax error is produced syntax error C arrays have no bounds checking DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.2 Using Arrays in C If size omitted, initializers determine it int n[ ] = { 2, 4, 6, 8 }; 5 initializers, therefore 5 element array int n [4]; n[0] = 2; n[1] = 4; n[2] = 6; n[3] = 8; n [0] 2 n [1] 4 Memory location n [2] 6 n [3] 8 DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.3 Arrays and Functions The function prototype: void fillArray (int ages[ ], int numElements); The function definition header: void fillArray (int ages[ ], int numElements) The function call: fillArray (ages, SIZE); Notice that we are passing only the name of the array (the address) and that we aren’t returning anything (the function is void) because we will be modifying the original array from within the function. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.4 Two Dimentional Array Multiple subscripted arrays Tables with rows and columns (m by n array) Like matrices: specify row, then column Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 7.4 Two Dimentional Array Initialization int b[ 2 ][ 2 ] = {{ 1, 2 },{ 3, 4 }}; Initializers grouped by row in braces If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 Chapter 8 Pointers DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.1 Concepts Variables that holds the address of an object in the program Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.2 Pointer Variables Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain address of a variable that has a specific value (indirect reference) Indirection – referencing a pointer value DDC1123 PENGATURCARAAN I (C)
8.3 Accessing Variable Through Pointer REV00 8.3 Accessing Variable Through Pointer & (address operator) Returns address of operand int y = 5; int *yPtr; yPtr = &y; yPtr “points to” y // yPtr gets address of y yPtr y 5 yptr 500000 600000 Address of y is value of yptr DDC1123 PENGATURCARAAN I (C)
8.4 Pointer Declaration and Definition REV00 8.4 Pointer Declaration and Definition Pointer declarations * used with pointer variables int *myPtr; Declares pointer to an int (pointer of type int *) Multiple pointers require using a * before each variable declaration int *myPtr1, *myPtr2; Can declare pointers to any data type Initialize pointers to 0, NULL, or an address 0 or NULL – points to nothing (NULL preferred) DDC1123 PENGATURCARAAN I (C)
8.5 Initialization of Pointer Variable * REV00 8.5 Initialization of Pointer Variable * After pointer variable has been declared we can use the assignment operator to initialize the variable to any of the following: The value NULL An address The value of another pointer variable DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.6 Pointer and Functions Pointer to function Contains address of function Similar to how array name is address of first element Function name is starting address of code that defines function Function pointers can be Passed to functions Stored in arrays Assigned to other function pointers DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.7 Array and Pointer Arrays and pointers closely related Array name like a constant pointer Pointers can do array subscripting operations Declare an array b[ 5 ] and a pointer bPtr To set them equal to one another use: bPtr = b; The array name (b) is actually the address of first element of the array b[ 5 ] bPtr = &b[ 0 ] Explicitly assigns bPtr to address of first element of b DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.7 Array and Pointer Element b[ 3 ] Can be accessed by *( bPtr + 3 ) Where n is the offset. Called pointer/offset notation Can be accessed by bptr[ 3 ] Called pointer/subscript notation bPtr[ 3 ] same as b[ 3 ] Can be accessed by performing pointer arithmetic on the array itself *( b + 3 ) DDC1123 PENGATURCARAAN I (C)
8.8 Memory Allocation Function (malloc( ) and calloc( ) REV00 8.8 Memory Allocation Function (malloc( ) and calloc( ) Malloc declaration: malloc ( size ); Where size = number of bytes of memory to be allocated. After a successful call, malloc ( ) returns a pointer to the first byte of the region of memory allocated from the heap. If failure occurs (i.e. not enough memory), malloc ( ) will returns a null pointer. DDC1123 PENGATURCARAAN I (C)
8.8 Memory Allocation Function (malloc( ) and calloc( ) REV00 8.8 Memory Allocation Function (malloc( ) and calloc( ) Calloc declaration: calloc ( numberElement, sizeElement ); Where numberElement = the number of elements in the array. sizeElement = bytes required for each elements in array. Calloc function initialises the allocated memory to 0, whereas malloc function does not. Memory allocated using malloc( ) is limited by size of unsigned int. DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.9 Array of Pointer Arrays can contain pointers For example: an array of strings char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; Strings are pointers to the first character char * – each element of suit is a pointer to a char DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 8.9 Array of Pointer The strings are not actually stored in the array suit, only pointers to the strings are stored suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’ ’D’ ’i’ ’m’ ’o’ ’n’ ’d’ ’C’ ’l’ ’u’ ’b’ ’S’ ’p’ DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 Chapter 9 String DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 9.1 String Concepts Strings Series of characters treated as a single unit Can include letters, digits and special characters (*, /, $) String literal (string constant) - written in double quotes "Hello" Strings are arrays of characters String a pointer to first character Value of string is the address of first character DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 9.2 C String String in C is an array of characters ending with null character ( \0 ) The standard library contains string functions for: Copying Concatenating Comparing Locating substrings Basic memory management DDC1123 PENGATURCARAAN I (C)
9.3 String Input/Output Function REV00 9.3 String Input/Output Function DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 9.4 Array of String char *strcat(char *s1, const char *s2) Appends string s2 to array s1. The first character of s2 overwrites the terminating NULL character of s1. The value of s1 is returned char *strcpy(char *s1, const char *s2) Copies string s2 into array s1, value of s1 is returned DDC1123 PENGATURCARAAN I (C)
9.5 String Manipulation Function REV00 9.5 String Manipulation Function String handling library has functions to Manipulate string data Search strings Tokenize strings Determine string length DDC1123 PENGATURCARAAN I (C)
9.5 String Manipulation Function REV00 9.5 String Manipulation Function DDC1123 PENGATURCARAAN I (C)
Chapter 10 Derived types- Enumerated, Structure and Union REV00 Chapter 10 Derived types- Enumerated, Structure and Union DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.1 The Type Definition typedef Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example: typedef struct Card *CardPtr; Defines a new type name CardPtr as a synonym for type struct Card * typedef does not create a new data type Only creates an alias DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.2 Structure Structures Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.2 Structure struct card { char *face; char *suit; }; struct introduces the definition for structure card card is the structure name and is used to declare variables of the structure type card contains two members of type char * These members are face and suit DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.3 Accessing Structure Accessing structure members Dot operator (.) used with structure variables card myCard; printf( "%s", myCard.suit ); Arrow operator (->) used with pointers to structure variables card *myCardPtr = &myCard; printf( "%s", myCardPtr->suit ); myCardPtr->suit is equivalent to ( *myCardPtr ).suit DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.4 Complex Structure Initializer lists card oneCard = { "Three", "Hearts" }; Assignment statements card threeHearts = oneCard; Could also declare and initialize three Hearts as follows: card threeHearts; threeHearts.face = “Three”; threeHearts.suit = “Hearts”; DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.5 Array of Structure In C we can combine different types to come up with the composite data type. If the array elements belong to the same student such array are called parallel arrays. int idno[array_size] int year[array_size] char status[array_size] DDC1123 PENGATURCARAAN I (C)
10.6 Structure and Function REV00 10.6 Structure and Function Passing structures to functions Pass entire structure Or, pass individual members Both pass call by value To pass structures call-by-reference Pass its address Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Pass the structure DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 10.7 Union Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Conserves storage Only the last data member defined can be accessed DDC1123 PENGATURCARAAN I (C)
DDC1123 PENGATURCARAAN I (C) REV00 REV00 10.7 Union union declarations union Number { int x; float y; }; union Number value; Valid union operations Assignment to union of same type: = Taking address: & Accessing union members: . Accessing members using pointers: -> DDC1123 PENGATURCARAAN I (C)