(Slides) C Programming Tutorial

SlideShow Transcript

Slide 1: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 C Programming A computer needs to be programmed to solve a problem. ? (1)C is a programming language developed at AT&T bell labs. (2)Any programming Language can be divided in to two categories. (3)Problem oriented (High level language) (4)Machine oriented (low level language) (5)C is considered as a middle level Language. (6)C is modular,portable,reusable (7)C is a language of few words that are known as keyword. (8)C code can be written in routines called function (9)Algorithm: to understand about the program (10)C is famous because reliable,simple,easy (11)Compactness,generality,efficiency,modularity and simplicity www.intellibitz.com training@intellibitz.com

Slide 2: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Preparing to program (1)Determine the objective of the ? ? program. (2)Determine the methods you want to use . (3)Create the program to solve the problem (4)Run the program for output www.intellibitz.com training@intellibitz.com

Slide 3: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Feature of C Program Structured language ? General purpose language ? Portability ? Code Re usability ? Ability to customize and extend ? Limited Number of Key Word ? www.intellibitz.com training@intellibitz.com

Slide 4: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Structured Language (1)It has the ability to divide and hide all the information and instruction. (2)Code can be partitioned in C using functions or code block. (3)C is a well structured language compare to other. www.intellibitz.com training@intellibitz.com

Slide 5: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Portability Portability is the ability to port or use the ? software written . One computer C program can be ? reused. By modification or no modification. ? www.intellibitz.com training@intellibitz.com

Slide 6: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 General Purpose Language (1)Make it ideal language for system programming. (2)It can also be used for business and scientific application. (3)ANSI established a standard for c in 1983. (4)The ability of c is to manipulate bits,byte and addresses. (5)It is adopted in later 1990. www.intellibitz.com training@intellibitz.com

Slide 7: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Code Re usability and Ability to Customize and Extend (1) A programmer can easily create his own function (2)It can can be used repeatedly in different application (3)C program basically collection of function (4)The function are supported by 'c' library (5)Function can be added to 'c' library continuously www.intellibitz.com training@intellibitz.com

Slide 8: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Limited number of keywords and unix library function There are only 32 keywords in 'C' ? 27 keywords are given by ritchie ? 5 is added by ANSI ? the strength of 'C' is lies in its in-built function ? unix system provides as large number of C ? function some function are used in operation . ? other are for specialized in their application ? www.intellibitz.com training@intellibitz.com

Slide 9: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 'C' program structure Pre-processor directives ? Global declarations ? Main( ) ? { ? Local variable deceleration ? Statement sequences ? Function invoking ? } ? www.intellibitz.com training@intellibitz.com

Slide 10: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Writing,compiling and executing Program need to be compiled before execution ? 'C' is case sensitive ? Linking is the process of joining other program files ? All keywords are lowercased ? C is case sensitive ? Keywords cannot be used for any other purpose ? C statement always ends with a semicolon ? No blank spaces are allowed with in a variable,constant ? or keyword File should be have the extension .c ? www.intellibitz.com training@intellibitz.com

Slide 11: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Recap of previous session Introduction to programming ? Features of 'C' ? Writing,Compiling,Linking and executing ? Writing a 'C' program ? www.intellibitz.com training@intellibitz.com

Slide 12: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Introduction Data types are used to declare a variety of ? different values. Variables are important tool of a programmer ? They are used to keep account of various ? values . Like in a game ,weight or height of the ? player etc www.intellibitz.com training@intellibitz.com

Slide 13: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Data types Variable is an identifier ? Variable must be declared before it is used in the program ? 'C' has 5 basic built-in data types ? 'C' supports aggregates data types ? Data type defines a set of values that a variable can store ? along with a set of operations that can be performed on it. A variable takes different values at different times ? Modifiers are used to alter the meaning of the base type to fit ? the needs of various situations more precisely . www.intellibitz.com training@intellibitz.com

Slide 14: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 'C' has five basic built in data type Char (character value) ? Int (integer value) ? Float (Floating point value) ? Double (Double floating point value) ? Void (Valueless) ? www.intellibitz.com training@intellibitz.com

Slide 15: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Void is used to Declare explicitly that a function is not ? returning a value Declare explicitly that a function has no ? parameter Create generic pointer ? 'C' also supports several aggregate types ? including structure ,union ,enumeration and user defined types. www.intellibitz.com training@intellibitz.com

Slide 16: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Declaring a variable A variable should be declare before it is used in the program ? Example: data-type var-list; ? Data type must be valid data type and var-list may be consist ? of one or more identifier names separated by commas operator. The declaration indicates the compiler about the variable ? names and types of data Example : int count; ? double balance; ? float amount; ? Int, double,and float are keywords and cannot be used as ? variable names. www.intellibitz.com training@intellibitz.com

Slide 17: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Assigning values Values can be assigned to variable using the assignment operator ? (=). var-name=expression; ? An expression can be a single constant or combination of ? variables,operators and constants. Data-type var-name=constant; ? int value=250; ? char name= “salini” ? double amount =76.80 ? www.intellibitz.com training@intellibitz.com

Slide 18: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Type Modifier The basic data types may have various modifiers preceding ? them except type void. A modifier is used to alter the meaning of the base type to fit ? the needs of various situations more precisely. The list of modifier: Signed ? Unsigned ? Long ? Short ? www.intellibitz.com training@intellibitz.com

Slide 19: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Character This is a group of 8 data bits. ? 'C' represents either a letter of roman alphabet. ? Small integer in the range of 0 through to +255. ? To give a named memory area in which a single ? letter has to be stored Declaration ? char letter; www.intellibitz.com training@intellibitz.com

Slide 20: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Integer There are two types of integers Short ? Long ? The actual number of bits used in these types is implementation dependent. For sixteen bit machine ,the long integer is two machine ? words long,and short integer is one machine word long. short int smaller_number; long int big_number; www.intellibitz.com training@intellibitz.com

