P. 1


|Views: 5|Likes:
Published by Naveen Kumar

More info:

Published by: Naveen Kumar on Feb 01, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less






Joseph's College

Notes for Programming Language C

r Lecture I
Objectives: What is a program? Why need programs? The programming step Introduction to C programming
What is a program? A program is a set of computer instructions that direct the computer to operate according to the sequence of the instructions. A program mimics the ways that human beings work: - sequence - looping - decision Why needs programs? - more reliable - free people from routine work - computer is more efficient in performing certain tasks. The programming steps - develop the algorithm for the task Algorithm: is set of steps designed for solving a problem. Stepwise refinement: is to express a routine with a step by step description. For example, 1. Receive borrow book request from borrower. 2. Process book borrow request. 2.1 Chek borrowers’ ID is in registration. 2.2 Check book’s ID is in library. 2.3 If both OK, record down the borrower’s ID and book’s call number. 3. repeat step 1 until library closed. - coding : is the process of transforming the requirement or algorithm into suitable programming languages. For example, Algorithm in stepwise refinement: 1. read in a character. 2. if the character is ‘y’ or ‘Y’, then output ‘ok’ and repeat step 1. 3. if the character is ‘n’ or ‘N’, then output ‘bye’. The corresponding C program for the above stepwise refinement: #include <stdio.h> #include <stdlib.h> main( ) { char c; c=' '; while (1) { if (c != '\n') printf("Read in a character"); c = getchar( ); if ((c=='y') || (c=='Y')) printf("ok"); if ((c=='n') || (c=='N')) { printf("bye");

Computer Studies

Page 1

St. Joseph's College
exit(0); }

Notes for Programming Language C

} } - compiling : translating the source code into object code. - linking : link different program modules and resolve the memory addresses to form an executable code. - loading : load the executable code into available free space and adjust the address. - running : execute the programs. - test and debug : test the program if they follow what we expected. Debug is to correct any program errors in the program. The program may contain errors. Three major types of errors: 1. Syntax Error Due to not following the grammer of programming language. 2. Semantic Error Due to the program not conforming the requirment logic. 3. Run-time Error Error discovered during run-time. For example, divide by zero. - syntax error can be easily detected by compiler while the semantic error is more difficult to correct. - test plan should be carefully drafted to make sure the system behave as the users’ request. - test cases can be generated by computer or input by users. Test cases can be either real life or artificial. Debugging Tools include: - screen/file dump - integrated debugging tools * program trace step/procedure * set watches/breakpoint * browse the content of register/CPU/RAM Introduction to C programming

+ Strengths of C
Small Size (A top-quality C compiler operate in only 256K of total memory) Language Command Set is small Original C language contain a mere 27 keywords ANSI C stnadard has an additional 5 reserved words Borland C++ added 45 more keywords C provides a rich set of library functions for input/output, arithmetic operations and string manipulation Speed close to assembly language equivalents Not strongly typed A structured language for-loop, if, if-else, case (switch) statements, while loops, local variables and call-byvalue C supports the concept of separate compilation and linking (Support of Modular Programming) Easy interface to Assembly Language Routines Bit Manipulation Pointer Variables Flexible Structures : Multidimensional arrangements are built from combinations of one-dimensional arrays Memory Efficiency : the lack of built-in functions saves programs from unnecessary codes Portability Special Function Libraries : available : graphics and database, screen windowing, communications.

Computer Studies

Page 2

