Вы находитесь на странице: 1из 142

LEARNING C

ABHISHEK DWIVEDI IT DEPARTMENT


ABHISHEK DWIVEDI

AVIT, CHENNAI.
2/27/12

WHICH TOPIC U WANNA STUDY ???


INTRODUCTION CONSTANTS & VARIABLES OPERATORS & EXPRESSIONS STRUCTURE OF A C PROGRAM CONTROL STRUCTURES ARRAYS AND STRINGS FUNCTIONS STORAGE CLASSES STRUCTURES & UNIONS POINTERS DYNAMIC MEMORY ALLOCATION FILE MANAGEMENT IN C COMMAND LINE ARGUMENTS ABHISHEK DWIVEDI 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

1967 1970 1972

BCPL

B C

ALGOL Algorithmic Language


ABHISHEK DWIVEDI

CPL

2/27/12 Combined

C Tokens

A token is an atomic unit (smallest indivisible units) in a program.

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

The C character set


The C character set includes the upper case letters A to Z, the lower case a to z, the decimal digits 0 to 9 and certain special characters.

Letters

a, b, c, z

Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special characters ~,.;:?!()[]{}/\< >=+ -$#@&*%^

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

Underscore | ABHISHEK DWIVEDI

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

The standard keywords are


auto continue enum if short switch volatile int break default extern long signed typedef while case do float char double for const else goto return struct

register sizeof union static

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

Size (No. of Bytes)


1 2 4 8 0 1 1 2 3 4

Range
0 to 255 -32768 to +32767 -2,147,483,648 to +2,147,483,647 Approximately 15 digits of Precision

-128 to 127 0 to 255 -32768 to +32767 0 to 65535 -2,147,483,648 to +2,147,483,647

ABHISHEK DWIVEDI

2/27/12

Constants and Variables


A constant is a literal, which remain unchanged during the execution of a program. A constant is a fixed value that cannot be altered during the execution of a program. C constants can be classified into two categories.

Primary Constants Secondary Constants

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

Rules for constructing Real constants

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

Rules for constructing Characters constants


A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas point to the left. For example, A is valid character constant whereas A is not. The maximum length of a character constant can be 1 character. Note: Every character has its ASCII (American Standard Code for Information Interchange) value. That means every character is interchange with integer constant. For example, ABHISHEK DWIVEDI 2/27/12 A value is 65 and a value is 97.

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

The purpose of each Type Declaration instructions to declare the type of

instruction

variables used in a C program

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

Operators & Expressions


An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in program to manipulate data and variables. The data items that operators act upon are called operands. Some operators require two operands, while others act upon only one operand. The operators are classified into unary, binary and ternary2/27/12 ABHISHEK DWIVEDI

Types of operators
C has four classes of operators
1.

Arithmetic Operators Relational Operators Logical Operators Bit-wise Operators

2.

3.

4.

In addition, C has some special operators, which are unique to C, they are
1.

Increment & Decrement Operators Conditional Operators


ABHISHEK DWIVEDI Assignment Operators, etc. 2/27/12

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
|

Ones Complement Bitwise OR Bitwise AND Bitwise Exclusive OR (XOR) 2/27/12

& ^ >>

Right Shift ABHISHEK DWIVEDI Left Shift <<

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;

These operators are very useful in loops.

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

Hierarchy (precedence) of operators The priority or precedence in which the operations of an


arithmetic statement are performed is called the hierarchy of operators. The operators of at the higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as the Associativity property of an operator. PRECEDENCE OF OPERATORS (Arithmetic operators * Multiplicatio Left to right 3 only)
n / % + Division Modulo Addition Subtraction ABHISHEK DWIVEDI 3 3 4 4 2/27/12
Operator Description Associativity Rank

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 */.

The second line


# include <stdio.h> tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of header files, contain the information about input and output functions. stdio.h means Standard Input Output Header file. This file contains the information about printf() function.

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.

The fourth line


void main( ) is the stat of the main program. The word main is followed by a pair of ordinary parenthesis ( ), which indicates that main is also a function.

The fifth line


{
ABHISHEK DWIVEDI 2/27/12

Description (contd)
The seventh line
printf( Welcome to C); this function causes its arguments to be printed on the screen on the computer.

The eight line


getch( ); is reads the single character directly from the keyboard without printing on the screen.

The ninth line


} the right brace represents the ending of the program.