Slide 21: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Real number Float offers two sizes-float and double that ? are similar to integer type Approximately float represents six significant ? digit and double is twelve. float length_of_water_line; double displacement; www.intellibitz.com training@intellibitz.com

Slide 22: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Signed and unsigned prefixes The deceleration can be preceded by the word ? unsigned for both the character and integer types which the range so that 0 is the minimum,and the maximum is twice that of the signed data type. If the word in memory is going to be used as a bit ? pattern or a mask and not a number, the use of unsigned is strongly urged. The default for the int types is always signed,and ? char is machine dependent. www.intellibitz.com training@intellibitz.com

Slide 23: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Character Set Characters are used to form the words, numbers and ? expression The characters in 'C' are grouped into the following categories: character set- alphabets from A....Z,a....z ? All decimal digits from 0.....9 ? Special characters include , . ; : ? '\" !/ \\ |~-$ % # & ^ * _ + < > ( ) { } [ ] blank space www.intellibitz.com training@intellibitz.com

Slide 24: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Keywords and Indentifier Every ' C' word is classified as either a keyword or an ? identifier. All identifier have fixed meaning, which can not be changed. ? Rules for identifier Legal characters are a-z, A-Z,0-9 and _ ? Case significant ? The first character must be a letter or _ ? Identifier can be of any length ? The reserved keywords should not be used as identifier. ? Valid identifier invalid identifier Count . 1count ? Test23 .hi! ? high_bal . high balance ? www.intellibitz.com training@intellibitz.com

Slide 25: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 keywords Auto double int struct break ? Long switch case enum register ? Typedef char extern return union ? Float unsigned short continue for ? Signed void default goto sizeof ? Volatile do if static while ? Else const ? www.intellibitz.com training@intellibitz.com

Slide 26: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Constants Supports numerical as well as character constants. ? 'C' supports several types of constants. ? 'C' has two types of modifier. ? Variable of type const cannot be modified ? Constants are fixed values that do not change ? during the execution of a program. 'C' supports both numeric and character constants ? www.intellibitz.com training@intellibitz.com

Slide 27: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 C supports several types constant Numeric constant ? Integer constant ? Floating point (real) constant Character constant ? Single character constant ? String constant The following rules apply to all numeric constant ? Non- digit characters and blanks cannot be included ? Can be preceded by minus sign www.intellibitz.com training@intellibitz.com

