Vous êtes sur la page 1sur 43

C&DS for I CSE-B LITS

Unit-II Getting started with C


History of C: C is originally developed by Dennis Ritchie at AT and Ts Bell Laboratories in 1972. Condition was evolved from ALGOL, BCPL and B and uses many concepts from these languages and added the concept of data types and other powerful features. One of the most popular operating systems, UNIX is developed in C. Many version of C were proposed and to assure that the C language remains standard, ANSI (American National Standards Institute) appointed a technical committee in 1983 to define a standard for C. The committee approved a version in 1989 and is referred to ANSI C. It is later approved by ISO (International Standards Organization). Features of C: The increasing popularity of C is due to its many desirable qualities: It is a highly portable language and can be easily implemented in different operating systems. It is robust language; with its rich set of built in functions and operators we can write any complex programs easily. Programs written in C are efficient and fast than other languages like BASIC. C language is well suited for structured programming, in which the programmer thinks of a problem in terms of function modules or blocks. A proper collection of these modules (blocks) make a complete program. That is why a C program can termed as a collection of different functions. One of those functions is compulsory and is it the main() function. C compiler starts execution of the program by making a call to main function. C has ability to extend itself; we can continuously as add our own functions to the C Library. Learning C language is similar to learning the English language. The classical method of learning English to learn the set of alphabets (character set in C), words (tokens) and sentences(sentences) and paragraphs (program). It is just that they are termed differently in C. Character Set: The character set of C language contains the following: Alphabets A, B, C, .X, Y Z a, b, c.. x, y, z