ABHISHEK DWIVEDI

2/27/12

Rules to write a C program


1. All C statements must end with semicolon. 2. C is case-sensitive. That is, upper case and lower case characters are different. Generally the statements are typed in lower case. 3. A C statement can be written in one line or it can split into multiple lines. 4. Braces must always match upon pairs, i.e., every opening brace { must have a matching closing brace }. 5. Every C program starts with void main( ) function. 6. Comments cannot be nested. For example, /* Welcome to C ,/* programming*/ */ A comment can be split into more than one line.

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.

Compilation of the Program


Turbo C compiler is user friendly and provides integrated program development environment. Thus, selecting key combination can do compilation. That means press Alt + F9 for compilation.

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

Floating Single floating point number point ABHISHEK DWIVEDI 2/27/12

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

Conditional & loop structures


A conditional structure can be implemented in C using
The if statement The if-else statement The nested if-else statement The switch statement.

whereas loop control structures can be implemented in C using


while loop do-while loop for statement
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

The if statement : Program


Program /* Inputting year is Leap or not */ #include<stdio.h> #include<conio.h> void main() { int year; clrscr(); printf(Enter year:); scanf(%d,&year); if(year%4==0)
ABHISHEK DWIVEDI 2/27/12 Output 1 Enter year:1990 Not leap year Output 2 Enter year:1996 Leap year

The if-else Statement


The general form of if-else statement is if (condition) statement1; else statement2; If the condition is true, then statement1 is executed. Otherwise if the condition is false, then the statement2 is executed. Here statements statement1 and statement2 are either simple statements or compound statements. That is if (condtion) { statements
ABHISHEK DWIVEDI 2/27/12

/* if block */

The if-else Statement : Program


Program /* Single digit or not */ #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf(Enter a number:); scanf(%d,&n); if(n<=9)
ABHISHEK DWIVEDI 2/27/12 Output 1 Enter a number:5 Single digit Output 2 Enter a number:12 Not single digit

Nested if-else Statements


When a series of conditions are involved, we can use more than one if-else statement in nested form. This form is also known as if-else if-else statements. The general form of ifelse if-else statement is if (condition) statements; else if (condition) statements; else statements; Note that a program contains number of else if statements and must be ended with else statement.

ABHISHEK DWIVEDI

2/27/12

Nested if-else Statements : Program Program


/* To check whether +ve, -ve or zero */ #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf(Enter a number:); scanf(%d,&n); If(n>0)
ABHISHEK DWIVEDI 2/27/12 Output 1 Enter a number: -2 -ve Output 2 Enter a number:0 zero Output 3 Enter a number:5 +ve

The Switch Statement


The Switch statement is an extension of the if-else if-else statement. The switch makes one selection when there are several choices to be made. The direction of the branch taken by the switch statement is based on the value of any int (or int compatible) variable or expression. The general form of Switch statement is shown below. switch (variable) { case constant1:statement 1; case constant2:statement 2; case constant3:statement 3; ABHISHEK DWIVEDI
2/27/12

The Switch Statement : Program


Program /* Letter -> color name */ #include<stdio.h> #include<conio.h> void main() { char x; clrscr(); printf(Enter a char:); scanf(%c,&x); switch(x)
ABHISHEK DWIVEDI 2/27/12 Output 1 Enter a char:w w->white Output 2 Enter a char:b b->black Output 3 Enter a char:c No color

The exit( ) Function


The exit( ) is a function in the standard library of C. This function causes immediate termination of the program and execution control return to the operating system. In general, the termination to exit( ) function is 0 to indicate that termination is normal. Other arguments may be used to indicate some sort of an error.

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

For loop While loop Do-While loop

ABHISHEK DWIVEDI

2/27/12

The For Loop


The for loop is used to repeat the execution statement for some fixed number of times. The general form of for loop is for(initialization;condition;increment/decrement) statement; where the statement is single or compound statement. initialization is the initialization expression, usually an assignment to the loop-control variable. This is performed once before the loop actually begins execution. condition is the test expression, which evaluated before each iteration of the loop, which determines when the loop will exist. increment is the modifier expression, which changes the value of loop control variable. This expression is executed at the end of each loop.

ABHISHEK DWIVEDI

2/27/12

The For Loop : Program


Program /* Print 1 to 10 numbers */ #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for(i=1;i<=10;i++) printf(\n%d,i); getch(); } ABHISHEK DWIVEDI 2/27/12 Output 1 2 3 4 5 6 7 8 9 10

The While Loop


The while loop is best suited to repeat a statement or a set of statements as long as some condition is satisfied. The general form of while loop is initial expression; while(conditional-expression) { statement; increment/decrement; } where the statement (body of the loop) may be a single statement or a compound statements. The expression (test condition) must results zero or non-zero.
ABHISHEK DWIVEDI 2/27/12

The While Loop : Program


Program /* Print a message 3 times */ #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); while(i<=3) { printf(\nJiffy Solutions);
ABHISHEK DWIVEDI 2/27/12 Output Jiffy Solutions Jiffy Solutions Jiffy Solutions

The do-while loop


The structure of do-while loop is similar to while loop. The difference is that in case of do-while loop the expression is evaluated after the body of loop is executed. In case of while loop the expression is evaluated before executing body of loop. The general form of do-while statement is do { statement; }while(expression); where statement is a single statement or compound statement. In contrast to while loop statement (body of loop), do-while loop is executed one or more times.

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

Single Dimensional Array


The general form of Single Dimensional array is: datatype variable[size]; Example: int A[20]; Initialization of arrays during declaration Similar to other datatypes, the array also can be initialized at the time of declaration. int num[5] ={3,2,1,5,4}; char name[15] = {c,o,m,p,u,t,e,r,s}; float rate[] = {20.5,15.75,12.34};

ABHISHEK DWIVEDI

2/27/12

Single Dimensional Array : Program Single Dimensional Program illustrating


Array #include<stdio.h> #include<conio.h> void main() { int a[5],i; clrscr(); printf(Enter 5 elements into an array:); for(i=0;i<=4;i++) scanf(%d,&a[i]);
ABHISHEK DWIVEDI printf(The 5 elements are:); 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

Two-Dimensional Array : Programs Two printf(The 4 elements Program Illustrating


Dimensional arrray
#include<stdio.h> #include<conio.h> void main() { int a[2][2],i,j; clrscr(); printf(Enter 4 elements into array:); for(i=0;i<=1;i++) {
ABHISHEK DWIVEDI 2/27/12

are:\n); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { printf(%d ,a[i][j]); } printf(\n); } getch(); }