#define allows programmers to relate symbols with constant or expression within the program..math.. If the header files are resided in system directory. The content of header files contains definition of some predefined constant / expression / functions. .h .h” The most often used system-defined header files are: .dos. Header files promote standardization of constant / expression names.h .string.h> #include <stdlib.main( ) Denote the main program. For example.graphics.All preprocessor directives start with ‘#’ . Joseph's College Notes for Programming Language C + Weaknesses of C Not Strongly Typed Side effect of unexpected change to a variable Lack of Run-Time Checking + Spirit of C Trust the programmer Don’t prevent programmer from doing what needs to be done Keep the language small and simple + Preprocessor Directive .St. #include <stdio. For example. Header files can be user-defined or system-defined.h .. For example.h .float. } Computer Studies Page 3 .h .h” means header file.Preprocessor directive allows programmer to include files or define constant / expression / functions before the actual compilation takes place.h . #include “c:\user\header\myfile. they can be double quoted.h .stdlib. #define MAX_LINE 1000 #define MAX_USER 200 #define SQR(X) X*X .stdio.#include allows programmers to include content of another file into the current program content. For example.h> main( ) { . #include <dos.h> If the header files are resided in user directory.The available preprocessor directives are: #include #define . they can be quoted with bracket. System-defined header files are constant / expression defined by the C compiler for library reference. User-defined header files are constant / functions / expression defined by users. All programs start here. + Header File The file extension is “..

Syntax return [ <expression> ] .483.768 to unsigned int 16 bits 0 to short int 16 bits -32. Joseph's College Notes for Programming Language C . funcP(A).7 * (10**-308) long double 80 bits 3. main( ) { .647 to 3..768 unsigned long 32 bits 0 long 32 bits -2. } Note: return can also return a value.7 * (10**+308) to 1. } . The C function complete and return to the caller function.535 32.147. The most common data types are: * integer * char * float : single-precision floating point * double : double-precision floating point * short : 16-bits integer * long : 32-bits integer * unsigned Other more complicated data types are: * array * structure * pointer * file Each data type has a size limit: Type Length Range unsigned char 8 bits 0 to char 8 bits -128 to enum 16 bits -32. return.648 float 32 bits 3.295 to 2.767 to 4.767 65.967.St.1 * (10**+4932) Computer Studies Page 4 .return (keyword) Exits immediately from the currently executing function to the calling routine... For example double sqr(double x) { return (x*x). } .294. For example.4 * (10**-4932) 255 127 32.768 to int 16 bits -32.Data Type All data in C belong to a data type. C language has a rich set of data types..147.4 * (10**+38) to 1...767 to 32. char funcP (char *s) { . optionally returning a value.483.4 * (10**-38) double 64 bits 1.

C80. constant declarations e. enumeration constant : the first name in an enum has value 0. long constant : terminated by "l" or "L" unsigned long : terminated by "ul" or "UL" float : terminated by "f" or "F" octal : leading zero "0" hexadecimal : leading "0x" or "0X" character constant : enclosed by single quotes For example.g.Declaration variable declarations e. "C40"./*. float x = 1. line[80]..g. etc. and so on e. enum boolean { NO. int limit = MAXINT + 1.Variables Variables are main memory storage for holding data values.*/ The pairs /* */ is for bracketing comment. */ constant expression evaluated during compilation rather than run-time For example. int x. * first character should be alphabetic / underscore. BW80. for example: AMY_SCORE. YES }. const double e = 2.. numeric constant : 3444 45 4. the next 1. char ch. CAR_NO are variables denoting the score of Amy and car number. char esc = '\\'. Variables are used to represent an object.. enum modes { LASTMODE = -1. BW40=0. variable declaration with an initializer e..Constants Constants are used for denoting some values which will not be changed during program execution. const char msg[ ] = "warning: ". Computer Studies Page 5 .14 . Joseph's College Notes for Programming Language C . y. The value of C40 is 1 (BW40 + 1).g. int i = 0. * case-sensitive Examples for valid variable names: A A1 _1 _a A_1 Examples for invalid variable names: 1a a! a 3 . C40. #define MAXLINE 1000 #define pi 3. "LASTMODE". MONO = 7 }. z.St. . are the constant names.71828182845905. /* "modes" is the type tag.5 455e34 0222 0xabc character constant : ‘a’ ‘b’ ‘c’ (use ‘ ’) string literal : enclosed by double quotes string constant : “this is a boy” (use “ ”) We can define symbol to represent constant. "BW40".0e-5. BW80 = 2 (C40 + 1). Naming convention: * allow characters: alpha-numeric / underscore.g. etc.

There are other place holders for other data type: %s string %d decimal %c character %f float Special notation for non-printable characters.St. .. For example.. For example.’. /* This program is for calculating personal tax */ The C compiler will ignore those comment. For example.boyname). Comment is important for documenting the program. the written date etc. Comment make the programs more readable.// For single line comment. .statement terminator (. use // is more convenience. Joseph's College Notes for Programming Language C For example. %s is replaced by the content of string variable boyname. printf(“hello”). .... Each statement is terminated with ‘. Each statement is the smallest indivisable instruction meaning to a computer just like a sentence in English grammar. special algorithm taken. All those special characters start with ‘\’. Output constant string or character to monitor.simple I/O function *printf(.. They are not part of the executable code.. the author.{. // c is sum of a and b // effect from here to end of line .} for grouping a set of statements as a compound statement. c:=a+b. printf(“His name is %s”. eg. b=3. \a alert [bell] character \b backspace \f formfeed \r arriage return \v vertical tab \\ backslash \? question mark \' single quote Computer Studies Page 6 . } It also used for defining the start and end of subroutine. Output formatted string to monitor. \n newline \t horizontal tab \0 null character or string terminator.) C program is composed of statements. { a=1. The compound statment is treated as a unit. For example. the function.) printf is a system-defined function. For example..