Slide 28: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Escape sequences Certain non printing characters as well as the backslash (\\) ? and the apostrophe('), can be expressed in terms of escape sequence. Example for new line \\n ? Bell \\a carriage return \\r ? Backspace \\b formfeed \\f ? Horizontal tab \\t quotation mark \\” ? Vertical tab \\v apostrophe \\' ? Backslash \\\\ question mark \\? ? Null \\0 ? www.intellibitz.com training@intellibitz.com

Slide 29: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Access modifier C has two type modifiers that can be used to control the way in which ? variables may be accessed or modified. These are Const ? example const int my_age=39; Volatile ? example volatile int date www.intellibitz.com training@intellibitz.com

Slide 30: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Operator Three kinds of operators. ? Two types of casting. ? 'C' includes a class of operators . ? That act upon a single operand to produce a new ? value. Ternary operator operates on three operands. ? 'C' is very rich in built -in operator. ? An operator is a symbol that indicates the compiler ? to perform specific mathematical or logical manipulation. www.intellibitz.com training@intellibitz.com

Slide 31: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Three general classes of operator Arithmetic operator ? ? Relational operator ? Assignment operator Special operators to perform particular task Ternary (conditional) operator ? Size of operator ? Comma operator ? & Operator ? . and -> operator ? www.intellibitz.com training@intellibitz.com

Slide 32: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Arithmetic Operators Operator Action Example _ Subtraction a-b + Addition a+b * Multiplication a*b / division a/b % modulus Division a%b - Decrement a- or -a ++ increment a+ or ++ www.intellibitz.com training@intellibitz.com

Slide 33: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 casting When operand differ in type they may undergo type ? conversion before the expression takes on its final value. ? The final result will be expressed in the highest precision possible, consistent with data type of the operand. There are two types of casting ? Implicit ? Explicit www.intellibitz.com training@intellibitz.com

Slide 34: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Implicit casting If either operand is long double, convert the ? other to long double If either operand is double , convert the other ? to float. Convert char and short to int. ? If either operand is long convert the other to ? long. www.intellibitz.com training@intellibitz.com

Slide 35: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Explicit casting The expression can be converted to a different data ? type if desired data type, enclosed in parentheses (data type) expression ? int a+m; ? sqrt ((double)x) ? The cast produces the value of the proper type;x ? itself is not altered www.intellibitz.com training@intellibitz.com

Slide 36: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Linking with math library This is following code links to the math library ? cc -o cast cast.c – lm the -l switch stands for 'library' The library that is searched in the case is libm.a the path u search that is '/usr/lib' where libm.a is found. www.intellibitz.com training@intellibitz.com

Slide 37: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Unary operator 'C' include a class of operators that act upon ? a single operand to produce a new value. ? The most common unary operation is unary minus. Example ? -143 -(a+m) ? -12 -3.2 www.intellibitz.com training@intellibitz.com

Slide 38: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Increment and Decrement x=x+1; x+=1; x++; x=x-1; x-=1; www.intellibitz.com training@intellibitz.com

Slide 39: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Postfix and Prefix A postfix expression is obtained by post ? fixing a++ or – operator ? The value of the expression is the value of the operand. x=10; y=++x; x=10; y=x++; www.intellibitz.com training@intellibitz.com

Slide 40: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Relational and Logical operator Operator Meaning ? < is less then <= is less then or equal to > is greater then >= is greater then or equal to == is equal to != is not equal && Logical AND || Logical OR ! Logical NOT www.intellibitz.com training@intellibitz.com

Slide 41: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Conditional (:?) Operator var=exp1?exp2:exp3 x=10; y=x>9 ?100:200; x=10; if (x>9) { y=100; } else { y=200; } www.intellibitz.com training@intellibitz.com

Slide 42: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Recap of previous session Data type ? ? Constants ? Operator www.intellibitz.com training@intellibitz.com

Slide 43: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 POINTERS Simply stated, a pointer is an address. Instead of ? being a variable, it is a pointer to a variable stored somewhere in the address space of the program. It ? is always best to use an example so load the file named POINTER.C and display it on your monitor for an example of a program with some pointers in it. For the moment, ignore the data definition statement ? where we define index and two other fields www.intellibitz.com training@intellibitz.com

Slide 44: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 POINTERS CONT.. ? beginning with a star. It is properly called an ? asterisk, but for reasons we will see later, let's agree to call it a star. If you observe the statement in line 8, it ? should be clear that we assign the value of 39 to the variable named index. This is no surprise, we have ? been doing it for several programs now. The statement in line 9 however, says to assign to pt1 a ? strange looking value, namely the variable index with www.intellibitz.com training@intellibitz.com

Slide 45: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 POINTERS CONT.... ? An ampersand in front of it. In this example, pt1 and pt2 ? are pointers, and the variable named index is a simple variable. Now we have a problem similar to the old chicken and egg problem. We need to learn how to use pointers in a program, but to do so requires ? that first we define the means of using the pointers in the program. The following two rules will be somewhat confusing to ? you at first, but we need to state the definitions before we can use them. Take your time, and the whole ? thing will clear up very quickly. www.intellibitz.com training@intellibitz.com

Slide 46: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 POINTERS ? TWO VERY IMPORTANT RULES ? The following two rules are very important when using ? pointers and must be thoroughly understood. 1. A variable name with an ampersand in front of it ? defines the address of the variable and therefore points to the variable. . 2. A pointer with a star in front of it refers to the value ? of the variable pointed to by the pointer line. www.intellibitz.com training@intellibitz.com

Slide 47: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 POINTERS ? Twelve of the program can be read as \"The stored ? (starred) value to which the pointer pt1 points is assigned the value 13\". This is commonly referred ? to as dereferencing the pointer. Now you can see why it is convenient to think of the asterisk as a star, it sort of sounds like the word store. MEMORY AIDS ? 1. Think of & as an address. ? 2. Think of * as a star referring to stored. ? www.intellibitz.com training@intellibitz.com

Slide 48: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 NULL POINTERS #include ? int *ip = NULL; ? if(ip != NULL) ? printf(\"%d\\n\", *ip); ? www.intellibitz.com training@intellibitz.com

Slide 49: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 NULL POINTERS #include ? ? char *mystrstr(char input[], char pat[]) { ? char *start, *p1, *p2; ? for(start = &input[0]; *start != '\\0'; start++) ? { /* for each position in input string... */ ? p1 = pat; /* prepare to check for pattern string there */ ? p2 = start; ? while(*p1 != '\\0'){ ? if(*p1 != *p2) /* characters differ */ ? break; ? p1++; ? p2++; ? } ? if(*p1 == '\\0') /* found match */ ? return start; ? } ? ? return NULL; ? } ? www.intellibitz.com training@intellibitz.com

Slide 50: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Equivalence in Array and pointer There are a number of similarities between arrays and pointers ? in C. If you have an array ? int a[10]; ? ? you can refer to a[0], a[1], a[2], etc., or to a[i] where i is an int. If ? you declare a pointer variable ip and set it to point to the beginning of an array: ? int *ip = &a[0]; ? www.intellibitz.com training@intellibitz.com

Slide 51: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Arrays and Pointers as Function Arguments int getline(char *line, int max){ ? int nch = 0; ? int c; ? max = max - 1; /* leave room for '\\0' */ ? #ifndef FGETLINE ? while((c = getchar()) != EOF) ? #else ? while((c = getc(fp)) != EOF) ? #endif{ ? if(c == '\\n') ? break; ? if(nch < max){ ? line[nch] = c; ? nch = nch + 1; ? } ? } ? if(c == EOF && nch == 0) ? return EOF; ? line[nch] = '\\0'; ? return nch; ? } ? www.intellibitz.com training@intellibitz.com

Slide 52: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 String char internal_string_1[] = \"Hello\"; ? char internal_string_2[] = \"world\"; ? char *p1 = &internal_string_1[0]; ? int len = strlen(&internal_string_2[0]); ? www.intellibitz.com training@intellibitz.com

Slide 53: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Preprocessor Directives Preprocessor directives are instructions to ? the compiler that begin with a # sign. ? Executed before the compilation begin. ? Most frequently used directives - #include - #define www.intellibitz.com training@intellibitz.com

Slide 54: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Notes It instruct s the compiler to include a header file,specified within angled ? brackets or double quote,after the #include statement into the source code A header or a standard library contain a set of related functions,which ? perform various tasks in a program. Header file generally have extension '.h'. ? stdio.h contains a set of console i/o functions ? #include referred to as nested includes. ? The number of nesting varies from compiler to compiler. ? Header files are usually placed in a special library called include . ? If the name of the header file is specified in angled brackets,the file ? searched for in this directory the file name is enclosed in double quotes,the file is looked for in an implementation-defined manner. www.intellibitz.com training@intellibitz.com

Slide 55: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Macros Macro is imperative that there is no space between the macro name ? and the opening parenthesis. #include “stdio.h” #define START 0 /*starting point of loop*/ #define ENDING 9 /*Ending point of loop*/ #define MAX (A,B) ((A)>(B)?(B):(A)) /*Max macro definition*/ #define MIN (A,B) ((A)>(B)?(B):(A)) /*Min macro definition*/ main ( ) { int index, mn,mx; int count = 5 . mx=max (index,count); mn=min(index,count); . . } www.intellibitz.com training@intellibitz.com

Slide 56: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Getchar( ) The simplest i/o function to read the input and show the ? standard output . The getchar( ) function reads a single character from the ? console. The function does not require any arguments,through a pair ? of parentheses must follow the word getchar. Example ? =getchar( ); char name; name =getchar( ); www.intellibitz.com training@intellibitz.com

Slide 57: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Putchar( ) Single character can be written to the terminal using the ? 'C' library function putchar( ) Example putchar (var_name) name ='A' putchar(name) The above putchar ( ) will display the character A on the screen www.intellibitz.com training@intellibitz.com

Slide 58: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Printf( ) The printf( )function provides certain features that can be effectively exploited to ? control the alignment and spacing of prints outs on the terminal. printf(“format-string”,arg1,arg2,arg3,......); ? The format -strings defines the way in which the subsequent argument ? arg1,arg2...are to be displayed. The format string consist of two types ? -Character that will be printed on the terminal. -format commands that defines the output format of each argument Printf(“hello %c %d %s”, 'x', '12', “there!”); will display hello x 12 there! www.intellibitz.com training@intellibitz.com

Slide 59: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Scanf( ) Scanf is used for reading in data from the standard input ? (keyboard). Scanf (“format-string” &arg1,&arg2...); The format string may include: Field specifier ? Optional field width ? Optional white and non-whit character. Example: scanf (“%d”, &count); www.intellibitz.com training@intellibitz.com

Slide 60: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 List all format Code Format %c Character %d Signed decimal integer %i Signed decimal integer %e Scientific notation[e] %E Scientific notation[E] %f Decimal floating point %o unsigned octal %s String of character %u unsigned decimal integer %x unsigned Hexadecimal (lower) %X unsigned Hexadecimal (upper) %p dispaly a pointer %% print a % www.intellibitz.com training@intellibitz.com

Slide 61: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Mixed data Output It is permitted to mix data types in one printf ? statement. Example Printf (“%d%f%s%c, a,b,c,d); this is big advantage in the 'C' . www.intellibitz.com training@intellibitz.com

Slide 62: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Types The type of a variable determines what kinds of values it may take on. An ? operator computes new values out of old ones. An expression consists of variables, constants, and operators combined to perform some useful computation. In this chapter, we'll learn about C's basic types, how to write constants and declare variables of these types, and what the basic operators are. As Kernighan and Ritchie say, ``The type of an object determines the set ? of values it can have and what operations can be performed on it.'' This is a fairly formal, mathematical definition of what a type is, but it is traditional (and meaningful). There are several implications to remember. www.intellibitz.com training@intellibitz.com

Slide 63: INTELLIBITZ ? Technologies System Engineer (C) SE_CCC_V1.0.0 Types 1. The ``set of values'' is finite. C's int type can not represent all of the integers; its float type can not represent all floating-point numbers. 2. When you're using an object (that is, a variable) of some type, you may have to remember what values it can take on and what operations you can perform on it. For example, there are several operators which play with the binary (bit-level) representation of integers, but these operators are not meaningful for and may not be applied to floating-point operands. 3. When declaring a new variable and picking a type for it, you have to keep in mind the values and operations you'll be needing. In other words, picking a type for a variable is not some abstract academic exercise; it's closely connected to the way(s) you'll be using that variable. www.intellibitz.com training@intellibitz.com

Slide 64: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Types cont... There are only a few basic data types in C. The first ones we'll be ? encountering and using are: ? * char a character ? * int an integer, in the range -32,767 to 32,767 ? * long int a larger integer (up to +-2,147,483,647) ? * float a floating-point number ? * double a floating-point number, with more precision and ? perhaps greater range than float www.intellibitz.com training@intellibitz.com

Slide 65: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Constants A constant is just an immediate, absolute value found in an ? expression. The simplest constants are decimal integers, e.g. 0, 1, 2, 123 . Occasionally it is useful to specify constants in base 8 or base 16 (octal or hexadecimal); this is done by prefixing an extra 0 (zero) for octal, or 0x for hexadecimal: the constants 100, 0144, and 0x64 all represent the same number. (If you're not using these non-decimal constants, just remember not to use any leading zeroes. If you accidentally write 0123 intending to get one hundred and twenty three, you'll get 83 instead, which is 123 base 8.) www.intellibitz.com training@intellibitz.com

Slide 66: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Declaration .You may wonder why variables must be declared before use. There are two reasons: 1. It makes things somewhat easier on the compiler; it knows right away what kind of storage to allocate and what code to emit to store and manipulate each variable; it doesn't have to try to intuit the programmer's intentions. 2. It forces a bit of useful discipline on the programmer: you cannot introduce variables willy-nilly; you must think about them enough to pick appropriate types for them. (The compiler's error messages to you, telling you that you apparently forgot to declare a variable, are as often helpful as they are a nuisance: they're helpful when they tell you that you misspelled a variable, or forgot to think about exactly how you were going to use it.) www.intellibitz.com training@intellibitz.com

Slide 67: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Function calls printf(\"Hello, world!\\n\") ? printf(\"%d\\n\", i) ? sqrt(144.) ? Getchar() ? ? www.intellibitz.com training@intellibitz.com

Slide 68: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Expression statement Most of the statements in a C program are ? expression statements. An expression statement is simply an expression followed by a semicolon. The lines ? i = 0; ? i = i + 1; ? and ? printf(\"Hello, world!\\n\"); ? ? www.intellibitz.com training@intellibitz.com

Slide 69: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 If statement if( expression ) ? { ? statement1 ? statement2 ? statement3 ? } ? ? www.intellibitz.com training@intellibitz.com

Slide 70: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Boolean expression < less than ? <= less than or equal ? > greater than ? >= greater than or equal ? == equal ? != not equal ? www.intellibitz.com training@intellibitz.com

Slide 71: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 While loop int x = 2; ? ? while(x < 1000) ? { ? printf(\"%d\\n\", x); ? x = x * 2; ? } ? ? www.intellibitz.com training@intellibitz.com

Slide 72: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 For loop for (i = 0; i < 10; i = i + 1) ? printf(\"i is %d\\n\", i); ? www.intellibitz.com training@intellibitz.com

Slide 73: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Break and continue #include ? #include ? Main() { ? int i, j; ? printf(\"%d\\n\", 2); ? for(i = 3; i <= 100; i = i + 1) ? { ? for(j = 2; j < i; j = j + 1) ? { ? if(i % j == 0) ? break; ? if(j > sqrt(i)) ? { ? printf(\"%d\\n\", i); ? break; ? } ? } ? } ? return 0; ? } ? www.intellibitz.com training@intellibitz.com

Slide 74: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Character output The library function putc ( ) writes a single character to a specified ? stream. Its prototype, in stdio.h int putc (int ch,FILE *fp) ? With other character function ,it is for mally called a type int,but ? only the lower-order byte is used. To write a line of characters to a stream fputs( ) library function is ? used. fputs( ) doesn't add a new line to the end of the string if you want u ? have to include it. char fputs(char *str,FILE *fp); www.intellibitz.com training@intellibitz.com

Slide 75: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 File pointer and Fopen ifp = fopen(\"input.dat\", \"r\"); ? if(ifp == NULL) ? { ? printf(\"can't open file\\n\"); ? exit or return ? } ? www.intellibitz.com training@intellibitz.com

Slide 76: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 I/O with file pointer #include ? /* Read one line from fp, */ ? /* copying it to line array (but no more than max chars). */ ? /* Does not place terminating \\n in line array. */ ? /* Returns line length, or 0 for empty line, or EOF for end-of-file. */ ? int fgetline(FILE *fp, char line[], int max) { ? int nch = 0; ? int c; ? max = max - 1; /* leave room for '\\0' */ ? while((c = getc(fp)) != EOF) { ? if(c == '\\n') ? break; ? if(nch < max) ? { ? line[nch] = c; ? nch = nch + 1; ? } ? } ? if(c == EOF && nch == 0) ? return EOF; ? line[nch] = '\\0'; ? return nch; ? } ? www.intellibitz.com training@intellibitz.com

Slide 77: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Predefined Stream ? if((ifp = fopen(filename, \"r\")) == NULL) { fprintf(stderr, \"can't open file %s\\n\", filename); exit or return } www.intellibitz.com training@intellibitz.com

Slide 78: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Closing files Although you can open multiple files, there's a limit ? to how many you can have open at once. If your program will open many files in succession, you'll want to close each one as you're done with it; otherwise the standard I/O library could run out of the resources it uses to keep track of open files. Closing a file simply involves calling fclose with the file pointer as its argument: fclose(fp); ? www.intellibitz.com training@intellibitz.com

Slide 79: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Character Input/output #include ? /* copy input to output */ ? Main() { ? int c; ? c = getchar(); ? while(c != EOF) ? { ? putchar(c); ? c = getchar(); ? } ? return 0; ? } ? www.intellibitz.com training@intellibitz.com

Slide 80: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 UNIX File Redirection UNIX has a facility called redirection which allows a program to access a ? single input file and a single output file very easily. The program is written to read from the keyboard and write to the terminal screen as normal. To run prog1 but read data from file infile instead of the keyboard, you ? would type prog1 < infile ? To run prog1 and write data to outfile instead of the screen, you would type ? prog1 > outfile ? Both can also be combined as in ? prog1 < infile > outfile ? Redirection is simple, and allows a single program to read or write data to ? or from files or the screen and keyboard. Some programs need to access several files for input or output, redirection ? cannot do this. In such cases you will have to use C's file handling facilities. www.intellibitz.com training@intellibitz.com

Slide 81: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Memory Management Dynamic memory management www.intellibitz.com training@intellibitz.com

Slide 82: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Agenda Introduction / Overview ? Memory Leak ? Valgrind ? Bounds Checker ? Case study ? Summary ? Reference ? www.intellibitz.com training@intellibitz.com

Slide 83: INTELLIBITZ Technologies Introduction / System Engineer (C) Dynamic memory management Overview Memory Allocation At Run Time Is Referred ? As Dynamic Memory Allocation. Dynamic Memory Management Plays Is An ? Explicit Action In Language Like C , C++. Hard Track Problems ? Freeing An Allocated Memory Twice. – Running Off The Edges Of The Alloc ‘d Buffer. – Failing To Keep Track Of Alloc ‘d Block. – www.intellibitz.com training@intellibitz.com

Slide 84: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Memory Leak What is ? ? Chunk of Memory Allocated and Never been – Freed in the Course of Program. Typically happens when you reset pointer to – NULL or to a New Address without freeing it first. How to Solve ? ? Find out where exactly Memory Leak Occurred. – www.intellibitz.com training@intellibitz.com

Slide 85: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Memory Leak cont… Why is it Bad? ? Reduces the performance of the Application. – Memory Intensive and Long Run Application May Fail. – Leads to Application Crash. – Difficult to Detect. – Are there any Tools ? ? Valgrind – Bounds Checker – Rational Purify Plus – Memprof – www.intellibitz.com training@intellibitz.com

Slide 86: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind Developed by Julian Seward. ? It is Non-Intrusive. ? Finds Memory Leak in any Application without ? Recompilation. Identifies ? Un-initialized Data. – Reading/Writing Memory after it has been freed. – Reading/Writing Memory off the allocated Block. – Memory Leaks – www.intellibitz.com training@intellibitz.com

Slide 87: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Installation ? Where do I get Installable ? – http://valgrind.kde.org/ ? How to Install ? – From Source Package (valgrind-2.0.0.tar.bz2) ? $bunzip valgrind-2.0.0.tar.bz2 – $cd valgrind-2.0.0 – $./configure –prefix=“installation-directory” – $make – $make install – From Binary Package (valgrind-2.0.0-1.rh90.dag.i386) ? #rpm –i –v valgrind-2.0.0-1.rh90.dag.i386 – www.intellibitz.com training@intellibitz.com

Slide 88: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Usage ? Valgrind [val-opt] prog-to-check [prog-opt] – Example ? Valgrind –skin=memcheck ls –l – ? `“skin” --- specifies one of the functionality valgrind supports ? “ls –l” --- specifies the program to be analyzed. Valgrind writes a commentary,detailed error reports and – other significant events in user friendly format. Output Format – ===process-id=== Message-from-valgrind ? example – ? ===12343=== Invalid Read www.intellibitz.com training@intellibitz.com

Slide 89: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Functionality Support ? Valgrind generates reports based on the value – specified in the “skin” option. The supported skin/functionalities are – Memcheck ? Addrcheck ? Helgrind ? Cachegrind ? www.intellibitz.com training@intellibitz.com

Slide 90: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Memcheck ? Detects uninitialized data/memory block. – Detects Memory Leak. – Detects Invalid Memory Read/Write. – Slow compared to other functionality. – Addrcheck ? Light Weight version of Memcheck. – Does not check for Uninitialised data/Memory. – Faster than Memcheck. – www.intellibitz.com training@intellibitz.com

Slide 91: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Cachegrind ? Profiles I1,D1 and L2 Caches. – Simulates I1,D1 and L2 Caches. – Helgrind ? Idenitifies Memory Location Which are accessed – without Synchronization. Identifies Data Race in Multithreaded Programs. – www.intellibitz.com training@intellibitz.com

Slide 92: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Memcheck ? It supports 2 flags – --leak-check=[no/yes] ? When disabled (no) , identifies the number of alloc ‘d and – freed block. When enabled (yes) , identifies the memory leaks. – --show-reachable=[no/yes] ? When disabled (no) , reports block of memory for which – pointer it is not available and not freed. When enabled (yes) , reports block of memory for which – pointer is available and and not freed. www.intellibitz.com training@intellibitz.com

Slide 93: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Uninitialised Memory (example1.c) ? int main () { char *cptr = NULL; cptr = (char *) malloc (sizeof (char)) ; if (cptr) { printf (\"Value of cptr = [%c]\\n\" ,cptr [0]) ; } free (cptr) ; cptr = NULL ; return 0 ; } $gcc –o example1 –g example1.c $valgrind –skin=memcheck –leak-check=yes ./example1 www.intellibitz.com training@intellibitz.com

Slide 94: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Reading/Writing Freed Memory ? int main () { char *cptr = NULL; cptr = (char *) calloc (1, sizeof (char) * 128) ; if (cptr) { strcpy (cptr , \"Example...2\") ; free (cptr) ; printf (\"The Program Name is [%s]\\n\" , cptr) ; strcpy (cptr , \"End of Example 2\" ) ; } return 0 ; } www.intellibitz.com training@intellibitz.com

Slide 95: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Reading/Writing off the allocated block ? int main () { char *cptr = NULL; cptr = (char *) calloc (1, sizeof (char) * 10 ) ; if (cptr) { strcpy (cptr , \"Example3\") ; printf (\"Character At position 10 is [%sc]\\n\" , cptr [10]) ; cptr [10] = 'c' ; } free (cptr) ; cptr = NULL ; return 0 ; www.intellibitz.com training@intellibitz.com

Slide 96: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Memory Leak ? int main () { char *cptr = (char *) calloc (1, sizeof (char) * 25) ; if (cptr) { strcpy (cptr , \"Hello!\") ; } function () ; } void function () { char *ptr = NULL ; ptr = (char *) calloc (1 , sizeof (char) * 128) ; if (ptr){ strcpy (ptr , \"Example 5\") ; } } www.intellibitz.com training@intellibitz.com

Slide 97: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Illegal Memory Free ? int main () { char *cptr = (char *) calloc (1, sizeof (char) * 128) ; if (cptr) { strcpy (cptr , \"Testing...\") ; printf (\"The string is [%s]\" , cptr) ; free (cptr) ; } free (cptr) ; return 0 ; } www.intellibitz.com training@intellibitz.com

Slide 98: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Valgrind cont… Advantages ? Good memory checker and more, can also be used for – profiling. Really Fast for Memory Checker. – Code doesn’t be instrumented. – It is an open source and with excellent support – Disadvantages ? Only available for Linux x86 – Might sometimes give false positives if code is compiled – with optimization. www.intellibitz.com training@intellibitz.com

Slide 99: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Bounds Checker Available on Window9x/2000/NT Platform. ? Can be Used With Windows ME , If Windows ? ME took kit is installed. Bounds Checker can be used with VC++ ? Integrated Environment or as a Standalone Application or from Dos Command Line. www.intellibitz.com training@intellibitz.com

Slide 100: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Bounds Checker cont… What it does? ? Identifies Memory Overrun. – Memory Leak. – Dangling Pointer. – Windows Function Failure. – Invalid Argument to windows Function. – Stack Memory Overrun. – Array index out of bound. – Returning Pointer to Local Variable – www.intellibitz.com training@intellibitz.com

Slide 101: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Bounds Checker cont… Using Microsoft Visual C++ IDE ? – On file menu , click open workspace to locate and open your program. – On bounds check menu , click integrated debugging to enable bounds checker. – On the build menu, point to start debug, and then click go. www.intellibitz.com training@intellibitz.com

Slide 102: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Bounds Checker cont… Using Bounds Check ? Standalone Application Start Bounds Checker – Standalone Application On Bounds Checker File – menu, click Open. Select the file you want to – load and click open On the program menu , click – Run. www.intellibitz.com training@intellibitz.com

Slide 103: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies main () ? { char *name = NULL ; int n = -1; name = (char *) malloc (10) ; printf (\"String is [%s]\\n\" , name) ; name [n] = 'U' ; name [10] = 'O' ; name = (char *) calloc (1 , sizeof (char) * 10) ; free (name) ; printf (\"The character at position 10 is [%c]\\n\" , name [10]) ; free (name) ; return 0 ; } www.intellibitz.com training@intellibitz.com

Slide 104: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Array Index Outoff ? Range In C language array – index starts from ‘0’. Since n = -1 , name[n] = – ‘U’ is an invalid write. Bounds checker – identifies the above error as Index Out of Range. www.intellibitz.com training@intellibitz.com

Slide 105: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Memory Overrun ? The memory block – allocated for name is 10 bytes. name [10] = ‘O’ is an – invalid write. Bounds checker – identifies the above error has writing overflows memory. www.intellibitz.com training@intellibitz.com

Slide 106: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Memory Leak ? The pointer “name” pointing – to previously allocated memory is reassigned with new pointer before freeing the memory block to which it was pointing. Pointer to previously – allocated memory is lost. Bounds Checker Identifies it – as memory leak. www.intellibitz.com training@intellibitz.com

Slide 107: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies Dangling Pointer ? Trying to access – memory which has been freed. Bounds Checker – Identifies it has Dangling Pointer. www.intellibitz.com training@intellibitz.com

Slide 108: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Case studies cont… Dangling Pointer ? Trying to free already – freed memory. Bounds Checker – Identifies the above as Dangling Pointer. www.intellibitz.com training@intellibitz.com

Slide 109: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Summary Most of the hard to trace bugs occurs in dynamic ? memory management. Invalid free,read/writes are the most common ? errors. Care Should be taken to avoid Array Index Out of ? Range Memory Leak should be avoided. ? All Variables should be initialized. ? www.intellibitz.com training@intellibitz.com

Slide 110: INTELLIBITZ Technologies System Engineer (C) Dynamic memory management Reference Website ? – Valgrind http://valgrind.kde.org/ ? -Bounds Checker ? http://www.compuware.com/products/devpartner/bounds.htm www.intellibitz.com training@intellibitz.com

Slide 111: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Linked list This section teaches the concepts of linked list using an example. ? Consider an institute that maintains records of students. ?Data processing frequently involves storing and processing data that is organized ito a list. ?Linked list is a self-referential data structure and consecutive collection of related data structure. ?Each element of the list can be made to have a field, called the link or pointer,which contains the address of the next element in the list. ?In this case successive elements need not occupy adjacent space in memory which also makes it easier to insert and delete elements in the list. www.intellibitz.com training@intellibitz.com

Slide 112: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Concept of linked list Used to store a series of data of any type ? Allows to manage the data effectively ? Also known as one-way list ? A linear collection of data elements called ? nodes A self-referential data structure ? www.intellibitz.com training@intellibitz.com

Slide 113: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Arrays An array is a collection of contiguous storage ? locations. Each location holds one element. All elements must be of the same type. The elements are referenced by position using an integer variable or constant called the subscript or index. In C language, the first position is position 0. www.intellibitz.com training@intellibitz.com

Slide 114: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Array cont....... The array name represents the address of the ? beginning of the array. Since arrays are considered to be large structures, we do not want to waste time and space copying arrays when we pass them to subroutines. Therefore, an array is passed by reference, even if the data stored in the array won't be changed. In C-language arrays are automatically passed by reference. www.intellibitz.com training@intellibitz.com

Slide 115: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Array cont....... In general, there are two values a ? user needs to be able to process an array correctly, namely, the maximum size of the array and the current size of the array. Here is a typical C- language array declaration. www.intellibitz.com training@intellibitz.com

Slide 116: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Array cont....... #define MAX_SIZE 100 ? ? int x[MAX_SIZE]; /* an array of integer */ ? int curSize; /* how many elements are currently being ? used */ Since numbering the elements starts at 0, the elements ? of array x are x[0].. x[MAX_SIZE-1]. The companion variable curSize tells us that valid data is stored at x[0]..x[curSize-1]. www.intellibitz.com training@intellibitz.com

Slide 117: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Other String Handling Functions As well as sprintf and sscanf, the UNIX system has a ? number of other string handling functions within its libraries. A number of the most useful ones are contained in the file, and are made available by putting the line #include ? near to the head of your program file. ? A couple of the functions are described below. ? A full list of these functions can be seen using the man ? command by typing man 3 strings www.intellibitz.com training@intellibitz.com

Slide 118: INTELLIBITZ Technologies System Engineer (C) Programs with SE_CCC_V1.0.0 Several Files When writing a large program, you may find it ? convenient to split it several source files. This has several advantages, but makes compilation more complicated. This section will discuss advantages and ? disadvantages of using several files in a program, and advise you on how to divide a program between several files, should you wish to do so. www.intellibitz.com training@intellibitz.com

Slide 119: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Advantage of using several files The main advantages of spreading a program across several files are: ? Teams of programmers can work on programs. Each programmer works on a different file. An object oriented style can be used. Each file defines a particular type of object as a datatype and operations on that object as functions. The implementation of the object can be kept private from the rest of the program. This makes for well structured programs which are easy to maintain. Files can contain all functions from a related group. For Example all matrix operations. These can then be accessed like a function library. Well implemented objects or function definitions can be re-used in other programs, reducing development time. In very large programs each major function can occupy a file to itself. Any lower level functions used to implement them can be kept in the same file. Then programmers who call the major function need not be distracted by all the lower level work. When changes are made to a file, only that file need be re-compiled to rebuild the program. The UNIX make facility is very useful for rebuilding multi-file programs in this way. www.intellibitz.com training@intellibitz.com

Slide 120: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 How to Divide a Program between Several Files Where a function is spread over several files, each file will contain one or more functions. One file will include main while the others will contain ? functions which are called by others. These other files can be treated as a library of functions. Programmers usually start designing a program by dividing the problem into easily managed sections. Each of these sections might be implemented as one or more functions. All functions from each section will usually live in a single file. Where objects are implemented as data structures, it is usual to to keep all functions which access that object in the same file. The advantages of this are; The object can easily be re-used in other programs. www.intellibitz.com training@intellibitz.com

Slide 121: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 How to Divide a Program between Several Files All?related functions are stored together. Later changes to the object require only one file to be modified. Where the file contains the definition of an object, or functions which return values, there is a further restriction on calling these functions from another file. Unless functions in another file are told about the object or function definitions, they will be unable to compile them correctly. The best solution to this problem is to write a header file for each of the C files. This will have the same name as the C file, but ending in .h. The header file contains definitions of all the functions used in the C file. Whenever a function in another file calls a function from our C file, it can define the function by making a #include of the appropriate .h file. www.intellibitz.com training@intellibitz.com

Slide 122: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Organization of Data in File Any file must have its data organized in a certain order. This will ? typically be: A preamble consisting of #defined constants, #included header files and typedefs of important data types Declaration of global and external variables. Global variables may also be initialized here. One or more functions. The order of items is important, since every object must be defined before it can be used. Functions which return values must be defined before they are called. This definition might be one of the following: www.intellibitz.com training@intellibitz.com

Slide 123: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Organization of Data in File Where the function is defined and called in the same file, a full declaration of ? the function can be placed ahead of any call to the function. If the function is called from a file where it is not defined, a prototype should appear before the call to the function. A function defined as float find_max(float a, float b, float c) { /* etc ... ... */ would have a prototype of float find_max(float a, float b, float c); The prototype may occur among the global variables at the start of the source file. Alternatively it may be declared in a header file which is read in using a #include. It is important to remember that all C objects should be declared before use. www.intellibitz.com training@intellibitz.com

Slide 124: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Compiling Multi-File Programs This process is rather more involved than compiling a single ? file program. Imagine a program in three files prog.c, containing main(), func1.c and func2.c. The simplest method of compilation (to produce a runnable file called a.out) cc prog.c func1.c func2.c ? If we wanted to call the runnable file prog we would have to ? type cc prog.c func1.c func2.c -o prog ? In these examples, each of the .c files is compiled, and then ? they are automatically linked together using a program called the loader ld. www.intellibitz.com training@intellibitz.com

Slide 125: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Separate Compilation We can also compile each C file separately using the cc -c option. This produces ? an object file with the same name, but ending in .o. After this, the object files are linked using the linker. This would require the four following commands for our current example. cc -c prog.c ? cc -c func1.c ? cc -c func2.c ? ld prog.o func1.o func2.o -o prog ? Each file is compiled before the object files are linked to give a runnable file. ? The advantage of separate compilation is that only files which have been edited ? since the last compilation need to be re-compiled when re-building the program. For very large programs this can save a lot of time. The make utility is designed to automate this re-building process. It checks the ? times of modification of files, and selectively re-compiles as required. It is an excellent tool for maintaining multi-file programs. Its use is recommended when building multi-file programs www.intellibitz.com training@intellibitz.com

Slide 126: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Using make with Multi-File Programs We have already used make to build single file programs. It was really ? designed to help build large multi-file programs. Its use will be described here. Make knows about `dependencies' in program building. For example; ? * We can get prog.o by running cc -c prog.c. ? * This need only be done if prog.c changed more recently than prog.o. ? make is usually used with a configuration file called Makefile which ? describes the structure of the program. This includes the name of the runnable file, and the object files to be linked to create it. Here is a sample Makefile for our current example # Sample Makefile for prog ? # ? # prog is built from prog.c func1.c func2.c ? ? www.intellibitz.com training@intellibitz.com

Slide 127: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Using make with Multi- File Programs CONT.... ? # Object files (Ending in .o, ? # these are compiled from .c files by make) ? OBJS = prog.o func1.o func2.o ? # Prog is generated from the object files ? prog: $(OBJS) ? $(CC) $(CFLAGS) -o prog $(OBJS) ? # ^^^ This space must be a TAB. ? # Above line is an instruction to link object files ? This looks cluttered, but ignore the comments (lines starting with #) andthere are just 3 lines. ? When make is run, Makefile is searched for a list of dependencies. The compiler is involved to ? create .o files where needed. The link statement is then used to create the runnable file. make re-builds the whole program with a minimum of re-compilation, and ensures that all parts ? of the program are up to date. It has many other features, some of which are very complicated. For a full description of all of these features, look at the manual page for make by typing ? www.intellibitz.com training@intellibitz.com

Slide 128: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Reading lines while((c = getchar()) != EOF && c != '\\n') ? { ? if(nch < max) ? { ? line[nch] = c; ? nch = nch + 1; ? } ? } ? www.intellibitz.com training@intellibitz.com

Slide 129: INTELLIBITZ Technologies System Engineer (C) SE_CCC_V1.0.0 Reading number #include ? ? char line[256]; ? double x; ? printf(\"Type a floating-point number:\\n\"); ? getline(line, 256); ? x = atof(line); ? www.intellibitz.com training@intellibitz.com

Slide 130: INTELLIBITZ Technologies PHP Web Programming TD_PHP_V1.0.0 IntelliBitz Technologies Training Division 168, Medavakkam Main Road Madipakkam, Chennai 91. PH: +91 044 2247 5106 www.intellibitz.com training@intellibitz.com www.intellibitz.com training@intellibitz.com