Handling of Character Strings


A string is an array of characters. There is no string built-in data type in C. But we can declare string as an array of characters. To recognize a character array, it should end with a null character (\0). For example, the string SCIENCE would be stored as S C I E N C E \0 The length of a string is the number of characters it contains excluding null character. Hence, the number of locations needed to store a string is one more than length of string. In this example, the length of the string is 7.

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.

Reading and writing strings


The scanf(), printf() function is used with %s with format specification to read and print a string. Example: char str[30]; scanf(%s,str); printf(%s,str); In the case of reading strings, the ampersand (&) is not required before the string variable name. As mentioned earlier, one of the limitations of the scanf() function is that it is not capable of holding multiword strings, even though it can read them.

ABHISHEK DWIVEDI

2/27/12

Reading and writing strings : Program Program


#include<stdio.h> #include<conio.h> void main() { char line[80]; clrscr(); printf(Enter a line\n); scanf(%s,line); printf(The entered line is: %s,line); getch();
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

strlen() strlwr() strupr() strcpy() strcmp() strrev()

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

strcat() function : Program


Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char s1[30],s2[15]; clrscr(); printf(Enter String1:); gets(s1); printf(Enter String2:); gets(s2); printf(The entire string is: ABHISHEK DWIVEDI %s,strcat(s1,s2));

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

strcmp() function : Program


Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char s1[25],s2[25]; int c; clrscr(); printf(Enter string1:); gets(s1); printf(Enter string2:); gets(s2); c=strcmp(s1,s2); if(c>0) printf(String1 > String2); else if(c<0) printf(String2 > String1); else printf(Both are equal); getch(); }

Output Enter String1:abc Enter String2:ABC String1 > String2

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

strcpy() function : Program


Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char s1[15],s2[15]; clrscr(); printf(Enter String1:) gets(s1); printf(The String2 is:%s,strcpy(s2,s1)); getch(); }

Output Enter String1:Millennium The String2 is:Millennium

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

strlen() function : Program