Arithmetic and logic operators and their precedence Arithmetic operators: addition + substraction multiplication * integer/float division / (quotient) integer division % (remainder) unary positive +n unary negative -n (where n is a no. break and continue. c=1. switch. .St.Conditional statements: if. Joseph's College \" \000 \xhh double quote octal number hexadecimal number Notes for Programming Language C . a=4. The getchar( ) function will get a value from the keyboard and assign to variable c. .else.) For example. . . .Initialised the variables You can initialised the variable during declaration.. c=getchar( ). int c=4.Variation of assignment statement.getchar( ) get a character from the standard input keyboard and return the values. Both c and d contain same value 1.b.Arithmetic and logic operators and their precedence. Note: Assignment operator is destructive: means the old value of the variable will be destroyed and replaced by the value of the left side.Assignment statement = Put the value from the left side to variable on the right.Multiple assignment For example. a=5. a=b=c=d=4. .c. For example. variables a.b=5. do .Classwork Variation of assignment statement .. Computer Studies Page 7 . r Lecture II Objectives: . while. d=c.d will be assigned with the same value 4.looping structures: for.Simple assignment For example. The left side of the assignment statement must be a variable. For example. b and c will be initialised with values 4 and 5. . For example.

m=m%n. ++m. Relational operators: Compare the left value with the right.St. m=m*n. m=m*n. Truth Table for ‘AND’ X Y X&&Y T T T T F F F T F F F F Truth table for ‘OR’ X Y X||Y T T T T F T Computer Studies Page 8 .b. --n. !((c>d) && (a<c)) (a!=b) || (b>2*n) The truth value of the above expressions depend on the values of a. n=3. m=++n. m=m%n. Other variation of arithmetic operators: m+=n equivalent to m-=n equivalent to m*=n equivalent to m/=n equivalent to m%=n equivalent to Notes for Programming Language C m=m+n. m=n++. assigning the value of n to m before incrementing n. m=m-n. increment the value of m by 1. decrement the value of n by 1 before assigning to m. m=n--. m=--n. assigning the value of n to m before decrementing n. decrement the value of n by 1. == equal to != not equal < less than > greater than <= less than or equal to >= greater than or equal to For example. increment the value of n by 1 before assigning to m. m=m/n. 3==5 false 3!=3 false a>b truth value depend on a and b’s value m+n >= 3%2 truth value depend on m and n’s value Logical operators: && Logical ‘AND’ operator || Logical ‘OR’ operator ! Logical ‘Not’operator Example. Precedence level of arithmetic operators: The arithmetic operators follow the rule multiplication and division come before addition and subtraction. Some special arithmetic operators: m++. n--.c. m=m-n. Joseph's College m=4. m=m+n. m=m/n.

(type) * & * / % + << >> < <= > >= == != & Associativity left to right right to left left to right left to right left to right left to right left to right left to right ! - sizeof Computer Studies Page 9 . >>= Operator ( ) [ ] -> . %= +=. &= ^=. Joseph's College F T F F Truth table for ‘Not’ X !X T F F T T F Notes for Programming Language C Precedence Precedence refers to the priority of the operator in evaluation. |= <<=. /=..St. structure member reference unary minus + unary addition ++ increment -decrement ! logical negation ~ one’s complement * address sizeof size of an object (type) type cast (coercion) * multiplication / division % modulus + addition subtraction << left shift a bit >> right shift a bit < less than <= less than or equal > greater than >= greater than or equal == equal != not equal & bitwise AND ^ bitwise exclusive OR | bitwise OR && logical AND || logical OR ?: conditional expression = assignment operator *=. ++ -. Below is a priority list: ( ) function call/bracket [] array element reference -> pointer to structure member reference . -=.

e. However. Computer Studies Page 10 . The conditional statement . . x = f( ) + g( ) f( ) may be evaluated before g( ) or vice versa. thus no extra parenthese is needed for the following boolean expression. if ( n > 0 ) { if (a > b) z = a. ^. Order of evaluation The precedence of the bitwise logical operators &. all relational operators have a greater precedence than logical operators. e. the following program segment should be used. the else may be considered to go with the outer if. else action 2.g. j=5. For example. because if wrong indentation is used.g. | ). If the else is really used for the outer if. e. if ( n > 0 ) if (a > b) z = a. If condition is true then action 1 else action 2. &. Explicit type conversions can be forced. else { i=4. else z = b. } Note that the whole condition part should be bracketed.g.If (condition) action 1. (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') More attention should be paid on expressions involving one of the associative and commutative operators (+.Switch (n) { case 1: printf(“single”). *. x can depend on the order of evaluation.St. It is called "coerced" or "cast". There may be an ambiguity in the following example. e. ^ and | falls below = = and ! =. sqrt ( ( double ) n ) the integer n is coerced into a double value before the function sqrt acts on it. if ((A>B) && (D<E)) i=3.g. } else z = b. Joseph's College ^ | && || ?: += -= Notes for Programming Language C left to right left to right left to right left to right right to left right to left = etc. if ( ( x & MASK ) = = 0 ) the expression x & MASK must be fully parenthesized. thus if either f( ) or g( ) alters an external variable that the other depends on.

while loop Do. There are three kinds of looping statements: . .i+j). use BREAK statement. ending condition and the post-action. case 3: printf(“divorced”).do. Notes for Programming Language C } Another more simple conditional statement is SWITCH statement. Note .For loop For loop is similar to while loop except it allows you to specify: * the pre-condition * condition for looping and * the post-action Each of the above parts is separated by “. Before the loop is executed. while (i<20) { printf(“%d\n”.While loop provides the simplest way of doing repetitive job whenever the condition part is true. (i<10) && (j<20) is the condition for the loop to be executed. pre-cond.There can be more than one statement in each conditional path.. Feature: must execute at least once.) printf(“A”). condition for loop post-action for (i=0.(i<10) && (j<20) . i++. Computer Studies Page 11 . The looping statement Loop statement allows us to execute a set of statements repetitively. printf(“ok”). } Note .”.for loop . both i.i). If you want to stop the matching after successful match. You can omit the pre-condition. i++..while loop provides an alternative for while loop.while loop They have different conditions to exit the loop.i++.j=0 . Whenever the variable n match the conditional value.. for (.The matching continue even if successful match. } while (i<10). do { printf(“%d”.the execution may not execute at all depending on the value of i before entering the loop. Joseph's College case 2: printf(“married”). For example.while loop .j++) printf(“%d”.St. . For example. j set to 0. i++.. the path will be executed.do. But this will cause INFINITE loop !!!! .j++ are the post actions to be executed after each loop. . default: printf(“single”).i).. For example.. For example..The switch body should be bracketed to define the effect of switch statement. .

all case statement will be checked.e. printf(“%d”. 20. depending on which case occured first. Convert the input integer n into a string with leading sign. print Celsius-Fahrenheit table for celsius = 0.break.St. the control flow is transferred back to the condition statement. while (i>0) { k+=i. Switch (a) { case 1: printf(“man”). 300. 3. Classwork 1. 300. case 3: printf(“boy”). . The continue statement is used for loop and not for switch..break. -90 convert to -90).break. (i.j++) { k-=1. if (k>20) continue.k=2. . } Note if without break statement. For example.break..i<20.break The break statement will cause the exit of switch and loop structure.break. 20. .. [Hint : fahrenheit = (9 x celsius) / 5 + 32] 2. case 2: printf(“woman”).statement will be ignored and the flow is back to checking for I>0... i--.. case 4: printf(“girl”).k). Whenever encounter the loop statement. Use for-loop. Use the function scanf to get in an input integer n. .i++. } The loop terminated for i<20 or k<0. if (k<0) break.Continue statement The continue statement complement the break statement. Joseph's College Notes for Programming Language C The loop will be executed at least once no matter the initial value of i. Use while-loop. for (i=0. 78 convert to +78. } if k>20 then i-. default: printf(“human”). print Fahrenheit-Celsius table for celsius = 0. Computer Studies Page 12 .

Array is for storing a set of data with same data type. int a[4]={1. int stdmrk[2][4]. Example for one dimensional array.1 What is array? .2 More about array . . the total number of elements is n x m x r.you can initialise an array during declaration For example.St. For example. For initialising stdmrk[3][5].5. . int stdmrk[2][4]={{1.Each element in the array is referenced by the index. int stdmrk[10].2.Declaration of array using square bracket. For initialising. For example.Array and loop has close relationship.What is array? .4}.6}} For the general multi-dimensional array of the form a[n][m][r]. The above declaration allocate ten slots. 43 44 78 45 23 45 89 95 67 56 0 1 2 3 4 5 6 7 8 9 Note that the index number start from 0.4}.{3. The effect is as follow: array a 1 2 3 4 . stdmrk[0][0]=70. stdmrk[0][1]=70. represents 2 classes with each class 4 students. int stdmrk[5].Array is a data type.More about array . stdmrk[5]=3. Each slot can store an integer.Multi-dimensional array Dimension refers to the number of reference index required to identify an element in the array. III.3.4.2. One dimensional array is called linear array. . You can imagine an array as a list of boxes. int stdmrk[40]. Computer Studies Page 13 . Care must be taken not to assign value that exit the array size. 40 student marks for a class. Joseph's College Notes for Programming Language C r Lecture III Array Objectives: .3 Array and loop . III.Array and loop III.3. If more than one index is required is called multi-dimensional array. Example for multi-dimensional array. This type of errors may make the computer hang up. stdmrk[0][2]=70. Each box is referenced by an index.

b=&a.1 What is pointer and its uses? . //b is set to point at head of c b++. // this statement is equivalent to a=‘c’ . stdmrk[2][2]=80.The dereferencing operator (*) char a.St.i++. . Joseph's College Notes for Programming Language C . Therefore. * strcpy * strncpy * strlen * strcmp * strncmp * strcat * strncat Computer Studies Page 14 .A constant string is double quoted. for example. stdmrk[2][3]=80. r Lecture IV Pointer and String What is pointer and its uses? C subroutines for manipulating string IV. b=&a. for (i=0.Pointer declaration is done by prefixing the variable name by ‘*’. . .C provides a set of useful string function The “string. *b. //2nd element of c is incremented by 1 IV. //the variable that pointed by b is assigned // with value ‘c’. .String in C is usually declared as array of character. float *floatpt. //b is moved to second element of c (*b)++. *b=‘c’.2 C subroutines for manipulating string .A string terminator is denoted by ‘\0’ (null character) . array name itself is a pointer. stdmrk[2][4]=80. b=c. int *intpt. . “he is a boy” . char c[10]. For example.j++) a[i][j]=70+i*10.h” should be included.*b. it can be imagined as an arrow pointing to the variable. For example. the above initialisation of array can be simplified by using loop.The address operator (&) char a. //the pointer b is assigned a’s address .Pointer is physically a variable contains the address of another variable.j=0. char d[20]=“This is a string”. . but logically. char *charpt.A string is a sequence of characters ended with a string terminator.Each pointer has a data type which should be the same to that variable it pointed at.Uses of pointer is usually for referencing the element of an array.*b.(i<=2)&&(j<=4). For example.

strlen calculates the length of string strlen returns the length of the string.h” included.str2.ss[20]=“He is a boy”.*str2. =0 if str1 is equal to str2. char *str2) Returns <0 if str1 is less than str2. char str1[20]. int n=10. one more header file “math. char *str2. int stringlen. int n) Return <0 if first n characters of str1 < str2. char *strcat(char *destin. For example. printf(strcat(str1. Computer Studies Page 15 .ss). For example. // output “I am a boy” char *strncat(char *str1. if (strncmp(str1. //ts contains “He is a bo” unsigned strlen(char *str) Return the number of characters in str.str2[20]=“ a boy”. For example.10). For example. strcpy(ts. if (strcmp(str1.n)) printf(“The first 10 characters are different”). >0 if first n characters str1 > str2. char *strcpy(char *destin. The target string might not be null-terminated if length of source is maxlen or more. char ss[20]=“He is a boy”. char *source) Return a string which is equivalent to appending source to the end of destin.ss. int strncmp(char *str1. The target string should be large enough to hold the source string plus a string terminator. strcmp comp ares str1 with str2.ts[30]. strcat concatenates the destin and source by appending source to the end of destin string. strncpy(ts.str2[20]. int n). For example. Joseph's College Notes for Programming Language C * atoi * atol * atof For atoi and atol. char *source.h” should be included.str[20].str2)) printf(“they are different”). char str1[20]=“I am”. printf(“ss length is %d”. int strcmp(char *str1. strlen(ss)). For atof. // ts contains “He is a boy” char *strncpy(char *destin. >0 is str1 is greater than str2. int slen. char ss[20]=“He is a boy”. “stdlib. strncpy copies exactly maxlen characters from source into destination.str2)).St. strncmp compares the first n characters of str1 with str2. char str1[20]. char ts[20]. not counting the null character. char *source) Return destin+strlen(source) strcpy copies a string from source to target and add a string terminator at the end of target string. int maxlen) Return destin. For example. =0 if first n characters str 1 = str2.

b=4. strncat concatenates n characters from str2 to str1 and append a null character at the end.b=4.b).avoid duplicate code . char s[10]=“ 121”.A large problem can be partition into smaller manageable unit of problem. For example.St.logic more clear V. an integer if the input string can be converted into integer. printf(“%d”. . //output “I ama boy” int atoi(char *nptr) Return the 0 if the input string cannot be converted into integer. Advantages of using functions: .easier to code and more readable .b=4. printf(strncat(str1.b).function data type Computer Studies Page 16 . int a=5. char s[10]=“ 121”. an double if the input string can be converted into double. // b is now 126 long atol(char *nptr) Return the 0 if the input string cannot be converted into long.easier to debug . // b is now 126 r Lecture V Functions and storage classes Why needs functions? How to define functions? Why need different storage classes and their characteristics? V. b=a+atoi(s). char s[10]=“ 121”. an long if the input string can be converted into long.Function implement the same concept of solving the smaller manageable unit. str2[20]=“a boy”.b). int n=5. printf(“%d”.2 How to define functions? . .n)). long a=5. Joseph's College Notes for Programming Language C Returns a string by appending n characters of str2 to the end of str1 and append a null character at the end.A powerful problem solving method is partition. For example.The manageable unit is more easier to be solved.1 Why needs functions? . // b is now 126 double atof(char *nptr) Return the 0 if the input string cannot be converted into floating number. b=a+atof(s). char str1[20]=“I am”. printf(“%d”. . b=a+atol(s). For example. double a=5. For example.str2.Function declaration includes: * function return data type * function name * function parameter list .

The function can use this address to modify the content of that variable. //display 4 instead of 5 } void functionA(int *b) Computer Studies Page 17 . For example. Joseph's College Notes for Programming Language C A function after execution should return a value of the designated data type to the main program. When the program body reference the name of the function name. printf(“The tax is %d”.b)). //still display 5 } void functionA(int b) { b=4.b=2000. . main( ) { int a. For example. The value/variable passed in should match the parameter list data type. printf(“%d”. a=5. main( ) { int a.1).caltax(a. a=5. } . int bonus) { return ((salary+bonus)*0.Passed by reference The address of the variables are passed into the function. . //pass the address of variable a printf(“%d”. If no value need to be returned.Two ways of parameter passing * passed by value * passed by reference The default way of passing parameter is passed by value in C.St. a). * The return data type is integer.function name A function should be called using its name. The function itself cannot alter the value of the variable passed in. } main( ) { int a=10000. int caltax(int salary. * The actual parameter is a and b. a). . For example. it is identical to execute the statements inside the function.Passed by value Only the value of the variable is passed into the actual parameter. functionA(&a). .function parameter list A function should take in value for processing. * The formal parameter is salary and bonus. using void. The value of salary and bonus is replaced by salary and bonus. functionA(a). The parameter list act as an interface between the function and the program body that call it. } * The function name is caltax.

//Global variables main( ) { . especially when the program size is large. For example. One way of limiting the scope is through the declaration of local variables. a=3.. the global one will be ignored. Thus..St.h> #define MAXLINE 10 int a.... even the main().. we should better limit the scope of that variable. Joseph's College Notes for Programming Language C { *b=4. Local variables are declared at the beginning of a function and is only visible within the function. local variables eliminates the possibility of modifying the global variable accidentally even with the same global variable name. //refer to global ‘a’ b=8. The default mode for parameter passing is passed by value. V..Variable scope The scope of the variable refers to the effect or visibility region of that variable within the program. b=3..Global variables The global variable is declared before any functions... #include <stdio. For example.b.Local variable As global variables creates debugging problem.h> #include <stdlib.h> #include <stdlib.. //output 8 } int functionA( ) Computer Studies Page 18 . //refer to global ‘b’ printf(“%d”.h> #define MAXLINE 10 int a.b. There are two types of variables classified by their scope: * Global variables * Local variables .3 Storage classes . } One of the uses of pointer is for passed by reference.. //refer to global ‘a’ } int functionA( ) { . The only way we can alter the variable passed in is through the pointer access to access the variable. #include <stdio. //refer to global ‘b’ } . Global variables are visible at any where within the C programs. a=3.b). If the local variable names are the same as the global one... Global variable is very convenience for accessing but it also creates a problem of debugging the program It is difficult to trace which program part alter the content of that global variable. //Global variables main( ) { .

// variable i is made static in the memory printf(“%d”. //refer to local ‘b’ // This assignment statement affect local // but not global variable ‘b’ } . Joseph's College Notes for Programming Language C { int b..i). This i occupies the same // memory space as in the original i // declared in other progrom file.Extern A C program may be divided into partition called modules. int functionA( ) { static int i. Each program files can be separately compiled. it should be declared as extern. output may be arbitrary number.Static Local static variable will retain the value of the previous function call for next call.. For the second time to call functionA. } When the functionA is first called. } For the first time to call functionA. output must be 3.Local variable are further divided into: * Auto * Static They are different for the life span between the same function call for several time. the value of the variable i may not be 3.Auto Auto is the default mode for local variable. if i is not declared as extern. For example. the auto variable i is set to 3. Separate compilation saves time for compiling a small program file must be faster than a large single program. For examp le. After the function is executed.. If the variables are defined in another program file but need to reference in this program file. The static variable will reside in the memory even after the function call. i:=3.St. The previous value will be retained after the functionA finished. That means the life span of that local variable is within the life span of that function. Computer Studies Page 19 . printf(“%d”. int functionA( ) { auto int i. it will cause double declaration compilation error. b=3.. the auto mode local variables will be destroyed. #include <iostream. If the functionA is called for second time. Different compiled program files are linked together to form an executable program. // variable i is declared in somewhere // else. We can group several modules inside different program files. // local variable b . .i). . i=3.h> extern int i. .

File names are divided into: * Physical file name The actual physical names found in disk. You should close all the files or otherwise the files may not be updated.96 * Logical file name The logical meaning file names are those names reference in C program.Files variables are declared as a file pointer using the reserved word “FILE” which must be in upper case. * r+ Open an existing file for update (reading or writing).int fclose(FILE *stream).Files are used for storing data of unlimited size theoretically. fclose also free all the file buffers.St. FILE *myfile. FILE *student_detail_96. Using logical file name is more convenience in the program. student_detail_96 = fopen(“stddet.C functions for handling files * fopen * fclose * feof * fscanf * getc * putc * fputs * fgets * ftell * fseek . char *type). stddet. .Files can be view as a sequence of related data with same type.C supports files access in * sequence mode * random access mode . * a+ Open for append. open (or create if the file does not exist) for update at the end of file. * a Append.e. . The available open modes are: * r Open for reading only. i.File *fopen(char *filename. open for writing at end of file or create for writing if the file does not exist. As you can bind different physical file names to that same logical name without the need to change the program code after. * w Create for writing only.1 File uses and declaration . . . For example.Files enable to store data permantely on external storage.”r”). Computer Studies Page 20 . disk. eg. * w+ Create a new file for update. For example. The second parameter denotes the open mode. . eg.96”. fclose return 0 if the file is closed successfully. Joseph's College Notes for Programming Language C r Lecture VI Files and Structures Files uses and declaration What is structure and its uses? VI. student_detail_file_96 fopen allow us to bind the logical file name with that physical one.

int fputs(char *string. FILE *stream) fputs returns the last character of the string. if (fputs(s. VI. } . long offset. char c.int fseek(FILE *stream. FILE *myfile. int n. char s[10]={‘a’.myfile). Joseph's College Notes for Programming Language C FILE *myfile. The symbols below represent these values: fromwhere File location SEEK_SET(0) file beginning SEEK_CUR(1) current file pointer position SEEK_END(2) end-of-file long offsetbytes=10. printf(“%s”. char c=‘f’. FILE *myfile. .St..’b’.’b’. c=getc(myfile).myfile)=“abc”) printf(“it is a success”). int fromwhere) fseek return 0 if successfully moved or non-zero for failure. if (fgets(s. if (!fseek(myfile. . FILE *myfile. 1 or 2.offsetbytes. main( ) { . . FILE *myfile.char *format .’c’}. . char s[10]={‘a’.’c’}. FILE *myfile..int putc(int ch.SEEK_SET)) printf(“seek is successful from start”).int fscanf(FILE *stream. . putc(c. FILE *stream) fgets returns the argument string if success.. FILE *myfile. Otherwise return EOF error.long ftell(FILE *stream) ftell returns the current file pointer located in stream. feof return 0 if not at end return 1 if at end of file For example.int getc(FILE *stream) getc returns the character read from the input stream. if (!fclose(myfile)) // file closed successfully printf(“file processing is ended”). . Otherwise. long offsetfrom. The offset is measured in bytes from beginning of file.int feof(FILE *stream) feof is used for checking the file pointer reached the file end or not.FILE *stream) putc returns ch and put the ch into the output stream. fromwhere should be 0.2 Structures Computer Studies Page 21 . EOF is returned.char *fgets(char *string. if (!feof(myfile)) printf(“not end of file”).myfile)=‘c’) printf(“put string success”). getc(myfile)). offset=ftell(myfile).

* All member fields resided in the same memory location. They are all overlapped in the same memory location. }.Each attribute in a record can be access through the dot notation.year=1994. struct birthday { int mon. . . For example. struct man { struct birthday manbirth.Structures resemble records. float flnum. * Only one field of the member will be used For example. dnum.St. it can have other structure. man. union number { int intnum. . int day. . man. flnum.Structures group a set of attributes for describing an object. Joseph's College Notes for Programming Language C . . .Union * Union is quite like structure.Declaration of structure struct is a reserved word for declaring structure. int year.Each attribute belong to a data type. char name[30]. }.name=“James”. Computer Studies Page 22 . For example. }.Nested structure Within a structure. double dnum.manbirth. The type of number can be only one of the form: intnum.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->