Академический Документы
Профессиональный Документы
Культура Документы
AVIT, CHENNAI.
2/27/12
Introducing C
C is a programming language developed at AT & T Bell Laboratories of USA in 1972, designed and written by Dennis Ritchie.
C is highly portable i.e., software written for one computer can be run on another computer.
An important feature of C is its ability to extend itself. A C program is basically a collection of functions.
ABHISHEK DWIVEDI
2/27/12
Historical Development of C
Year Language ALGOL Developed by International Committee Cambridge University Martin Richards at Cambridge University Ken Thomson at AT & T Dennis Ritchie at AT & T Remarks Too general, too abstract Hard to learn, difficult to implement Could deal with only specific problems Could deal with only specific problems Lost generality of BCPL and B restored
1960 1963
CPL
BCPL
B C
CPL
2/27/12 Combined
C Tokens
The most basic elements in a C program recognized by the compiler are a single character or a group of characters called C tokens.
The compiler cannot breakdown the token any further. For example, the words main, { (brace), ( (parenthesis) are all tokens of C program.
ABHISHEK DWIVEDI
2/27/12
Types of tokens.
1. Keywords Examples: float, int, double, while, for. 2. Identifiers Examples: main, amount 3. Constants Examples: 12.4, 7894 4. Strings Examples: CSM, Thursday 5. Special Symbols
ABHISHEK DWIVEDI
Examples: [,], {, }, (, )
2/27/12
Letters
a, b, c, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
ABHISHEK DWIVEDI
2/27/12
Character/ Symbol
~
Meaning
tilde Period Ques. mark Double Quote Left parenthesis Left Bracket Left Brace Slash Less than Equal to Minus Hash Ampersand Percent , ; : ) ] } \ > ! + $ *
Character/ Symbol
Meaning
Comma Semicolon Colon Single Quote Right Parenthesis Right Bracket Right Brace Back Slash Greater than Exclamatory Mark
.
?
( [ {
/ <
= # & % _
Plus Dolor Sign Asterisk (or star) Carat Vertical Bar 2/27/12
Identifiers
Identifiers are distinct names given to program elements such as constants, variables, etc. An Identifier is a sequence of letters, digits, and the special character _ (underscore). 1. It must start with either a letter or underscore. _
2. No commas or blanks are allowed within a variable name. 3. The upper case and lower case letters are treated as distinct, i.e., identifiers are casesensitive. 4. An identifier can be of any length. 5. No special symbol can be used in a variable name.
ABHISHEK DWIVEDI
2/27/12
Keywords
Keywords are predefined tokens in C. These are also called reserved words. Key words have special meaning to the C compiler. These key words can be used only for their intended action; they cannot be used for any other purpose. C has 32 keywords.
ABHISHEK DWIVEDI
2/27/12
unsigned void
ABHISHEK DWIVEDI
2/27/12
Data types
A data type defines a set of values and the operations that can be performed on them. Every datatype item (constant, variable etc.) in a C program has a datatype associated with it. C also has a special datatype called void, which, indicates that any data type, i.e., no data type, does not describe the data items.
ABHISHEK DWIVEDI 2/27/12
Data types
Char Int Float Double Void signed char unsigned char short signed int short unsigned int Long singed int
Description
Single character An integer Floating point number Floating point number No data type Character Unsigned character Short signed integer Short unsigned integer Long signed integer
Range
0 to 255 -32768 to +32767 -2,147,483,648 to +2,147,483,647 Approximately 15 digits of Precision
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Rules for constructing Integer constants constant must have at least one An integer
digit. It should not contain either a decimal point or exponent. If a constant is positive, it may or may not be preceded by a plus sign. If it is a negative, it must be preceded by a minus sign. Commas, blanks and non-digit characters are not allowed in integer constants. The value of integer constant cannot exceed specified limits. The valid range is 32768 to +32767.
ABHISHEK DWIVEDI 2/27/12
Real constants
Real values are often called floating-point constants. There are two ways to represent a real constant decimal form and exponential form. In exponential form of representation, the real constant is represented in two parts. The part appearing before e is called mantissa, whereas the part following e is called exponent.
ABHISHEK DWIVEDI
2/27/12
The mantissa part and the exponential part should be separated by a letter e. The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive. The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive. Range of real constants expressed in exponential form is - 3.4e38 to 3.4e38.
ABHISHEK DWIVEDI
2/27/12
String constants
A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, blank space or special characters. Note that is null string or empty string. And the single string constant A is not equivalent to the single character constant A. Each string constant must end with a special character \0. This character is called null character and used to terminate the string. The compiler automatically places a null \0 character at the end of every string constant. DWIVEDI ABHISHEK 2/27/12
Escape sequence
Some non-printing characters and some other characters such as double quote (), single quote (), question mark (?) and backslash (\), require an escape sequence. A list of commonly used backslash character constants is given below.
Escape Sequence Meaning
Bell Back Space Tab New line Vertical tab Form feed
ASCII value
Escape Sequence
Meaning
Carriage return Double Quote Single Quote Question Mark Back Slash Null
ASCII value
\a \b \t \n \v \f
7 8 9 10 11
\r \ \ \? \\ \0
13 34 39 63 92 0
12 ABHISHEK DWIVEDI
2/27/12
Variables
A variable can be considered as a name given to the location in memory. The term variable is used to denote any value that is referred to a name instead of explicit value. A variable is able to hold different values during execution of a program, where as a constant is restricted to just one value. For example, in the equation 2x + 3y = 10; since x and y can change, they are variables, whereas 2,3 and 10 cannot change, hence they are constants. The total equation is known as expression.
ABHISHEK DWIVEDI 2/27/12
Rules for constructing variable names of a variable is composed of one to several The name
characters, the first of which must be a letter . No special characters other than letters, digits, and underscore can be used in variable name. Some compilers permit underscore as the first character. Commas or Blanks are not allowed with in a variable name. Upper case and Lower case letters are significant. That is the variable income is not same as INCOME. The variable name should not be a C key word. Also it should not have the same name as a function that is written either by user or already exist in the C library.
ABHISHEK DWIVEDI
2/27/12
C Instructions
There are basically four types of instructions in C: Type Declaration Instruction Input/Output Instruction Arithmetic Instruction Control Instruction
ABHISHEK DWIVEDI
2/27/12
instruction
Input/Output instruction To perform the function of supplying input data to a program and obtaining the output results from it. Arithmetic instruction to perform arithmetic operations between constants and variables. to control the sequence of execution of various statements in a C program. 2/27/12
Control instruction
ABHISHEK DWIVEDI
Types of operators
C has four classes of operators
1.
2.
3.
4.
In addition, C has some special operators, which are unique to C, they are
1.
2.
3.
Arithmetic Operators
There are five arithmetic operators in C. The following table lists the arithmetic operators allowed in C:
Operator Meaning
+ _ * / %
Addition Subtraction; also for unary minus Multiplication Division Modulo division (remainder after integer division) ABHISHEK DWIVEDI 2/27/12
Relational Operators
Relational Operators are symbols that are used to test the relationship between two variables or between a variable and a constant. We often compare two quantities, and depending on their relation takes certain decisions. These comparisons can be done with the help of relational operators. C has six relational operators as shown below.
Operator > >= < <= == != Meaning
Greater than Greater than or Equal to Less than Less than or Equal to Equal to Not equal to
ABHISHEK DWIVEDI 2/27/12
Logical Operators
Logical Operators are symbols that are used to combine or negate expressions containing relational operators. C has three logical operators as defined below.
Operator
&& || !
Meaning
Logical AND Logical OR Logical NOT
ABHISHEK DWIVEDI
2/27/12
Bitwise operators
The lowest logical element in the memory is bit. C allows the programmer to interact directly with the hardware of a particular system through bitwise operators and expression. These operators work only with int and char datatypes and cannot be used with float and double type. The following table shows the bitwise operators that are Operato available in C. Meaning
r
|
& ^ >>
Increment & Decrement operators operators for adding and subtracting a C has two very useful
variable. These are the increment and decrement operators, ++ and -- . These two operators are unary operators. The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. Therefore, the following are equivalent operations. ++i --i is equivalent to i = i + 1;
is equivalent to i = i 1;
ABHISHEK DWIVEDI
2/27/12
Assignment operators
In addition to usual assignment operator =, C has a set of shorthand operators, that simplifies the coding of a certain type of assignment statement. It is of the form var op = exp where var is a variable, op is a C binary arithmetic operator and exp is an expression. Equivalent
Statement
a+=b a-=b a * =b a*=b+c a%=b a*=a
Statement
a=a+b a=a-b a=a*b a = a * ( b+ c) a=a%b a=a*a 2/27/12
ABHISHEK DWIVEDI
Conditional Operator
C provides a peculiar operator ? : which is useful in reducing the code. It is ternary operator requiring three operands. The general format is exp1 ? exp2 : exp3; where exp1, exp2 and exp3 are expressions. In the above conditional expression, exp1 is evaluated first. If the value of exp1 is non zero (true), then the value returned will be exp2. if the value of exp1 is zero (false), then the value returned will be exp3.
ABHISHEK DWIVEDI
2/27/12
Structure of a C program
C programs consist of one or more functions. Each function performs a specific task. A function is a group or sequence of C statements that are executed together. The following is a simple C program that prints a message on the screen.
/* A simple program for printing a message */ # include <stdio.h> # include <conio.h> void main( ) { clrscr( ); printf(Welcome to C);
ABHISHEK DWIVEDI 2/27/12
Description
The first line
/* A simple program for printing a message */ is a comment line. Comments in the c program are optional and may appear anywhere in a C program. Comments are enclosed between /* and */.
ABHISHEK DWIVEDI
2/27/12
Description (contd)
The third line
# include <conio.h> tells the compiler to read the file conio.h and include its contents in this file. conio.h means Consoled Input Output Header file. This file contains the information about clrscr() and getch() functions.
Description (contd)
The seventh line
printf( Welcome to C); this function causes its arguments to be printed on the screen on the computer.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Execution of C Program
Steps to be followed in writing and running a C program. Creation of Source Program
Create a C program file in various C compilers are available under MS-DOS, Turbo C Editor etc.
Program Execution
In Turbo C environment, the RUN option will do the compilation and execution of a program. Press Ctrl + F9 for execution the program.
ABHISHEK DWIVEDI
2/27/12
printf( ) Function: Writing Output Data ) function is used to write information to standard The printf(
output (normally monitor screen). The structure of this function is printf(format string, list of arguments); The format string contains the following: 1. Characters that are simply printed on the screen. 2. Specifications that begin with a % sign and define the output format for display of each item. 3. Escape sequence characters that begin with a \ sign such as \n, \t, CharacterA single character \b etc. c
d s f Integer String Signed decimal integer Prints character strings
Character Argument Resulting Output
scanf( ) Function: getting user input The real power of a technical C program is its ability to
interact with the program user. This means that the program gets input values for variables from users. The scanf( ) function is a built-in C function that allows a program to get user input from the keyboard. The structure of this function is scanf(format string &list of arguments); Examples scanf(%d, &a ); scanf(%d %c %f ,&a, &b, &c );
ABHISHEK DWIVEDI
2/27/12
CONTROL STRUCTURES
The control flow statements of a language determine the order in which the statements are executed. We also need to be able to specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true. Also we need to be able to carry out a statement or a group of statements repeatedly based on certain conditions. These kinds of situations are described in C using Conditional Control and Loop Control structures.
ABHISHEK DWIVEDI
2/27/12
The if statement
The if statement is used to control the flow of execution of statements. The general form of if statement is if (condition) statement; Suppose if it is required to include more than one statement, then a compound statement is used, in place of single statement. The form of compound statement is if (condition) { statement1; statement2; } If the condition is true, then the statement/statements will
ABHISHEK DWIVEDI 2/27/12
/* if block */
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
LOOPS
A portion of program that is executed repeatedly is called a loop. The C programming language contains three different program statements for program looping. They are
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ARRAYS
An Array is a collection of same data type. The elements of an array are referred by a common name and are differentiate from one another by their position with in an array. The elements of an array can be of any data type but all elements in an array must be of the same type. The general form of declaring a array is type array_name[size]; where type is a valid datatype, array_name is the name of the array and size is the number of elements that array_name contains. Example: int A[100]; int data type of elements that an array
ABHISHEK DWIVEDI 2/27/12
ARRAYS (Contd)
The individual elements of an array can be referenced by means of its subscript (or index) Suppose A is an array of 20 elements, we can reference each element as A[0] 1st element A[1] 2nd element A[2] 3rd element : : A[19] 20th element Note: Subscript enclosed within parenthesis. In C subscript starts from 0. That is, if we declare an array of size n, then we can refer the elements from 0 to (n-1)th element. ABHISHEK DWIVEDI 2/27/12
ABHISHEK DWIVEDI
2/27/12
Two-Dimensional Array
The general form of Two-Dimensional Arrays is type array_name[row_size][column_size]; Example: int a[2][2]; Initializing Two-Dimensional Arrays Like the one-dimensional arrays, following their declaration with a list of initial values enclosed in braces may initialize two-dimensional arrays. For example, int a[2][2] ={1,2,5,4}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as int a[2][2]={{1,2},{5,4}};
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Declaring and initializing string variables of declaration of string variable is The general form
char string-name[size]; where, string-name is the name of a string and size is the maximum number of characters the string-name can contain. Example: char name[30]; String variables can be initialized at the time of declaration. Example: char name[30] = Millennium;
A string can also be initialized at the time of declaration in ABHISHEK DWIVEDI 2/27/12 the following ways.
ABHISHEK DWIVEDI
2/27/12
String handling Functions: string.h provides a large set of string handling Every C compiler
library functions, which are contained in the header file string.h The following table shows some of the functions available in string.h header file. Function Meaning
strcat() String concatenate. Append one string to another. First character of string2 overwrites null character of string1. Returns the length of the string not counting the null character. Converts a string to lower case. Converts a string to upper case. Copies a string into another. Compares two strings Reverses a string ABHISHEK DWIVEDI 2/27/12
strcat() function
The strcat() function concatenates the source string at the end of the target string. For example Computing and Techniques on concatenation would result in string ComputingTechniques. The general form is strcat(string1, string2); strong2 appends to string1 and the first character to string2 overwrites null character of first string1. This function returns the first argument i.e., string1. The string2 remains unchanged.
ABHISHEK DWIVEDI
2/27/12
Output Enter String1:Jiffy Enter String2:Solutions The entire string is: Jiffy Solutions
2/27/12
strcmp() function
strcmp() function compares two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. The general form is: strcmp(string1, string2); If the two strings are same, strcmp() returns a value 0. If they are not same, it returns the numeric difference between the ASCII values of the first non-matching characters. That is, it returns less than 0 if string1 is less than string2, and greater than 0 if string1 is greater than string2.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
strcpy() function
The general form is: strcpy(String1, String2); The strcpy() function is used to copy the character string from String2 to String1. This function returns the result string String1 the String2 remains unchanged. String2 may be a character array or a string constant.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
strlen() function
This function strlen() counts the number of characters present in a string. The counting ends at the first null character. The general form is strlen (String1); The strlen() function returns the length of the argument String1 excluding the null character. The argument may be a string constant.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Functions
Functions are building blocks of C. Function performs the same set of instructions on different sets of data or at different portions of a program. C functions can be classified into two categories, namely library functions and user-defined functions. main is an example of user-defined functions. printf and scanf belong to the category of library functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a userdefined function has to be developed by the user at the time of writing a program. The general form of C function is Return-type Function-name (parameter list) parameter declaration; { ABHISHEK DWIVEDI 2/27/12
programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.
The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited. Many other programs may use a function. This means that a C programmer can build on what others have already done, instead of starting over, from scratch. As mentioned earlier, it is easy to locate and isolate a faulty function for further investigations.
ABHISHEK DWIVEDI
2/27/12
Category of functions
A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: Category 1: Functions with no arguments and no return values. Category 2: Functions with arguments and no return values. Category 3: Functions with arguments and return values.
ABHISHEK DWIVEDI
2/27/12
Recursion
Recursion is a technique to be used to call itself. In C, it is possible for the functions to call themselves. A function is called recursive if a statement with in the body of a function calls the same function itself. Program #include<stdio.h> #include<conio.h> long int fact(int); ABHISHEK DWIVEDI
2/27/12
long int fact(int n) { long int f; if(n==1) return 1; else f = n*fact(n-1); return f; }
All C programs must contain atleast one function. [The main() function serves this rule] A function can return only one value. Thus we should not specify two values to return. The return type in function declaration is optional. If no return type is specified it is assumed to be an integer which is default. When a function is not returning any value, void type can be used as return type. Parameter list is optional. C provides a statement return return expression
Return statement is used in function definition to communicate the return value to the calling function.
ABHISHEK DWIVEDI
2/27/12
Return statement indicates exit from the function and return to the point from where the function was invoked. There may be any number of return statements in function definition, only one return statement will activate in a function call. but
The variable declarations within the function (between braces { }) are local to the function and are not available outside the function. If there is no return statement, the program will return to the calling point after it reaches the end of the function body (}). A function call can be used wherever a variable of same type is used (except the left side of an assignment statement). There should be one to one correspondence between the actual and formal parameters in type, order and number. C allows recursion. That is a function can call itself. A C function cannot be defined in another function.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Variables
There are three basic places in a C program where variables will be declared:
inside the function, in the definition of function parameters, or outside of all functions.
These variables are called local variables, formal parameters, and global variables respectively.
ABHISHEK DWIVEDI
2/27/12
Local Variables
The body of any function comprises of two parts: declaration of variables and a set of executable statements. Variables declared inside a function are called local variables. This name derives from the fact that a variable inside a function can be used only inside that function. An attempt on our part or access the local variable of one function in another, will draw an error from the compiler: Identifier undefined.
ABHISHEK DWIVEDI
2/27/12
Block
Yet another place to declare variables is inside any block: these variables are called block variables and these can be used only inside that block.
ABHISHEK DWIVEDI
2/27/12
Storage classes
The storage class of a variable dictates how, when and where storage will be allocated for the variable. The different storage classes available are:
1.
2.
3.
4.
ABHISHEK DWIVEDI
2/27/12
Auto
Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private (or local) to the function in which they are declared. Because of this property, automatic variables are also refereed to as local or internal variables. A variable declared inside a function without storage class specification is, by default, an automatic variable. One important feature of automatic variables is that their value cannot be changed accidentally by what happens in some other function in the program. This assures that we may declare and use the same variable name in different functions in the same program without causing any confusion to the compiler.
ABHISHEK DWIVEDI
2/27/12
Auto : Program
#include<stdio.h> #include<conio.h> void function1(); void function2(); void main() { int m = 1000; clrscr(); function2(); printf(%d\n,m); getch(); } ABHISHEK DWIVEDI 2/27/12 void function1() { int m = 10; printf(%d\n,m); } void function2() { int m = 100; function1(); printf(%d\n,m); }
Register
It is possible for use to attribute the register storage class to certain variables. We can tell the compiler that a variable should be kept in one of the machines registers, instead of keeping in the memory (where normal variables are stored). Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs. This is done as follows: register int count; The important point while using register variables is, registers of CPU do not have addresses. Thus, we should not refer the address of a register variable. For example,
ABHISHEK will result an error : 2/27/12 The following statementDWIVEDI
Register : Program
#include<stdio.h> #include<conio.h> void main() { register int count; int sum; clrscr(); for(count=0;count<10;count++) sum = sum + count; printf(The sum is:%d,sum); getch(); ABHISHEK DWIVEDI 2/27/12
Extern
This is the default storage class for all global variables. Extern storage class variables get initialized (to zero in the case of integers) automatically, retain their value throughout the execution of the program and can be shared by different modules of the same program. However, assuming int intvar;is present in a.c., to be also to have proper binding with the same variable, b.c (another file) should have extern int intvar.
ABHISHEK DWIVEDI
2/27/12
Extern : Program
a.c file #include<stdio.h> #include<conio.h> int intvar; extern float f; void main() { char ch; funct(ch,intvar); printf(%f,f); getch(); }
ABHISHEK DWIVEDI 2/27/12
b.c file float f = 84.237; extern int intvar; funct(char c, int intvar) { char c1,c2; : : }
Static
The static storage class has a number of implications depending upon its usage. The default storage class for all local variables is auto. This can be changed to static by prefixing the declaration with the keyword static as in static int intvar. A local variable with static storage class is still a local variable as far as its scope is concerned, it is still available only inside the function in which it is declared. But certain other properties of the variable change; It gets initialized to zero automatically, is initialized only once, (during program startup) and it retains its value throughout the execution of the program. When applied to a global variable, the global variable becomes inaccessible outside the file in which it is ABHISHEK DWIVEDI 2/27/12 declared.
Static : Program
Program:
#include<stdio.h> #include<conio.h> void main() { function1( ); function1( ); function1( ); getch(); } void function1()
ABHISHEK DWIVEDI 2/27/12 Output The value of n is 1 The value of n is 2 The value of n is 3
declared
Where
Scope
Life
Storage
Auto or none
Local
Memory
Register
Local
garbage value
CPU registers
Static
Local
Zero
until program ends, Memory value of the variable persists between different function calls Memory
Extern
Global
Zero
All files including other While any of these files where declared files are active. extern That is, as long as the programs execution doesnt come to an end
ABHISHEK DWIVEDI
2/27/12
Structures
A structure is a convenient tool for handling a group of logically related data items. These fields are called structure elements or members. Declaring A Structure The general form of a structure declaration statement is given below: struct <structure name> { structure element1; structure element2;
ABHISHEK DWIVEDI 2/27/12 Example: struct book { char name[20]; char author[15]; int pages; float price; }
The closing brace in the structure type declaration must be followed by a semicolon. It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the form of the structure. Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.
ABHISHEK DWIVEDI
2/27/12
ARRAYS OF STRUCTURES
we may declare an array of structures, each element of the array representing a structure variable. For example, struct class student[100]; defines an array called student, that consists of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration: struct marks { int sub1; int sub2; int sub3; }s[5];
ABHISHEK DWIVEDI 2/27/12
The salary structure contains a member named allowance which itself is a structure with three members. The members contained in the inner structure namely dearness, house_rent, and city can be referred to as employee.allowance.dearness employee.allowance.house_ren t employee.allowance.city
UNIONS
Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows: union item { int m; float x; char c; }code;
ABHISHEK DWIVEDI
2/27/12
SIZE OF STRUCTURES
We normally use structures, unions, and arrays to create variables of large sizes. The actual size of these variables in terms of bytes may change from machine to machine. We may use the unary operator sizeof to tell us the size of a structure (or any variable). The expression sizeof(struct x) will evaluate the number of bytes required to hold all the members of the structure x. If y is a simple structure variable of type struct x, then the expression sizeof(y) would also give the same answer.
ABHISHEK DWIVEDI 2/27/12
Pointers
Pointers are another important feature of C language. They are a powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers.
A pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling the data tables. Pointers reduce the length and complexity of a program. They increase the execution speed. The use of a pointer array to character strings results in saving of data storage space in memory.
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
DECLARING POINTERS
In C, every variable must be declared for its type. Since pointer variables contain addresses that belong to a separate data type, they must be declared as pointers before we use them. The declaration of a pointer variable takes the following form: datatype *pt_name; This tells the compiler three things about the variable pt_name.
The asterisk (*) tells the variable pt_name is a pointer variable. pt_name needs a memory location.
For example, int *p; declares the variable p as a pointer variable that points to an integer data type. Remember that the type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer. Similarly, the statement float *x; declares x as a pointer to a floating point variable.
2/27/12
INITIALIZING POINTERS
Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement such as p = &quantity; which causes p to point to quantity. That is, p now contains the address of quantity. This is known as pointer initialization. Before a pointer is initialized, it should not be used.
ABHISHEK DWIVEDI
A pointer variable can be initialized in its declaration itself. For example, int x, *p=&x; is perfectly valid. It declares x as an integer variable and p as a pointer variable and then initializes p to the address of x. Note carefully that this is an initialization of p, not *p. And also remember that the target variable x is declared first. The statement int *p=&x, x; is not valid.
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Task
Allocates requested size of bytes and returns a pointer to the first byte of the allocated space. Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. Frees previously allocated space.
calloc
Free
realloc
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
We know that a string is an array of characters, terminated with a null character. Like in one-dimensional arrays, we can use a pointer to access the individual characters in a string.
ABHISHEK DWIVEDI
ABHISHEK DWIVEDI
File Management in C
A file is a place on the disk where a group of related data is stored. Like most other languages, C supports a number of functions that have the ability to perform basic file operations, which include:
Naming a file, Opening a file, Reading data from a file, Writing data to a file, and Closing a file.
ABHISHEK DWIVEDI
2/27/12
fopen()
fclose() Getc() putc() fprintf() fscanf() getw() putw() fseek() Ftell() rewind()
Creates a new file for use Opens an existing file for use. Closes a file which has been opened for use. Reads a character from a file. Writes a character to a file. Writes a set of data values to a file. Reads a set of data values from a file. Reads an integer from a file. Writes an integer to file. Sets the position to a desired point in the file Gives the current position in the file Sets the position to the beginning of the file. ABHISHEK DWIVEDI 2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
Many recent compilers include additional modes of operation. When the purpose is appending, They include: the file is opened with the current r+ The existing file is opened to contents safe. A file with the the beginning for both reading specified name is created if the and writing. file does not exist. w+ Same as w except both for reading and writing If the purpose is reading, and if it a+ Same as a except both for exists, then the file is opened with reading and writing. the current contents safe; We can open and use a number otherwise an error occurs. of files at a time. This number however depends on the system ABHISHEK DWIVEDI we use. 2/27/12
CLOSING A FILE
A file must be closed as soon as all operations on it have been completed. The general form is: fclose(file_pointer);
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
ABHISHEK DWIVEDI
2/27/12
We know that every C program should have one main function and that it marks the beginning of the program.
But what we have not mentioned so far is that it can also take arguments like other functions. In fact main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system. The variable argc is an argument counter that counts the number of arguments on the command line. The argv is an argument vector and represents an array of character pointers that point to the command line arguments
The size of this array will be equal to the value of argc. For instance, for the command line given above, argc is three and argv is array of three pointers to strings as shown below: argv[0] PROGRAM argv[1] X_FILE argv[2] Y_FILE In order to access the command line arguments, we must declare the main function and its parameters as follows: main(argc,argv); int argc; char *argv[]; The first parameter in the command line is always the program name and therefore argv[0] always represents the program name.
ABHISHEK DWIVEDI
2/27/12
printf("Contents of %s file\n\n",argv[1]); fp=fopen(argv[1],"r"); for(i=2;i<argc;i++) { fscanf(fp,"%s",word); printf("%s",word); } fclose(fp); printf("\n\n"); for(i=0;i<argc;i++) printf("%*s\n",i*5,argv[i]); getch(); }
ABHISHEK DWIVEDI
2/27/12