Program
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[30]; clrscr(); printf(Enter a string:); gets(str); printf(The length of a ABHISHEK DWIVEDI string is:%d,strlen(str));
2/27/12 Output Enter a string: Millennium Software Solutions The length of a string is:29

strupr(), strlwr(), strrev() functions is used to convert The strupr() function


the string into upper case. The strlwr() function is used to convert the string into lower case. The strrev() function prints the entire string in reverse order.

ABHISHEK DWIVEDI

2/27/12

strupr(), strlwr(), strrev() functions : Program


Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[15]; clrscr(); printf(Enter a string:); gets(str); printf(The upper case string is: ABHISHEK DWIVEDI %s,strupr(str));
2/27/12 Output Enter a string:millennium The upper case string is:MILLENNIUM The lower case string is:millennium The reverse string is:muinnellim

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

Advantages of user-defined functions: It facilitates top-down modular programming. In this

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

Functions with no arguments and no return values


Program #include<stdio.h> #include<conio.h> Function Declaration void printline(); void main() { clrscr(); printline(); /*Function Declaration*/

printf(This illustrates the use of C functions\n); printline(); getch(); ABHISHEK DWIVEDI


2/27/12

Arguments but no Return values Program


#include<stdio.h> #include<conio.h> void swap(int,int); void main() { int a,b; clrscr(); printf(Enter 2 numbers:); scanf(%d%d,&a,&b); swap(a,b); getch(); /* Function Call*/
2/27/12 ABHISHEK DWIVEDI

Arguments with Return Values


Program #include<stdio.h> #include<conio.h> int big(int,int); void main() { int a,b,max; clrscr(); printf(Enter 2 numbers:); scanf(%d%d,&a,&b); max = big(a,b);
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; }

Important points about functions


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

Important points (Contd)

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

Functions with Arrays


Like the values of simple variables, it is also possible to pass the values of an array to a function. To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts, and the size of the array as arguments. For example, the call largest(a,n); will pass all the elements contained in the array a of size n. The called function expecting this call must be appropriately defined. The largest function header might look like: int largest(array,size); int array[]; int size;

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

Global Variables Variables of three C program consists


sections namely: the preprocessor directives, the global variable section and finally the functions. The variables that are declared in the global variable section are called global variables. While a local variable can be used only inside a function in which it is declared, a global variable can be used anywhere in the program.

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.

Auto Register Extern Static

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

Storage Type class

Default initial value


garbage value

declared

Where

Scope

Life

Storage

Auto or none

Local

within the function within the function where it is declared

until function is no longer active

Memory

Register

Local

garbage value

within the function within the function where it is declared

until function is no longer active

CPU registers

Static

Local

Zero

within the function within the function where it is declared

until program ends, Memory value of the variable persists between different function calls Memory

Extern

Global

Zero

A heat of all functions within a file

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; }

Important points while declaring a structure type:

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

ACCESSING STRUCTURES ELEMENTS


We can assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator . Which is also known as dot operator or period operator. The general form is Structure-Variable. Structure-Member; For example, book1.price; We can also use scanf to give the values through the keyboard. scanf(%s,book1.name); scanf(%d,&book1.pages); are valid input statements. 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

ARRAYS WITHIN STRUCTURES


C permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single-or multi-dimensional arrays of type int or float. For example, the following structure declaration is valid: struct marks { int number; float sub[3]; }s[2];
ABHISHEK DWIVEDI 2/27/12

STRUCTURES WITHIN STRUCTURES