Digits 0, 1, 2, 3.9 Special symbols: ~ ` ! @ # % $ & * ( ) _ - + = | \ { } [ ] : ; < > , . ? / C Tokens: In a C program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements. Token are formed with the combinations of characters in character set of C. The keywords, identifiers, constants, string literals, and operators are examples of tokens. Punctuation characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.

JYOTHI

Page 1

C&DS for I CSE-B LITS

Constants: A constant is a quantity that doesnt change during the execution of the program. Constants are also called literals. C supports various kinds of constants (different kind of constants for different data types).

Integer Constants: Integer constant refers to a sequence of digits. Decimal integer consists of a set of digits, 0 through 9. Integer can negative or positive. Negative integers are indicated by using the unaryoperator minus (-). Eg: 867 -124 Real Constants: are also called floating point constants. These can be represented in 2 forms fractional form or exponential form. In fraction form a decimal point is used. Eg: 23.456 768.45 -945.45 The real constant is represented in 2 parts namely mantissa and exponent. Mantissa appears before e and exponent appears after e. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Eg: 3.2e-5 4.1e8 +467e31 Note: ANSI C supports unary plus (+) which was not supported earlier.
JYOTHI Page 2

C&DS for I CSE-B LITS

Character Constants: A character constant is either a single alphabet or a single digit or a single special symbol enclosed within single inverted commas (apostrophes). Eg: A g 9 * Each character has an integer value known as ASCII (American Standard Codes for Information Interchange) code. For example the ASCII code associated with a is 97. To print the ASCII code of a character we can use the format specifier %d instead of %c while in the printf statement. String Constants: A string Constant is a sequence of characters enclosed in a pair of double quotes. The character may be alphabets, digits, special characters and blank spaces. Eg: INDIA Backslash Character Constants (Escape Sequences): C supports special kind of characters which are formed by combining the normal characters with the escape character (\). These characters have special meaning. Each represents a single character although it has 2 characters. Some of Escape Sequences: \b \f \n \r \t \v blank space form feed new line carriage return horizontal tab vertical tab \ \ \? \\ \0 \a single quote Double Quote Question Mark back slash Null audible alert

Keywords Keywords are the word in C which has fixed meaning and these meanings cannot bechanged. They serve as the building blocks of the program. The following is the list of 32 keywords in C. auto case const default double enum float goto int struct register typedef short unsigned sizeof volatile break char continue do if else extern for static long switch return union signed void while

Identifiers Identifiers are user defined names formed with different combinations of alphabets, digits and underscore in character set with certain rules. Identifiers are used to name the variables, functions, arrays, etc. Rules to forming identifiers (user defined name): Identifiers must start with an alphabet or underscore. Identifiers cannot contain special character other than underscore. Maximum length should be 31 characters. Should not be a keyword
JYOTHI Page 3

C&DS for I CSE-B LITS

Variables: Variable is data name that may be used to store the data value. Unlike constants (literals) variables may have different value during the execution of program. In general a meaningful name is chosen for a variable depending upon the context on the program. Variable names are case sensitive and therefore variable AMOUNT is different from variable amount. Since the variable name is identifier, the above mentioned rules need to be followed. Eg: x, sum, Avg, Root1, Nearest_Number. Declaring of variables: Before using the variables in a program, they should be declared. Declaration tells the compiler what the variable name is and what type of data it can store. Undefined usage of variables results in error during compilation. Syntax: <data type> <name>; Separate statements need to be used to declare variables of different kinds. Multiple variables of same kind can be defined in a single statement by separating them with commas (separate statements are also allowed). Eg: int a,b,c; float x; char str; Initializing and assigning value to Variables: To initialize or assign a value to a variable we use the assignment operator =. The variable can be initialized during declaration or can be assigned a value anytime later. Eg: int a=3; int sum=0; int x; x=45; If a variable is not initialized; unpredicted values will be stored, until any value is assigned. Data Types: Data Types are used to specify what type of data can be stored, exchanged or returned by a variable or a function. C supports a variety of data types which can be classified into two groups: Primary (Fundamental or Primitive) Data Types User Defined Data Types (Derived Data Types) Primary Data Types: C compiler supports 5 fundamental data types namely int, float, double, char and void. Many compilers also support extended data types such as long int, long double, unsigned int, short int, unsigned long int, unsigned short int, unsigned char, etc. Integer types (int): Integers are the natural numbers (1, 2, 3.) including 0 and their negatives (-1, -2, -3,.). int is the keyword used to declare variable or functions of type integer. On a 16 bit computer when an integer is declared it is allocated 2 bytes of memory.
JYOTHI Page 4

C&DS for I CSE-B LITS

Eg: int x; The range of integers that can be stored depends on the word length of the computer. If we use a 16 bit word length, the size of the integer is limited to the range -32768 to -32767 (i.e - 215 to 2151). A signed integer uses the first bit for sign and 15 bit for the magnitude of the integer. If the first bit is 1 then it indicated negative numbers. If it is Zero then it is positive number. A 32 bit word length computer can store integers ranging from -2147483648 to 2147483647. The range of the integers can be restricted or increased by qualifying int with the proper combination keywords short, long and unsigned. short decreases the range where as long and unsigned increases the range. The use of qualifier signed is optional because by default integers are signed integers. Note: To distinguish long integer literals from regular literals they are appended by a qualifier L (or l). Similarly U (or u) is appended for unsigned integers. For L and U any case can be used. Eg: 56789U (unsigned int) 987654321ul (unsigned long integer) 987.34567784787L (long double) Floating Point Data Type: Floating point numbers are real numbers which can have fractional values (decimal point). Floating Point numbers are stored with 6 digits of precision and uses 32 bits (4 bytes) of memory. The keyword used is float. double can be used to increase the range real numbers and also to increase the accuracy with higher precision. Double (double precision numbers) uses 64 bits of memory (8 bytes) giving a 14 digit precision. To increase the precision even more we can use long double which uses 80 bits. Eg: float avg; double discriminant; long double acc_value;

Character Type: A single character type can be declared using the key word char. Character uses 8 bits (1 byte) of memory for storage. While storing the chars the corresponding ASCII value is stored in binary format. The qualifiers signed and unsigned can be used to change the range of chars. By default char is signed char whose range is -128 to 127, where as the range of unsigned char is 0 to 255. Ex: char c; Void Types: The void has no values. It is generally used to specify the type of the function and a function is said to be void when it does not return any value. There will not be any void variables. The size and range of different data types on a 16 bit computer are listed here:

JYOTHI

Page 5

C&DS for I CSE-B LITS

Reading and Displaying Data: As we have seen earlier, variables can be assigned values with the help of the assignment operator. Another way of assigning a value to variable is by using scanf function.The general format of scanf is: Reading scanf(control string, &variable1,&variable2,);
The control string can be a format specifier or a collection of format specifiers which specify

the type of the values that can be read into the variables (variable1, variable2,..etc).
The ampersand symbol (&) before each variable is a pointer operator; which indicates the

address of the variable. This means that the values read are stored in the address of the variable. Eg: scanf(%d, &var1); %d is the format specifier which specifies that a integer value must be read from the user console (or terminal). Displaying To display any text (or string) or the value of any variables, we can use the printf function. General format: printf(Simple String); printf(Simple String + Control String, variable1, variable2,); printf(Control String, variable1, variable2,); Control string specifies the type of the value that is displayed from the variables. Eg: printf(Hello World); printf(Value of the variable x is %d, x); printf(%f, avg); The following are the various format specifier that we can used in scanf and printf functions
JYOTHI Page 6

C&DS for I CSE-B LITS

Format Specifier %d %i %c %s %f %u Operators:

Used to Represent signed decimal integer signed decimal integer character string (character array) Floating Point Number Unsigned int

Comment used in both scanf and printf (same used in both scanf and printf as above) In scanf multi word strings cannot be read. By default displays the 6

C supports a huge variety of operators. An operator is use to ask the computer to perform certain mathematical or logical manipulations. Operators are used to manipulate data and variables. Following are the categories of operators in C: 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operator 5. Increment and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators Arithmetic Operators: These operators are used to perform the basic Arithmetic operations such as addition, subtraction, multiplication and division. If both operands of an arithmetic operation are integers then it is called integer expression and the result of the integer expression will be an integer. Operator + * / % Eg: 2+3 5/2 5%2
JYOTHI

Description This is used to perform addition on integers or real numbers. This used to perform subtraction on integers or real numbers. This is also used as unary minus This is called asterisk and is used to perform multiplication. Forward slash operator is used to perform division Modulo Division. Can be used only for integers and produces reminder of integer division

the result is 5 the result is 2 and not 2.5 (decimal part is truncated in integer division) the result is 1 (% returns the reminder of integer division of 5 by 2)
Page 7

C&DS for I CSE-B LITS

If an expression has both real operands (float or double) then it is called real expression and result will be a real number. 5.0/2.0 the result is 2.5 4.3/8.45 0.508876 Relational Operators: These operators are used to compare two quantities to determine the relation between those quantities. An expression that contains relational operators is called relational expression. The result of the relational expression is either one or zero (true or false in advanced languages). Zero corresponds to false and one corresponds to true. Eg: a<b i<20 u>=34 etc Following are the 6 relational operations Operator < <= > >= == Description used to check if the left hand operand is less than right hand operand less than or equal to used to check if the left operand is greater than right hand operand greater than or equal to used to check if the value of left operator is equal to right hand operator.

!= not equal to Binary Relational operations can be performed on multiple arithmetic expressions. In such cases the arithmetic expression are evaluated first and then the results are compared. Eg: (a+2) < (b-c); Logical Operators: Logical Operators are used to perform logical AND, logical OR and NOT. Logical operators are used to check more than one condition. && || ! Logical AND Logical OR Logical NOT

&& and || are binary operations and ! is a unary operator. An expression which combines 2 or more relational expressions by using logical operations is called a compound relational expression. Eg: a>b && x==10 d<=f || r>=e !(d!=f) NOT (!) has only operand and can represented as !Op1. If Op1 is a Non-Zero value then the result of !Op1 is zero. If the value of Op1 is zero then the result of !Op1 is 1. Assignment Operators:
JYOTHI Page 8

C&DS for I CSE-B LITS

Assignment operators are used to assign the result of an expression to a variable. The operator = is used for assignment. Eg: v1= 20; v2= v1+v3; C also supports shorthand assignment operators of the form v op= exp;

where v is a variable, exp is an expression and op is a binary arithmetic operation. The operator op= is known as the shorthand assignment operator. The statement v op= exp is equivalent to v = v op exp. The operation op can be +, -, %, / or *. Eg: a *=b (a= a*b) x += 2 (x= x+2) a /= n+2 [a= a/(n+2)] Shorthand assignment makes the statement more concise and easy to read and makes it more efficient. Increment and Decrement Operators: Both the operators are unary and operate on only one operand. Increment operator is ++ and increases the value of the operand by 1. Decrement operator is and subtracts 1 from the operand. Based the place the operator is placed w.r.t operand there can post increment and pre decrement. Similarly post decrement and pre decrement also exists. If the operator is placed before the operand then it is pre (increment or decrement) else if it placed after the operand then it called post (increment or decrement). Eg: i++(post increment) j--(post decrement) ++i (pre increment) --j(pre decrement)

i++ and ++i are equivalent to i=i+1 and --j and j-- are equivalent to j=j-1. ++i and i++ mean the same when they are independent statements. But when used in a expression they behave differently. In an expression when ++i is used, the value of i is incremented before it is used in the evaluation of the expression, where as when i++ is used, the previous value i is first used for evaluating the expression and later incremented. Sample code for illustration: int a=5,b,c; a++; //increment value of a by 1 so a value is 6 --a; //decrements the value of a by one and so value of a will be 5 b=a++; //since post increment is used, the value of a (5) is assigned to b and later //incremented. Therefore b will be 5 and a will be 6 c=++a; //since pre-increment is used, the value of a is incremented before assigning it to c // Therefore value of c will be 7 and value of a will be 7 printf(%d %d %d,a,b,c); Output: 7 5 7 Conditional Operator: The conditional operator ?: is used to form conditional expressions of the form
JYOTHI Page 9

C&DS for I CSE-B LITS

exp1 ? exp2 : exp3;


where exp1, exp2 and exp3 are expressions. exp1 is evaluated first and if it is nonzero (true), then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is zero (false) then exp3 is evaluated and it becomes the value of the expression (can be assigned to any variable).

Eg: q = (f>g)?f:g The above statement makes the variables to be assigned with greatest of both f and g. If f=5 and g=6 then f>g condition returns false and so q=g i.e. q=6. Bitwise Operators: These operators are used to manipulate the data at bit level. They can be used for testing the bits, shifting them right or left. Bitwise operators may not be applied to float or double. Bitwise AND & is used to perform AND operation on individual bits of the operands. It is a binary operation and needs two operations. Eg: c=2 & 3; First the two operands are converted into binary bits and then AND operation is applied on individual bits. If assume the word length of a computer as 16bit we will have 16 digits in the binary conversion. 2_ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 3_ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 ---------------------------------------2 & 3 _ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 _ 2 (result) Bitwise OR | (single pipeline) is used to perform OR operation on individual bits of the operands. This is again a binary operations and it needs 2 operands. Eg: j= 5 | 9; First 5 and 9 are converted into binary system and later on OR operation is performed on each bit of the numbers. 5_ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 9_ 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 --------------------------------------5 | 9 _ 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 _ 13 (result) Bitwise exclusive OR ^ this is similar to the operations except that it performs exclusive OR operation on Shift left or left shift << is used to shift the significant bits of the operand to left. Eg: c= a<<b; Where a is operand whose bits has to be shifted left and b is number of positions that they should be shifted. The result of the operation is assigned to c. Let value of a be 5 and value of b be 1. This means the significant bits of the binary conversion of 5 should be shifted left by one position. 5_ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 5<<1_ 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 _ 10
JYOTHI Page 10

C&DS for I CSE-B LITS

In the above illustration the underlined bits are the significant bits as all other digits before them are zeros. They are shifted left and gap formed on the right is filled with zero. Note: Left shifting a number by one position will double the value (in above case result of 5<<1 is 10). Therefore x=x<<1 will simply double the value of x. Similarly x=x<<2 will make it four times. Shift right or right shift >> is used to shift the significant bits of the operand to right. Eg: c= a>>b; Where a is operand whose bits has to be shifted right and b is number of positions that they should be shifted. The result of the operation is assigned to c. Let value of a be 4 and value of b be 1. This means the significant bits of the binary conversion of 4 should be shifted left by one position. 4_ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 4>>1_ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 _ 2 In the above illustration the underlined bits are the significant bits as all other digits before them are zeros. They are shifted right and gap formed on the left is filled with zero. Notice that right most digit (0 in this case) is eliminated. Note: Right shifting a number by one position will half the value (in above case result of 4>>1 is 2). Therefore x=x>>1 will simply reduce the value of x to half. Similarly x=x>>2 will make it reduced to 1/4th. Ones Complement ~ (can also be referred to as bitwise NOT) is a unary operation that applies on a single operand and performs logical NOT operation on individual bits of the binary conversion of the operand. Eg: c= ~a; where a is the operand on which ones complement is applied and the value is assigned to c. Let value of a be 6. 6 0000000000000110 ~6 1111111111111001 Special Operators: C supports some special operators such as comma (,) operator, sizeof operator, pointer operator (& and *) and member selection operators (, and ->). Comma Operator , is used to link the related expressions together. A comma-linked expression is evaluated left to right. The value of the right most expression is the value of the combined expression. Eg: x = (a = 34, b = 4, a+b); In the above statement first the value 34 is assigned to a and then 4 us assigned to b and the addition (a+b) is performed and the result of a+b is stored in x. Since comma operator has lowest precedence use of parenthesis is compulsory. Sizeof operator is a compile time operator and which is performed on only one operand to find the number of bytes the operand occupies. The operand may be a variable, constant or a data type. This operator is generally used to find the size of arrays, structures, etc.
JYOTHI Page 11

C&DS for I CSE-B LITS

Eg:

x= sizeof(sum); printf(The size of int is %d,sizeof(int));

Operator Precedence and Associativity: In general expressions can involve many operators and when multiple operators are used, The order in which operations are performed should be defined. The precedence and associativity of operators are used to determine how an expression involving multiple operators should be evaluated. There are different levels of precedence and the operation involving highest precedence operator will be evaluated first. The operators of same precedence are evaluated either from left to right or right to left depending on the associativity property of the operator. Most of the operator will have left to right associativity where some of them have right to left associativity. Here is a table:

Type conversions:

c allows two types of type conversions. 1. Implicit type conversion. 2. Explicit type conversion.

Implicit type conversion: C automatically converts any intermediate values to the proper type so that the expression can be evaluated correctly. This automatic conversion is known as implicit-type conversion. In this the variables of the lower type are automatically converted to higher type.

Conversion hierarchy:

JYOTHI

Page 12

C&DS for I CSE-B LITS

Explicit type conversion: In this it is possible to convert one data type from another data type according to our requirement. This process is known as explicit type conversion or casting a value. Syntax: (type_name)expression. Example X=(int) 6.5 A=(int)21.3/(int)4.5 Z=(int)a+b Decision Making Statements: Simple if statement: The if statement is a powerful decision making statement and is used to control the flow of execution of statements. The general form of a simple if is: Syntax: if (test expression) { Statement-block; } Statement-x; Where: The statement block can be a single statement or a group of statements. Test expression is a logical or relational expression. If the test-expression is true, the statement block is executed and the control continues to statement-x. If the test expression is false then statement block inside the if is skipped and the execution continues with statement-x. Therefore when the test-expression is true both statement block and statement are executed where as in other case only statement-x is executed. The flow of simple can be represented in the following way: Action 6.5 is truncated to integer 6. evaluated 21/4 and result is 5. a is converted to integer then added to b.

Eg: Program to check if a number is even or not. #include<stdio.h>


JYOTHI Page 13

C&DS for I CSE-B LITS

void main() { int num; printf(Enter the number: ); scanf(%d, &num); if(num%2==0) printf(The entered number %d is a even number, num); if(num%2==1) printf(The entered number %d is a odd number, num); } De Morgans Rule: when applying logical NOT on complex relational expressions we have to keep in mind that the expressions will be evaluated using De-Morgans rule. Eg: !(a||b && !(p>q)) will be equivalent to !x && !b || !p < !q !(a && b) c !a || !b if..else statement: This is the extension of simple if statement and the general form is if(test-expression) { Statement-block-x; //true block } else { Statement-block-y //false block } Statement-block-z; If the test-expression is true, then the Statement-block-x (true block) is executed; if the test expression is false, then the Statement-block-y is executed. In both the cases the control is passed to Statement-block-z. The flow of the if..else statement can be show in the following way:

Eg: The above program can be re-written in the following way.


JYOTHI Page 14

C&DS for I CSE-B LITS

#include<stdio.h> void main() { int num; printf(Enter the number: ); scanf(%d, &num); if(num%2==0) printf(The entered number %d is a even number, num); else printf(The entered number %d is a odd number, num); } Note: _ An else cannot exist without the if block; else should always pair with if. _ After a single if block, there can be only one else block following it. _ There cannot be any other statements between if block and else block. Nested if else statements: When a series of decisions are involved, we may have to use more than on if-else statements in the nested form and it can be something like this. if(condition-1) { Statement-block-a; if(condition-2) Statement-block-b; else { Statement-block-c; } } else { Statement-block-d; } Statement-block-e; Flow Chart:

if-else ladder: The if-else ladder is another way of using multiple if. This is used when choice has to be made among multiple blocks of statements based on various test conditions. The general form of ifelse ladder is: if(condition 1) statement-1;
JYOTHI Page 15

C&DS for I CSE-B LITS

else if(condition-2) statement-2; else if(condition-n) statement-n; else statement-default; statement-x; In the above illustration when condition-1 is true only statement-1 is executed and when condition-2 is true only statement-2 is executed and in general when condition-n is true statementn is executed. Therefore statement 1 through n are executed mutually exclusive (if one is executed rest all are skipped). When all n conditions are false, then the statement-default in the last else is executed. In an if-else ladder each else block is paired with the if statement immediately above it. The flow chart for the above general form is as follows:

Switch Statement: A switch control structure or statement is an alternative to if..else ladder. It is also known as multiple branch selection statement. In order to use switch control statement, four keywords are required. They are: switch, case and break. The general form follows: switch (expression) { case value-1: statement block-1; break; case value-2:
JYOTHI Page 16

C&DS for I CSE-B LITS

statement block-2; break; default: default-block; break; } statement-x; The expression is an integer expression or a character. Cannot be a real or other expression. The value-, value-2, are the constants or constant expressions and are known as case labels. These labels are the possible values of the expression given in switch. Case labels end with : which are followed by statement blocks. There cannot be two case labels with same value. When a switch is executed, the value of expression is compared with case labels and the statement block defined in that case is executed. The break statement at the end of each block causes the exit from the switch statement, there by achieving the exclusivity among the multiple statement blocks. In other words;when expression evaluates to value-1, only statement-block1 is executed; if it is value-2 only statement-block-2 is executed and so on. The default executed when the value of expression matches none of the case labels. The default section is generally defined at the end of switch and it is optional. When it is used as last section, usage of break statement is also optional. When default is not defined and none of the case labels match the expression value, the execution continues to statement-x without executing any block in the switch. Absence of break in any of the case block makes the execution to continue with the next case statements as well until break is reached or end of switch is reached. Flow Chart illustrating the selection of statements in switch: Ex:

Ex: #include<stdio.h> main() { int day; printf(Enter day value); scanf(%d,&day);


JYOTHI Page 17

C&DS for I CSE-B LITS

switch(day) { case 1: printf(Sunday);break; case 2: printf(monday);break; case 3: printf(tueday);break; case 4: printf(wednesday);break; case 5: printf(thursday);break; case 6: printf(friday);break; case 7: printf(Saturday);break; default: printf(Illegal choice); } The goto statement: _ C supports goto statement to support unconditional branching from one point to another point of program. In other words goto statement makes the flow of control to jump to a location in the program unconditionally. _ goto requires a label to identify the place where the control has to be jumped. Label can be any valid name followed by a colon :. The label is place just above the statements where the control has to be transferred. _ Depending on place of the label in the program goto will result in either forward jump or backward jump. Below is a illustration:

Eg: main() { int x,y; read: scanf(%d, &x); if(x<0) goto read; y=x*x; if(y<25) goto read; }

JYOTHI

Page 18

C&DS for I CSE-B LITS

Note: In a structured programming like C, it not essential to use goto. Since the control is made to jump unconditionally here and there, the best practice is to avoid goto statements until unless it is inevitable (not avoidable). In a nested loop structure when a break statement is used in the inner most loops, it will just break the inner most loop and continue the execution of outer loop(s). If there is requirement where in all loops execution has to be stopped we can use goto.

Looping Control Structures Looping control statement allows a statement or a set of block of statement to be executed for repetitive number of times conditionally. In other words, as long as certain condition is true, a statement or a block of statements are repeatedly executed. Depending on the position of the control statement in the loop, a control structure may be of two types: Entry Controlled Loops - if the condition check (control statement) is at the start of the loop then the loops are called Entry controlled loops. Exit Controlled Loops - if the condition check (control statement) is at the end of the loop then the loops are called Exit controlled loops. The loop body is guaranteed to execute at least once.. The flow chart for the 2 kinds of loops is shown below::

C language provides three control structures for looping. They are: 1. while 2. do..while 3. for The while statement:
JYOTHI Page 19

C&DS for I CSE-B LITS

The while is the simplest of the looping structures in C.. It is an entry controlled loop.. The general form of while statement is:: while(test-expression) { statement-block;; ////body of the loop } If the test condition evaluates to true (1 or any non-zero value) then the statement-block in the body of the loop is executed.. Once the statement-block is executed,, the test-condition is tested again,, if it is true then the body executes again.. This continues until the condition evaluates to false.. Once the condition is false,, the control transferred to the statement after the loop.. The body of the loop can contain any number of statements.. The braces are needed only when there are multiple statements.. When there is only one statement, braces can be omitted.. while(test-condition) statement;; Eg: int i = 5; //initiaization while (i<=10) //condition check { printf (%d,i); i++; //incrementing } The above code will display numbers from 5 to 10. The do statement (do.... while loop): In contrast with while loop, in do-while loop the loop condition is testing while exiting the loop structure.. Therefore do-while is an exit controlled loop.. This allows the body of the loop to be executed at least once.. The general form follows:: do { set of statements; }while(test-condition);; Note: do-while structure should always be ended with a semi colon after the test condition. first and at end of the loop if the test-condition is evaluated to true then the loop body is repeated and so on. if the test-condition is evaluated to false then the control exits the loop and continues to the next statement after loop if one exists. Eg: int x; do { printf (Enter a value:: );; scanf(%d,, &x);; }while(x<90);;
JYOTHI Page 20

C&DS for I CSE-B LITS

The above code continuously reads the value of x until it is entered below 90. The for statement: The for loop is another entry controlled loop. It is one of the powerful & flexible control structure used for repetitive tasks. The general form is as follows: for( initialization ; test-condition; increment/decrement) { loop-body; } Generally for loops are controlled by the count of a control variable (counter or loop variable) and so they best suit to implement counter control loops. The counter is initialized in the initialization section when the loop is first reached. The test-condition is verified before executing the loop body every time and if it evaluated to true, the loops continues to iterate (repeat). If the condition fails for very first time, loop will execute at all. After each execution of for loop (iteration), the counter is either incremented or decremented as required. Eg:: 1. for(x = 1;;x<=10;;x++) printf(%d ,,x);; Output:: 1 2 3 4 5 6 7 8 9 10 Eg:: 2.. for(x=10;;x>=1;;x---) printf(%d ,,x);; Output:: 10 9 8 7 6 5 4 3 2 1 Additional Features of for loop:
1. There can be more than one comma separated initializations in the initialization section of

for loop.. can be more than one comma separated increment//decrement in the increment//decrement section of for loop.. Eg:: for(i=0,,sum=0; i<10 && sum<1000; i++,sum+=x) 3. All three sections of the for loop are optional. Therefore a empty for loop for(; ;) can also exist. Since there is no condition check to terminate the loop, this executes infinite times..
2. There

Note: while coding with any kind of loops,, enough care should be taken that the condition is specified such that the loop terminates at some point of time.. If not it may result in infinite loop and the program will never terminate. Nesting of oops: Any of the control structures can be nested with another control structure.. If loop control structure appears within the body of another loop, then that can be called Nesting of loops. We can nest any number of loops at a time.. Any combination of the above three loops can be used for nesting.. Eg:: for(i=0; i<3; i++) {
JYOTHI Page 21

C&DS for I CSE-B LITS

for(j=0;j<2;j++) printf(i=%d, j=%d,i,j);; } Output: i=0,, j=0 i=0, j=1 i=1, j=0 i=1, j=1 i=2, j=0 i=2, j=1 In the above code 2 for loops are nested.. In the outer loop i varies from 0 to 3 and for every value of i, j varies from 0 to 1.. Therefore the printf() within the inner most executes (3x2) 6 times.. Use of break statement to jump out of a loop: The break statement can be used to jump out of the loop (early exit). When a break is executed inside a loop (any of the three) the execution of the loop wll be terminated and the control will be transferred to the statement after the loop. In a nested structure if a break appears inside an inner loop,, then the execution of inner loop for that particular iteration of outer loop will be terminated. The control continues to execute with next statement (after inner loop)in outer loop body and consecutive iterations of outer loop are continued as usual.. If there is a requirement that the control should completely jump out of the inner loop then goto should be used whose label is defined just before the statement after the outermost loop.. Eg:: for(i=0; i<=5; i++) { if(i==3) //when i is equal to 3 break; //will terminate the loop printf(%d , i); } Output:: 0 1 2 (notice the loop body not executed after i value 3) Use of continue statement: The continue statement is used for skipping a part of the loop body. When a continue statement is executed, the compiler skips the statements following the continue statement and continues execution with the next iteration of the loop. In contrast with break, the continue will not terminate the entire execution of the loop rather it just skips the execution of the code for the current iteration and continues with the next iteration. In a nested structure, if continue is used in the inner loop, then the portion of code inside inner loop is skipped for that particular iteration of the inner loop and continues with next iteration of inner loop. Eg: for(i=0; i<5; i++) { if(i==3) //when i is equal o 3 Continue;//skip the rest of the loop body for the current iteration printf(%d , i); } Output: 0 1 2 4 5 (notice the part of loop body is skipped for i value 3 and is continued for the next iterations)

JYOTHI

Page 22

C&DS for I CSE-B LITS

Arrays
Arrays: An array is a contiguous blocks of memory that holds similar kind of values. In some other way, an array is a sequence of homogeneous or similar kind of items. An array can be defined as a group of similar kind of items referred by a common name. A specific element in the array is located or identified by its index value (also called subscript). C supports different types of Arrays. They are: 1. Single dimensional arrays 2. Two-dimensional arrays 3. Multi-dimensional arrays. Single dimensional arrays: An array with one subscript variable is known as single dimensional array. It is also known as linear list or simply list. Declaring of arrays: The general form of array declaration is as follows: type array_name[size]; where type is the data type of the elements that the array can store, array_name can be any Identifier to identity he array and size is a integer value which indicated the maximum number of elements the array can store.. The size is mentioned in square brackets following the name. Eg: int a[10]; // an array of 10 integers char s[20];// an array of 20 characters or simpe a string.. float f[15];// an array of 15 floating point values.. Initializing of arrays: The elements of a array can be initialized when they are declared. The following is the general form: type array_name[n]={v1,v2,v3,v4,....vn}; Where n is size of array and v1,,v2,,v3,,..vn are the initial values of the elements in the array..
JYOTHI Page 23

Unit-III

C&DS for I CSE-B LITS

Eg: in a[6] = { 10, 15, 12, 18, 20, 25}; When arrays are initialized mentioning of size in square brackets is optional for example the Statement, int a[] = { 10, 15, 12, 18, 20, 25}; will automatically create any array a of size 6 with mentioned initial values for its elements. A statement int a[6] = { 10,, 15,, 12} will actually create 6 memory locations but will initialize only first three elements.. Symbolic represenation of elements of the arrays: int a[6] = { 10, 15, 12, 18, 20, 25}; Accessing elements of a array: The individual elements of an array can be accessed (or referenced) by specifying the subscript (or Index).. Index values always start from 0.. Each element is referred as a[0], a[1], a[2] Index values should not be negative values and the range of indices is 0 to n-1 (bounds of the array) where n is the size of the array. While programming, care should be taken that the index should not be out of the array bounds. Size of array should always be positive.. Reading all values or displaying all values of array: In general loops are used to read all values or display all values or to perform any operation on each of the elements in array. And most often for loop is used Eg: #include<stdio..h> void main() { int i, sum=0, scores[11] ={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; float avg; clrscr(); for(i=0; i<11; i++) //for each of 11 players { printf(Enter the score of player %d: ,i+1); scanf(%d, &scores[i]); //read the score of the player sum+=scores[i]; //accumulate the sum of scores } avg=(float)sum/11; //caculate avg printf(The total score of team is %d and average of per player is %f,sum,avg); getch(); } Two-dimensional arrays (2D- Arrays): An array wiith two subscript variables is known as two-dimensional array (2D-Array). These are generally used to store a table of values. The first subscript specifies number of rows & the second subscript specifies number of columns. This is also called as double dimensional array. Declaration general form is as follows:: Data_type array_name [ no. of rows][no. of columns];
JYOTHI Page 24

C&DS for I CSE-B LITS

Eg:: int a[4][4];/// an integer array with 4 rows & 4 columns Char str [5][15]; //a char. Array with 5 rows & 15 columns (or) a set of 5 names // with 15 characters in each name. Initializing of 2D-Array can be done like this. int [3][2] = {{4,6},{10,56},{-4,5}}; or int[3][2]={4,6,10,56,-4,5} Symbolic representation follows: int a[3][4] = { 11, 55, 44, 33, 77, 99, 88, 67, 22, 25, 78, 87}; 11 55 44 33 77 99 88 67 22 25 78 87 Here a[0][0] = 11 , a[0][1] = 55, a[0][2] = 44, a[0][3] = 33 a[1][0] = 77, a[1][1] = 99 ... a[2][0] = 22, a[2][1] = 25 Advantages of Arrays: 1. Arrays can hold a collection of identical values. 2. Accessing of array elements is easy (since they are stored in continuous memory locations). 3. Pointer can be applied on arrays. 4. More flexible. Disadvantages of arrays: 1. As the array size is fixed, we cannot increase or shrink the size. Hence it may lead to wastage of memory. 2. Insertions & deletions are difficult to perform. 3. Unable to hold different kinds values. Note: If the dimension of an array is increased beyond 2 then it is called Multi-Dimensional array. In general, more than 3D-arrays are not used.

Functions
Def: A function is a self-contained block of statements that perform a particular task. Functions can be sometimes called sub-routines or sub-modules, etc. A C program can be thought of as a collection of these functions. Any C program contains at least one function called main( ) . The C compiler starts the program execution by calling the main function. Functions can be broadly classified into 2 types: 1. Built-in Functions (Predefined functions or Library functions) 2. User-defined functions Built-in functions are pre-defined in C library and are ready to use. They are categorized into different header files (with extention .h). To use any built-in function we just need to include the corresponding header file using the preprocessor directive #include. Eg: printf(), scanf(), getch(), clrscr(), random(), abs(), fabs(), gets(), puts(), etc. User-defined functions:
JYOTHI Page 25

C&DS for I CSE-B LITS

A function which is written by an user at the time of writing a program is called a user defined function. Advantages of using functions: We can divide a complex program into small individual functions. The length of the source program can be reduced by using functions. It makes compiling and testing easy. Elements of user defined functions Every user defined function consists of 3 parts. 1. Function declaration (or) function prototype. 2. Function call 3. Function definition. Function declaration (or) function prototype: Like variables, all functions in a condition-program must be declared before they are invoked. This is called as function prototype. Syntax: Function-return type function _name(type of the parameters ); Ex: int mul(int,int); Function call: A function can be called simply by using the function name followed by list of parameters. Ex: int y; y=mul(10,5);/*function call*/ Function definition: The function definition consists of actual implementation of the function. The general form of declaring and defining a function is as follows: return_type function_name(parameter-list) { function-body(); return (exp); } Where, return_type is the type of the value that the function can return, function_name can be any unique identifier. The function name should be unique and therefore no two functions in program can have same name. The parameter-list is the list of parameters (also called arguments) that are to be send while calling the function. The functionbody is the set of statement that are executed when the function is called. These statements are used to achieve the specific task that the function is intended for. Types of functions according to arguments and return values: 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. 1. Functions with arguments and no return values. 2. Functions with arguments and no return values. 3. Function without arguments and return values. 4. Functions with arguments and return values. Functions with arguments and no return values
JYOTHI Page 26

C&DS for I CSE-B LITS

When a function has no arguments, it does not receive any data from the calling function. Similarly it does not return any value means the calling function does not receive any data. So there is no data transfer between the calling function and called function. Ex: #include<stdio.h> void function1( ); main() { clrscr(); function1(); getch(); } void function1( ) { Printf(thi is an example function which does not take arguments and no return values); } Functions with arguments and no return values: In this the called function receives data from the calling function. but it does not return any value to the calling function. #include<stdio.h> #include<conio.h> void add(int,int); void main() { int a,b; clrscr(); printf("enter a,b values\n"); scanf("%d%d",&a,&b); add(a,b); getch(); } void add(int x,int y) { int z=x+y; printf("aum of a,b=%d",c); } Function without arguments and return values: In this the called function does not take any arguments from the calling function but it return values to the calling function. #include<stdio.h> int getnumber(); void main() { int a; clrscr(); a=getnumber(); printf("a=%d",a); getch(); } int getnumber()// add(int x,int y)
JYOTHI Page 27

C&DS for I CSE-B LITS

{ int n; printf("enter number\n"); scanf("%d",&n); return n; } Functions with arguments and return values. In this the called function takes arguments from the calling function and similarly it returns data to the calling function. so in this data transfer done form calling to called function and vise versa. #include<stdio.h> #include<conio.h> int add(int,int); void main() { int a,b,c; clrscr(); printf("enter a,b values\n"); c=a+b; printf("c=%d",c); getch(); } int add(int x,int y) { int z=x+y; return Z; }

Standard functions:
C provides a rich collection of standard functions whose definitions have been written and ready to use in our programs. To use these functions we must include the corresponding header files at the top of our program. Math functions Most of the mathematical functions are in either the math.h (or) stdlib.h header files. (I). absolute value function : An absolute value is the positive rendering of the value regardless of its sign. Ex: Abs(3) returns 3 Abs(-3) returns 3. Fabs(-3.5) returns 3.5. (II).ceiling function : A ceiling is the integer value that is greater than or equal to arguments number. Ex: Ceil(1.1) returns 2.0 Ceil(3.4) returns 4.0 Ceil(-4.2) returns -4.0
JYOTHI Page 28

C&DS for I CSE-B LITS

(III) Floor function: A floor is the integer value that is less than or equal to arguments number. Ex: Floor(1.9) returns 1.0 Floor(-1.9) returns 2.0 (IV)Round function: The round function returns the nearest integer value of a number. Ex: Round(1.9) returns 2.0 Round(2.3) returns 3.0 Round(-1.5) returns -2.0. (V) Power function: The power function returns the value of x raised to y that is xy Ex: Pow(2,3) returns 8. (VI) Square root function: This function returns the square root of arguments given number. Ex: Sqrt(25) returns 5.0

Scope:

Variable scope rule: Internal (or) local: Variable declared inside a function are local to the function and cannot be used in any other function. External (or) global: Variables declared outside all functions (on top of all functions) are called global variables and can be accessed in all functions of the program. If a local variable is declared with the same name as global variable then the local variable will override the global variable.

Storage Classes
The variable declared in C can be qualified by four different storage classes. These storage classes determine various properties of the variables such as scope, life, default value and memory in which they are stored. The four storage classes are as follows: Type Automatic variables External Variables Static Variables Register Variables

Keyword auto extern static register

Scope of variable defines which part of the program that the variable is accessible.
Page 29

JYOTHI

C&DS for I CSE-B LITS

Longevity or Life refers to the period during which a variable retains a given value during execution of a program. In general scope and life of all variables will be same (except in case of static variables). Memory: Variables can be stored in either RAM (primary memory) or CPUs register memory. Default value of different variables depends on the storage type used to define them.

auto:
The storage class auto is used for declaring automatic variables that are local a particular

function.
By default all variables in a function as auto variables therefore explicit usage of auto

keyword while declaring them is not necessary The scope and life of auto variables is only with the function body that they are defined. The formal arguments (parameters) of a function are also auto variables. The auto variables are created when the function execution starts and are destroyed(recycled) at the end of the function execution. The default value of auto variables is unpredictable and sometimes called as garbage value. All auto variables are stored in the primary memory (RAM). Eg: double f; auto double f; static:
The storage class static is used for declaring static variables that are local a particular

function. The value of the static variable persists (is retained) among multiple function calls. The scope of these variables is only with the function that they are defined. The default value of the static variables is 0. If they are explicitly initialized to a different value, the initialization happens when the function in which they are defined is called for the first time. For the consecutive calls of the same function the static variables are not initialized rather the value of the variable in the previous execution of the function is retained. Therefore the scope and life of the static variables are not same. The scope is limited to only the function body but the life persists among multiple function calls. Memory: The static variables are stored in the primary memory (RAM). Eg: main() { int i; for(i=0;i<3;i++) func(); } func() { static int x; //declaration of static variable (default value is zero) int y=0; //by default this will be auto variable x++; y++; printf(x= %d, y=%d\n,x,y); } Output: x=1, y=1 x=2, y=1
JYOTHI Page 30

C&DS for I CSE-B LITS

x=3,y=1 register: The register variables are same as auto variables except that they are stored in CPUs registers. Therefore the scope and life of the register variables are limited to the function in which they are defined. The default value of the register variables is unpredicted (or garbage value). Memory: They are stored in the CPU registers. In general the variable whose value is used many times is stored in CPU registers. By using this there will not be any time consumed by CPU to get these values from memory. (fast and easy access) Since the register memory is limited, huge number of variables should not be declared as register variables. Extern:
External Variables are the ones which are defined outside any function. Many a times these

are referred as Global variables. In general these are defined on top of all the functions in a C program. The scope and life of the global variables (or external variables) is the entire program. The default value of the global variables is zero. Memory: These are stored in primary memory. Use of extern key word: The extern keyword is used to declare the external variables in the functions which do not have default access to the external variables (global variables). When the variables are declared using extern, it is just to indicate that the function wants to use a variable declared externally and so no memory will be allocated for this declaration. Eg: main() { extern int x; //no memory allocated for extern declaration (main does not have direct access to x printf(Display in Main: %d\n, x); } int x; //external variable declaration memory will be allocated and default value is zero void disp() { x=90; //disp() can directly access x because it is defined after actual declaration of x printf(Display in disp: %d\n,x); } Output: Display in Main: 0 //since initial value of x is 0 Display in disp: 90 Type qualifiers: a type qualifier adds three specific attributes to variables. 1. Const 2. Volatile 3. Restrict Constants: The keyword for the constant type qualifiers is const. A constant variable must be initialized when it is declared and it cannot be changed later. Ex: const float p=3.145; ..
JYOTHI Page 31

C&DS for I CSE-B LITS

p=3.24

//it is invalid

Volatile: The volatile qualifier tells the compiler that an object value may be changed by entities other than this program. Restricted: The restrict qualifier, which is used only with pointers, indicates that the pointer is only the way to access the variable. Ex: restrict int a=10; int *ptr; ptr=&a; in this we can access a only through ptr. Eg: Factorial of a number using a user defined function factorial(). #include<stdio.h> int factorial(int); main() { int n,f; printf("Enter the number to find its factorial: "); scanf("%d",&n); f=factorial(n); //calling the function to find the factorial printf("%d!=%d",n,f); } int factorial(int num) { int fact,j; if(num==0||n==1) //Zero factorial is 1 return 1; else { for(j=1;j<=num;j++) fact*=j; return fact; //returning the calculated factorial } } Recursion: If a function calls itself, then it is called Recursion. Recursion is sometimes called circular definition. This is because using recursion, solution for a problem is defined in terms of the smaller instances of the same problem. While solving any problem using recursion, enough care should be taken that it will not result in infinite function calls. Infinite functions can occur when the function calls itself unconditionally. Eg: The above fact() function can be changed to use recursion as follows: #include<stdio.h> int factorial(int num) { if(num==0||num==1) //factorial of zero is 1
JYOTHI Page 32

C&DS for I CSE-B LITS

return 1; else return num*fact(num-1); //n! can be represented as n*(n-1)! } main() { int n,f; printf("Enter the number to find its factorial: "); scanf("%d",&n); f=factorial(n); //calling the function to find the factorial printf("%d!=%d",n,f); }

Preprocessor commands:
Preprocessor commands, as the name suggests, are the instructions that are executed before the source code passes through the compiler. The program that processes the preprocessor command lines or directives is called arguments preprocessor. Preprocessor directives are placed in the source program before the main line. before the source code passes through the compiler, it is examined by the preprocessor for any preprocessor directives. If there are any, appropriate actions (as per the directives) are taken and then the source program is handed over the compiler. They all begin with the symbol # in column and do not require arguments semicolon at the end. Directive Function #define #undef #include #ifdef #endif #ifndef #if #else Ex: #define max 10 Will replace all occurrences of max with 10. defines a macro substitution. undefines a macro. specifies the files to be included. test for a macro substitution. specifies the end of #if. test whether the macro is not defined. test a compile time condition. specifies the alternative when #if test fails.

#include<filename>

(or)

#includefilename

/*write a c program to demo preprocessor directive*/


#include"stdio.h" #include"conio.h" #define pi 3.14 main() { float r,arear; clrscr(); printf("enter radius of the circle\n"); scanf("%f",&r); area=pi*r*r; printf("area=%f",area); getch(); }
JYOTHI

Page 33

C&DS for I CSE-B LITS

Parameter passing methods


Generally functions communicate with each other by passing arguments. Arguments can be passed into 2 different ways. 1. Call by value 2. Call by reference. Call by value:

In this function, information is passed to the called function by passing the values of parameters. This is the default mechanism for argument passing. In this a copy of actual parameters will be passed to the called function via formal parameters. The call by value mechanism does not change the content of the arguments in the calling function even if they are changed in the called function. this means that any changes made to the formal arguments within the function do not affect the actual arguments. #inlcude<stdio.h> void swap(int, int); void main() { int a,b; printf("enter a,b values\n"); scanf("%d%d",&a,&b); printf("before swap\n"); printf("a=%d\nb=%d",a,b); swap(a,b); printf("after swap\n"); printf("a=%d\nb=%d",a,b); getch(); } void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } Output: Enter a,b values 10 20 Before swap a=10 b=20. After swap a=10 b=20. Decription: here main() is a calling function and swap is a called function, the arguments used inside the main() a,b are referred as actual arguments and the arguments used inside the swap()
JYOTHI Page 34

C&DS for I CSE-B LITS

are referred as formal or temporary arguments. Since we passed only the values of the actual arguments to the called function, the values of the actual arguments cannot be changed.

CALL BY REFERENCE: In the Call by reference mechanism the function is allowed to access the actual memory locations of the caller variables. This is possible only with pointers because pointers are special variables which can store the address of the other variables. This is a mechanism of invoking a function by passing reference of actual parameters. Therefore formal arguments can change the values of actual arguments. //write a C program to implement call by reference mechanism #include<stdio.h> void swap(int *, int *); main() { int a,b; printf("enter a,b values\n"); scanf("%d%d",&a,&b); printf("before swap\n"); printf("a=%d\nb=%d",a,b); swap(&a,&b); printf("after swap\n"); printf("a=%d\nb=%d",a,b); getch(); } void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; } Output: Enter a,b values 10 20 Before swap a=10 b=20. After swap a=20 b=10.

JYOTHI

Page 35

C&DS for I CSE-B LITS

Passing arrays to functions:


Like the values of simple variables it is also possible to pass the values of array to function. To pass a one-dimensional array to a called function, it is sufficient to list the name of the array, and the size of the array as arguments. Ex: int a[10]; max(a,10);//function call /*program to pass array as argument to a function*/ main() { int m; int a[5]={1,2,22,32,42}; clrscr(); m=max(a,5); printf("max element:%d",m); getch(); } int max(int a[],int n) { int i,m; m=a[0]; for(i=1;i<=n;i++) { if(a[i]>m) m=a[i]; } return m; }

JYOTHI

Page 36

C&DS for I CSE-B LITS

Unit IV POINTERS

Pointers A pointer is a variable, which holds the address of another variable. In fact pointer can

hold memory address of any object in the C program such as variable (of any type) an array or a structure. In some other way, Pointers are one of the derived data types in C. Pointer is one of the striking features of C. It is the strongest and at the same time dangerous feature in C. Pointers are used to increase efficiency. They improve the accessibility & provide support for dynamic memory allocation. They add power and flexibility to a C program. Memory organization: Memory is sequential collection of storage cells and each cell is known as 1 Byte and has number associated called Address. The address values typically vary from 0 to n-1, n being the size of the memory in Bytes (capacity of the memory). Therefore the address values for a 64KB RAM will vary from 0 to 65535. The pointers are used to store these values. Since all address values are of type unsigned int, the format specifier %u is used for displaying a pointer (address value). Therefore any kind of pointer is allocated only 2 Bytes of memory. Pointer Declaration: In order to declare & use a pointer variable, two operators are required. They are 1. Address of (&) operator. 2. Indirection operator (*). The general form follows: data_type *ptr_name; The above declaration says the compiler that ptr_name is a pointer that stores the address another variable which is of type the data_type. No matter ever is the data_type the compiler just assigned 2B of memory since ptr_name just stores the address value (unsigned int). Eg: int v = 53; int *p; p = &v; // address of k is assigned to p. 5002 8097 printf(v= %d,*p); Note: Here p holds the address of v, to get address of v we can use address of operator (&v) has again its own address. Moreover, an address is always an unsigned integer value. So it occupies 2 bytes. To display an unsigned integer value, use %u as its format specifier. char ch = x; char *p; p = &ch; float f = 78.89f; float *x; x = &f; double d = 89.89898; double *k; k = & d;

From the above example, user can understand that to hold the address of integer value, an integer pointer is required & to hold a character value address, a character pointer is required and so is the case with the other data types too.
JYOTHI Page 37

C&DS for I CSE-B LITS

Eg: 1. #include<stdio.h> #include<conio.h> void main() { int *p; int k = 10; p = &k; (*p)++; // through p the value of k is incremented by 1. printf(%d %d,a *p); } Pointer Expressions: The values of variables can be accessed through its pointer by using indirection operator (*). Therefore the operation that we perform on normal variables can be performed when they are accessed though pointer. Eg: int x, y, z; int *p1,*p2; p1=&x; p2=&y;
//Now we have addresses of variables x and y in p1 and p2 and therefore values of x and y can be givenas *p1 and *p2. z=*p1+*p2; //this is equivalent to z=x+y; z=*p1 / *p2; //this is equivalent to z=x/y; notice the space given between / and *p2.

Note: while performing division in pointer expression, care should be taken that space is given between division operator (/) and indirection operator (*) so that the compiler does not understand it as a beginning of a multiline comment (/*). Invalid Usage of Pointers: In general the address of a variable is stored in a pointer that is declared using the data type same as that of the variable. In other words the data type used to declare the variable and the pointer should be same. The complier does not throw an error when the data types are mismatched. This is because the compiler sees all pointers as unsigned integer and so the address of float variable can be stored in an int type pointer. Eg: int *p; float f; p=&f; //wrong assignment. This allowed by the compiler as it see all pointers as unsigned int. Advantages of pointer: Pointers provide efficient way of handling arrays. Use of pointer arrays for strings saves memory when the different strings of different lengths. Pointers can be used to (indirectly) return multiple values from a function via function arguments (call by reference). Pointers permit references to functions and thereby facilitating passing of functions as
JYOTHI Page 38
//But this is an improper assignment.

C&DS for I CSE-B LITS

arguments to other function.


Pointers allow C to support dynamic memory allocation and this allows this allows

manipulation of dynamic data structures such as stacks, queues, linked lists and trees. Increase the execution speed and thereby reduce the execution time. Disadvantages: As the pointer directly deal with the address locations in the system memory, improper handling of pointers can cause serious problems to the system. If a pointer is arbitrarily assigned an address value which actually is storing the address of some other program, any change done to pointer value can affect the working of other program and my sometimes crash the application. Therefore at most care should be taken while coding with pointers. Address Arithmetic (Pointer Operations): There are some limited operations that can be performed on pointers (addresses). In fact we are only allowed to use increment/decrement and addition/subtraction of integer value. When the pointer is incremented (p++) the address value is incremented by length of the data type that it points to. This length is called the scale factor. The length of the data type is given in the number of bytes it occupies in the memory. In general on a 16 bit word length computer, the following is list of length of various data types: char 1 byte int 2 bytes float 4 bytes double 8 bytes long int 4 bytes short int 1 byte, etc The address value in pointer is also decremented by scale factor when decrement operator is used(p--). When an integer n is added/subtracted to/from a pointer then the address value is incremented/decremented by n times the scale factor. Eg: #include<stdio.h> void main() { int x,*p; float f, *fp; clrscr(); p=&x; //let's assume the address of x is 4000 fp=&f; //let's assume the address of f is 5000 printf("p=%u, p+1=%u, p+4=%u\n\n",p,p+1,p+4); printf("fp=%u, fp+1=%u, fp+4=%u\n\n",fp,fp+1,fp+4); getch(); } Output: 4000, 4002, 4008 5000, 5004, 5016 Rules of Pointer Operations:
JYOTHI Page 39

C&DS for I CSE-B LITS

1. A pointer variable can be assigned the address of another variable which is of same type. 2. A pointer variable cannot be assigned an address of another variable which is declared with a different data type. (refer to invalid use of pointer above) 3. A pointer variable can be assigned the value of another pointer variable. 4. A pointer can be initialized to NULL or zero value. 5. A pointer variable can be pre-fixed or post-fixed with increment or decrement operators. 6. An integer value may be added or subtracted from a pointer variable. 7. When two pointers point to the objects of the same data types, they can be compared using relational operators. 8. When two pointers point to the same array, one pointer variable can be substracted from another. 9. A pointer cannot be multiplied by a constant. 10. Two Pointers cannot be added. 11. A value cannot be assigned to an arbitrary address (i.e &x= 80; is illegal).

Pointer to Pointers:
Since pointers are also variables, the addresses of pointers can also be stored in another variable which is called as pointer to pointer. A chain of pointers can be formed to any extent. Eg: int x,*p1,**p2; p1=&x; p2=&p1; Here p1 stores the address of x and p2 stores the address of p1. This is called as multiindirections. &x, p1, *p2 gives the address of x and x, *p1, **p2 gives the value of x. Pointers and Arrays: Pointers concept can be applied to arrays too. All elements of array are stored in continuous memory locations. Usually an array name holds a base address in memory. Hence a pointer can hold the base address to access the array elements. Once the base address is found, it becomes easy to access remaining elements in the list. The following program illustrates the same. #include<stdio.h> void increment(int *, int); void main() { int a[5] = {11, 12, 13, 14, 15},i; clrscr(); increment(a, 5); for(i=0;i<5;i++) printf(%4d,a[i]); getch();
JYOTHI Page 40

C&DS for I CSE-B LITS

} void increment(int *p, int n) { int i; for(i=0;i<n;i++) { *p = *p+4; p++; } } Output: - 15 16 17 18 19 In the function increment each of the elements in the array are accessed and are incremented by 4 each. Each element in array is accessed by incrementing the pointer. In case of a 2-dimentional array, the name of the array will be a pointer to pointer. int a[2][3]; For the above 2-D array, a will be holding the address of the first row and *a will be holding the address of the first element in the first row. Therefore to access a value in a 2-D array by using pointers, we first need get the address of the first element of in the corresponding row and move to corresponding column required. The following are the expressions that can be used along with their meanings. a a+i *(a+i) *(a+i)+j *(*(a+i)+j) pointer to first row. pointer to ith row. pointer to first element of ith row. pointer to the jth element of ith row. value of the element in jth column of ith row.

Dynamic Memory Allocation


In general when the variables or simple arrays are declared, memory is assigned to them by the compiler before executing the program. This is called static allocation of memory. Consider the below array: float a[20]; Here we mentioned the size of the array as 20, the complier allocated 20 memory locations each of size 4 bytes. This memory which is statically allocated to array cannot be changed while the program is running. It cannot be either decreased or increased. This may lead to wastage of memory when elements stored less than 20 in number. It also restricts us to store a maximum of 20 elements. C allows us to create memory dynamically during the execution of the program. It provides a set of functions for dynamic memory allocation. They are: 1. malloc() 2. calloc() 3. realloc() 4. free() malloc()
JYOTHI Page 41

C&DS for I CSE-B LITS

malloc() is used to create a single block of memory dynamically. The size of the memory location is being sent as a argument. The function malloc() returns the address of the first byte in the memory created. syntax: data_type *p; //pointer of type data_type p=(data_type*) malloc (sizeof(data_type));
//memory is created and address is stored in the pointer

The address returned by malloc should be type casted into corresponding pointer type. To specify the size of memory location we use sizeof operator so that it works on different system with different word length (16bit or 32 bit or so). The initial value stored in the new memory created by malloc() is unpredictable. If the system is failed to allocate requested size of memory to any pointer variable then it returns NULL address. calloc() calloc() is used to create a collection of memory locations dynamically. It is primarily used to allocate memory for arrays. This function takes 2 arguments, first being the number of memory locations needed and second one is the size of each memory location. The value in memory created is initialized to zero or NULL depending on the data type. syntax: data_type *p; p=(data_type *) calloc ( n, sizeof (data_type) ); The above statement creates n memory locations can store data of type data_type and return the address of first memory location. Therefore subsequent memory locations can be accessed by incrementing the pointer p. realloc() realloc() used to adjusts the size of the memory location which is already created. In normal cases, this function increases/decreases the size of memory without changing the address. While adjusting the size, if needs more memory and is not available at the current address then it changes the address and returns the new address (after allocation the memory). This function needs two arguments, first being the pointer to memory previously created, second should be new size required for the memory location. syntax: p=(data_type*)malloc(sizeof(data_type)); //memory is created here p=(data_type*)realloc(p,sizeof(data_type)+2); //memory is resized here and stored in same pointer Note: All the three function discussed above are defined in alloc.h (or) stdlib.h and it need to be included while coding. Eg: #include<stdio.h> #include<conio.h> #include<stdlib.h> void main()
JYOTHI Page 42

C&DS for I CSE-B LITS

{ int *p,sum=0; int i,n; clrscr(); printf("Enter the number of values:"); scanf("%d",&n); p=(int *)calloc(n,sizeof(int)); for(i=0;i<n;i++) { printf("Enter the value of %d element: ",i+1); scanf("%d",p+i); sum+=*(p+i); } printf("\n\nThe sum of all given numbers is %d",sum); getch(); } free() free() is used to release the previously allocated memory to the system. When the memory allocated is no longer needed then they should be freed using the free function. syntax: free(pointer);

JYOTHI

Page 43

Vous aimerez peut-être aussi