Structures within a structure means nesting of structures. Nesting of structures is permitted in C. Let us consider the following structure definition: struct salary { char name[20]; char dept[10]; struct { int dearness;
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

ACCESSING THE ADDRESS OF A VARIABLE


The actual location of a variable in the memory is system dependent and therefore, the address of a variable is not known to us immediately. We can determine the address of the variable with the help of the operator & in C. We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable returns the address of the variable associated with it. For example, p = &quantity; would assign the address to the variable p. The & operator can be remembered as address of.

ABHISHEK DWIVEDI

2/27/12

ACCESSING ADDRESSES OF VARIABLES : PROGRAM


#include<stdio.h> #include<conio.h> void main() { char a; int x; float p, q; clrscr(); a = A; x = 125; p = 10.25, q = 18.76;
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.

ABHISHEK DWIVEDI pt_name points to a 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

ACCESSING A VARIABLE THROUGH ITS POINTER


Once a pointer has been assigned the address of a variable, the question remains as to how to access the value of the variable using the pointer. This is done by using another unary operator * (asterisk), usually known as the indirection operator. Consider the following statements: int quantity, *p, n; quantity = 179; p = &quantity; n = *p;

ABHISHEK DWIVEDI

2/27/12

ACCESSING A VARIABLE THROUGH ITS POINTER (CONTD)


The first line declares quantity and n as integer variables and p as a pointer variable pointing to an integer. The second line assigns the value 179 to quantity. The third line assigns the address of quantity to the pointer variable p. The fourth line contains the indirection operator *. When the operator * is placed before a pointer variable in an expression, the pointer returns the value of the variable of which the pointer value is the address. In this case, *p returns the value of the variable quantity, because p is the address of quantity. The * can be remembered as value of address. Thus the value of nDWIVEDI 179. ABHISHEK would be 2/27/12

POINTERS AND ARRAYS


When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element. If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following assignment: p = x; This is equivalent to p = &x[0]; When handling arrays, instead of using array indexing, we can use pointers to access array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method is much faster than array indexing.

ABHISHEK DWIVEDI

2/27/12

DYNAMIC MEMORY ALLOCATION


C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many languages permit a programmer to specify an arrays size at run time. The process of allocating memory at run time is known as dynamic memory allocation. In C language there are four library routines known as memory management functions that can be used for allocating and freeing memory during program execution.

ABHISHEK DWIVEDI

2/27/12

Memory Allocation Functions


Function
malloc

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

Modifies the size of previously allocated space.

ABHISHEK DWIVEDI

2/27/12

Allocating a Block of Memory


A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. Use of malloc Function #include<stdio.h> #include<conio.h> void main() { int *p, n, i; clrscr(); printf(Enter n value:); scanf(%d,&n); It takes the following form: p = (int) malloc(sizeof(int)*n); printf(\nEnter %d ptr = (datatype numbers:,n); *)malloc(byte-size); for(i=0;i<n;i++) ptr is a pointer of type scanf(%d,*(p+i)); datatype. The malloc returns printf(\nThe numbers are:); a pointer (of datatype) to an for(i=0;i<n;i++) area of memory with size byteprintf(\n%d,*(p+i)); size. getch(); } Example: ABHISHEK DWIVEDI 2/27/12

Allocating Multiple Blocks of Memory


calloc is another memory allocation function that is normally used for requesting memory space at run time for storing derived data types such as arrays and structures. While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all bytes to zero. The general form of calloc is: ptr = (datatype *) calloc (n,elem-size); The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space, a NULL pointer is returned.

ABHISHEK DWIVEDI

2/27/12

Releasing the Used Space


Compile-time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic run-time allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. We may release that block of memory for future use, using the free function: free(ptr); ptr is a pointer to a memory block which has already been created by malloc or calloc.
ABHISHEK DWIVEDI 2/27/12

Altering the Size of a Block


It is likely that we discover later, the previously allocated memory is not sufficient and we need additional space for more elements. It is also possible that the memory allocated is much larger than necessary and we want to reduce it. In both the cases, we can change the memory size already allocated with the help of the function realloc. This process is called the reallocation of memory. For example, if the original allocation is done by the statement ptr = malloc(size); then reallocation of space may be done by the statement ptr = realloc(ptr, newsize);

ABHISHEK DWIVEDI

2/27/12

POINTERS AND CHARACTER STRINGS


Program #include<stdio.h> #include<conio.h> void main() { char *str; int i=0; clrscr(); printf(Enter a string:); gets(str); while(*str!=\0) { i++; str++; } printf(\nThe length is:%d,i); getch(); } 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

POINTERS AND FUNCTIONS


Program : Pointers as function Parameters #include<stdio.h> In functions we can pass the #include<conio.h> duplicate values for the actual void main() parameters, but we can pass the { address of a variable as an int a,b; clrscr(); argument to a function in the printf(Enter 2 numbers:); normal fashion. scanf(%d %d,&a,&b); printf(\nBefore exchange: a=%d, b= When we pass addresses to a %d,a, b); function, the parameters swap(&a,&b); receiving the addresses should printf(\nAfter exchange: a=%d, b= be pointers. The process of %d,a, b); calling a function using pointers getch(); to pass the addresses of variable } is known as call by address. void swap(int *x, int *y) { int z; z = *x; *x = *y; ABHISHEK DWIVEDI *y = z; 2/27/12

POINTERS AND STRUCTURES


We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables. Suppose product is an array variable of struct type. The name product represents the address of its zeroth element. Consider the following declaration: struct inventory { char name[30]; int number; } product[3], *ptr;
Program: Pointers to Structure variables #include<stdio.h> #include<conio.h> struct invent { char name[20] ; int number; }product[3], *ptr; void main() { clrscr(); printf(INPUT\n\n); printf(Enter name and number(3 records):); for(ptr = product;ptr<product+3;ptr+ +) scanf(%s %d,ptr->name,&ptr>number); printf(\n\nOUTPUT); for(ptr = product;ptr<product+3;ptr+ +) printf(\n%s\t%d,ptr->name,ptr2/27/12 >number);

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

High level I/O functions


Function Name Operation

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

DEFINING AND OPENING A FILE


If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include: Filename. Data Structure. Purpose. Following is the general format for declaring and opening a file: FILE *fp; fp = fopen(filename, mode);

ABHISHEK DWIVEDI

2/27/12

DEFINING AND OPENING A FILE (CONTD)


The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, FILE is a structure that is defined in the I/O library. The second statement opens the file named filename and assigns as identifier to the FILE the pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program. The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be one of the following: r open the file for reading only. w open the file for writing only. a open the file for appending (or adding) data to it. Note that both the filename and mode are specified as strings. They should be enclosed in double quotation marks.

ABHISHEK DWIVEDI

2/27/12

DEFINING AND OPENING A FILE (CONTD)


When trying to open a file, one of the following things may happen: When the mode is writing a file with the specified name is created if the file does not exist. The contents are deleted, if the file already exists.

Consider the following statements: FILE *p1, *p2; p1 = fopen(data,r); p2 = fopen(results,w);

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

INPUT/OUTPUT OPERATIONS ON FILES


Once a file is opened, reading out of or writing to it is accomplished using the standard I/O routines that are listed. The getc and putc Functions The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar functions and handle one character at a time. Assume that a file is opened with mode w and file pointer fp1. Then, the statement putc(c, fp1); writes the character contained in the character variable c to the file associated with FILE pointer fp1. Similarly, getc is used to read a character from a file that has been opened in read mode. For example, the statement c = getc(fp2); would read a character from the file whose file pointer is fp2. The file pointer moves by one character position for every ABHISHEK DWIVEDI 2/27/12 operation of getc or putc. The getc will return an end-of-file marker

Program : Writing to and Reading from a File


PROGRAM #include<stdio.h> #include<conio.h> void main() { FILE *f1; char c; clrscr(); printf(Data Input\n\n); f1 = fopen(INPUT, w); while((c=getchar()!=EOF) putc(c,f1);
ABHISHEK DWIVEDI 2/27/12

The fprintf & fscanf Functions


The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf and scanf functions, except of course that they work on files. The first argument of these functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp, control string, list); where fp is a file pointer associated with a file that has been opened for writing. The control string contains output specifications for the items in the list. The list may include variables, constants and strings. Example: fprintf(f1, %s %d %f,name,age,7.5); Here, name is an array variable of type char and age is int variable.

ABHISHEK DWIVEDI

2/27/12

The fscanf Function


The general format of fscanf is fscanf(fp, control string, list); This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string. Example: fscanf(f2, %s %d, item, &quantity); Like scanf, fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF.

ABHISHEK DWIVEDI

2/27/12

COMMAND LINE ARGUMENTS


It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. For example, if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE, then we may use a command line like C:\TC>PROGRAM X_FILE Y_FILE PROGRAM is the filename where the executable code of the program is stored. This eliminates the need for the program to request the user to enter the filenames during execution.

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.

How do these parameters get into 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

Program : Command line Arguments


#include<stdio.h> #include<conio.h> void main(argc,argv) int argc; char *argv[]; { FILE *fp; int i; char word[15]; clrscr(); fp = fopen(argv[1],"w"); printf("\nNo.of arguments in Command line=%d\n\n",argc);

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(); }

for(i=2;i<argc;i++) fprintf(fp,"%s",argv[i]); fclose(fp);

ABHISHEK DWIVEDI

2/27/12

!!! YOU NK HA T DI IVE : BY DW H EK HI S AB


Write your feedback dwivedi.2512@gmail.com to

Вам также может понравиться