You are on page 1of 132

MC9212-Problem Solving and Programming Unit IV & V

The basic structure of C programs


C program can be viewed as group of building blocks called functions. A function is a subroutine that may includes one or more statements designed to perform specific task. To write a C program, we first create functions and then put them together. A C program may contain one or more section shown in figure

Documentation section // it includes program name, author name, program description, version, etc Link section //this section is used to link & load header files that required to execute current program Definition section // this section includes definition of symbolic constant and macros Global declaration section // it includes external variable definition and declaration main ( ) function section { Declaration part //all the variables used in the program has to be declared here Executable part //it should contain at least one execution statement } Subprogram section // all user defined function definitions falls under this section Function 1 Function 2 (User-defined functions) Function n Figure : An overview of a C program Documentation section consists of a set of comment line giving the name of the program, the author and other detail, The link section provides instructions to the compiler to link the system library, used in the current program. The definition section defines all symbolic constants & macros There are some variable that are used in more than one function. Such a variable are called global variable and are declared in the global declaration section that is outside of all functions. This section also declares all the user-defined functions Every C program must have one main( ) function section. This section contain two parts, declaration part and executable part. The declaration part declare all the variables used in the executable part. There is atleast one statement in the executable part. These two part must appear between the opening and closing brace. The closing brace of main function section is the logical end of the program. all statements in the declaration and executable part end with semicolon

Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V The sub program section contains all the user-defined functions that are called in the main function. User defined functions are generally placed immediately after the main function, although they may appear in any order All sections other than main function section are optional.

Programming style
C is free form language. That is, the C compiler does not care, where on the line we begin typing. Although several alternative styles are possible, we should select one style and use it with total consistency First write the program in lowercase letters. C program statements are written in lowercase letters. Uppercase letters are used only for symbolic constant Braces ({ & }) groups program statement together and mark the beginning the end of functions A proper indentation of braces and statements would make a program easier to read and debug Since C is a free-form language, we can group statements together on one line. The statements a = b; x = y +1; z = a + x; Can be written on one line as a = b; x = y +1; z = a + x; The program main( ) { printf(hello C); } Can be written on one line as main( ) { printf(hello C); } However, this style make the program more difficult to understand and should not be used

Executing a C program Executing a program written in C involves series of steps. These are 1. 2. 3. 4. creating the program compiling the program linking the program with function that are needed from the C library executing the program

The following figure illustrates the process of creating, compiling and executing a C program. Although these steps remain the same irrespective of the operating system, only the system commands for implementing the steps may differ on different operating system The operating system control entire operation of the computer system. all input / output operations are channeled through the operating system. operating system which is an

Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V interface between the hardware, software and program user, and handle the execution of user program Two most popular O/S today are UNIX (for minicomputer) and MS-DOS (for microcomputer) System Ready Program code Enter Program Source program Edit source Program Compile source program

C compiler

Syntax Error? No System library Object code

Yes

Link with system library Executable Object code

Data Input

Execute Object code

Data error

Logic and Data Error? No error Correct output Stop

Logical error

THE UNIX SYSTEM


In UNIX environment the program must be entered into file. The file name can consist of letters, digits and special character followed by dot and letter c. example: hello.c The file can be created with the help of text editors, either ed or vi. The command for loading the editor and creating the file is ed filename.c (or ) vi filename.c If the file existed before, it is loaded, otherwise new file created with name you have mentioned. Once code has been entered into the file, it is saved on disk. This file is known as source program Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V Compiling and linking Now the program is ready for compilation, assume that the file you have created is named file1.c .The compilation command to achieve this task under UNIX is cc file1.c The source program instructions are now translated into a form that is suitable for execution by the computer. The translation is done after examining each instruction for its correctness. If everything is alright, the source program is translated and stored on another file with the name file1.obj. This program is known as object code. Linking is the process of putting together other program files and function required by the source program. Under UNIX , the linking is automatically done when cc command is used If any mistake in the syntax and semantics of the language discovered, they are listed out at the end of the compilation process. Error should be corrected in the source program with the help of text editor (vi editor) The compiled and linked program is called the executable object code and is stored automatically in special file called a.out Executing the program Execution is simple task. Issue the following commend in the shell prompt a.out It would load the executable object code into the computer memory and execute the instruction Creating your own executable file Linker will always store the executable object code in the file called a.out. when we compile another program, this file will be overwritten by the executable object code of the new program. If we want prevent from happening, we should rename the file immediately using command mv a.out newfilename we may also achieve this by specifying an option in the cc command as follows: cc o name source-file.c Multiple source file to compile and link multiple source program files, we must append all the files names to the cc command cc file-1.c file-n.c these files will be separately compiled into object file called file-i.o and then linked to produce an executable program file a.out as shown in figure .C .C .C library

.O

.O

.O

a.out It is also possible to compile each ifle separately and link them latere. For example commands Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V cc -c mod1.c cc -c mod1.c Will compile source file mod1.c and mod2.c into objects files mod1.o and mod2.o. they can be linked to gather by command cc mod1.o mod2.o We may also combine the source file and object file as follows cc mod1.c mode2.o

MS-DOS SYSTEM
In MS-DOS environment, source file can be created using any text editors, but the file name should ends with .c extension like pay.c. Then the command MSC pay.c Under MS-DOS operating system would load the program stored in the file pay.c and generate the object code. This code is stored in another file under name pay.obj, etc. In case of any language error are found, the compilation is not completed. The program should then be corrected and compiled again The linking is done by using command link pay.obj Which will generate the executable code with the filename pay.exe. now the command pay would execute the program and gives the result You can also use special sophisticated editor such as TC to create source file. This will highlights keywords while typing source code, and provides help for the syntax of different c commands. Without going to command prompt, source program can be complied by pressing alt-F9 and executed by pressing ctrl-F9, and can see the output by pressing alt-F5 commands CHARACTER SET The character that can be used to form to form basic program elements such as constants (words and numbers), variables, operators, expression etc. The characters set in C are grouped into the following categories: 1. Letters 3. special characters 2. digits 4. white spaces the entire list is shown in the following table Digits - 0 9 Letters Uppercase AZ Lowercase a z Special characters , comma \ backslash < less than sign . period ~ tilde > greater than sign White spaces ; semicolon _ underscore ( left parenthesis Blank space : colon $ dollar sign } right parenthesis Horizontal tab ? question mark % percent sign [ left bracket Carriage return apostrophe & ampersand ] right bracket New line quotation mark ^ caret [ left brace Form feed ! exclamation mark * asterisk ] right brace | verticalbar - minus sign # number sign / slash + plus sign

Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V The compiler will ignore white space unless they are part of a string constant. White space may be used to separate words, and are prohibited between the character of keywords and identifiers May non-English keyword do not supports all the character mentioned in the above table. ANSI C introduces the concept of trigraph sequence to provide a way to enter certain character that are not available on some keyboards. Each eah trigraph sequence consist of three characters( two question mark followed by another character) as shown in following table Trigraph sequcene Translations ??= # number sign ??( [ left bracket ??) ] right bracket ??< { left brace ??> } right brace ??! | left bracket ??/ \ back slash ??~ tilde

C TOKENS
In a passage of text, individual words and punctuation marks are called tokens. Similarly in C program, the smallest individual units are known as C tokens as shown in figure. There are six classes of tokens: identifiers, keyboards, constants, string constant or string literal, operators, and special symbols as shown in the following figure C TOKENS keywords float while Identifier Constant -15.5 100 strings ABC year Special symbols operators + * ,

main [] amount {} Figure: C tokens and example Blanks, horizontal and vertical tabs, new lines, form feed and comments are not included in the tokens KEYWORDS AND IDENTIFIERS Every C word is classified as either a keyword or an identifier. All keyword have fixed meanings and these meaning cannot be changed KEYWORDS There are certain reserved words, called keywords, that have standard, predefined meaning in C. these keywords can be used only for their intended purpose; they cannot be used as programmer-defined identifiers Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V Keywords servers as basic building blocks for program statements. The list of all keywords of ANSI are listed in the following table The standard keywords are auto extern sizeof break float static case for struct char const if typedef switch goto default do long unsigned register IDENTIFIER Identifier refer to the name of the variables, functions, array and name of other user defined objects. These are user defined names and consist of a sequence of letters and digits, with letter as first character Rule for defining identifiers The first character of an identifier must be alphabet (or) underscore subsequent character could be either letters, digits (or) underscore Any other special character will not be included in identifier names In an identifier upper & lower case are treated as distinct or different An identifier can be arbitrarily long. Some implementations of C recognize only first eight characters, but most of the compilers recognize up to 31 characters Identifier could not be same as C keyword or function name included in C library. Valid identifiers X y12 sum_1 tmp _temperature invalid identifiers 4th X Order-no Error flag -count sum@sal reason the first character must be letter Illegal characters() Illegal character( - ) Illegal character ( blank space ) hypen(-) is not allowed. @ special character not allowed here.

CONSTANTS (is also called LITERALS) Constants refer to fixed values that the program may not alter during program execution. C support several types of constants as illustrated in figure. CONSTANTS Numeric constant Integer constants Real constants Non-Numeric constant

Single character String constant constant Constant can be any of basic data types. There are four basic types of constants. They are integer constant, floating point constant, character constant and string constant. There are also enumeration constant and backslash character constant

Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V

NON-NUMERIC CONSTANT CHARACTER CONSTANT Character constant are single character that are enclosed in a single quotes e.g.: char flag = T, ch=Y; STRING CONSTANT More than one character or sequence of characters enclosed in double quotes are called string constant. The character may be letter number, special characters and blank space E.g.: char name [ ] ={a,n,a,,n,d}; or char name[ ]=anand;
BACKSLASH CHARACTER CONSTANT (also referred to as escape sequence)

Non-printable characters on the keyboarded are impossible to enter into a string constant. So that C include the special character called backslash character constants listed bellow You should use the backslash character constant in the output to represent non-printable characters in the keyboard. Using backslash character constant instead of their ASCII equivalents to help ensure portability \b backspace \\ backslash \f form feed \v vertical tab \n new line \a alert(bell) \r carriage return \t horizontal tab \ Single quote \? question mark \ Double quotes \octal-number - octal escape sequece \0 null \xhexadecimal-number hex escape sequence

NUMERIC CONSTANTS The following rule apply to call numeric- type constants - Comma and blank spaces cannot be included within the constant - The constant can be preceded by a minus(-) sign if desired - The value of the constant may not exceed specified minimum and maximum bounds

Integer constant - numeric value with out fractional part An integer constant refers to a sequence of digits. There are three types of integer constants namely decimal integer, octal integer and hexadecimal integer Decimal integers consist of a set of digits 0 thro 9, preceded by an optional or + sign. Valid decimal integers are : 123, -123 0 +78 - e.g.: int a=10; HexaDecimal integer constant& Octal integer constant It is sometimes easier to use a number system based on 8 or 16 bit rather then 10 The number system based on 8 is called octal & uses the digits 0 thro 7.

Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus letters A through F. numeric constant preceded with 0X will be treated as hexadecimal constant - e.g.: int h1=0X80,h2=0XAF1; numeric constant preceded with zero(0) will be treated as octal constant - int oc1=012;

Unsigned and Long integer constants Unsigned integer constant may exceed the magnitude of ordinary integer constants, but they may not be negative An unsigned integer constant can be identified by appending the letter U to the end of the constant Long integer may exceed the magnitude of ordinary integer constants, but require more memory within computer Long integer constant can be identified by appending the letter L to the end of the constant Unsigned long integer may be specified by appending letters UL at the end of the constant e.g.: 5000U 12345678L 34565UL

Real constants - numeric with fractional part


Integer numbers are inadequate to represent quantities that vary continuously, such as distances, height, temperature, prices and so on. These quantities are represented by number containing fractional part like 17.567. Such a number are called real constant or floating point constants Further example of real constants are: 0.000043 -0.76 345.76 +234.0 It is possible to omit digits before the decimal point, or digits after the decimal points. That is, 215. .95 -.71 +.5 are all valid real numbers - E.g.: double t=21.45; Real number may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e+02 in exponentical notation e+02 mean multiply by 102. the general form is Mantissa e exponent Mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer number with an optional plus or minus sign. The letter e separating the mantissa and the exponent and can be written either lowercase or uppercase. Example of legal floating point constant are 0.65e4 12e-2 1.2e+5 3.18E3 -1.2E-1 Embedded white space is not allowed

SYMBOLIC CONSTANTS Symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a sting constant Panimalar Engineering College

MC9212-Problem Solving and Programming Unit IV & V Symbolic constant are usually defined at the beginning of the program. The symbolic constant may then appear later in the program in place of numeric constant, character constant etc. When program is compiled, each occurrences of symbolic constant name replaced by its corresponding constant values The syntax to define symbolic constant is #define <symbolic-constant-name> <constant-value> e.g.: #define PI 3.1415 #define TRUE 1 Symbolic-constant-name typically written in uppercase letters. Also note that statement not ends with semicolon Once symbolic constant was defined, you can only access the value of the symbolic constant anywhere in the program, but you cannot change the value of the symbolic constant. For example area = PI * radius * radius;

advantage of symbolic constants (1) modifiabllity : It makes modification of the program easy for programmer. Since only in only place programmer need to change value, which will replaced in place where symbolic constant used in the program (2) understandability : when numeric values used in program, it use is not always clear, especially when the same value used in different places of the program. but assigning symbolic name to such a constant frees us from these problem VARIABLES Variable is an identifier that is used to store a single data item at a time. Unlike constant that remain unchanged during program execution, a variable may different value at different times during program execution The data item must be assigned to the variable at some point in the program. The data item can then be accessed later in the program simply by referring to the variable name Rules for declaring variable All variable must be declared before they can appear in executable statements. Declaration consists of data type, followed by one or more variable names ending with semicolon. The following statements describes rule for declaring variable Variable name must consist of letter, digits, and underscore characters, subject to the following conditions They must begin with alphabet (or) underscore. subsequent character could be either letters, digits (or) underscore In an identifier upper & lower case are treated as distinct or different An identifier can be arbitrarily long. Some implementations of C recognize only first eight characters, but most of the compilers recognize up to 31 characters Identifier could not be same as C keyword or function name included in C library. White space are not allowed Syntax for variable declaration is Panimalar Engineering College

10

MC9212-Problem Solving and Programming Unit IV & V DATA-TYPE variable_list; (Or) DATA-TYPE variable1[,variable2,]; DATA-TYPE can be any valid c data type eg. int a,b,c=10; float balance,mark1,mark2; char ch=Y; Variables can be declared in three basic places: 1. Inside function variable inside function is called local variable, is also known as automatic variables Void main() { //local variable declaration int a; } here a is only known inside function main 2. In the definition of function parameters variable definded inside function parameter is called as formal parameters, is also called as argument to function Void makeSum(int a,int b,int c) { //here a,b,c are formal parameters } 3. Out side all funtion : variable declared outside all function is called as global variables. int count =0; float PI=1.314; void main() { //here count and PI are global variables, accessible inside all function } void function1(){ } ACCESS MODIFIERS:(also referred as cv-qualifiers) There are two modifiers that control how variables may be accessed or modified. These qualifiers are CONST , VOLATILE They must be preceded the TYPE-MODIFIERS and TYPE-NAME

CONST Variables
Values of these variable cannot be changed by your program Value can be assigned to those variable only when it is declared The compiler place variables of this type into read-only memory(ROM). E.g.: const int PI=3.1415; const qualifiers can be used before pointer variable declared as formal parameter in function Panimalar Engineering College

11

MC9212-Problem Solving and Programming Unit IV & V If the pointer is specified as const in the parameter declaration, the function code cannot be able to modify actual value of variables

Volatile
This modifier tells the compiler that a variables value may be changed in the way not explicitly specified. For example you can pass global variable address to Operating system clock routine, to hold real time of the system e.g.: volatile char *port; volatile char date; OVERFLOW AND UNDERFLOW OF DATA Problem of overflow occurs when the value of a variable is either too big or too small for the data type to hold. The largest value taht a variable can hold also depends on the machine. Since floating point value are rounded off to the number of significant digits allowed, an overflow normally result in the largest real value, where as underflow results in zero C does not provides any warning or indication of integer overflow. It simply gives incorrect results

STATEMENTS
A Statement causes the computer to carry out some action. There are three different class of statement in C. They are expression statement, compound statements, and control statement Expression statement an expression statements consists of an expression followed by a semicolon. The execution of an expression statement causes the expression to be evaluated Example A=3; C=a+b; ++I; Printf(area = %f ,area); Compound statement consist of several individual statements enclosed within pair of braces { }. The individual statements may themselves be an expression statements, compound statement or control statements. Compound statement does not end with semicolon Example { Pi=3.1415; Perimeter=2 * pi * radius; Area= pi * radius * radius; }

Panimalar Engineering College

12

MC9212-Problem Solving and Programming Unit IV & V Control statements are used to create special program features, such as logical tests, loops and branches. Many control statement require that other statements be embedded with in them Example while(cnt<=n) { Sum+=a[cnt]; Cnt++; } Control statement can be further classified into the following Selection - if, switch (conditional statement) Iteration - while, for, do-while (loop statement) Jump - break, continue, goto, return Label - case, default, user-defined labels

OPERATOR AND EXPRESSIONS

EXPRESSIONS
An Expression is a combination of one or more variables, constants that are interconnected by one or more operators. The expression may consist of single entity, such as constant, a variable, an array elements or a reference to a function Expression can also represent logical conditions that are either true or false. In C condition true or false represented by integer values 1 or 0 respectively Example a+b x==y c=x+y*z a < b && a < c tmp=pow(d,3)+(1.32/c) y=10 ++i

OPERATORS An operator is a symbol that tells the computer to perform certain mathematical and logical manipulations. Operators are used in programs to manipulate data and varaibles. They usually form a part of the mathematical or logical expression C supports rich set of operators. C operators can be classified in to number of categories. They includes 1. Arithmethic operators 2. relational operators 3. logical operators 4. assignment operators 5. increment and decrement operators 6. conditional operators 7. bitwise operators 8. special operators - pointer operator ( & and * ) Panimalar Engineering College

13

MC9212-Problem Solving and Programming Unit IV & V member selection operator (. and ->) size of operator stringi-zing and token passing operator (# and ##) comma operator

1. Arithmetic operator - the operands acted upon by arithmetic operators must represent numeric values. Thus , the operand can be integer , floating point quantities or characters + addition subtraction * multiplication / division % remainder after integer division (modulus operator) Integer arithmetic If both operands in a single arithmetic expression such as a + b are integers, then the expression is called an integer expression, and the operation is called integer arithmetic. Integer arithmetic yield result as integer value. Assume a and b are integer, a=14 and b=4, then we have the following result a - b=10 a / b =3 (decimal part truncated) a * b=56 a % b=2 (remainder of division) Real arithmetic Arithmetic operation involving only real operand is called real arithmetic. A real operand may assume values either in decimal or exponential notation. Assume a and b and c are float, then we will have: a =6.0/7.0 then a will have 0.857143 c =-2.0/3.0 then c will have 0.66667 b =1.0/3.0 then b will have 0.333333 Mixed-mode arithmetic If one of the operand is real and other is integer, then expression is called a mixed-mode arithmetic expression and the result will be always real number. Thus 15/10.0 = 1.5 where as 15/10 = 1 2. Assignment operators ( = ) the syntax of the assignment operator is

variable = expression ; left side of the assignment operator must always be a viable and right side of the assignment operator can be constant, variable or expression. e.g.: a=10; b=c; res=x+y*10; (Multi assignment also possible such as x=y=z=20;) 3. Increment & Decrement operators ( ++, -- ) rule for ++ and -- operators Panimalar Engineering College

14

MC9212-Problem Solving and Programming Unit IV & V increment and decrement operators are unary operator and they requires variable as their operand when prefix ++ 4. Additional assignment operators ( +=, -=, *=, /=, %= ) Example meaning a+=10 a=a+10 b-=c b=b-c x*=10 x=x*10 5. unary operator - C include a class of operator that act upon a single operand to produce a new value. Such a operators are known as unary operators . unary operator usually preceeds their single operands, though some operator are written after their operands. Most commonly used operation is unary minus, where a numerical constant, variable or expression is preceded by minus sign Example -735 -x - (b * b 4 * a * c) 6. Relational operators - relational operators are used to construct relational expression. Relational expressions are always evaluated either as true or as false. 1 treated as true and 0 treated as false. Relational expressions are used in the conditional and iterative statements. If relational relational expressions in the conditional statements evaluated to true then the body of conditional statement get executed, otherwise ignored

< <= >

less than lessthan or equal to greater than

>= == !=

greater than or equal to equal to not equal to

EXAMPLE X>Y (I+K) >= (T+1) J==2 7. Logical operators It is used to concatenate the result of more than one relational expression && AND | | OR ! NOT EXAMPLE (X > Y && X > Z) (!FLAG && T> 10)

8. The conditional operator (or) Ternary operator ( ? : ) The simple conditional operation can be carried out with conditional operator.
General form exp1? exp 2: exp 3; If exp1 return true, exp2 is evaluated, otherwise exp3 evaluated. It is similar to simple-if ,the advantage over if here is ,that you can use ternary operator collaboration with printf E.g: printf(%d is greater than %d ,%d ,a>b?a:b,a,b); big=(a>b?a:b);

Panimalar Engineering College

15

MC9212-Problem Solving and Programming Unit IV & V 9. bit wise Operators ^ (Exclusive or)

(Ones complement (not)) << (left shift) Bitwise operator are used to testing, setting (or) shifting actual bits in a byte (or) word, which corresponds to char and integer type data and variants. You cannot use bitwise operators on float, double, long double, void etc. Bitwise AND, OR, NOT are governed by the same truth table as their logical equivalents, except that they work bit by bit XOR P Q P^Q 0 0 0 1 0 1 0 1 1 1 1 1 Bitwise operations most often find application in device drivers-such as modem program, disk file routine, printer routine. Because bitwise operations can be used to mask off certain bits such as parity. Parity bit confirms that the rest of the bits in the bytes are unchanged. 11000001 (a=65) with parity bit &01111111 (127) -----------01000001 -----------the bit-shift operators <<, >> move all bits in a variable to the right (or) left as specified. Syntax : (1)shift-right variable >> number of bit positions; (2)shift-left variable << number of bit positions; as bits are shifted off one end ,0's are brought in the other end. In the case of a signed, negative integer, a right shift will cause a 1 to be brought in so that the sign bit is preserved. A shift is not rotate, that is the bits shifted off one end do not come back around to other end .The bit shifted off are lost. Bitwise shift operators can also quickly multiply and divide integers. Shift right effectively divides a number by 2 Shift left effectively multiply a number by 2 x=7; x=x<<1; binary value for 7: 0000 0111 after x<<1 the value in x is : 0000 1110 which is equivalent to 14 x=7; x=x>>1; after x>>1 the value of x is : 0000 0011 which is equivalent to 3 ones complement(~)
It reverses state of each bit in its operand. That is, all 1s are set to 0, all 0s are set to one Panimalar Engineering College

>> & |

(right shift) (bitwise and ) (bitwise or)

16

MC9212-Problem Solving and Programming Unit IV & V Is often used in cipher routines. X=7; X=~ x; After ones complement 0000 0111 1111 1000

10. The & and * pointer operator The first operator & is referred as an address operator. It is used find out the physical address of the given variable. This operator will take operand as variable name either primitive type or user-defined type The second pointer operator is *,which is the complement of & is referred as pointer inderation operator. It is used to retrieve the data stored in the memory address that pointer variable holding it example int x=10; int *p1=&x; printf("\nx=%d,&x=%p",x,&x); printf("\n*p=%d,p=%p",*p1,p1); //printing value of x & address of x through pointer p1

11. sizeof compile-Time operator


It returns the size of the variable or data-type in byte E.g.: double f; prinf(%d,sizeof(f)); //will print 4 printf(%d,sizeof(int)); //will print 2

12. Comma operator The comma operator is used to string together several arithmatic expressions in the assignment statement. In general, right side of the assignment operator, you can have only one expression, but not more than one expression But with the help of comma operator, you can pass more than one expression on right side of assignment operator If there are more than one expressions in the assignment, they are evaluated from right to left one by one, but only the result of right most expression is assigned to the left-side variable of assignment operator E.g.: int a=10,b=12,c; c=(a++,b--,a+b-2); Now c will have value as 20 Comma operator also used in the for statement and in the variable declaration. In for statement, this operator is used to pass more than one expression in both initialization part and increment part.. For example, it is possible to write for loop in the folloing manner: for(expression1, expression2,; condition ; expression3, expression4, ) statement; e.g.: for(i=0,j=0;i<10;i++,j--)

Panimalar Engineering College

17

MC9212-Problem Solving and Programming Unit IV & V In varaiable declaration, if you want to declare more than one variable of same type, it has to be separated by comma operator e.g.: int x,y,z;

13. The Dot(.) & arrow(->) operators these operators are used to access individual elements of structure & union. structure & unions are compound data types that may be referenced under single name dot operator is used to extract or store information from/into individual member of structure variables arrow operator is used to extract or store information from/into structure pointer variables 14. The [ ] & ( ) operators [ ] operator is also called array index operator or subscript operator. It is used to access or store individual elements of an array variable e.g.: int x[10]; x[0]=10;x[9]=90; ( ) operator is referred as function-call operator. It is used to invoke function anywhere e.g.: float x=sqrt(16); from

DATA TYPES
C supports several different types of data, each of which may be represented differently within the computers memory. The basic data types are listed below. An ANSI C supports three classes of data types: 1. primary (or fundamental) data types 2. derived data types 3. user-defined data types

Primitive (or fundamental) data types All C compilers supports five fundamental data types, namely integer(int), character (char), floating point(float), double-precision floating point (double) and void Many of them also offer extended data types such as long int and long double. Various data types and the terminology used to describe them is given below Primary data types Integral types Signed int short int long int Integer Unsigned types unsigned int unsigned short int unsigned long int Character char signed char unsigned char

Floating point types float double long double

void

Panimalar Engineering College

18

MC9212-Problem Solving and Programming Unit IV & V The ranges of basic four types are given in the following table. Typical memory requirements are also given. Note: memory requirements for each data type may vary from one C complier to another Range -128 to +127 -32,768 to +32,767 -3.4e-38 to 3.4e+38 -1.7e-308 to 1.7e+308 Typical memory requirement 1 byte 2 bytes 4 bytes(1 word) 8 bytes(2 word)

Data type Char Int Float Double

Integer types Integer are whole numbers with range value supported by particular machine. Generally it occupy one word of storage, and since the word size of machine vary(typically 16 or 32 bits), the size of the integer depends on the computer used The basic data type can be augmented / improved by the using data type qualifiers or type modifiers.They are (i) short (ii) long (iii) signed (iv) unsigned. For example integer quantities can be defined as short int, long int or unsigned int A short int may require less memory than an ordinary int . long int will have double the amount of memory of int (4 bytes) An unsigned int has the same memory requirements as ordinary int. however in the case of an ordinary int, the leftmost bit is reserved for the sign. But unsigned integer will only store positive number The range of value for integer is -32,768 to +32,767, but for unsigned int is 0 to 65,535 short int int long int Floating point types Floating point numbers are stored in 32 bits ( 4 bytes) with 6 digit precision. Floating point number are defined in C by the keyword float When accuracy provided by the floating point number is not sufficient, the type double can be used to the number. A double data type takes 64 bits (8 bytes) and giving a precision of 14 digits. They are known as double precision numbers To extend the precision further, we may use long double which uses 80 bits (10 bytes) The relaitionship among floating types is illustrated below float double long double Character types The char type is used to represent single character, and character should be enclosed in single quotation mark. it usually takes 8 bits (1 Byte) of internal storage. The qualifier signed or unsigned explicitly applied to char data type. While unsigned have value between 0 and 255, signed char have values from -128 to +127 Panimalar Engineering College

19

MC9212-Problem Solving and Programming Unit IV & V Void types void is special data type, which has no values. We dont use void type to declare variable, instead it is used in the function definition. It is used to specify the return type of the function, if the function does not return any result to the calling program it is also used as formal parameter in the function definition, if the function does not accept any argument e.g.: void displayoutput(void) { /* some code here */ } you can also use explicitly void as formal parameter in the function definition, if the function does not accept any argument, during the function call DECLARATION OF VARIABLE declaration of variable does two things: - it tells the compiler what the variable name is - it specifies what type of data the variable will hold declaration of variable must be done before they are used in program Primary Type Declaration a variable is used to store value of any data type. that is the name has nothing to do with is types. Syntax for variable declaration is DATA-TYPE variable_list; (Or) DATA-TYPE v1,v2,vn; DATA-TYPE can be any valid c data type. v1,v2,vn are the name of the variables. Variable are separated by commas, and declaration must end with semicolon. eg. int a,b,c=10; float balance,mark1,mark2; char ch=Y;

2. Derived data types the following are called derived types - Array - Functions - Pointer 3. User Defined data Type Declaration - typedef - enumeration

typedef
typedef feature allows user to define new data-type from existing pre-defined or user defined data types once type definition has be established, new variables from new data-type can be created as we are creating from any other pre defined data types It takes the general form typedef existing-data-type new-data-type;

Panimalar Engineering College

20

MC9212-Problem Solving and Programming Unit IV & V where the existing-data-type is any valid data type, new-data-type is an alias name for existing-data-type. E.g. : typedef double balance; This statement tells the complete to recognize balance as another name for double. Next you could create float variables using balance such as balance over_due; Now balance can be used in another typedef. E.g. typedef balance overdraft; It tells the compiler to recognize overdraft as another name for balance, which is another name for double The following example describes another usage of typedef. typedef float height[100]; height men,women; the above code define height as a 100 element, floating-point array type hence, men and women are 100 element floating point array. Another way to express this is typedef float height; height men[100],women[100]; typedef feature is particularly convenient when defining structures, since it eliminates the need to repeatedly write struct structure-name whenever a structure is referenced. Hence the structure can be referenced more concisely in general the user-defined structure type can be written as typedef struct { datatype member1; datatype member2; }structure-name; now instance of the structure can be created similar to the following structure-name varaiable1, variable2,..; note that here no struct keyword used in front of structure-name example typedef struct { int acc_no; char acc_type; char acc_name[80]; double balance; }BankAccount; here BankAccount is new user-defined structure, instance of that data-type can be created as follows BankAccount acc1, acc2; Panimalar Engineering College

21

MC9212-Problem Solving and Programming Unit IV & V

enumeration
C supports another user-defined data type called enumerated data type An enumeration is a set of named integer constant that specify all the legal values a variable of that type may have. Syntax enum enum-name{enumeration-list } [variable-1,variable-2,]}; Where enum is a required keyword, name could be any valid C identifier Enumeration list must be separated by comma. First name in the enumeration-list will be assigned value 0, second name will be assigned value 1 and so on. It may be possible to starts with any other number instead of zero, simply by assigning any whole number to the first name in the enumeration-list Eg:enum color{black, red, green, blue, yellow, purple, navy, white} clr1; now the values of the symbols black assigned to zero, red assigned to 1, green assigned to 2 and so on enum department { sales=101,purchases,training,research,production}; Now values of these symbols sales assigned to 101, purchases to 102, training to 103 and so on Once enumeration is defined, the instance of that type of variable can be created and assigned values similar to the following enum department dept; dept=production; Example enum departments{sales=101, purchases, research, training}dept1; enum digits{zero,one,two,three,four,five,six,seven,eight,nine,ten}; void main() { int i; enum departments d2[]={purchases,training,research,sales}; enum digits dd; the value of dd 5 Output for(i=0;i<4;i++) 102 printf("\n %d",d2[i]); 104 103 dd=five; 101 the value of dd 5 if(dd==five) printf("\n the value of dd %d",dd); } Storage class define the existence of variable during the program execution. In other words, storage class refers to the permanence of a variable, and its scope within the program

DECLARATION OF STORAGE STORAGE CLASSES

Panimalar Engineering College

22

MC9212-Problem Solving and Programming Unit IV & V There are four different storage-class specifications in C: automatic, external, static and register. They are identified by the keywords auto, extern, static and register, respectively Storage class associated with a variable can sometime be established by the location of the variable declaration with in the program Variables which is declared inside function referenced only by statements that are inside the block in which the variables is declared. It is created upon control entering into it's block & destroyed upon exit Auto is the keyword used to declare local variables, but without any keyword it is assumed to be auto. So that this keyword virtually never used. In C variables must declared before any other "action" statement. Advantage of declaring local variables with in a conditional block is that memory for the variable will be only allocated if needed The general syntax for storage class specification are : Storage-specifiers [Storage-specifiers] data-type (or) data-type variable-name; variable-name-1 [,variable-name-2];

Code fragment shown below describe several typical variable decalrations auto int a,b,c; extern float root1,root2; static int count; register int a,b;

AUTOMATIC VARIABLE (auto) These are all declared always within a function and are local to the function in which they are declared. That is, the scope is confined to that function Automatic variable defined in different function therefore be independent of one another, even though they have the same name This includes formal argument declarations such as formal parameters It is not necessary to mention auto keyword explicitly in front of variable declaration An automatic variable does not retain its value once control is transferred out of its defining function. Therefore, any value assigned an automatic variable within the function will be lost once the function is exited Example: main( ) { /* auto variable declaration */ int x,y,sum; float avg; auto char name[30]; .. } EXTERNAL/ GLOBAL VARIABLE (extern) External variables, in contrast to automatic variables, are not defined to single functions, their scope extends from the point of definition through the remainder of the program. Since external variables are recognized globally, they can be accessed from any function that falls within their scope. They retain assigned values within this scope. Therefore an external Panimalar Engineering College

23

MC9212-Problem Solving and Programming Unit IV & V variable can be assigned a value within one function, and this value can be used(by accessing the external variable) within another function. The storage-class specifier extern is not required in an external variable definition, since the external variables will be identified by the location of their definition within the program. If a function requires an external variable that has been defined earlier in the program, then the function may access the external variable freely, without any special declaration within the function. On the other hand, if the function definition precedes the external variable definition, then the function must include a declaration for the external variable. An external variable declaration must begin with the storage-class specifier extern. The name of the external variable and its data type must agree with the corresponding external variable definition that appears outside of the function. Storage space for external variables will not be allocated as a result of an external variable declaration. Example: extern int x; // external variable declaration void readX( ) { printf(x? ); scanf(%d,&x); } int x; //external variable definition main( ) { readX( ); printf(X=%d,x); x+=10; printf(X=%d,x); }

STATIC VARIABLES Static variables are defined within a function in the same manner as automatic variables, except that the variable declaration must begin with the static storage-class designation. Static variables can be utilized within the function in the same manner as other auto variables. But the difference between auto and static variable is that the former will not retain its value between function call, but later will retain its value between function call Static variable will be initialized only once during the first call to the function, from the next call onwards, static declaration statement will not get executed Example #include<stdio.h> #include<conio.h> long int fibo() { static long int f1=-1,f2=1; long int f; f=f1+f2; f1=f2; f2=f; Panimalar Engineering College

24

MC9212-Problem Solving and Programming Unit IV & V return f; } main( ) { int cnt,n; clrscr(); printf("How many fibonacci do you need to print: "); scanf("%d",&n); for(cnt=1;cnt<=n;cnt++) printf("\t%ld",fibo()); getch(); } Output How many fibonacci do you need to print: 7 0 1 1 2 3 5 8

Suppose if variable f1, f2 is not declared as static variable, it does not retain its old value assigned in the previous function call.So that every time f1 and f2 will be initialized to -1 and 1, so that output will always zero, because f1 and f2 will be treated as auto variable

REGISTER VARIABLE only auto variable of type int, char or its pointer types can be declard as register variable. Variable of other types such as float, double or array variable of any typec cannot be declared as register The values of register variables are kept in the register of the CPU rather than in memory, where normal variables are stored Operation on a register variable could occur much faster than on a normal variable because the register variable was actually held in the CPU & did not require seek and access time to determine or modify its value You can only apply the register specifiers to local variable, formal parameter in a function. Global Register variables cannot be declared as register variable Example: register int count;

register char choice;

assignment statement is used to assign value the the variable Its general signature is as follows: variable-name = constant / variable / expression Some of the example are int x,y,z; x=10; y=x; z=x*x+y*y/2; isPrime=y;

Panimalar Engineering College

25

MC9212-Problem Solving and Programming Unit IV & V TYPE CONVERSIONS IN EXPRESSION Implicit Type Conversion C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate value to the proper types so that the expression can be evaluated without loosing any significance. This automatic conversion is known as implicit type conversion int i, x; float f; double d; long int l; x = l / i

i *f

-d

long long float float int

float float

double double

During evaluation it adheres to very strict rule of type conversion. If operands are of different types, the lower types is automatically converted to the higher type before the operation proceeds. The result is of higher type. A typical conversation process is shown in the figure below:

Sequence of Rules is applied while evaluating expression is given below: All short and char are automatically converted to int; then 1. if one of the operands is long double, the other will be converted to long double and the result will be long double 2. else, if one of the operands is double, the other will be converted double and the result will be double 3. else, if one of the operands is float, the other will be converted float and the result will be float 4. else, if one of the operands is unsigned long int, the other will be converted unsigned long int and the result will be unsigned long int 5. else, if one of the operands is long int, the other is unsigned int, then a. if unsigned int can be converted long int, the unsigned int operand will be converted as such and the result will be long int b. else, both operands will be converted to unsigned int and the result will be unsigned int 6. else, if one of the operands is long int, the other will be converted long int and the result will be long int 7. else, if one of the operands is unsigned int, the other will be converted unsigned int and the result will be unsigned int the conversion hierarchy is shown below

Panimalar Engineering College

26

MC9212-Problem Solving and Programming Unit IV & V long double double Conversion hierarchy float unsigned long long unsigned int int char short The final result of an expression is converted to the type of the variable on the left of the assignment operator before assigning value to it. however the following changes are introduced during the final assignment 1. float to int causes truncation of the fractional part 2. double to float causes rounding of digits 3. long int to int causes dropping of the excess higher order bits We have discussed how C performs type conversion automatically. However there are instances when we want to force a type conversion in a way that is different from the automatic conversion Consider, for example, the calculation of ratio of females to male in town. int female_number, male_number; float ratio; . ratio = female_number / male_number; since female_number and male_number are declared as integer in the program, the result of female_number / male_number is an integer, ratio would represent whole number instead of fractional value, even though it is declared as float. This problem can be solved by explicitly type casting any one of the operand as float as shown below ratio = (float) female_number / male_number; The operator (float) convert the female_number to floating point, so that result of division will have fractional number. the process of such a local conversion is known as explicit type conversion, explicit conversion or explicit type casting. the general form of casts is variable1=(datatype) variable2 / expression cast operator this is one of the unary operator example : long int x=1234; int a=(int) x; EXAMPLE

Explicit type conversion


x = (int) 7.7 a = (int) 21.3 / (int) 4.5

ACTION 7.5 converted to integer 7 by truncation Evaluated as 21/4 and result would be 5

Panimalar Engineering College

27

MC9212-Problem Solving and Programming Unit IV & V

OPERATOR PRECEDENCE AND ASSOCIATIVITY


Each operator in C has a precedence associated with it. This precedence is used to determine how an expression involving more than operator evaluated. There are distinct levels of precedence and an operator belong to one of these levels. The operators at the higher level of precedence are evaluated first. Operator of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as associativity property of an operator The following table provides complete list of operators, their precedence levels, and rule of association. The groups are listed in the order of decreasing precedence. () [] -> . ! ~ ++ -- (typecast) * (pointer) & sizeof * / % + << >> < <= > >= == != & ^ | && || ?: Lowest = += -= *= /= etc. Consider the following conditional statement: int x=20,y=5; if( x==10 +15 && y <10 ) The precedence of rule says that the addition operator has higher priority than the logical operator && and relational operators == , <. Therefore, the addition of 10 and 15 is executed first. This is equivalent to: if( x==25 && y <10 ) From given data, x==25 is FALSE (0) and y < 10 is TRUE (1). Notice that operator < enjoys highest priority that operator ==, y < 10 is tested first and then x==25 is tested Finally we get if( FALSE && TRUE ) because one of the condition FALSE the complex condition is FALSE; Precedence Highest Opeartor Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right

Rule of precedence and associativity Precedence rules decides the order in which different operators are applied Associativity rule decides the order in which multiple occurrences of the same level operator are applied

MANAGING INPUT AND OUTPUT OPERATIONS


Reading, processing and writing of data are three essential functions of a computer program. More program take some data as input from keyboard and display the processed data on monitor, often known as information or result. C provides set of built-in functions to read Panimalar Engineering College

28

MC9212-Problem Solving and Programming Unit IV & V different types of information from keyboard and display result in the screen. They are called as standard I/O and listed below

Standard Input/ Output Functions Or Standard I/O


DATA INPUT FUNCTIONS CHARACTER INPUT FUNTIONS / READING CHARACTER The getchar( ) function The getch( ) function The getche( ) function The getch( ) function The prototype of the getch( ) function is int getch(void); This function get character from console ( keyboard) , but does not display the character to the monitor. It will only single character from keyboard e.g.: char ch; ch=getch(); the getche( ) function The prototype of the getche( ) function is int getche(void); This function gets character from console(keyboard) and display the same to the monitor. It read will only single character from keyboard e.g.: char tmp=getche(); the getchar( ) function This function will accept read array of character from keyboard until new line character is encountered, but assign only first character to the character variable used left side of the function. This function will also all characters inputted in the monitor The prototype of the getchar( ) function is int getchar(void); e.g.: char ch=getchar(); READING STRING /STRING INPUT FUNCTION gets( ) gets( ) function offer simple alternatives to the use of scanf for reading string. The prototype of the function is char *gets(char * string) it collect input from keyboard until newline character is encountered. The newline character will not be placed in string and return pointer to the argument string example char name[50]; gets(name); Panimalar Engineering College

29

MC9212-Problem Solving and Programming Unit IV & V FORMATTED INPUT / READING MIXED DATA the scanf ( ) function It performs formatted input from keyboard. This function can be used to enter any combination numerical values, single character and string. The syntax of the function is given below scanf(conversion-character-list,arg1,arg2, ) Here the conversion-character-list can be any of the valid C conversion character, and arg1, arg2, are arguments that represent the individual input data items. Each conversion character must begin with a percent sign (%) More frequently used conversion characters(scanf /printf format codes) are listed below Conversion Character Meaning Data item is a single character %c Data item is a decimal integer %d Data item is floating point value %f Data item is floating point value %e Data item is floating point value %g Data item is short integer %h Data item is decimal, hexadecimal or octal %i Data item is an octal integer %o Data item is a string followed by white space character %s Data item is an unsigned decimal integer %u Data item is a hexadecimal integer %x Data item is sequence of character those defined in the set % [] Data item is sequence of character those not defined in the % [^] set Example void main( ) { int a; float b; char name[30]; ... scanf(%s %d %f, name, &a, &b); } Each variable name in the argument list must be preceded by and ampersand (& ) other than string variable or character array variable

RULE FOR SCANF Each variable to be read must have a field specification For each field specification, there must be a variable address of proper types Any non white space characters used in the format string must have a matching character in the user input Never end the format string with whitespace. It is a fatal error Scanf read until: Panimalar Engineering College

30

MC9212-Problem Solving and Programming Unit IV & V a white space character is found or a maximum number of characters have been read or an error detected or end of the file is reached

DATA OUTPUT FUNCTIONS


WRITING A CHARACTER / CHARACTER OUTPUT FUNCTION putchar(), putch()

putchar ( ) function is used to display value of the character variable on standard output such as monitor Syntax : int putchar (char ch) e.g.: char ch=t; putchar(ch); On success putchar return ch otherwise it return EOF putch( ) function works in similar way the putchar( ) function works Syntax: int putch (char ch) e.g.: char ch=m; putch(ch);

WRITING STRING \ STRING OUTPUT FUNCTION puts() this will display the content of the string variable to standard output monitor. Syntax int puts(char *s) e.g.: char name[ ]=HELLO; puts(name); on successful completion, puts return the last character written, otherwise a value EOF is returned

FORMATTED OUPUT FUNCTION \ WRITING MIXED DATA printf( ) It is used to display formatted output on the monitor. This function can be used to output any combination of numerical values, single characters and strings. It is similar to the input function scanf, except that its purpose is to display data rather than to enter into the computer Function signature: int printf(conversion-character-list,arg1,arg2, ) Here the conversion-character-list can be any of the valid C conversion character, and arg1, arg2, are arguments that represent the individual input data items. Each conversion character must begin with a percent sign (%). Here variable need not preceded by ampersand character ( & ) You can use all conversion character used in the scanf ( refer scanf conversion table)

Panimalar Engineering College

31

MC9212-Problem Solving and Programming Unit IV & V MORE ABOUT THE scanf FUNCTION (Formatting the Inputs) When you are reading the data-item for particular variable using scanf function, it is possible to limit the number of characters allowed to read, by specifying a maximum field width for that data item To do so, an unsigned integer indicating the field width is placed with in the control string, between the percent sign(%) and the conversion character The data may contain fewer characters then specified field width; however the number of characters in the actual data item cannot exceeds the specified field width. Any character that extends beyond the specified field width will not be read. Such a leftover character may be incorrectly interpreted as the components of the next data item Example: #include<stdio.h> void main() { int a,b,c; clrscr(); printf("enter a b c values\t"); scanf("%3d %2d %3d",&a,&b,&c); printf(" the value of a,b and c are %d, %d and %d",a,b,c); getch(); } Different possible input and output for the above program shown below enter a b c values 22 3 666 the value of a,b and c are 22, 3 and 666 enter a b c values 1011 33 666 the value of a,b and c are 101, 1 and 33 enter a b c values 123456786 the value of a,b and c are 123, 45 and 678 In the first case all the inputs are having either lower than or equal to the specified field width, so that all the values as it is assigned to the corresponding variable But in the second case field width of the first variable is 3 but corresponding input-data have 4 so that first three bit of information assigned to variable a, fourth bit will be assigned to variable b, input-data 33 will be assigned to variable c and input-data 666 will be abandoned Another example void main( ) { int x; float y; char z; clrscr(); printf("enter x y z values\t"); scanf("%3d %5f %c",&x,&y,&z); printf(" the value of x,y and z are %d, %f and %c",x,y,z);

Panimalar Engineering College

32

MC9212-Problem Solving and Programming Unit IV & V getch(); } The input and possible output are shown below enter x y z values 10 123.4556 m the value of x,y and z are 10, 123.4 and 5 Most version of C allows certain conversion characters with in the control string to be preceded by a single-letter prefix, which indicates the length of the corresponding argument. For example an l (lower case L) is used to indicate either signed or unsigned integer argument or a double-precision argument Similarly h is used to indicates signed or unsigned short integer In some version of C the use of upper case L to indicate long double Conversion character O indicates input or output data should be octal and X indicates hexadecimal, E indicates the scientific notation. Example void main() { short x,y; long a,b; double m,n; clrscr(); printf("enter x a m values\t"); scanf("%hd %ld %lf",&x,&a,&m); printf("enter y b n values\t"); scanf("%ho %lx %le",&y,&b,&n); printf("\nthe value of x,a and m are %hd, %ld and %lf",x,a,m); printf("\nthe value of y,b and n are %hd, %ld and %lf",y,b,n); getch(); } The possible inputs& outputs are shown below enter x a m values 11 45 54.56 enter y b n values 10 1A 1E3 the value of x,a and m are 11, 345 and 54.560000 the value of y,b and n are 8,26 and 1000.000000 Input-datas for variable y, b and n are in the form of octal, hexadecimal and scientific notation form of fractional number. All the inputs are automatically converted to decimal form when it is stored in appropriate variable

MORE ABOUT THE printf FUNCTION MINIMUM FIELD WIDTH When you are printing the values of the variables, Minimum field width can be specified by preceding the conversion character by an unsigned integer. If the number of character in the corresponding data item is less than the specified field width, then the data item will be preceded by enough leading blanks to fill the specified field If the number of characters in the data item exceeds the specified field width, then additional space will be allocated to the data item

Panimalar Engineering College

33

MC9212-Problem Solving and Programming Unit IV & V This is just opposite to the maximum field with of scanf function

EXAMPLE void main( ) { int i=12345; float x=456.789; clrscr(); printf("\n%03d %05d %08d",i,i,i); printf("\n%03f %010f %013f",x,x,x); printf("\n%03E %013E %016e",x,x,x); getch(); } The output of the above program shown below 12345 12345 00012345 456.789000 456.789000 000456.789000 4.567890E+02 04.567890E+02 00004.567890e+02 The first line of integer displays a decimal integer using three different minimum field width ( three characters, five characters, and eight characters).but the input-data have width of 5, so if fieldwidth you have specified is smaller than the input-data system will allocate extra space required to display the whole data. If width of the input-data is smaller than the specified width the remaining space will be filled with zero (0). Note that the third value in the first line preceded with 000 indicates that minimum field width maintained at 8. the data-item made up of width 5 system adds three 0s in front of it Note the first value in the second line. The field width 3 you specified is smaller than the width of the data-item, data-item displayed as it is. But the third data-item will be preceded by three 0s to maintain minimum field width 13

MAXIMUM DECIMAL POINT WIDTH Default value for fraction-part of floating point number is always six. Some time is also possible to specify the maximum number of decimal places for a floating point value. This specification is known as precision. The floating point number will be rounded if it must be shortened to conform to a precision specification Example 1 void main() { float x=123.456; clrscr(); printf("\n%7f %07.1f %7.3f",x,x,x); printf("\n%012e %012.5e %012.3e",x,x,x); } The output of the above example is 123.456001 00123.5 123.456 1.234560e+02 01.23456e+02 0001.235e+02

Panimalar Engineering College

34

MC9212-Problem Solving and Programming Unit IV & V The first value in the first line is displayed with width of ten. because default width of the fractional part of floating point number is 6, the whole part of the input data is 3 plus one space width for decimal point (whole part(3)+fractional part(6) + one decimal point = 10 ). But minimum field width you have specified is 7, which is smaller than input-data size, whatever the input-data size that much amount of space will be allocated. For the second value, the total width is seven. In that for fractional part, it will allocate only one space, for whole part it will allocate 5 space , for decimal point it will allocate one space, but in the input-data whole part having only 3 digit the remaining three two space filled with zero

Example 2 You can also specify the maximum number of character for the string by using dot operator in the conversion character. the following example demonstrate how string length could be restricted when printing it using printf void main() { char data[]="hexadecimal"; clrscr(); printf("\n%10s \n%15s \n%15.5s \n%.5s",data,data,data,data); getch(); } The output of the above program hexadecimal hexadecimal hexad hexad For the first output, the size of the data item is larger than the minimum field width you have specified, so that whatever the data-size that much amount of space will be allocated For the second output, the field width you have specified is 15 but the data size is only 11, so that remaining 4 widths will be filled with space. The default justification is right, so the space will be filled on left side For the third output, the total width you have specified is 15, but for data, the maximum field width is only 5 by explicitly specifying (.5). so that only first 5 characters of the data-item will displayed, 10 space will be filled in front of the data For the fourth output the maximum field width you have specified is only 5, so that whatever may be the input-data, only first five characters of the data-item will be displayed

COMMONLY USED OUTPUT FORMATTING FLAGS In addition to the field width, the precision and the conversion character, each character group with in the control string can include a flag, which affects the appearance of the output. The flag must be placed immediately after the percent sign (%).

Panimalar Engineering College

35

MC9212-Problem Solving and Programming Unit IV & V FLAG + 0 #(with o- and xtype conversion) #(with f- and gtype conversion) MEANING Data item is left justified within the field A sign (either + or -) will precede each signed numerical data item. Without this flag, only negative data items are preceded by a sign Causes leading zeros to appear instead of blanks. Applied only data item that are right justified Blank space will precede each positive signed numerical data item. This flag is overridden by the + flag if both are present Causes octal and hexadecimal data items to be preceded by 0 and 0X, respectively Causes a decimal point to be present in all floating point numbers, even if the data item is a whole number. Also prevent the truncation of trailing zeros in g-type conversion

The following program demonstrate how to use flags main(){ int x=30; float y=12, z=-3.33; clrscr(); printf(":%6d:%7.0f:%10.1e:\n\n",x,y,z); printf(":%06d:%+07.0f:%010.1e:\n\n",x,y,z); printf(":%-+6d:%-7.0f:%-010.1e:\n\n",x,y,z); printf(":%7.0f:%#7.0f:%7g:%#7g:\n\n",y,y,z,z); printf("%#6d %#6o %#6x\n\n",x,x,x); getch(); } The output of the above program shown below : 30: 12: -3.3e+00: :000030:+0000012:-0003.3e+00: :+30 :12 :-3.3e+00 : : 12: 12.: -3.33:-3.33000: 30 036 0x1e

DECISION MAKING AND BRANCHING

CONTROL STATEMENTS When we try to execute any program, the instructions were executed in the same order in which they appeared within the program. In practice, we have number of situations where we may have to change the order of execution of statements based on certain conditions, or repeat a group of statements until certain specified conditions are met. By using control statements we can test condition. If condition satisfied, we can execute some set of statements, otherwise we can ignore the execution of those set of statements This is also known as control statement or decision making statements. It is also called branching or selection statement Sometime the program may need to execute group of instruction repeatedly, until some logical condition has been satisfied. This is known as looping

Panimalar Engineering College

36

MC9212-Problem Solving and Programming Unit IV & V

C language possesses such decision making capabilities and supports the following statements known as control or decision making statements. They are 1. if statement 2. switch statement 3. conditional operator statement 4. goto statement

DECISION MAKING WITH IF STATEMENT


If statement is a powerful decision making statement, and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. There are different forms of if statement exists in C. They are
o o o o Simple if If else Nesting of ifelse Cascaded if (or) else if ladder Entry

SIMPLE IF STATEMENT
The general form of simple if statement is if (expression/condition) { Statement-block; } statement-x;

test expression ?

TRUE

Statement - block FALSE The statement-block may be single statement or group of statements. If the expression / condition true, the statementblock will be executed; otherwise the Statement - x execution will jump to the statement- x without executing the statement-block. Remember, when the condition is true Next-statement both statement-block and statement-x are executing in the sequence The flow chart of simple if is shown next to the syntax E.g.: code segment if(category == SPORTS) { marks = marks + bonus_marks; } printf(%f,marks); .. The program tests the type of category of student. If the student belongs to the SPORTS category, then additional bonus_marks are added to his marks before they are printed. For other students bonus_marks are not added Panimalar Engineering College

37

MC9212-Problem Solving and Programming Unit IV & V

THE IF ELSE STATEMENT


It is an extension of the simple if statement. The general form is if (expression/condition){ true-block-statement[s]; } else{ false-block-statement[s]; } statement-x; This statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test. If expression return true, then the true-blockstatement[s] are executed; otherwise false-block-statement[s] are executed. The else portion of the if-else statement is optional e.g.: code fragment int a,b; scanf(%d %d,&a,&b); Entry if(a>b) printf(%d is bigger than %d ,a,b); else printf(%d is bigger than %d ,b,a); TRUE FALSE test expression ?

True-block statement

False-block statement

Statement - x

NESTING OF IFELSE STATEMENTS

Next-statement The body of the one if statement can contain another if statement. This arrangement is called Nested IF. In C any number of nested if is possible. If all the condition is true only the final statement will get executed. If any one of the condition at any stage is failed the statement defined in the inner most if will never get executed if (expression1/condition1) { if (expression2/condition2) { statement[s]-1; } [ else

SYNTAX

Panimalar Engineering College

38

MC9212-Problem Solving and Programming Unit IV & V { }] statement[s]-2;

} [else { statement[s]-3; }] The flow chart of nested if else is shown below Entry

FALSE

test condition 1 ?

TRUE

FALSE Statement-2

test condition 2 ?

TRUE

Statement-3

Statement-1

Statement - x

Next-statement e.g.: if(gender==F) { if(married==Y) { if(havechild==Y) } }

Bonus=1000;

ELSEIF LADDER / CASCADED IF STATEMENT This form of if is alternate to switch statement. This form of if can have only one if statement, followed by any number of else if statement, followed by zero or one else statement

Panimalar Engineering College

39

MC9212-Problem Solving and Programming Unit IV & V When the first if statement return true then the body of the if will be executed, the remaining part of ladder-if will never get executed. Otherwise the very first else if statement is tested. If this return true than the body of this conditional statement will get executed, the remaining portion of ladder-if will be ignored and so on The flow chart of else if ladder is given below Entry

TRUE

condition 1 ?

FALSE

Statement-1

TRUE

condition 2 ?

FALSE

Statement-2 TRUE condition 3 ? FALSE

Statement-3 TRUE condition 4 ? FALSE


Default-statement

Statement-n

Statement - x

Next-statement SYNTAX:

if (expression1/condition1) { statement[s]; } else if (expression2/condition2){ statement[s]; }

Panimalar Engineering College

40

MC9212-Problem Solving and Programming Unit IV & V else if (expression2/condition2){ statement[s]; } else{ statement[s]; } if(mark >=80) strcpy(grade,distinction); else if(mark >=60) strcpy(grade,first class); else if(mark >=50) strcpy(grade,second class); else if(mark >=40) strcpy(grade,third class); else strcpy(grade,Fail);

e.g.:

THE SWITCH STATEMENT


This is alternate to the cascaded if (if-else ladder). This switch statement causes a particular group of statement to be chosen from several available groups. The selection is based upon the current value of variable or expression, which is included within the switch statement

SYNTAX switch(expression/variable) { case constant-1: statement sequence-1; break; case constant-2: statement sequence-2; break; default : statement sequence-N; break; } Statement-x; nested switch is also possible If the expression or variable is an number type of variable, the constant value should not need to be enclosed in either single quotation or double quotation mark If variable or expression is of character type, the constant value should be enclosed in single quotation mark ( )

Panimalar Engineering College

41

MC9212-Problem Solving and Programming Unit IV & V If variable is of string type, the constant value should be enclosed in double quotation mark ( ) If no case matching for corresponding value of the variable, default option will get executed The flowchart of switch functionality is shown below E.g.: int a,b,c; char opt,action[20]; opt=getchar(); Switchscanf(%d %d,&a,&b); expression switch(opt) { case + : c=a+b; Expression = value1 strcpy(action, sum ); block-1 break; case - : c=a-b; Expression = value1 strcpy(action, difference ); block-2 break; . case * : c=a-b; strcpy(action, product ); Default (no match) default break; block default: strcpy(action, invalid action); } Statement-x printf( the %s of %d and %d is %d,action,a,b,c); . TERNARY OPERATOR/CONDITIONAL OPERATOR/THE ? : OPERATOR This statement just alternate to the simple if. The only major difference between simple if and ternary operator is that we cannot use if statement inside printf() function, but we can use ternary operator inside printf() function Syntax : Exp1?Exp2:Exp3;

If Exp1 is evaluated to true than Exp2 is executed; otherwise Exp3 will be executed e.g.: int a,b; printf( %d is bigger,(a>b)?a:b);

DECISION MAKING AND LOOPING


Sometime the program may need to execute group of instruction repeatedly, until some In looping, sequence of statements is executed until some conditions for termination of the
loop are satisfied. A program loop therefore consists of two segments, one is known as the body of the loop and the other known as the control statement. Control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop logical condition has been satisfied. This is known as looping

Panimalar Engineering College

42

MC9212-Problem Solving and Programming Unit IV & V Entry Entry test condition? True Body of the loop False Body of the loop

test condition? True

False

(a) entry control

(b) exit control

Depending on the position of the control statement in the loop, the control structure may be

classified as the entry-control loop or the exit-control loop. The flowcharts in the following figure illustrate these structure In the entry-control loop, the control conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. In the case of exit-control loop, the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time The test condition must be carefully stated in order to perform the desired number of loop executions, otherwise, the control sets up an infinite loop and the body executed over and over again The looping process, in general would includes the following four steps: o Setting and initialization of a counter o Execution of the statement in the loop o Test for a specified condition for execution of the loop o Incrementing the counter The C language provides three loop construct for performing loop operations. They are o The while statement o The do statement o The for statement

Categories of loops Based on the nature of variable and the kind of value assigned to it for testing the control expression, the loop may be classified into two general categories o Counter-controlled loops o Sentinel-controlled loops Counter-controlled loops
When we known in advance exactly how many times the loop will be executed, we use a counter-controlled loop. We use control variable known as counter. The counter must be Panimalar Engineering College

43

MC9212-Problem Solving and Programming Unit IV & V initialized, tested and updated properly for the desired loop operations. The number of times we want to execute the loop may be a constant or a variable that is assigned a value. A counter controlled loop is sometime called definite repetition loop or deterministic loop. Example for counter-controlled loop is for loop

Sentinel-controlled loops
In a sentinel controlled loop, a special value called a sentinel value is used to change the loop control expression from true or false. For example, when reading data we may indicate the end of data by special value, like 1 and ^Z. The control variable is called sentinel variable. A sentinel-controlled loop is often called indefinite repetition loop because the number of repetitions is not known before the loop begin executing

THE WHILE STATEMENT / THE WHILE LOOP While loop is also called pre-conditional loop. The body of the while loop keep executed repeatedly until the condition become false Initialization of the variable, increment of the variable should be done manually. If you forgot to increment the variable which is tested in the condition, it may leads to infinite loop SYNTAX while (test-condition) { body of the loop; } It is an entry controlled loop statement. The test-condition is true, then the body of loop is executed. After execution of the body. The test-condition once again evaluated and if it true, the body is executed once again. This process is repeated until the test-condition becomes false E.g.1: sum =0; while(n<=10) { sum = sum + n * n; n = n +1; } printf(sum = %d,sum); In the above code, the loop is executed 10 times for n = 1,2,..,10, and produce result as sum of the square of first 10 natural numbers. The variable n is called counter or control variable E.g.2: FILE *fp; fp=fopen(w,file1.txt); char ch; while((ch=getchar( ))!=EOF) fputc(ch,fp);

Panimalar Engineering College

44

MC9212-Problem Solving and Programming Unit IV & V In the above code, the loop is repeatedly executed until ^Z character is pressed from keyboard and write to the file called file1.txt. This is typical example for sentinelcontrol loop. ^Z is called sentinel-value and variable ch is called sentinel variable DO-WHILE LOOP / THE DO STATEMENT do-while statement is similar to while statement, but the only difference is that this will first execute the body of the loop and than test the condition. So that even, first time itself the condition fails also the body of the loop will be executed at least once. But in while loop the body of the loop will never get executed SYNTAX : do { statement[s]; }while(test-condition); Since the test-condition is evaluated at the bottom of the loop, the dowhile construct provides exit-controlled loop and therefore the body of the loop is always executed at least once. e.g.: int a,sum=0; do { printf(input number to sum? ) scanf(%d,&a); sum+=a; printf(do you wish to add one more data to sum(y/n): ); ch=getchar(); } while( ch == Y || ch == y); printf(sum=%d,sum); The above program add all numbers given by user, and display sum of those numbers. This is typical example for sentinel-control loop, and variable ch is called sentinel variable For loop has three part, the first part is an initialization part , where you can initialize variable. The initialization-part will be executed only once for the first ireration The second part is an conditional part , if this conditional part satisfied then only, the body of the for loop will be executed Third part is an increment part, where you can increment the value of certain variables. This part will be executed from second iteration to until the end of the loop. For the first iteration, it does not be executed All the three part should be separated using semicolon (;). You can initialize more than one variable at initialization part, but each initialization statement should be separated by comma. Similarly you can increment/decrement more than one variables in the increment part, but individual statement must be separated by comma.

THE FOR LOOP / THE FOR STATEMENT


Panimalar Engineering College

45

MC9212-Problem Solving and Programming Unit IV & V SYNTAX: for(intialization1[,initialization2,..];condition;increment1[,increment2,]) { statement[s]; } e.g.: for(i=0;i<5;i++) printf( \n%d, i); One of the important points about the for loop is that all three actions, namely initialization, testing, and incrementing, are placed in the for statement itself, thus making them visible to the programmer and users, in one place. The for statement and its equivalent of while and do statements are shown below: For While Dowhile for(n=1;n<=10;++n) n=1; n=1; { do while(n<=10) { { .... } n=n+1; n=n+1; } } while(n<=10);

Additional feature of for loop


The for loop in C has several capabilities that are not found in other loop constructs. For example more than one variable can be initialized at a time in the for statement The statement p = 1; for (n=0;n<17;++n) can be rewritten as for (p=1, n=0;n<17;++n) Notice that the initialization section has two parts p=1 and n=0 separated by comma. Like initialization section, the increment section may also have more than one part. For example, the loop for (n=1, m=50 ; n<=m ; n=n+1, m=m-1) { p = m / n; printf(%d %d %d\n, m, n, p); } is perfectly valid. The multiple arguments in the increment section are separated by commas the third feature is that the test-condition may have any compound relation and the testing need not be limited only to the loop control variable. Consider the example below sum=0; for (i=1; i <20 && sum<100; i++) { sum=sum+i; printf(%d %d\n, i, sum); }

Panimalar Engineering College

46

MC9212-Problem Solving and Programming Unit IV & V Another unique aspect of for loop is that one or more sections can be omitted, if necessary. Consider the following statements:

m = 5; for ( ; m!=100 ; ) { printf(%d\n,m); m=m + 5; } Both initialization and increment sections are omitted in the for statement. The initialization has been done before the for statement and the control variable is incremented inside the loop. In such a cases initialization section and increment section are left blank. However, the semicolons separating the sections must remain. If the test-condition is not present, the for statement sets up an infinite loop. Such a loop can be broken using break or goto statement in the loop. so statement for( ; ; ) { if(condition) break; } is still valid statement. We can setup time-delay loop using null statement as follows: for(j=1000; j > 0; j--) ; A loop is executed 1000 times without producing any output; it simply causes time delay. Notice that semicolon without statement will be known as null statement

Nesting of for loops


Nesting of one for loop with in another is allowed in C. ANSI C allows upto 15 levels of nesting. However some compilers permit more.for example, two loops can be nested as follows:

for(i = 1; i < 10; ++i) { Outer for( j = 1; j != 5 ; ++ j) loop { Inner . loop .. } } The nesting may continue up to any desired level. The loop should be properly indented so as to enable reader to easily determine which statements are contained within each for statement For every single iteration of outer loop; the whole iteration of inner loop get executed

Selecting a loops:
To choose one of the three loop supported by C, we may use the following strategy: Panimalar Engineering College

47

MC9212-Problem Solving and Programming Unit IV & V Analyze the problem and see whether it required a pre-test or post-test loop If it requires a post-test loop, then we can use only one loop, dowhile If it requires a pre-test loop, then we have two choices: for and while Decide whether the loop termination requires counter-based control or sentinel-based control Use for loop if the counter-based control is necessary Use while loop if the sentinel-based control is required Note that both the counter-controlled and sentinel-controlled loops cab be implemented by all the three control structures

JUMPS IN LOOPS
UNCONDITIONAL BRANCH STATEMENTS/ UNCONDITIONAL CONTROL STATEMENT

The following are the list of unconditional control statement. 1) goto 2) continue 3)break 4) return GOTO With the help of goto statement, you can able to execute set of instruction repeatedly without any loop statement Because of existence of break & continue, there is little need for GOTO. there are no programming situation that require goto programming situation where it is useful is, jumping out of a set of deeply nested loops goto statement requires a LABEL for this type of operation Label is a valid identifier followed by colon(:). jumping from one function to another function using goto is not possible. So that GOTO and LABEL must be defined with in same function label can be defined either before or after goto e.g: x=1; loop1: x++; if(x<1000) goto loop1; It also used to jump within the loop or jump out of loop as shown below: Jump within loop Jump out of loop / exit from loop while() for() { { if(error) for() goto stop; { . Exit if(condition) if(error) From goto abc; goto stop; loop Jump exit . . within from . } loop two abc: . . } loops } stop: stop: . .

Panimalar Engineering College

48

MC9212-Problem Solving and Programming Unit IV & V

BREAK
this statement will be used to force immediate termination of a loop, bypassing the normal loop conditional test You can also use it to terminate a case in the switch statement. When break statement encounter inside loop, loop will be terminated, control will be transferred to next statement after loop. This cannot be used inside if statement Various ways of breaking loop with break shown below while(test-condition) do (a) { (b) { if(.) if(.) break; break; . . . . } } while(test-condition); .. .. for(initialization; test-condition; increment) (c) { if() break; . } . e.g.: for(i=1;i<5;i++) { for(j=1;j<5;i++) { if(j>i)break; printf(\t%d,j); } printf(\n); }

CONTINUE (skipping part of loop)


instead of forcing loop termination, continue statement forces the next iteration of the loop to take place when continue statement get executed inside the loop, all statements available after continue statement will not get executed, instead next iteration takes place e.g.: for(i=1;i<5;i++) { for(j=1;j<5;i++) { if(i == j)continue; printf(\t%d,j); } printf(\n); } Panimalar Engineering College

49

MC9212-Problem Solving and Programming Unit IV & V the following figure show various way of bypassing loops with continue while(test-condition) Do (a) { (b) { if(.) if(.) continue; continue; . . . . } } while(test-condition); (c) for(initialization; test-condition; increment) { if() continue; . }

RETURN The general syntax is return [ variable / expression ]; Return statement may or may not have return-value associated with it. If return statement has value associated with it, that value becomes return value of the function void function does not need to have return statement but non void function must have return statement If return occurred with in void function, then return value of that function is undefined. e.g.: double area(double radius) { return PI * r * r; }

ARRAYS
WHY DO WE NEED ARRAY?
Ordinary variable of any types ( such as int, float, char) will hold only one data at a time, when you put any new data on variable that already holding data, the old value will be erased and new data will be placed in that. But sometime we need to hold one data those having common characteristics in single variable. But this not possible using ordinary variable To overcome this anomalies C provides feature called array. Array can be of any type such as int, char, float, struct or any other data-type, even it could be pointer also DEFINITION OF AN ARRAY An array is a collection of data of same type that are referred to through a common name. An array is a fixed-size sequenced collection of elements of same type. It is simply a grouping of like-type data A specific element in an array is accessed by an index or subscript. Subscript or index should not be negative Panimalar Engineering College

50

MC9212-Problem Solving and Programming Unit IV & V All arrays consist of continuous memory locations The first element of array will have index as zero Array may have one to several dimensions. It can be single dimensional array, multidi

Some examples where the concept of an array can be used - list of temperature recorded every hour in a day, or month or a year - list of employee in an organization - list of products and their cost sold by a store - test scores of a class students - list of customers and their telephone numbers - table of daily rain fall data

ONE-DIAMENTIONAL ARRAY
A list of items can be given one variable name using only one subscript and such a variable is called single-subscripted variable or one dimensional array The subscript of an array can be integer constant, integer variables, or an expression that yield integer. C perform no bounds checking and therefore, care should be exercised to ensure that the array indices are within the declared limits

DECLARATION OF ONE DIMENSIONAL ARRAY Arrays are declared in mush same way as ordinary variables, except that each array name must be accomplished by a size specification The size should be always positive integer, and should be enclosed in square bracket, followed by variable name An one dimensional array can be declared as follows [storage-class] data-type array-variable-name[size] Storage-class is optional, and size could be any positive integers. Data-type indicates type of data to be stored in on array Size define how many number of maximum elements the array can hold the amount of storage required to hold an array is directly related to its type and size totalbytes=sizeof(base-type) *size-of-array Example int A[20]; char text[80]; static float marks[100]; In the above declaration A is an integer array variable, which can hold maximum of 20 integer elements as data text is an character array variable , accept and store maximum of 80 characters marks is an integer variable, can able to store maximum of 100 floating-point values Once the array-variables are declared, you can store individual elements of an array using subscript or index Example: assigning values to the variable having different data-type A[0]=120; A[1]=10; text[0]=S; marks[40]=88.5; Panimalar Engineering College

51

MC9212-Problem Solving and Programming Unit IV & V INITIALIZATION OF ONE-DIMENSIONAL ARRAY An array can be initialized at either of the following stages o At compile time o At run time Compile time initialization An array can be initialized during declaration itself. The general form of initialization of array is data-type array-name [size]={list of values separated by comma}; The following examples shows how to initialize one dimensional array variable having different data-type for e.g.: (i) int marks[ ]={10, 20,30 ,40 ,50 ,60 ,70 ,80 ,90}; (ii) here marks is an integer array variables its size is 9.Array at index 0 is initialized with 10, at index 1 is initialized with 20 , and so on float weight[10]={50,76.6,45.3,60,77}; it is not necessary to mention the size of the array variable. But you can explicitly mention the size. The size of the array variable weight of base type float is 10 but you are initializing only 5, so that remaining 5 locations automatically initialized with zero char name[ ]=Kajendran; (or) char name[ ]={K,a,j,e,n,d,r,a,n,\0};

(iii)

when you initialize char array variables, the values could be either enclosed in double quotation mark or single quotation mark. When you enclose character in single quotation mark, you have to include last character as null character to indicate the end of the string

(iv) char city[5]={B}; This will initialize first element to B and remaining four to NULL. Note that an initialization statement int group[8]={0,0,0,0,0,0,0,0}; Can be written as int group[8]={0}; This will initialize all the elements of array group to zero

Run-Time Initialization
Array can be explicitly initialized at run time. This approach is usually applied for initializing large array. Consider the following program segment of a C program float sum[100]; .. .. for(i = 0; i<100; i=i+1) { if(i<50) Panimalar Engineering College

52

MC9212-Problem Solving and Programming Unit IV & V else sum[i]=0.0; sum[i]=1.0;

} .. The first 50 elements of the array sum are initialized to zero while the remaining 50 elements are initialized to 1.0 at run time We can also use a read function such as scanf to initialize an array. For example, the statements int x [3]; scanf(%d %d %d,&x[0], &x[i], & x[2]); will initialize array elements with the values entered through the keyboard

TWO-DIAMENTIONAL ARRAY
There could be situations where a table of value will have to be stored. Consider the following data table, which shows the value of three items and four sales girls

Salesgirl #1 Salesgirl #2 Salesgirl #3 Salesgirl #4


Item1 342 876 987 987

Item2 768 677 567 564

Item2 768 554 432 655

The table contains a total of 12 values, three in each line. We can thing of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular sales girl and each column represent values of sales for particular item C allows us to define such a tables of items by using tow-dimensional arrays. The table discussed above can be defined in C as v[4][3]

DECLARATION OF ONE DIMENSIONAL ARRAY

The general syntax for declaring two dimensional array is given below [storage-class] data-type array-name [row_size] [column_size]; Example int v[4][3]; float Ta[20][20]; static double box[10][10][10]; Variable Ta is a two dimensional array and can hold maximum of 400 float elements. Variable box is three dimensional array, having maximum of 1000 location, so it is capable of holding maximum 1000 double elements in case of two-dimensional array, the following formula yields the number of bytes of memory needed to hold it Total no.of Bytes=size of 1st index*size of 2nd index*size of (base type). two dimensional array v are stored in memory as shown in figure below col 0 col 1 col 2 v[0][0] v[0][1] v[0][2] Row 0

Panimalar Engineering College

53

MC9212-Problem Solving and Programming Unit IV & V v[1][0] Row 1 v[2][0] Row 2 v[3][0] Row 3 Initialization of two-dimensional array The simplest form of multi-dimensional array is the two dimensional array. The following code demonstrate how two dimensional array can be initialized (i) int d[ ] [2]= {{1,1}, {1,2},{3,4},{5,2},{6,3}}; ( or ) int d[ ] [2]={1,1,1,2,3,4,5,2,6,3}; When you initialize two dimensional arrays, you have to mention the size of the second dimension of the array. But first dimension is an optional, it is not necessary to mention first dimension. According to the number of the values you have passed, compiler will automatically assume the first dimension. First dimension of variable d is 5 (ii) int mat[3][4]={{1,2,3}, {4,5,6}, {7,8,9}}; for variable mat first dimension is 3 and second dimension is 4, but for each row you passing only three value, so that compiler will automatically assume 4th column of each row as zero mat[0][0]=1 mat[0][1]=2 mat[0][2]=3 mat[0][3]=0 mat[1][0]=4 mat[1][1]=5 mat[1][2]=6 mat[1][3]=0 mat[2][0]=7 mat[2][1]=8 mat[2][2]=9 mat[2][3]=0 (iii) int tmp[3][4]={1,2,3,4,5,6,7,8,9}; In case of tmp only last row, last three columns will be assumed as 0 shown below tmp[0][0]=1 tmp[0][1]=2 tmp[0][2]=3 tmp[0][3]=4 tmp[1][0]=5 tmp[1][1]=6 tmp[1][2]=7 tmp[1][3]=8 tmp[2][0]=9 tmp[2][1]=0 tmp[2][2]=0 tmp[2][3]=0 But initialization of two dimensional character array is different from initialization of int, float, double, etc The following example demonstrate how to initialize two dimensional character array variables (iv) char name_list[ ] [40]={Kannan,Kumar,Arul,Bala,Vignesh}; Name_list is two dimensional array variable, each name can have maximum of 40 character length. The size of the first dimension of the name_list is 5 MULTI DIMENSIONAL ARRAYS Multi dimensional array are defined in much same manner as one dimensional arrays, except that a separate pair of square bracket required for each subscript. Thus two dimensional arrays will require two pair of square brackets; three dimensional arrays will require three pair of square brackets and so on. In general syntax of multi dimensional array shown below v[3][1] v[3][2] v[2][1] v[2][2] v[1][1] v[1][2]

Panimalar Engineering College

54

MC9212-Problem Solving and Programming Unit IV & V [storage-class] data-type array-name[size1][size1][sizeN]; Where sizei is the size of the ith dimension. Here, the storage class is an optional, datatype could be any user-defined or pre-defined data-type, size of the each dimension of the array should be always positive integers Here are some example: int survey[3][5][12]; float table[5][4][5][5]; Survey is the three-dimensional array declared to contain 180 integer type elements. Similarly table is a four-dimensional array containing 300 elements of floating-point type The array survey may represent a survey data of rainfall during the last three years from January to December in five cities

STATIC ARRAY
An array created at compile time by specifying size in the source code has a fixed size and cannot be modified at run time. The process of allocating memory at compile time is known as static memory allocation and the arrays that receive static memory allocation are called static array

DYNAMIC ARRAY
In C it is possible to allocate memory to arrays at run-time. This feature is known as dynamic memory allocation and the array created at runtime are called dynamic array Dynamic array are created using what are known as pointer variables and memory management functions malloc, calloc and realloc The concept of dynamic array is used in creating and manipulating data structure such as linked lists, stacks and queues

PROCESSING AN ARRAY
Single operations which involve entire arrays are not permitted in C. Thus if A and B are similar arrays (same data-type, same dimensionality, and same size), assignment operations, comparison operation, etc must be carried out on an element-by-element basis. This is usually accomplished with in a loop, where each pass though the loop is used to process one array element The number of passes through the loop will therefore equal to the number of array elements to be processed example : int a[5]={3,3,4,5,3}, b[5]={4,5,2,7,9},c[5]; here array variable a , b , c are of integer array variables of having same size. But we cannot execute assignment statement shown below c=a+b; /* this assignment statement will generate error during compilation*/ to accomplish the above task, we have to add individual elements of array using loop shown below for(i=0;i<5;i++) c[i]=a[i]+b[i];

Panimalar Engineering College

55

MC9212-Problem Solving and Programming Unit IV & V FUNCTIONS Why do we need functions? - to avoid repetition of statements in program - to make your program simpler and modular In some situation, the same set of statements will be placed repeatedly, in different part of the same program. This will cause the size of the program larger and it is difficult to debug , when any syntax error occurred To avoid this, the repeated instructions can be placed with in a single function, wherever you require those statements, there you can call that function. So that you have only one copy of the code instead of multiple copy. This will bring down Object file size considerably. C program can be modularized through the intelligent use of such functions. Thus the use of a function avoids the need for redundant programming of same instruction This division approach of function clearly results in a number of advantages - It facilitates top-down modular programming as shown in figure. In this programming style, the high-level logic of the overall problem is solved first, while the detail or each lower-level function are addressed later Main Program

Function A

Function B

Function C

B1

B2

The length of the source program can be reduced using functions at appropriate places It is easy to locate and isolate a faulty function for further investigations A function may be used by many other programs, instead of starting all over again from scratch

A multi function program


A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as black box that takes some data from the main program and return a value. The inner details of operation are invisible to the rest of the program. All that the program knows about function is: what goes and what comes out. Every C program can be designed using a collectionof these black boxes known as functions. consider a set of statements as shown below: void printline (void) { int i; for (i=1; i<40; i++) printf(=); printf(\n); }

Panimalar Engineering College

56

MC9212-Problem Solving and Programming Unit IV & V above set of statement defines a function called printline, which could print a line of 39 character length. This function can be used in program as follows: void printline(void); /* function declaration or function prototype */ main( ) { printline( ); printf(this illustrates the use of C functions\n); printline( ); } void printline (void) { int i; for (i=1; i<40; i++) printf(=); printf(\n); } This program will produce following output ============================================ this illustrate the use of C function ============================================ The above program contain two user-defined functions namely main( ) and printline( ). As we know the program execution always begin with the main function. During the execution of main( ), printline( ) function main( ) invoked twice { Any function can call any other function. In fact, it can call itself. A Called function function1( ); can also call another function. A function can } also be called more then once. The following figure illustrate the flow of control in a multi-function program function1( ) The functions can be placed in any order. A { called function can be placed either before or function2 ( ); after the calling function. However the usual } practice to put all the called functions at the end function2( ) { ELEMENTS OF USER-DEFINED } FUNCTIONS In order to make user-defined functions, we need to establish three elements that are related to functions o Function definitions o Function call o Function declaration DEFINITION OF THE FUNCTIONS A function definition, also known as function implementation shall includes the following elements

Panimalar Engineering College

57

MC9212-Problem Solving and Programming Unit IV & V 1. Function type / return type 2. Function name Function header 3. List of parameters 4. Local variable declarations 5. Function statements Function body 6. A return statement All six elements are grouped into two parts, namely o Function header (first three elements) o Function body (last three elements) The general syntax of the function is given below return-type function-name(data-type arg1, data-type arg2,) { local variable declaration; executable statement1; executable statement1; return statement; } return-type / function-type could be any valid C data-type either user-defined or predefined other than an array, even it could be pointer function-name is user-defined name, the rule to define function-name is same as the rule you follows to define variable Similarly data-type could be any valid C data-types, even it could be pointers, structure etc. Function may be without parameter, in which case the parameter list is empty. Even if there are no parameters, the parameters are still required. The first line return-type function-name(data-type arg1, data-type arg2,) is known as the function header and statements within the opening and closing braces constitute function body, which is compound statement

FORMAL PARAMETERS arg1, arg2,.. are the user-defined names similar to variable-name, these are called formal parameters or formal arguments formal parameters are used to receive the data sent by the calling program the identifier used as formal arguments are local in the sense that they are not recognized outside the function Formal parameters behave like other local variables inside function and are created upon control entry into the function and destroyed upon control exit Formal parameters hold the value of the actual parameters, you passing from the calling program In the example given below variable ch is called formal parameter BODY OF THE FUNCTION The function body contains the declarations and statements necessary for performing the required task. The body enclosed in braces, contain three parts, in the order given below: o Local variable declarations that specify the variables needed by the function o Function statements that perform the task of the function

Panimalar Engineering College

58

MC9212-Problem Solving and Programming Unit IV & V o A return statement that return the value evaluated by the function The code that constitute the body of function is hidden from the rest of the program, it could be single statement or compound statements Body of the function may or may not have return statement. The function have returntype as void, does not need to have return statement

RETURN STATEMENT Information is returned from the function to the calling portion of the program via the return statement. The return statement can take one of the following forms return expression/variable/constant; (or) return; The value of the expression or variable is returned to the calling portion of the program. The expression is optional, if the expression is omitted the return statement simply causes control to revert back to the calling portion of the program, without any transfer of information The data-type of expression should match with return-type of function Example in the following example to_upper is an user-defined function, which will accept character as argument and convert lower-case into upper-case,and return converted character as result to the calling program char to_upper(char ch) /* ch is formal parameter */ { return (ch>= 'a' && ch <='z') ? ('A'+ch -'a'):ch; } void main() { char name[20]; int i=0; clrscr(); printf("\nenter name in lower character : "); scanf("%s",name); while(name[i]!='\0') { name[i]=to_upper(name[i]); /* function call. name[i] is actual parameter or argument*/ i++; } printf("\nvalue of name after convertion: %s",name); getch(); } Output enter name in lower character : kannan value of name after convertion: KANNAN

Panimalar Engineering College

59

MC9212-Problem Solving and Programming Unit IV & V

ACCESSING A FUNCTION / FUNCTION CALL A function is accessed or called by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the name of the function ACTUAL ARGUMENT The arguments appearing in the function call are referred to as actual argument. This is also known as actual parameter The actual argument may be expressed as constant, variable or expression Remember that only value of each actual argument that is transferred into the function and assigned to the corresponding formal parameter. So that when you change the value of the formal parameter, it does not change the value of actual parameter E.g. char t1=x; char t2=to_char(tmp); In the above code fragment variable t1 is called actual argument to function to_char FUNCTION PROTOTYPE / FUNCTION DECLARATION The programmer defined function has always proceeded main. Thus when these program are compiled, the programmer-defined function have to be defined before the first function call However some programmers prefer a top-down approach, in which main appear ahead of all user defined functions. In such a situation, function-call from main will appear before function definition This confusing the compiler, so that you have to alert the compiler by giving instruction that the function definition coming later part of the program after main definition. A function-prototype is used for this purpose function prototypes are usually written in the beginning of the program after include statements, and is necessary only, when you define function after main( ). It consists of four parts o Function type / return type o Function name o List of parameters o Terminating semicolon the general form of function prototype is return-type function-name(data-type [variable],data-type [variable],); The function proto-type must have return-type followed by function-name, followed by zero or more arguments enclosed in parentheses and ends with semicolon(;). Parameter-name are not necessary in prototype declaration, but you are giving does not raise any error, only you need to pass data-type of the argument E.g.: long int fact(int); /* function prototype (or) function declaration */ void main() {

Panimalar Engineering College

60

MC9212-Problem Solving and Programming Unit IV & V int a; clrscr(); printf("\nenter number to find factorial: "); scanf("%d",&a); printf("\nthe factoral of %d is %ld",a,fact(a)); getch(); } long int fact(int t) /* function definition */ { long int cnt=1; while(t>0) cnt*=t--; return cnt; } Output enter number to find factorial: 5 the factoral of 5 is 120 prototype declaration may be placed in two places in a program 1. above all the function including main 2. inside a function definition when we place the function declaration above all the function, the prototype referred to as a global prototype. Such declarations are available for all the function in the program When we place the function declaration inside any function, the prototype referred to as a local prototype. Such declaration are available only to the function in which it is declared Parameters or arguments are used in three places: 1. in declaration (prototype) 2. in function call 3. in function definition parameters used in prototype and function definition are called formal parameters and those used in function calls are called actual parameters The actual and formal parameter must match exactly in type, order and number. Their name however do not need to match

FUNCTION THAT RETURN MULTIPLE VALUE Any C function can return maximum of only one value to the calling program using return statement. But we can also create function that can return more than one value to the calling program in C with the help of arguments. So arguments are not only used to receive information, it also can be used to send back information to the calling function The argument that are used to send out information are called output parameters The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator (*) Example void arithmetic_operation(int a, int b, int *sum, int *diff)

Panimalar Engineering College

61

MC9212-Problem Solving and Programming Unit IV & V { *sum = a + b; *diff = a b; } main ( ) { int x = 20, y=10, s, d; arithmetic_operation(x, y, &s, &d); printf(\n sum = %d \t difference = %d,*s, *d); } When the function is called the following assignment occurs - value of x to a - value of y to b - address of s to sum - address of d to diff

Call by value and call by reference / passed by value and passed by reference There are two way that argument can be passed to a subroutine The first one is known as call by value. In this method only the value of an actual argument is passed to the formal parameter of the function definition, but not the address the actual argument. In this case changes made to the formal parameter have no effect on the actual argument The second is known as call by reference. In this method, the address of an actual argument is passed to the corresponding formal parameters defined in the function with the help of address operator (&). Here the formal parameter must be the pointer variables of corresponding actual parameters But when you are passing array variable to the function, instead of passing the values of the array, address of the first element in the array will be passed. E.g.: example for passed by references #include<stdio.h> #include<conio.h> void swap(int *p,int *q) { int tmp; tmp=*p; *p=*q; *q=tmp; printf("\n\np,q value at the end of the function : %d, %d",*p,*q); } void main() { int i,j; clrscr(); printf("enter two number to swap : "); scanf("%d %d",&i,&j);

Panimalar Engineering College

62

MC9212-Problem Solving and Programming Unit IV & V printf("\n\nthe value of i, j before swap are %d %d",i,j); swap(&i,&j); printf("\n\nthe value of i, j after swap are %d %d",i,j); getch(); } Here the value of the actual arguments a, b will be changed after function-call swap, because you are passing address of the variables a, b get to function swap

RECURSION/ RECIRSIVE FUNCTION A function is said to be recursive if a statement in the body of the function calls the same function itself. Factorial is the best implementation for recursion. Otherwise we can say recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. Many iterative or repetitive problems can be written in this form Example #include<stdio.h> #include<conio.h> long int fact(int n) { if(n <= 1) return 1; else return n * fact( n - 1 ); } void main() { int a; clrscr(); printf("\nenter number to find factorial: "); scanf("%d",&a); printf("\nthe factoral of %d is %ld",a,fact(a)); getch(); } Output enter number to find factorial: 6 the factoral of 6 is 720

PASSING ONE DIMENSIONAL ARRAY TO THE FUNCTION


The entire array can be passed to a function as an argument. The manner in which array is passed differs from that of an ordinary variable The difference between passing array variable over ordinary variable is that when you are passing the array, actually your not passing all the individual values of array, instead you are passing the address of the first element of the array. so that whatever changes you done on the formal parameter will also affect the values of the actual parameters Panimalar Engineering College

63

MC9212-Problem Solving and Programming Unit IV & V But in case of ordinary variable, your are just coping the value of the actual argument to formal argument , not address of the actual argument The following code fragment shows how to pass array as actual parameter, and the corresponding formal parameters. Three different way of defining the corresponding formal parameter shown below. In the first one, the formal parameter is an pointer variable, in the second one, the formal parameter is declared in the same way as actual argument is declared but without size void sort (int *x) { } (or) void sort (int x []) (or) Void sort (int x[32]) { { } }

Void main () { int a [10] ; sort(a); }

To pass an array to a function, the array name must appear by itself, without brackets or subscripts as an actual argument with in the function call. All three declaration methods produce similar result because each tells the compiler that the formal parameter going to receive an integer array as argument void sort(int x (32}) {....} also works well because the compiler generates code that instructs sort () function going to receive a pointer - it does not actually create a 32 element array Example - the following example demonstrate how to pass array to function as array element as well as how to pass array to pointer. The program consists of two functions namely called readArray() and display(). readArray() accepts argument as integer array, where as display() accept argument as integer pointer. array variable a is declared in function main, readArray function is used to accept value for variable a, and function display is used to display the content of the array variable a When you are passing actual variable a to formal variable t, actually you passing the address of the first index of the array variable a. formal variable t will be treated as integer variable, so that t[0] will be interpreted as t+0, t[1] will be interpreted as t+1 and so on #include<stdio.h> #include<conio.h> #define N 5 void readArray(int t[]) { int i; for(i=0;i<N;i++) { printf("\n enter t[%d] = ",(i+1)); scanf("%d",&t[i]); } } void display(int *ptr) { Panimalar Engineering College Output enter t[1] = 10 enter t[2] = 20 enter t[3] = 30 enter t[4] = 40 enter t[5] = 50 The content of the array are : 10 20 30 40 50 The sum of the array element is 150

64

MC9212-Problem Solving and Programming Unit IV & V int sum=0,i; printf("\nThe content of the array are :\n"); for(i=0;i<N;i++) { printf("\t%d",*(ptr+i)); sum+=*(ptr+i); } printf("\n the sum of the array element is %d",sum); } void main() { int a[10]; clrscr(); readArray(a); display(a); getch(); } THREE RULE TO PASS AN ARRAY TO A FUNCTIONS 1. the function must be called by passing only the name of the array 2. in the function definition, the formal parameter must be an array type; the size of the array does not need to be specified 3. the function prototype must show that the argument is an array PASSING TWO DIMENSIONAL ARRAY TO THE FUNCTION Like simple arrays, we can also pass multidimensional array to the functions. The approach is similar to the one we did with one-dimensional arrays. The rules are simple 1. the function must be called by passing only the array name 2. in the function definition, we must indicates that the array has two dimensions by including two set of brackets 3. The size of the second dimension must be specified 4. The prototype declaration should be similar to the function header The function given below calculates the average of the values in two dimensional matrix double average(int x[][2], int M, int N) { int i,j; double sum=0.0; for( i=0; i<M ; i++) for( j=0; j<N ; j++) sum+=x[i][j]; return (sum/(M*N)); } The function should be used from main function shown below main() { int m=3,n=2; Panimalar Engineering College

65

MC9212-Problem Solving and Programming Unit IV & V double average(int [][2], int , int ); double avg; int matrix[3][2]={{1,2},{3,4},{5,6}}; avg=average(matrix,m,n); } PASSING STRING TO THE FUNCTION String can be passed to an array the same way, how numerical single dimensional array to be passed. 1. the function must be called by passing only the name of the array 2. in the function definition, the formal parameter must be an array type; the size of the array does not need to be specified 3. the function prototype must show that the argument is an array The following program demonstrate how to pass string to function char makeupper(char s[]) { int i=0; while(s[i]!=\0) if((ch>= 'a' && ch <='z')) s[i]=('A'+ch -'a'); } void main() { char name[20]; int i=0; clrscr(); printf("\nenter name in lower character : "); scanf("%s",name); makeupper(name); printf("\nvalue of name after convertion: %s",name); getch(); } POINTER Pointer can be used for three reasons First, pointers provide the means by which function can modify their calling arguments Second, pointer support dynamic memory allocation Third pointer can improve the efficiency of certain routines Pointers are one of the strongest but also one of the most dangerous features in C. Uninitialized pointer (or) pointer containing invalid values can causing bugs that are very difficult find

Definition of pointer Panimalar Engineering College

66

MC9212-Problem Solving and Programming Unit IV & V

A pointer is a special variable that hold a memory address other variable. In otherwords, If

one variable contains address of another variable, the first variable said to be pointer to the second one. Pointer variable can point to any type of variables such as int, char , float, structure, or any type of array variable

Pointer Variables declaration If a variable going to hold the address of another variable, it must be declared first. In pointer variable declaration , the name of the pointer variable must always begins with * followed by variable name A pointer declaration consists of a base type, followed by one or more space, followed vt an *, and the variable name

Syntax
Data-Type *variable-name1, variable-name2,; Type can be any data type, either pre-defined C data-type , user-defined data-type The base type of the pointer defines what type of variable address, the pointer can point to Technically, any type of pointer can point anywhere in the memory. However, all pointer arithmetic done relative to its base type, so that, it is important to declare the pointer correctly EG: Int count=10; Int *p; P=&count; places memory address of variable count into pointer variable P. Int cpy_cnt=*p;cpy_cnt receives the value at address pointing by P. Double a=11.121345,b; int *p; p=&a; b= *p; Here p does not contain full a value,it holds 2 bytes of information . Example Void main() { int x,*ptr; char ch, *cptr; x=10; ptr=&x; ch=M; cptr=&ch; printf(\nx=%d \t *ptr=%d\t address of x=%p,x,*ptr,ptr); printf(\nch=%c \t *cptr=%c\t address of ch=%p,ch,*cptr,cptr); getch(); } Output x=10 *ptr=10 ch=M *cptr=M address of x=FFF2 address of ch=FFF5

X(FFF2) 10 Ptr(3500) FFF2 Ch(FFF5) M Cptr FFF5

Panimalar Engineering College

67

MC9212-Problem Solving and Programming Unit IV & V

Note: either %p or %u can be used to print the value / address stored in any pointer variable Pointer Arithmetic
There are only 2 arithmetic operations that you may use in the pointer. They are addition and subtraction. Char *ch; Int *I; Char name[ ]=hello; Int a[ ]={13,156,57}; ch=name; i=a; 9000 h ch memory a 7000 13 9001 e ch+1 7001 9002 l ch+2 7002 9003 l ch+3 7003 156 9004 o ch+4 7004 7005 57 9005 \0

memory name

i i +1 i+2 When we do arithmetic ch+1, it is incrementing address by only one, because character datatype size is one byte But for i+1, it is incrementing current address by 2, because integer data-type size is 2 byte I is an integer pointer which pointing memory address 7000, after execution of I++; I point to address 7002 , not 7001. The same is true of decrements. So that according to the data-type pointer arithmetic will give different result

Pointer comparison
If (p<q) printf ( p points to lower memory than q); Pointer comparison are used when two or more pointer point to common objects , such as an array . EG: A pair of stack routine are developed that store and retrieve integer values.

Pointer and arrays


There is a close relationship between pointers and arrays. Char str[30],*p; P=str; P has been set to the address of the first array element of string array variable str. To access 5th element in str , you could write str[4] or *(p+4).

Panimalar Engineering College

68

MC9212-Problem Solving and Programming Unit IV & V

Array of pointer
Like any other variable, you can also create pointer array variable, in which by referring single variable name with different subscript, you can able to hold more than one address of particular type of variable, the following variable p can able to hold address 10 integer variables at a time with subscript range from 0,1,29 Int *p[10]; p[3]= &n;

POINTER TO POINTER MULTIPLE INDIRECTION pointer to the pointer is called multiple indirection Pointer can also point to another pointer variable that point to the target value. This situation is called multiple indirection or pointer to pointer A variable that is pointing to pointer variable must be declared with ** instead of * E.g.: int **pp; Here pp is not pointer to integer variable, but pointer to an integer pointer variable, which in turn pointing to another integer variable To access the target integer value indirectly pointed by a pointer to pointer variable , you must apply asterisk operator twice Eg.: void main() X(3000) { 10 int x,*p,**pp; x=10; P(3500) p=&x; 3000 pp=&p; printf(%d,**pp); PP(7000) printf(%d,*p); 3500 } here both the print statement will print value as 10 INITIALIZING POINTER Local pointer will not be automatically initialized, but global pointer are automatically initialized to NULL If local pointer is declared, before it has been assigned a value, it contain unknown value If you try to use the pointer, that has not been assigned value, you will probably crash your program

DYNAMIC MEMORY ALLOCATION


Dynamic memory allocation means, the program can obtain memory while it is running Neither global variable nor local variable can be added during run time C supports two complete dynamic allocation system. Cs dynamic memory allocation functions are : 1. void * malloc(int no-of-bytes); 2. void *calloc(size_t nitems, size_t size); 3. void free(void *p); 4. void *realloc(void *ptr,size-t size)

void * malloc(int no-of-bytes)

Panimalar Engineering College

69

MC9212-Problem Solving and Programming Unit IV & V malloc will obtain memory from heap, here heap is the region of free memory size of the heap is unknown, is generally contain large amount of free memory char *p; p=malloc(1000); (or) p=(char *) malloc(1000); here pointer variable p pointing to the starting address of thousand bytes of memory allocated by malloc In c, a void pointer is automatically converted to the type of pointer on the left side of an assignment. But always explicit type casting is good practice the follwing example allocates space for 30 integers. Int *P1; P1=(int ) malloc(30*sizeof(int)); The malloc( ) function returns a pointer of type void, which means that you can assign it to any type of pointer After a succesful call, malloc( ) return pointer to the first byte of the region of memory allocated from the heap If there is not enough available memory to satisfy malloc() request ,an allocation failure occures and malloc( ) will return NULL So that proper way to allocate memory and check whether memory allocated or not is shown below P1=(int *)malloc(50); If(p1==NULL) { printf(out of memory); exit(1); } free(void *P) The free function is the opposite of malloc( ) in that it reallocate previously allocated memory to the system Once the memory has been freed, it may be reused by a subsequent call to malloc( ). Example void main() { char *cptr; clrscr(); cptr=(char *) malloc(50); printf("\nenter the name : "); scanf("%s",cptr); printf("\ndata stored in address %u is %s",cptr,cptr); getch(); } Output enter the name : kajendran data stored in address 1880 is kajendran

Panimalar Engineering College

70

MC9212-Problem Solving and Programming Unit IV & V void *calloc(size_t nitems, size_t size) calloc provides access to the C memory heap, which is available for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation. calloc allocates a block (nitems * size) bytes and clears it to 0 void *realloc(void *ptr,size-t size) Attempts to shrink or expand the previously allocated block to size bytes. Returns the address of the reallocated block which can be different than the original address. If the block cannot be reallocated or size == 0, realloc returns NULL. Here size could be greater or less to original size previously allocated Is used to changes the size of the previously allocated memory pointed by ptr to that specified by size PASSING FUNCTION TO OTHER FUNCTIONS / POINTER TO THE FUNCTION Pointer not only holding address of the variables, but it can also hold the address of the function, which is called function pointer A pointer to the function can be passed to another function as an argument. This allows one function transferred to another as similar to passing variable from one function to another Let us consider first function as guest function, and second function as a host function. The guest is passed to the host, where it can be accessed. Successive call to the host can pass different pointer When a host function accepts the name of a guest function as argument, the formal argument must identify that argument as a pointer to the guest function The syntax of the declaration function-pointer shown below. This pointer will be defined as formal- argument in host function, which will always point to the guest function data-type (*function-name) ( ) (or) data-type (*function-name)(data-type1, data-type2,) (or) data-type(*function-name)(data-type1 arg1,data-type2 arg2) Here the first data-type refers to the return-type of the function, data-type1, data-type2 are order and types of the formal-parameters of the function First-type of pointer declaration only will points the function which have no formal parameter as arguments, and have return-type as same as mentioned in function-pointer declaration The second and third function-pointer declaration, are useful to point to the function those have formal parameter list The host function declaration could be as follows return-type host-function-name(data-type (*fn_ptr)(data-type1,data-type2,), ) { /* body of the host-fuction */ }

Panimalar Engineering College

71

MC9212-Problem Solving and Programming Unit IV & V The first argument to the host function is pointer to the other function, remaining argument could be any other formal parameters Example #include<stdio.h> #include<conio.h> int do_arithmatic(int (*pf)(int a,int b)) { int a,b,c; clrscr(); printf("\n read A : "); scanf("%d",&a); printf("\n read B : "); scanf("%d",&b); c=(*pf)(a,b); return c; } int prod(int a,int b) { return a*b; } int add(int a,int b) { return a+b; } void main() { int i; i= do_arithmatic (prod); printf("\n the product is %d",i); getch(); i= do_arithmatic (add); printf("\n the sum is %d",i); getch(); } output read A : 10 read B : 20 the product is 200 read A : 20 read B : 5

Panimalar Engineering College

72

MC9212-Problem Solving and Programming Unit IV & V the sum is 25 in the above example do_arithmatic is an host-function, which will accept argument as any function those have return-type as integer and formal-parameter as two integer-arguemnts from the main first-type do_arithmatic accept argument as function prod, and second time add POINTER AND SINGLE DIMENSIONAL ARRAY one-dimensional array can be represented in terms of pointer and an offset We can define a one-dimensional array as a pointer. At runtime, we can allocate enough memory required to hold one-dimensional array elements using dynamic memory allocation feature We can declare one-dimensional array variable as pointer shown below data-type *ptvar; Rather than Data-type array[size]; and memory can be allocated for pointer variable using ptvar=malloc(size*sizeof(data-type)); Here size is the size of the array. The advantage of the using pointer variable to hold array of elements, instead of defining array variable is that we can determine the size of the data requires to store, at runtime and can allocate only required amount of memory This help us to avoid unnecessary memory allocation, which happen in array variable, where memory size can be determined only at compile time Example : the following example show how to use pointer to hold array of elements #include<stdio.h> #include<conio.h> #include<stdlib.h> output enter the array size: 5 enter number1 : 50 enter number2 : 20 enter number3 : 30 enter number4 : 45 enter number5 : 12 the value of array are : 50 20 30 45 12

void main() { int *ptr,i,n; clrscr(); printf("enter the array size: "); scanf("%d",&n); ptr=(int *) malloc(n* sizeof(int)); for(i=0;i<n;i++) { printf("enter number%d : ",i+1); scanf("%d",(ptr+i)); } printf("\n\n the value of array are : \n\n"); for(i=0;i<n;i++) printf("%7d",*(ptr+i)); getch(); }

Panimalar Engineering College

73

MC9212-Problem Solving and Programming Unit IV & V POINTER AND MULTIDIMENSIONAL ARRAY Since a one-dimensional array can be represented in terms of pointer and an offset, it is reasonable to except that a multidimensional array can also be represented with equivalent pointer notation A two dimensional array, for example, is actually collection of one dimensional arrays. Therefore, we can define a two-dimensional array as a pointer to a group of contiguous onedimensional arrays. Thus a two dimensional array declaration can be written as Data-type (*ptvar)[size]; Rather than Data-type array[dimension 1][dimension 2]; This concept can be generalized to higher-dimensional arrays; that is Data-type (*ptvar) [dimension 1] [dimension 2][dimension n - 1]; Rather than Data-type array [dimension1][dimension 2][dimension n]; All dimensions must have only positive integer as values. Pointer variable must always enclosed with in the ordinary brackets Suppose X is a two dimensional integer array having 10 rows and 20 columns. We can declare X as int (*X)[20]; Rather than int X[10][20]; In the first declaration, X is defined to be a pointer to a group of contiguous, one dimensional 20-element integer arrays Thus X points to the first 20 element array, which is actually the first row (row 0) of the original two dimensional array Similarly (X+1) points to the second 20-element array, which is the second row (row 1) of the original two dimensional array and so on, as illustrated as below 1st one-dimensional array

(X+1)

........
(X + 9 ) *( X + 9)

2nd one-dimensional array

10th one-dimensional array *(X + 9) + 3 *(* (X+9) + 3)

The item in row 10, column 4 can be accessed by writing either Or X[9][3] *(* ( X+ 9 ) + 3 )

Panimalar Engineering College

74

MC9212-Problem Solving and Programming Unit IV & V Consider the second form, first, note that ( X + 1 ) is a pointer to row 2, therefore the object of this pointer , ( X + 1 ), refers to the entire row. Since row 2 is a one-dimensional array, * ( X + 1 ) is actually a pointer to the first element in row 2. we now add 5 to this pointer. Hence, ( * ( X + 1) + 4 ) is pointer to element 5 in row 2. The object of this pointer, *( * ( X + 1 ) + 4 , therefore refers to the item in column 5 of row 2, which is X[1][4] Now consider a three-dimensional floating point array T. This array can be defined as float (*T)[20][30]; Rather than float T[10][20][30]; In the first declaration, T is considered as a pointer to a group of contiguous twodimensional, 20 X 30 floating point array. Hence T points to the first 20 X 30 array, (T+1) points to the second 20 X 30 array, and so on. An individual array element within a multidimensional array can be accessed by repeated use of the indirection operator The following example demonstrate how to create two dimensional array variable using pointer and dynamic memory allocation #include<stdio.h> #include<conio.h> #include<stdlib.h> #define MR 20 Output void main() { enter row & col size of matrix : 3 X 3 int (*ptr)[10],i,j,nr,nc; clrscr(); enter the values of matrix (3 X 3) printf("enter row & col size of matrix : "); ==================== scanf("%d X %d",&nr,&nc); 1 2 3 for(i=0;i<nr;i++) 4 5 6 ptr=(int *)malloc(nc* sizeof(int)); 7 8 9 printf("\nenter the values of matrix (%d X %d)",nr,nc); printf("\n=====================\n"); for(i=0;i<nr;i++) for(j=0;j<nc;j++) scanf("%d",(*( ptr + i ) + j)); printf("\ndata\s pointed by ptr shown below\n "); printf("=======================\n"); for(i=0;i<nr;i++) { for(j=0;j<nc;j++) printf("%7d",*(*( ptr + i ) + j)); printf("\n"); } getch(); } Panimalar Engineering College Datas pointed by ptr shown below =================== 1 2 3 4 5 6 7 8 9

75

MC9212-Problem Solving and Programming Unit IV & V Ptr is a pointer which can hold two dimensional array elements, row can be of any size and column can be maximum of 20 elements (*(ptr+0)+0 ) retrieves the address of the 1st row, 1st column element, *( *(ptr+0)+0) retrieves the data stored in the 1st t row, 1st column Similarly (*(ptr+3)+4 ) retrieves the address of the 4th row, 5th column element, *( *(ptr+3)+4) retrieves the data stored in the 4th row, 5th column

Array of Pointers Already we discussed array of pointer in the previous unit, the following program demonstrate, how array of pointer can be manipulated #include<stdio.h> #include<conio.h> #include<stdlib.h> output #define N 3 enter number of columns void main() { int *p[N],c,row,col; clrscr(); printf("enter number of columns"); scanf("%d",&c); for(row=0;row<N;row++) p[row]=(int *) malloc(c* sizeof(int)); printf(" enter %d X %d matrix data \n",N,c); for(row=0;row<N;row++) for(col=0;col<c;col++) scanf("%d",p[row]+col); printf(\nResult); for(row=0;row<N;row++) { for(col=0;col<c;col++) printf("\t%d",*(p[row]+col)); printf("\n"); } getch(); } P[0] P[1] P[2] 1st one-dimensional array 2nd one-dimensional array 3rd one-dimensional array *(P[2]+0) * (X[2] + 3) (X [ 2] + 3) enter 3 X 4 matrix data 99 88 77 23 11 22 22 32 65 56 34 43 Result 99 11 65 88 22 56 77 22 34 23 32 43

Panimalar Engineering College

76

MC9212-Problem Solving and Programming Unit IV & V P[0] pointing to the first one dimensional array, p[1] pointing the second one dimensional array, and so on. This is similar to two dimensional array To access data in the 3rd row 2nd column use *(p[2]+1)

PRE DEFINED / LIBRARY FUNCTIONS 1.String handling functions string.h header file consists collection of functions, those are very useful to manipulate character array or string. The follows list shows some of the useful, string handling functions a) strcpy (char * s1, char *s2) here s1 s the destination string and s2 is the source string. After execution of this function, content of the variable s2 will be copied into the variable s1 example char a[ ]=welcome, b[40]; strcpy(b,a); printf(%s,b); printf will print value of b as welcome b) strcat(char *s1, char *s2) this function will concatenate value of string variable s1 with s2, the final result will be placed back to the variable s1 itself example char s1[ ]=Welcome , s2[ ]= to C Program; strcat(s1,s2); printf(%s,s1); now value of s1 is welcome to C program

c) strncat(char *s1,char *s2, unsigned int N) This work in the same way as strcat, except it will concatenate whole s1 value and, only the first N number of character from s2 and return the result back to the variable s1 itself example char s1[ ]=Welcome , s2[ ]=to C Program; strcat(s1,s2); printf(%s,s1,4); now value of s1 is welcome to C. when concatenating both the string, only the first 4 character of the second string will concatenated with value of the string s1

d) size_t strlen(char *s) It returns the number of characters in string s, not counting the terminating null character. example char s1[ ]=Hello ; int len; len=strlen(s1); now len will have value as 5 e) int strcmp(char *s1, char *s2) it will compares string s2 with s1 and return result as integer

Panimalar Engineering College

77

MC9212-Problem Solving and Programming Unit IV & V Returns a value that is < 0 if s1 is less than s2; == 0 if s1 is the same as s2; > 0 if s1 is greater than s2. Example: void main( ) { Output: char s1[ ]="Hello",s2[ ]="hello"; Hello is less than hello int flag; flag=strcmp(s1,s2); if(flag < 0) printf("%s is less than %s",s1,s2); else if(flag == 0) printf("%s and %s both are equal",s1,s2); else printf("%s is greater than %s",s1,s2); getch(); } variable flag will have value as -32, Because ASCII value of H , h are 72, 104 H h = 72 104 = -32

f) int strcmpi(char *s1, char *s2) (or) int stricmp(char * s1, char *s2) These functions will works in the same way as strcmp, except these will ignore the case of the text In the above example replace strcmp(s1,s2) with stricmp(s1,s2), and run the program. The it will produce output as Hello and hello both are equal g) int strncmp(char *s1,char *s2, int N) this is same as strcmp except, it will compare only first N number of character from both the string s1 and s2 example char s1[ ]="Welcome",s2[ ]="Well"; int flag; flag=strncmp(s1,s2,3); now flag=0, because first three character of both the string are equal

h) char *strlwr(char *s) it will converts s to all lowercase, and return back to s example char s1[ ]="RAJARAJAN"; strlwr(s1); printf(%s,s1); the output will be rajarajan

i) char *strupr(char *s) it will converts s to all uppercase, and return back to variable s example char s1[ ]="arun"; strupr(s1); Panimalar Engineering College

78

MC9212-Problem Solving and Programming Unit IV & V printf(%s,s1); the output will be ARUN

j) char *strrev(char *s) this function will reverse the string s and return the result in s itself example char s1[ ]="Panimalar"; strrev(s1); printf(%s,s1); the output will be ralaminaP

k) char *strchr (char *s1,char ch) It returns a pointer to the first occurrence of the character c in str; if c does not occur in str, strchr returns NULL. Example void main() { char *s1="I am here", *s2, ch='h'; clrscr(); Output

" h " is found in " I am here " at 6 s2=strchr(s1,ch); if(s2==NULL) printf("\n %c is not found in %s",ch,s1); else printf("\n \" %c \" is found in \" %s \" at %u",ch,s1,((s2-s1)+1)); getch(); } l) char *strset(char *s, char ch); - it sets all characters in s to c, quits when the first null character is found and returns a pointer to s. example void main() { Output char *s1="I am here",ch='h'; hhhhhhhhh strset(s1,ch); printf("%s",s1); } m) char *strstr(const char *s1, const char *s2) It finds the first occurrence of substring s2 in s1 and returns a pointer to the element in s1 that contains s2 (points to s2 in s1), or NULL if s2 does not occur in s1. Example void main() Output { " come " found in " welcome " at 4 Panimalar Engineering College

79

MC9212-Problem Solving and Programming Unit IV & V char s1[ ]="welcome",s2[ ]="come",*ptr; ptr=strstr(s1,s2); if(ptr!=NULL) printf(" \" %s \" found in \" %s \" at %u",s2,s1,((ptr - s1)+1)); getch(); } 2) Math.h library functions i) double ceil(double x) rounds up returns the smallest integer greater than or equal to x. example ceil(12.9)=13 ceil(15.2)=16 ii) double floor(double x) rounds down returns largest integer less than or equal to x. example floor(12.9)=12 floor(15.2)=15 iii) double pow(double x, double y) return the result of the x y as result example pow(2,3)=8 pow(3,4)=81 iv) double sqrt(double x) - calculates square root & returns the result example sqrt(4)=2 floor(25)=5 v) int abs(int x) return the absolute value of an integer example abs(-4)=4 floor(25)=25 vi) double fabs(double d1) - absolute value of a floating-point number example fabs(-54.3)=54.3 floor(25.22)=25.22 vii) viii) ix) x) xi) xii) xiii) double fmod(double x, double y) it will do integer division on floating-point number and return remainder as result. For example fmod(11.5,2)=1.5 double exp( double x) it return the e x as result. E.g.: exp(2.3)=19.9741 double log10(double x) it return log10(x) as sresult double log(double x) - it return ln(x) as reult double sin(double radian) double cos(double radian) double tan(double radian)

3. stdlib library functions i) int atoi(const char *s) - Converts a string to an int & returns the converted value of the input string. If the string cannot be converted, the return value is 0. Panimalar Engineering College

80

MC9212-Problem Solving and Programming Unit IV & V { example void main() output char s[]="101"; int i=atoi(s); printf("the value of i is %d",i); getch(); The value of i is 101

ii) iii) iv)

} long atol(const char *s) Converts a string to an long & returns the converted value of the input string. If the string cannot be converted, the return value is 0. double atof(const char *s) converts a string to floating point number, if sting contain valid number otherwise, return 0.0 char *itoa(int value, char *string, int radix) This is just opposite to the function atoi. It is used to convert integer to string, the possible values for radix are 2, 8, 10, and 16 based on the radix string contain different data. For example if radix is 2 then the binary value of the integer value will be stored in string. If radix is 10 then string contain passed integer value as it is. So that according to the radix conversion character could be either decimal base, binary base, octal base, or hexadecimal base Example void main() { int a; clrscr(); printf("enter any whole number "); scanf("%d",&a); printf("\n itoa(a,s,2) = %s",itoa(a,s,2)); printf("\n itoa(a,s,8) = %s",itoa(a,s,8)); printf("\n itoa(a,s,10) = %s",itoa(a,s,10)); printf("\n itoa(a,s,16) = %s",itoa(a,s,16)); getch(); } output enter any whole number 10 itoa(a,s,2) = 1010 itoa(a,s,8) = 12 itoa(a,s,10) = 10 itoa(a,s,16) = a

v)

char *ltoa(long value, char *string, int radix) - converts long to string. For a decimal representation, use radix=10. For hexadecimal, use radix=16, returns a pointer to the argument string. void exit(int status) - terminates program Before terminating, buffered output s flushed, files are closed, and exit functions are called. Status could any integer, either or non-zero. Value zero is to indicate normal program termination, any other non zero is to indicate abnormal program termination void abort(void) this is alternate to exit function is used to abnormally terminates a process

vi)

vii)

Panimalar Engineering College

81

MC9212-Problem Solving and Programming Unit IV & V

CHARACTER HANDLING FUNCTIONS int isalnum(int c); int islower(int c); int isalpha(int c); int isprint(int c); int isascii(int c); int ispunct(int c);

int iscntrl(int c); int isspace(int c); int isdigit(int c); int isupper(int c); int isgraph(int c); int isxdigit(int c);

The is... macros classify ASCII coded integer values by table lookup. Each macro is a predicate that returns a non-zero value for true and 0 for false. isascii is defined on all integer values. The other is... macros are defined only when isascii(c) is true or c is EOF. You can make each macro available as a function by undefining it (with #undef).

Return Value: The is... macros return a non-zero value on success. For each macro, success is defined as follows:

1. isalpha: c is a letter (A to Z or a to z) 2. isascii: the low order byte of c is in the range 0 to 127 (0x00--0x7F) 3. iscntrl: c is a delete character or ordinary control character (0x7F or 0x00 to 0x1F) 4. isdigit: c is a digit (0 to 9) 5. isgraph: c is a printing character, like isprint, except that a space character is excluded 6. islower: c is a lowercase letter (a to z) 7. isprint: c is a printing character (0x20 to 0x7E) 8. ispunct: c is a punctuation character (iscntrl or isspace) 9. isspace: c is a space, tab, carriage return, new line, vertical tab, or formfeed (0x09 to 0x0D, 0x20) 10. isupper: c is an uppercase letter (A to Z) 11. isxdigit: c is a hexadecimal digit (0 to 9, A to F, a to f)

USER DEFINED DATA TYPES / CUSTOM DATATYPE


There are five ways to create a custom data type are 1. Structure 2. union 3. enumeration 4. type def 5. bit field

Why do we need custom data type? The array, which is a data structure whose elements are all of the same data type. But it is not possible to store different types data with in the same variable itself But Structure, in which the individual elements can differ in type. Thus single structure might contain integer elements, floating-point elements and character elements. Pointer, arrays and other structures can included as elements within structure. The individual structure elements are referred as members (or) The variables that make up the structure are called members Generally all of the members of a structure are logically related

Panimalar Engineering College

82

MC9212-Problem Solving and Programming Unit IV & V

STRUCTURE AND UNIONS Introduction


If we want to represent a collection of items of different types using a single type in that case we can make use of structures. C supports a constructed data type known as structures packing data of different types. Structures are used to organize complex data. Example: Time : seconds, minutes, hours. Date : day, month, year. Book : author, title, price, year. City : name, country, population. Inventory: item, stock, value. DEFINING A STRUCTURE Consider a book database consisting of book name, author, number of pages, and price. struct book_bank { char title[20]; char author[15]; int pages; float price; }; The keyword struct structure to hold the details of four data fields, namely title, author, pages, and price. These fields are called structure elements or members. Each member belongs to a different type of data. Book_bank is the name of the structure and is called the structure tag. The tag name may be used to declare the variables that have the tag structures. The general form of a structure definition is: E.g.: Syntax: Struct employee Struct structure-type-name { { char name [30]; data-type member1; char design [30]; data-type member2; double Sal; char dept[30]; }emp;

}[structure- variables list;];

structure-name could be any user-defined name, and member1, member2 are individual member of the structure of any data-type In this declaration the keyword struct is required; It tells the compiler a structure is being declared A semicolon must terminate the declaration of the structure. At this point, no variable has actually been created only the form of data has been defined.

Panimalar Engineering College

83

MC9212-Problem Solving and Programming Unit IV & V

1. The template is terminated with a semicolon. 2. While the entire definition is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. 3. The tag name such as book_bank can be used to declare structure variables of its type, later in the program. DECLARING STRUCTURE VARIABLES A structure variable declaration is similar to the declaration of variables of any other data types. 1. It includes the following elements. 2. The keyword struct. 3. The structure tag name. 4. List of variable names separated by commas. 5. A terminating semicolon. Eg: struct book_bank,book1, book2, book3; Each one of these variables has four members as specified by the template. The complete declaration: struct book_bank { char title[20]; char author[15]; int pages; float price; }; struct book_bank,book1, book2, book3; (or) struct book_bank { char title[20]; char author[15]; int pages; float price; } book1, book2, book3; The use of tag name is optional. It is also allowed to combine both the structure definition and variables declaration in one statement. declare a variable of type EMPLOYEE, you could write as follows struct employee emp1; (or) struct employee em[100]; employee *p; The first variable is single employee variable, and the second variable is an employee array variable, which hold 100 employee object, p is an structure pointer variable of type employee You may also declare structure variable, when you declare a Structure it self; Struct employee {..}emp1,emp2,*p; When a structure variable is declared , the compiler automatically allocates sufficient memory to accommodate all of its members.

Panimalar Engineering College

84

MC9212-Problem Solving and Programming Unit IV & V

For e.g.: for emp1, c allocates 98 bytes of memory Note: Structure definition appears at the beginning of the program file, before any variables or functions arte defined. They may also appear before the main, along with macro definitions, such as #define. TYPE-DEFINED STRUCTURES The keyword typedef is also used to define a structure. The general form of it is: typedef struct { type member1; type member2; ------- ---------------- ----------} type_name; The type_name represents structure definition associated with it and therefore can be used to declare structure variables as: type_name variable1,variable 2,..; We cannot define a variable with typedef declaration.

ACCESSING STRUCTURE MEMBERS To access individual member of structure (.)dot operator ( period operator) is used if variable is ordinary structure variable If variable is structure pointer() structure pointer operator is used to access individual member of structure E.g.: emp1.sal=5000; (or) p->sal=5000 ; (or) (*p).sal=5000; em[10].sal=6000; STRUCTURE INITIALIZATION The member of the structure variable can be assigned initial values in much the same manner as the elements of an array The initial value must be appear in the order in which they will be assigned to their corresponding structure members, enclosed in braces and separated by commas. The general form is struct structure-name variable= { value1, value2,}; Examples struct account customer={2000, R, John,5000,{12,10,2003}}; struct employee emp_list[ ]={ {Amala,Clerk,5000,10}, {Bala,Admin,10000,20}, Panimalar Engineering College

85

MC9212-Problem Solving and Programming Unit IV & V

{Raja,programmer,15000,10}}; Here customer is an ordinary of type customer, emp_list is an array variable of type employee, having size as 3. for array variables inner flower braces are not necessary, it is only for our understanding purpose The compile time initialization of a structure variable must have the following elements: 1. The keyword struct. 2. The structure tag name. 3. The name of the variable to be declared. 4. The assignment operator= 5. A set of values for the members of the structure variable, separated by commas and enclosed in braces. 6. A terminating semicolon. Examples:(1) main () { struct { int weight; float height; } student = {60,180.45}; ------- ------------ ------} In the above example the value 60 to student.weight and 180.45 to student.height.It is also possible to initialize two structure variables. (2) Another method is to initialize a structure variable outside the function as shown below: struct st_record { int weight; float height; } student 1= {60,180.45}; main () { struct st_record student2 = {53,170.60}; ------- ------------ ------} RULE FOR INITIALIZING STRUCTURES There are few rules to keep in mind while initializing structure variables at compile time - We cannot initialize individual members inside the structure template

Panimalar Engineering College

86

MC9212-Problem Solving and Programming Unit IV & V

The order of values enclosed in braces must match the order of members in the structure definition It is permitted to have a partial initialization. We can initialize one the first few members and leave the remaing blank. The uninitialized members should be only at the end of the list The uninitialized members will be assigned default value as follows: Zero for integer and floating point numbers \0 for character and string

COPYING AND COMPARING STRUCTURE VARIABLES Two variables of the same structure type can be copied the same way as ordinary variables.If person1 and person2 belong to the same structure, then the following statements are valid: person1 = person2; person2 = person1; however statement such as person1 == person2; person2 != person1; Are not permitted. C does not permit loginal operations on structure variables. In case, we need to compare them. We may do so by comparig members individually WORD BOUNDARIES AND SLACK BYTES Computer stored sturctues using the concept of word boundary. The size of a word boundary is machine dependent. In a computer with two byte word boundary, the members of structure are stored left aligned on the word boundaries as shown below. 0 char 1 2 int 3

Slack byte A character data takes one byte and an integer takes tow bytes. One byte between them is left unoccupied. This unoccupied byte is known as the slack byte when we declare structure variables, each one of them may contain slack bytes and the values stored in such slack bytes ae undefined. Due to this, even if all members of two variables are equal, their strucutures do not necessariely compare equal

OPERATIONS ON INDIVIDUAL MEMBERS The individual members are identified using the member operator dot. A member with the dot operator along with its structure variable can be treated like any other variable name and therefore can be manipulated using expressions and operators. STRUCTURE WITHIN STRUCTURE One structure may be defined as a member of another structure. In such a situation, the declaration of the embedded structure must appear before the declaration of the outer structure Panimalar Engineering College

87

MC9212-Problem Solving and Programming Unit IV & V

example structure date { int month; int day; int year; } structure account { int custno; char custtype; char custname[40]; float balance; struct date lastpayment; }oldcustomer, newcustomer; The second structure (account) contain another structure (date) as one of its members. Note that declaration of date precedes the declaration of account. To assign the date of the last payment for oldcustomer, you have to use double dot operators like as follows Oldcustomer.lastpayment.day=12 Oldcustomer.lastpayment.month=10 Oldcustomer.lastpayment.year=2003

ARRAYS OF STRUCTURE VARIABLE and ARRAY WITHIN STRUCTURE Array variables can be created from structure, as we create from any other data-types. The period operator can be extended to array of structures, by writing Array-name [expression].member-name Array-name [expression].member-name will refer to specific member within a particular structure Example The following program demonstrate how to create array of structure variable of type Student. Note that student has individual member as marks, which is an integer array variable. Also demonstrate how values can be assigned to individual member of the structure struct Student{ char rollno[6], sname[25]; int marks[5]; }; void main() { int i,j; struct Student st[5]; clrscr(); for(i=0;i<5;i++) { printf("\nenter student Information %d",i+1); printf("\n=================="); Output enter student Information 1 ================ Roll Number? MC4k01 Stud Name? kannan mark 1? 55 mark 2? 66 mark 3? 45 mark 4? 76 mark 5? 56

Panimalar Engineering College

88

MC9212-Problem Solving and Programming Unit IV & V

printf("\nRoll Number? "); scanf("%s",st[i].rollno); printf("\nStud Name? "); scanf("%s",st[i].sname); for(j=0;j<5;j++) { printf("\nmark %d? ",j+1); scanf("%d",&st[i].marks[j]); } } getch(); } STRUCTURE AND POINTER The beginning of the address of the structure can be accessed in the same manner as any other address, through the use of the address (&) operator. Thus if variable represents structure-type variable then, &variable represents the starting address of that variable The general syntax of declaring structure variable is struct structure-name *pointer-variable; Once the structure pointer is declared you can assign address of the same type of structure variable shown below pointer-variable=&structure-variable; Example struct student *sptr; struct student st1={2k4202, Jayachandar,{50,90,20,55,45}}; sptr=&st1; Now individual member can be accessed using pointer variable is possible, either using pointer operator (->) or dot operator as show below sptr->marks[0]=78; (or) (*sptr).marks[0]=78; Here marks is a member of student and is an integer array variable having size 5.

THREE WAY TO ACESS STURCTURE MEMBER


There are three way to access individual members of structure. Consider the following example typedef { int x; int y; }VECTOR; Panimalar Engineering College

89

MC9212-Problem Solving and Programming Unit IV & V

VECTOR v,*ptr; ptr=&v; The identifier ptr is kanow as pointer that hase been assigned the address of the structure variable v. now the members can be accessed in three ways: o Using dot notation : v.x o Using indirection notation : (*ptr).x o Using selection notation : ptr -> x

SELF REFERENTIAL STRUCTURE & LINKED LIST


If structure having member as pointer variable to the same structure, the structure is said to be self referential structure The general syntax of self referential structure shown below structure structure-name { data-type member1; data-type member2; struct struct-name *name; }; Self-referential structures are very useful in applications that involves linked data structure, such as list and trees The basic idea of linked data structure is that each component within the structure includes a pointer indicating where the next component can be found. Therefore the relative order of the components can easily be changed simply by altering the pointers In addition, individual components can easily be added or deleted again by altering the pointer. As a result linked data structure is not confined to some maximum number of components. Rather, the data structure can expand or shrink in size as required Fig (a) Red Red Green Green Blue Blue NULL NULL

Figure (b) insertion of new node olive

Red

Green

Blue

NULL

Figure (c)

olive

Panimalar Engineering College

90

MC9212-Problem Solving and Programming Unit IV & V Figure (a) demonstrate how listed list can be created, figure (b) describes how new node con be inserted in the existing linked list, figure (c) describes how existing node removed from linked list Program The following program demonstrate how linked list are created and maintained #include<stdio.h> #include<conio.h> #include<math.h> #define line printf("\n==========================================="); struct student{ char rollno[8], sname[25]; struct student *next; }; void main() { int i,j; struct student *start,*node,*end; char ch; start=node=end=NULL; do { clrscr(); node=(struct student*) malloc(sizeof(struct student)); line; printf("\n student enrollment screen"); line; Output printf("\nRoll Number "); ================================ scanf("%s",node->rollno); student enrollment screen printf("\nStud Name "); ================================ scanf("%s",node->sname); Roll Number 2k4203 node->next=NULL; Stud Name guna ================================ if(start==NULL) do you wish to insert onemore record (Y/N):n { ================================ start=end=node; list of enrolled students are } =============================== else 2k4201 vimal { 2k4202 kumar end->next=node; 2k4203 guna end=node; ================================ } line; Panimalar Engineering College

91

MC9212-Problem Solving and Programming Unit IV & V

printf("\n do you wish to insert onemore record (Y/N): "); flushall(); ch=getchar(); }while(ch=='y' || ch=='Y'); clrscr(); line; printf("\n list of enrolled students are"); line; node=start; while(node->next!=NULL) { printf("\n%s\t%s",node->rollno,node->sname); node=node->next; } printf("\n%s\t%s",node->rollno,node->sname); line; getch(); } ADVANTAGE OF LINKED LISTS A linked list is dynamic data structure. Therefore the primary advantage of the linked list over arrays is that linked list can grow or shrink in size during the execution of a program. A linked list can be made just as long as required Another advantage is that a linked list does not waste memory space. It uses memory that that is just needed for the list at any point of time. This is because it is not necessary to specify the number of nodes to be used in the list The third advantage is that the linked list prodives flexibility is allowing the items to be rearranged efficiently. It is easier to insert or delete items by arrayning the links The major limitation of linked list is that the access to any arbitary item is little cumbersome and time consuming TYPES OF LINKED LISTS There are different types of linked list. The one we dicussed so far is known as linear linked list. The other linked list are o Circular linked list o Two-way or doubly linked list o circular doubly linked list The circular linked lists have no beginning and no end. The last item points back to the first item The dounly linked list uses dounle set of pointers, one pointing to the next item and other pointing to the preceding item. This allows us to traverse the list in either direction

Panimalar Engineering College

92

MC9212-Problem Solving and Programming Unit IV & V

HOW TO PASS STRUCTURES TO FUNCTIONS


There are several different ways to pass structure-type information to or from functions. Structure members can be transferred individually, or entire structure can be transferred. Individual structure members can be passed to a function as arguments in the function call, and single structure member can be returned via the return statement Each structure member is treated the same as ordinary single-valued variable You can also pass whole structure as argument to function, sometime you can pass structure to the structure pointer variable The following program demonstrates how to pass structure to function in different ways. First function printEm() accepts argument as structure employee itself Second function printPtr() accepts formal argument as pointer to the structure Third function increment() accepts formal parameter as individual member of the structure and increments the by the percentage passed as argument to function Program #include<string.h> struct date{ int day; char sep1; int mon; char sep2; int year; }; struct employee{ char ename[20]; struct date doj; double basic; }et; void printEm(struct employee tmp) { printf("\n\t employee name = %s",tmp.ename); printf("\n\t date of join = %02d%c%02d%c%02d", tmp.doj.day, tmp.doj.sep1, tmp.doj.mon, tmp.doj.sep2, tmp.doj.year); printf("\n\t salary = %9.2f",tmp.basic); printf("\n\npress any key to continue...."); getch(); } void printPtr(struct employee *tmp) { printf("\n\t employee name = %s",tmp->ename); printf("\n\t date of join = %02d%c%02d%c%02d",tmp->doj.day,tmp>doj.sep1,tmp->doj.mon,(*tmp).doj.sep2,tmp->doj.year); Panimalar Engineering College Output employee name = kannan date of join = 12/10/99 salary = 2200.00 press any key to continue.... employee name = arun date of join = 11/01/99 salary = 1000.00 salary = 4000.00

93

MC9212-Problem Solving and Programming Unit IV & V printf("\n\t salary } = %9.2f",(*tmp).basic);

double increment(double sal,double percent) { return sal+sal*(percent/100); } void main() { int i; struct employee *sptr; struct employee emp[]={"kannan",{12,'/',10,'/',99},2000, "arun",{11,'/',1,'/',99},1000}; struct employee e1={"Balan",{9,'/',9,'/',3},4000}; clrscr(); emp[0].basic=increment(emp[0].basic,10); for(i=0;i<2;i++) printEm(emp[i]); sptr=&e1; printPtr(sptr); getch(); }

UNION
Unions are same as structure contain members whose individual data type may differ from one another. However, members within the union all share the same storage location with in the computers memory. Thus, unions are used to conserve memory But each member with in structure is assigned its own unique storage location They are useful for application involving multiple members, where only any one of the member required to hold values at any one time The general syntax of the union shown below union union-name { data-type member1; data-type member2; }[varaibale1, variable2,]; Where union is a required keyword and other term have the same meaning in the structure definition Memory allocated to union variable is equal to the size of the member having the largest size All other member will share the same memory. so that only one member of union can be assigned value at any one time Panimalar Engineering College

94

MC9212-Problem Solving and Programming Unit IV & V Example #include<stdio.h> #include<conio.h> union myUnion { int size; char color; }y; void main( ){ union myUnion one; one.size=22; y.color='y'; printf("\n y.color = %c",y.color); printf("\n y.size = %d",y.size);

Output y.color = y y.size = 121 y.color = A y.size= 65

y.size=65; printf("\n y.color = %c",y.color); printf("\n y.size= %d ",y.size); } In the above example myUnion has two members. First one is size having data type as int, requires two bytes of memory The second member is color having data type as char, which requires one byte of memory. Among two members of union myUnion, memory required of size larger than other member color. So that for any instance of myUnion variable will be allocated two bytes of memory, which will be shared by both the members of the myUnion If myUnion could be structure, 3 bytes of memory will be allocated In the above example only for variable color we are assigning value as y, and variable size have not been initialized yet. Even though when we are printing the value of variable size, it is printing value as 121. This indicates that both size and color, shares the same memory Command line parameters - an argument to main ( ) Sometimes it is useful to pass information into a program from command line itself. A command line argument is the information that follows the programs name on the command line of the operating system. If you would like to pass argument from command line, the definition main function should be altered, and you have to define two special formal parameters argc and argv in main function argc is first formal parameter of type int, and argv is second formal parameter of character pointer array variable example: filename=cmdarg.c Output # include < stdio.h > # include < conio.h > void main (int argc, char * argv [ ] ) { if (argc = = - 1) Panimalar Engineering College d:\>cmdarg one two there no. of arguments are 3 they are one two three

95

MC9212-Problem Solving and Programming Unit IV & V { printf( please try to this program from command line); printf( \n usage: command list of argument); exit (0); } printf( no. of argument are %d , argc); printf( \n they are \n; for (i = 0 ; i< argc ;i++) printf(\n\t %s,argv[i]);

} program for function that return pointer # include < stdio.h >

char * match (char c, char *s ) { while ( c! = *s & & *s ) s ++; return s; } void main ( ) { char s [ 80] ,* p, ch; printf( enter string ); scanf(%s,s) ; printf( enter char to search= ); ch=getchar(); p = match(ch,s); if(p==NULL) printf(\n %c not found in the given string ,ch); else printf(\n %c found in the given string at location %d, ( p s)); }

THE C PREPROCESSOR
The preprocessor is a program that process the source code before it passes through compilers. It operates under the control of what is known as preprocessor directives Preprocessor dircective are placed in the source before the main line The C preprocessor is a collection of special statements, called directives, that are executed at the beginning of the compilation process The #include and #define statements are preprocessor directives. Additional preprocessor directives are #if, #elif, #else, #endif, #ifdef, #ifndef, #line and #undef The preprocessor also includes three special operators:defined, #, and ## These directives can be divided into three categories: o Macro substitution directive o File inclusion directives o Compiler control directives Panimalar Engineering College

96

MC9212-Problem Solving and Programming Unit IV & V MACROS SUBSTITUTION We have already seen that the #define statement can be used to define symbolic constants within a C program A the beginning of the compilation process, all symbolic constants are replaced by their equivalent text #define statement not only used to define symbolic constant, but also can define macros Macro is single identifiers that are equivalent to expressions, compound statement or group of statements. Macro resembles function in this sense But they are defined in different manner than function. Function and macros are treated differently during the compilation process Before compilation, all the macro call will be replaced by the content of the macro If macro have multiple line, every line must ends with backward slash (\), except the last There are three different types of macro substitution. They are o Simple macro substitution o Argumented macro substitution o Nested macro substitution Example #include<stdio.h> #define AREA length * width /*simple macro substitution*/ #define SQUARE(a) (a *a) /* argumented macro substitution */ #define CUBE(x) ( SQUARE (x) * x ) /* nested macro substitution */ /* multiline macro substitution */ #define line printf("\n"); \ for(i=0;i<30;i++) \ printf("="); void main() Output { enter length and width of square 20 10 int i; float length,width,m=3; ============================== clrscr(); area of squeare 200.00 printf("enter length and width of square "); ============================== scanf("%f %f",&length,&width); line; printf("\n area of squeare %9.2f",AREA); printf(\n m^3=%d,CUBE(m)); line; n=40; getch(); } The difference between macro and function are listed below M A C RO FUNCTION Content of the macro will be pasted in the Content of the function will not be pasted in place of macro call, before compilation. the place of function call. instead function will be individually compiled After compilation, the object program does After compilation, one copy of the function not have macro definition definition will be maintained in object file Panimalar Engineering College

97

MC9212-Problem Solving and Programming Unit IV & V Macro defined program will take huge amount of memory for object program Macro defined program will be take less amount of processor time Macro does not have return type #define statement is necessary to define macro Function defined program will take less amount of memory for object program Function defined program will take huge amount of processor time Function must have return type #define statement not necessary to define function

FILE INCLUSION The external file containing fiunctions or macro definitions can be included as part of program so that we need not rewrite those functions or macro definition. This is achieved by pre-processor directives #include filename where the filename is the name of the file containing the reqired definitions or functions. At this point the pre processor insert the entire content of the filename into the source code of the program. When the filename included within the double quotation mark, the search for the file is made first in the current working directory and then in the stranard include indectory Alternatively this directive can take the form # include <filename> In this case the file is searched only in the then in the stranard include indectory COMPILER CONTROL DIRECTIVES Preprocessor directive mostly appear at the beginning of a program, but this is not firm requirement. It may appear anywhere with the program. however, the directive will apply only to the portion of the program following its appearance The #if, #elif, # else and #endif directives are used most frequently. They permit conditional compilation of the source program, depending on the value of one or more true/false conditions. They are sometimes used in conjunction with the defined operator, to determine whether or not a symbolic constant or a macro has been defined within a program The following program demonstrate how to use preprocessor in your program Example #include<stdio.h> Output #include<conio.h> #ifdef N #else #define N 5 #endif /* (or) #ifndef N #define N 5 #end if (or) #if defined(N) Panimalar Engineering College enter data 5 data to sum 10 20 30 40 50 sum = 150 total number of data = 5

98

MC9212-Problem Solving and Programming Unit IV & V #else #endif */ void main() { int i,data,sum=0; printf("enter data %d data to sum\n",N); for(i=0;i<N;i++) { scanf("%d",&data); sum+=data; } printf("\n sum = %d \n total number of data = %d",sum,N); #undefN /*printf("the number of data = %d",N); //this statement will produce error*/ getch(); } In the above program, symbolic constant have not been defined , so that #ifdef N will return false, and else part will executed which will define symbolic constant N and it set to value 5 #define N 5

The stringizing operator( # )


It allows a formal argument within macro definition to be converted to a string. If formal argument in a macro definition is preceded by this operator, the corresponding actual argument will automatically be enclosed in double quotes Any special character such as ', " and \ will be automatically converted into their corresponding escape sequence characters ( e.g.: \', \" and \\ ) In addition the resulting string will automatically concatenated with any adjacent strings Example Output this is just string constant without without quotation #include<stdio.h> end of the program #include<conio.h> #define display(text) printf(#text "\n") void main( ) { display (this is just string constant without without quotation); display (end of the program); getch(); }

Panimalar Engineering College

99

MC9212-Problem Solving and Programming Unit IV & V

The token-passing operator ( ## ) This operators causes the individual items with in a macro definition to be concatenated, thus forming single item The general purpose of the token-pasting operator is illustrated in the following example #include<stdio.h> #include<conio.h> #define display(i) printf("x" #i " = %d\n ",x##i) void main() { Output int x1=10,x2=20,x3=30,xa=66; x1 = 10 display(1); x2 = 20 display (2); x3 = 30 display(3); xa = 66 display(a); getch(); }

DATA FILES
Many application requires that information be written to or read from an auxiliary memory device Information stored in the memory device in the form of data file. Data file allows us to store information permanently, and to access and alter that information whenever necessary C does not distinguish between sequential and direct access data files. How ever there two different types of data file, called stream oriented ( or standard) and system oriented (or low-level) data files Stream-oriented data file can be sub-divided into two categories. They are text file and unformatted data file Text files consists sequence of characters. These characters can be interpreted as individual data item or string or number. This file is readable by both human and machine Unformatted data file organize data into block containing contiguous bytes of information. These blocks represent more complex data structures such as array, structure and class System oriented file more closely related to computers operating system C Supports a number of function that have the ability to perform basic files operations. Which inclues: o Naming a file o Updating the data in the o Opening a file file o Reading a data from a file o Closing the file o Writing a data to a file The important file handling functions are o fopen( ) o fprintf( ) o fclose( ) o fscanf( ) o getc( ) o getw( ) o putc ( ) o putw( ) Panimalar Engineering College

100

MC9212-Problem Solving and Programming Unit IV & V o fseek( ) o ftell( ) o rewind( )

FUNCTIONS FOR OPENING AND CLOSING FILE To work with stream-oriented data file, the first step is to establish buffer area, where is temporarily stored while being transferred between the computers memory and data file. Buffer area allows information read from and written to the data file The buffer area is established by writing FILE *fp; Here FILE ( uppercase letters required ) is special structure type that establishes the buffer area pf is a pointer variable that indicates the beginning of the buffer area. It is often referred to as a stream pointer or simply stream. This is defined in the stdio.h header file A data file must be opened before it can be created or processed. This could be done using function fopen. The syntax given below FILE *fopen(const char *filename, const char *mode); The library function fopen will allocate buffer area and link buffer area with physical file you have specified. Finally return the file pointer that pointing to the buffer area. This function is typically written as Ptvr = fopen (file-name , file-type); Where file-name and file-type are strings that represent the name of the data file and in which the data file will be utilized. The name chosen for the file-name must be consistent with the rules for naming files, as determined by the computers operating system. The file-type must be one of the strings shown in Table Meaning Open an existing file in text mode for reading only Open a new file in text mode for writing only. If a file with the specified filename currently exists, it will be destroyed and a new file created in its place Open an existing file for appending (i.e., for a adding new information at the end of the file). A new file will be created if the file with the specified filename does not exists Open in binary mode Open in text mode. This is default mode explicitly not necessary to mention Allows read and write operation on file Open an existing file for both reading and writing Open a new file for both reading and writing. If a file with the specified file-

fopen

File-Type r w a b t + r+ w+

Panimalar Engineering College

101

MC9212-Problem Solving and Programming Unit IV & V name currently exists, it will be destroyed and a new file created in its place Open an existing file for both reading and appending. A new file will be created if the file with the specified file-name does not exists Open the file in binary mode for reading the content of the file Open the file in binary mode for writing the content to the file

a+ rb wb

The fopen function returns a pointer to the beginning of the buffer area associated with the file. A NULL value is returned if the file you have specified not found in read mode or error in creating new file in write mode Every data file must be closed at the end of the program. This can be accomplished with the library function fclose. The syntax is int fclose(ptvar);

fclose( )

returns 0 on success; it returns EOF if any errors are detected. It is good programming practice to close a data file explicitly using the fclose function, though most C compilers will automatically close a data file at the end of program execution, if a call to fclose is not present

CREATING A DATA FILE A data file must be created before it can be processed. A stream-oriented data file can be created in two-ways. i) One is create the file directly, using a text editor or a word processor ii) Second is to write a program that should accept information from keyboard and then writes it out to the data file. File your creating through C program can be either text file(formatted data file) and binary file (unformatted data fie) Unformatted data files can only be created with such specially written programs. FUNCTIONS TO READ AND WRITE FORMATTED DATA Formatted data can be read or written either character by character or in the form of integer, float, or string or in the form of any other predefined C data-types. Functions which are used to read or write formatted data listed below

fputc ( )
It is used to outputs a character to a stream. The syntax is given below int fputc(int ch, FILE *fp); This function will write stored in the chararcter variable ch into the buffer pointed by file pointer fp and moves the file pointer to the next location Example Panimalar Engineering College

102

MC9212-Problem Solving and Programming Unit IV & V #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> void main() { FILE *fp; char fname[80],ch; clrscr(); printf("enter the file name: "); scanf("%s",fname); fp=fopen(fname,"w"); if(fp==NULL) {

output enter the file name: sample.txt enter the content(type # to stop writing) this is sample program to create text file through C end # sample.txt created sucessfully..

printf("error creating file..."); getch(); exit(0); } printf("enter the content(type # to stop writing) \n\n"); while(1) { ch=getchar(); if(ch=='#') break; fputc(ch,fp); } printf("\n %s created sucessfully..",fname); getch(); fclose(fp); }

fgetc( )
The syntax int fgetc(FILE *fp);

This function is used to gets single character from a stream pointer by fp and move the pointer to the next position Example #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { FILE *fp; Panimalar Engineering College

103

MC9212-Problem Solving and Programming Unit IV & V char fname[80],ch; clrscr(); printf("enter the file name: "); scanf("%s",fname); fp=fopen(fname,"r"); if(fp==NULL) { printf("error opening file..."); getch(); exit(0); Output enter the file name: sample.txt the content of file sample.txt are ========================= this is sample program to create text file through C end ==========================

} printf("\n the content of file %s are \n",fname); printf("=======================================\n"); while(!feof(fp)) { ch=fgetc(fp); printf("%c",ch); } printf("\n==================================\n"); getch(); fclose(fp); }

fprintf( )
It allows us to sends formatted output to a stream. fputc ( ) allows us to write only char type data in the file but fprintf allows us to write any type of data such as integer, float, double, char, string The syntax int fprintf(FILE *fp, const char *format, ...); Uses the same format specifiers as printf, but fprintf sends output to the specified stream fp. fprintf returns the number of bytes output. In event of error, it returns EOF. The syntax is

fscanf( )
int fscanf(FILE *fp, const char *format, ...);

It will read formatted data from a stream and returns the number of input fields success fully scanned, converted, and stored; the return value does not include un stored scanned fields Example this example demonstrate how to use fprintf and fscanf to write formatted data of any type in file #include<stdio.h> #include<conio.h> Panimalar Engineering College

104

MC9212-Problem Solving and Programming Unit IV & V void main( ) { FILE *fp; char ename[20],ch; float sal; fp=fopen("emp.dat","w"); clrscr(); if(fp==NULL) { printf("error while creating ..."); getch(); exit(0); } A1:

Output: ============================ Employee Entry Screen ============================ Employee name Jackson Salary 9000 ============================ record inserted... do U want to insert one more (Y/N): N press any key to display records ============================ Employee Name Salary ============================ Amala 6000.00 Jackson 9000.00 ============================

clrscr(); printf("===================="); printf("\n Employee Entry Screen"); printf("\n==================="); printf("\nEmployee name "); scanf("%s",ename); printf("\n Salary "); scanf("%f",&sal); fprintf(fp,"%s\t%f\n",ename,sal); printf("\n==============================="); printf("\n record inserted..."); printf("\n do U want to insert one more (Y/N): "); fflush(stdin); ch=getchar(); if(ch=='y' || ch=='Y') goto A1; fclose(fp); fp=fopen("emp.dat","r"); printf("\n\n press any key to dispaly records"); clrscr(); printf("==============================="); printf("\n Employee Name Salary"); printf("\n==============================="); while(!feof(fp)) { fscanf(fp,"%s\t%f\n",ename,&sal); printf("\n%-20s %9.2f",ename,sal); }

Panimalar Engineering College

105

MC9212-Problem Solving and Programming Unit IV & V printf("\n==============================="); getch(); fclose(fp); } READING AND WRITING UNFORMATTED DATA FILES Some applications involve the use of data files to store blocks of data, where each block consists of a fixed number of contiguous bytes. Each block will generally represent a complex data structure, such as a structure or an array. For example, a data file may consist of multiple structures having the same composition, or it may contain multiple arrays of the same type and size. For such applications it may be desirable to read the entire block from the data file, or write the entire block to the data file, rather than reading or writing the individual components within each separately. The library functions fread and fwrite are intended to be used in situations of this type. These functions are often referred to us unformatted read and write functions. Similarly, data files of this type are often referred as unformatted data files. Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the number of data blocks being transferred, and the stream pointer.

fwrite( ) used to write unformatted data into the file. Structure or class can be used as
source of data.
The syntax is given below size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp); Writes n records of size bytes each & returns the number of records actually written. size_t is an user-defined data type derived from long int Thus, a typical fwrite function might be written as fwrite(&cust, sizeof(customer), 1, fp); Where cust is a structure variable of type customer, and fp is the stream pointer associated with a data file that has been opened for output

fread( ) - is used to read unformatted data from file. The destination of the data could
be structure or class. The size of the record in file and size of the structure / class should be same. Order and type of each filed in the structure and record must be same The syntax is given below
size_t fread(void *ptr, size_t size, size_t n, FILE *fp); It reads n records of size bytes each, and returns the number of records actually reads from file pointer fp. size_t is an user-defined data type derived from long int Thus, a typical fread( ) function might be written as fread(&customer, sizeof(customer), 1, fp);

Panimalar Engineering College

106

MC9212-Problem Solving and Programming Unit IV & V Where cust is a structure variable of type customer, and fp is the stream pointer associated with a data file that has been opened for input Example - following example demonstrate how to use fread and fwrite #include<stdio.h> #include<conio.h> #define line printf("\n\t"); \ for(i=1;i<45;i++) printf("="); int i; typedef struct { char name[15]; long int telno; }Telephone; Telephone a; void main() { FILE *fp; char ch; fp=fopen("tele.dat","w");

if(fp==NULL) { printf("error opening file..."); exit(1); } A1: flushall(); clrscr(); line; printf("\n\n\t Telephone Directory"); line; printf("\n\tName "); scanf("%s",a.name); printf("\n\tTelephone No "); scanf("%ld",&a.telno); fwrite(&a,sizeof(Telephone),1,fp); line; printf("\n\n insert one more record(y/n): "); fflush(stdin); ch=getchar(); if(ch=='y' || ch=='Y') goto A1; fclose(fp);

output ============================== Telephone Directory ============================== Name Ramanan Telephone No 897656 ============================== insert one more record(y/n): n press any key to display records... ============================== Telephone Directory ============================== Name Tel No ============================== kumaran 5643456 Ramanan 45688 ============================== =

Panimalar Engineering College

107

MC9212-Problem Solving and Programming Unit IV & V printf("\npress any key to display records..."); getch(); clrscr(); fp=fopen("tele.dat","r"); line; printf("\n\tTelephone Directory"); line; printf("\n\tName \t Tel No"); line; while(!feof(fp)) { a.telno=0; fread(&a,sizeof(Telephone),1,fp); if(a.telno!=0) printf("\n\t%-15s\t%10ld",a.name,a.telno); } line; getch(); } PROCESSING A DATA FILE Most data file applications require that a data file altered as it is being processed. For example, in an application involving the processing of customer records, it may be desirable to add new records to the file, to delete existing records, to modify the contents of existing records, or to rearrange the records. These requirements in turn suggest several different computational strategies. Consider for example, the problem of updating the records within a data file. There are several approaches to this problem. Perhaps the most obvious approach is to read each record from a data file, update the record as required, and then write the updated record to the same data file. However, there are some problems with this strategy. In particular, it is difficult to read and write formatted data to the same data file without disrupting the arrangement of the data items within the file. Moreover, the original set of records may become inaccessible if something goes wrong during the program execution. Another approach is to work with two different data files an old file (a source) and a new file. Each record is read from the old file, updated as necessary, and then written to the new file. When all of the records have been updated, the old file is deleted or placed into archival storage and the new file renamed. Hence, the new file will become the source for the next round of updates. Historically, the origin of this method goes back to the early days of computing, when data files were maintained on magnetic tapes.

Panimalar Engineering College

108

MC9212-Problem Solving and Programming Unit IV & V The method is still used, however, because it provides a series of old source files that can be used to generate a customer history. The most recent source file can also be used to recreate the current file if the current file is damaged or destroyed.

Functions those useful for finding and moving FILE pointer in file fseek and ftell are useful function, when you want to modify & update existing record in the file

fseek( ) is used to move file pointer of the stream to different location


the syntax is int fseek(FILE *fp, long offset, int origin); where offset is the new position of the file pointer relative to the origin and the origin have the following possible values SEEK_SET - seeks from beginning of file SEEK_CUR - seeks from current position SEEK_END - seeks from end of file this function will return 0 if successful or nonzero on failure the syntax is given below

ftell( ) This function will returns the current position of the file pointer in the stream
long ftell(FILE *fp); this function will returns the current file-pointer position on success or -1L on error rewind( ) - this function is used to reset the FILE pointer to the beginning of the stream regardless of current of the file pointer the syntax is void rewind(FILE *fp); EXAMPLE the following example demonstrate how to modify and update existing record in the file #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> #define line printf("\n"); \ for(i=1;i<30;i++) printf("="); int i; typedef struct { char name[15]; long int telno; }Telephone; Panimalar Engineering College

109

MC9212-Problem Solving and Programming Unit IV & V output Telephone a; void main() { FILE *fp; int found=0; char tname[15]; clrscr(); printf("enter the name to modify info : " ); scanf("%s",tname); fp=fopen("tele.dat","r+"); if(fp==NULL) { printf("error while opening file"); getch(); exit(1); } while(!feof(fp)) { fread(&a,sizeof(Telephone),1,fp); if(strcmpi(tname,a.name)==0) { found=1; break; } } line; if(found) { printf("\n name = %s \nOld.Tele No = %ld",a.name,a.telno); line; printf("\n\n\tNew Telephone No.: "); scanf("%ld",&a.telno); fseek(fp,-1L*sizeof(Telephone),SEEK_CUR); fwrite(&a,sizeof(Telephone),1,fp); line; printf("\nrecord modification successful"); } else printf("\nrecord not found for name %s ",tname); line; Panimalar Engineering College enter the name to modify info : kumaran ============================= name = kumaran Old.Tele No = 5643456 ============================= New Telephone No.: 9876765 ============================= record modification successful =============================

110

MC9212-Problem Solving and Programming Unit IV & V fclose(fp); getch();

FAQS 1. List difference between register and auto variable? Register variable and local variable both will be treated as local variable. So that both are visible only inside the function in which it is defined But the major difference between register and auto variables are Register Auto Only int, char type of variable can be Any valid pre-defined and user-defined type declared as register variable variable can be declared as auto register keyword is must to make any auto keyword is optional. By default all the variable as register variable variable defined without storage class will be treated as auto variable Variable declared as register will be stored in But auto variable will be stored in main the CPUs registers memory but not in the CPUs registers

1. Compare and contrast automatic variable and static variable?

Automatic
It is confined to the function in which it is declared It is created every time control enter into the function and destroyed when control exiting the function It wont retain value between function call

Static

It is also confined to the function in which it is declared It is created at the time of first function call, and destroyed only when exiting the program It will retain value of the variable between function call Variable of these types will not be But variable of these types will be initialized automatically initialized automatically. For example integer variable will be initialized to 0, float variable to 0.0 etc., Explicit qualification of variable not But explicit qualification of variable is required required e.g.: e.g.: void increment( ) void increment( ) { { int a; static int b; a++; b++; } } Here a is auto variable, because there is no Here b is static variable, since the qualification mentioned, It will be qualification is mentioned explicitly. It will automatically assumed as auto variable. It be automatically initialized to zero wont be automatically initialized

Panimalar Engineering College

111

MC9212-Problem Solving and Programming Unit IV & V

2. Compare and contrast array and structure

Array
Array variable are used to store more than one value of same data type Array is not an user-defined data type Individual elements of array can be accessed using index and array index operator [] e.g.: int a[10]; a[0]=10;

Structure
Structure variable is used to store more than one value of different data type But structure is an user-defined datatype Individual elements(members) of structure variable can be accessed either using dot(.) operator or using arrow (->) operator e.g.: struct employee e1; e1.empno=1000;

Array can be created for any data type but structure variable can be created only if including structure structure definition declared

3. Compare and contrast static global variable and static local variable Static global variable
Variable declared outside of all function and qualified explicitly as static, that variable is called global static variable e.g.: main() { static int x; }

Static local variable

Variable declared inside of any function and qualified as static, then it is called local static variable e.g.: static int y; void increment( ) { y++; } main() { printf(%d,y); } These types of variables will be These types of variable will also be automatically initialized automatically initialized It is accessible only within the function in It is accessible within the file in which it is which it is declared declared, outside of file not accessible Life time of these variable throughout the Life time of these variables will also program throughout the program

4. Why C is called structured programming?


To write C program we need to satisfy certain rules. C is collection of one or more function either defined within the file or using different files The structure of the C program is as follows: Panimalar Engineering College

112

MC9212-Problem Solving and Programming Unit IV & V All the C program must start with one or more #include directives. Followed by zero or more Macro and/or symbolic constant definition Followed by zero or more global variable declaration Followed by either user-defined function definition or function prototype (zero or more) Followed by main( ) definition Followed by zero or more user-defined function definition If programmer going to violate these rule, your program wont be compiled successfully For example if user-defined function defined after main( ) definition, there is an function prototype declared before main( ) definition. If this is not done compiler will produce error To write a C program some structure to be followed, So the C called structured programming language Example: #include<stdio.h> #include<conio.h> #define line printf(\n=====================); void add(int x,int y) { Printf(sum=%d,x+y); } int prod(int,int); main() { int p=10,q=20; add(a,q); printf(product=%d,prod(p,q); } int prod(int m,int n) { return m*n; }

5. Write a program to copy the content of one file into another?


#include<stdio.h> #include<conio.h> #include<stdlib.h> void main(int argc,char *argv[]) { char ch; FILE *fr,*fw; if(argc<3) { Panimalar Engineering College

113

MC9212-Problem Solving and Programming Unit IV & V printf("Try to run from command prompt"); printf("usage >copy sourcefile.ext targerfile.ext"); getch(); exit(0); } fr=fopen(argv[1],"r"); fw=fopew(argv[2],"w"); if(fr==NULL) { printf("source file not exists. please input valid one..."); getch(); exit(0); } while(!feof(fr)) { ch=fgetc(fr); fputc(ch,fw); } printf("\n%s copied successfully from %s",argv[2],argv[1]); fcloseall(); }

6. Compare and contrast structure and union?

Structure
Structure is an user-defined composite data type Memory allocated for structure is equal to sum of the memory allocated for the individual member of the structure All individual members of structure can be assigned value simultaneously without losing information e.g.: struct cricket{ char player[30]; 0 float avgscore; };

Union
Union also user-defined data type

Memory allocated for union is equal to the size of the variable having highest among structure member But only one member of the union member can be used at a time, since all the variable shares the same memory address e.g.: union color { char clr; int rgb; }; struct keyword required to create variable union keyword is required to create of type structure variable of type union

7. Write a short notes on string function strtok( )

Panimalar Engineering College

114

MC9212-Problem Solving and Programming Unit IV & V This function is used to tokenize the first string you have passed based on delimiter, you have passed as second argument to this function

Syntax: char *strtok(char *s1, const char *s2); The first call to strtok returns a pointer to the first character of the first token in s1, and writes a null character into s1 immediately following the returned token Subsequent calls with null for the first argument will work through the string s1 until no tokens remain The separator string, s2, can be different from call to call. Return Value: - On success, returns a pointer to the token found in s1. - When there are no more tokens, returns a null pointer The following example demonstrate use of strtok( ) Output: this is sample input for strtok

#include <string.h> #include <stdio.h> #include <conio.h> void main() { char input[40] = "this,is,sample,input,for,strtok"; char *p; clrscr(); /* strtok places a NULL terminator in front of the token, if found */ p = strtok(input, ","); if (p) printf("%s\n", p); /* A second call to strtok using a NULL as the first parameter returns a pointer to the character following the token */ while(1) { p = strtok(NULL, ","); if (p) { printf("%s\n", p); getch(); } else break; } getch(); }

Distinguish between external variable declaration and definition?


Panimalar Engineering College

115

MC9212-Problem Solving and Programming Unit IV & V An external variable declaration announces the properties of a variable, primarily its base type. If an external variable defined in other source file is to be referred from current file than external variable declaration mandatory. For external variable declaration variable should be explicitly qualified as extern. This tell the compiler that the variable of this type is already created and allocated memory in some other file, just make use of that variable instead of recreating it An external variable definition announces the base type of the variables, and also causes storage to be set aside. In case of external variable definition, extern keyword is optional Example If the lines int sp; double val[10]; . main() { } appear outside of any function, they define the external variable sp and val, causes storage to be set aside, and also serves the declaration fro the rest of the source file on the otherhand, the lines extern int sp; extern double val[]; announce the current file that sp and val are integer variable, already defined in some other file, so without allocating memory make use of that variable defined in other file. Arry size must be specified with the definition, but are optional with an external variable declaration There must be only one definition of an external variable among all the files that make up the source program; other file may contain external variable declaration to access it. So external variable declaration can appear in multiple files possible

What are C token?

There are six classes of tokens: identifiers, keyboards, constants, string constant or string literal, operators, and other separators. Blanks, horizontal and vertical tabs, new lines, form feed and comments are not included in the tokens

What are type qualifiers?


const and volatile are called type qualifiers. Const announce that its value will not be changed. Volatile announces that it has special properties relevant to optimization

What are multiplicative operators?


Panimalar Engineering College

116

MC9212-Problem Solving and Programming Unit IV & V *, / and % are called multiplicative oprators. * denotes multiplication and / denotes division and % denotes remainder

What are additive operators?


+ and - are called multiplicative operators. + denotes addition and denotes subtraction

What are storage class specifies?


Auto, register, static, extern and typedef are called storage speicifers

What are type specifies?


void, char, short, int, long, float, double, signed, unsigned, struct, union and enum are called type specifiers

What are type modifiers?


Singed, unsigned, short and long are called type modifiers. signed and unsigned qualification can be applied to int and char data types. Short and long qualification can be applied only to int data types

Explain void pointer


void *malloc(size_t size); void *calloc(size_t nitems, size_t size); void *realloc(void *block, size_t size); (i) (ii) Look at all the above dynamic memory allocation function. Note that all function return result as void pointer Using void pointer it not possible to do arithmetic operation such as +, -. Because the compiler does not know how many byte to be incremented or decremented using void pointer To do arithmetic on pointer, it is necessary you have to convert void pointer into appropriate data-type pointer. The following code fragment shows the conversion char *sptr; sptr=(char *) malloc(10); int *ptr; ptr=(char *) malloc(10); in the first example void pointer is converted into char pointer, so that when you are executing sptr++, complier will increment one byte in the second example void pointer is converted into int pointer, so that execution of every ptr++, will cause two byte to be incremented Both array and pointers are used to store collection of similar types of data in the consecutive memory address ARRAY POINTER Panimalar Engineering College

What are the similarities and difference between arrays and pointers?

117

MC9212-Problem Solving and Programming Unit IV & V Size of the array is determined at the time of declaration. Once the size is defined you cannot change later It is static binding. Which means compile time binding. Memory can be determined only at compile time Individual element of the array can be accessed using array index operator Memory allocated for array cannot be garbage collected programmatically Memory size for the pointer can be determined either during compile time or during runtime But for pointer, memory can be allocated at run time

Individual element can be accessed by doing pointer arithmetic such as + or But memory allocated for pointer can be garbage collected or freed through program by calling library function free() or delete() To allocate memory for array, there is no But to allocate memory to pointer, we library file required requires library function malloc(), realloc() or new

Errors
1. There are three types of errors in any programming language. They are Syntactic errors Execution error Logical errors 2. We need to write error free program, since errors will prevent the program being compiled (or) executed successfully Syntactic Errors 1. Syntactic errors relatively easy to find and correct. Since compiler will generate diagnostic message when syntactic errors have been detected during the compilation process. These diagnostic message are helpful in identifying the nature of and approximate location of errors. 2. Some of the common syntactic errors are Improperly declared variables A reference to the undeclared variables Incorrect punctuation such as missing semicolon at the end of the statement, etc Declaring variable after first execution statement 3. All errors may not be deducted on first pass. It may be necessary to correct some syntactic errors before other can be found Execution Errors 1. Execution errors on the other hand much troublesome. These errors occur only at runtime. Some of common execution errors are: 2. Some of the common syntactic errors are Numerical overflow of underflow Division by zero Attempting to compute logarithms or square roots of negative numbers Attempting to open file in read mode, which may not be exist Attempting to close file which may not be opened Attempting to read information from file beyond last character Attempting to move file pointer before the beginning of the file Panimalar Engineering College

118

MC9212-Problem Solving and Programming Unit IV & V Attempting to write into the file which may be read only Diagnostic message will be often generated in situation of these encountered, making it easy to identify and correct errors These diagnostic are called execution message or runtime message When execution errors occurs, you must determine location of the error with in the program Once the location of the error has been identified, the reason for the error must be determined

3. 4. 5. 6.

Logical Errors 1. Logical errors are closely related to execution errors 2. Logical error may not terminate program execution, instead it may not produce expected result 3. Detecting logical errors are very difficult, because there is no error message will be displayed 4. You have to thoroughly diagnose all the line of code, and input different possible values and check whether producing expected result and compare the generated result with manual calculation to find where logical errors occurred

Debugging Techniques
1. Methods are available for finding the location of execution and logical errors with in a program 2. Such a methods generally referred to as debugging techniques 3. The method available are: Error Isolation Tracing Watch values Break points Stepping Error Isolation 1. If the location of the error is not known, it can be detected by simply commenting portion of the program and then running to see whether disappear or not 2. If not disappeared comment another portion of the program and run again to find whether error disappear or not Tracing 1. It involves to display the values that are calculated internally at various location within the program by sing PRINTF() function 2. It verify that the values actually assigned to certain key variable correct or not Watch Values 1. A watch value is the value of the variable or expression, which is displayed as the program executes 2. By monitoring a few selected watch values, you can determine where the program begin to generate incorrect values 3. In C Watch values can be added by selecting add watch from debug menu Panimalar Engineering College

119

MC9212-Problem Solving and Programming Unit IV & V Break Points 1. Break point is temporary stopping point within the program. When the program is executed , the program execution will temporarily stop at where break point is encountered before the instruction being executed, execution may then resumed until the next break point is encountered 2. Break point are used in conjunction with watch values 3. This can be done by selecting add break point from the debug menu, break point may be later deleted by pressing F5 Stepping 1. Stepping refers to the execution of one instruction at a time, typically by pressing function key for execute each instruction. 2. Stepping can be carried out by pressing F7 3. Stepping is often used with watch values To avoid errors in Console I/O operations 1. To avoid errors in I/O operation, as a programmer you may foresee all possible error the end-user will do 2. You have to give user friendly message , before accepting data for error-prone fields, so that the end user do not input invalid data for concerned filed, which will avoid errors For example: 1. When accepting date-of-birth give the format such as dd/mm/yy to be displayed to enduser, so the end-user will feed in the same format, which will avoid errors 2. For department-no column, display possible range the user can input (100 to 900) 3. For unsigned int, display help to the user to only input non-negative values 4. Input only number with six possible digits for column pincode 5. For program that accept command line argument, display user friendly message that the user have to run the program from command line and how many argument they have to input from command prompt e.g.,: main() { int x,y,z; printf(input x: ); scanf(%d,&x); A1: printf(input y(other than zero): ); scanf(%d,&y); If(y==0) goto A1; Z=x/y; printf(\nz=%d,z); } To avoid errors in File I/O operations 1. While dealing with file the end-user will do the following mistakes Panimalar Engineering College

120

MC9212-Problem Solving and Programming Unit IV & V Input filename for reading content, which may not physically exists Attempting to append at the end of the physical file, which is read-only file, etc 2. You may able to write program, which may findout errors, and display user-friendly message, without terminating program abnormally e.g. 1: main() { char fname[30]; printf(\ninput filename to read content : ); scanf(%s,fname); fr=fopen(fname,"r"); if(fr==NULL) { printf("file not exists. please input valid one..."); getch(); exit(0); } This code fragment will display user-friendly message, when user input invalid filename, without corrupting application e.g.2: main() { char fname[30]; FILE *fp; A1: clrscr(); printf(\nenter filename to write : ); scanf(%s,fname); fp=fopen(fname,"r"); if(fr!=NULL) { printf("file already exists. please input new one..."); getch(); fclose(fp); goto A1; } fclose(fp); Fp=fopen(fname,w);

how can multiple assignment written in C? in what order the assignment be carried out?
int x,y,z; x=y=z=10;

Panimalar Engineering College

121

MC9212-Problem Solving and Programming Unit IV & V in the above code fragment, multiple assignment statement written in second line. Assignment of value is carried out from left to right. In case of our example, first value of 10 is assigned to z and then value of z is assigned to y and then value of y is assigned to x

Define scale factor in pointer?


Scale factor of pointer determine how many no.of byte have to be incremented and decremented while carrying out ++ or -- on pointer variable. This scale factor will be determined by looking at the base type of pointer variable. We cannot do any arithmetic on void pointer, that is why we are converting void pointer into appropriate base type pointer e.g.,: int *iptr; char *cptr; iptr=(int *) malloc(10); cptr=(char *)malloc(10); in the above code fragment, iptr holding starting address of 10 bytes of memory allocated by malloc and you can store maximum of 5 integer elements, similarly cptr holding starting address of 10 bytes of memory and can store maximum of 10 characters. *iptr=10; iptr++; // this will increment current address of iptr by 2 bytes *iptr=20; *cptr=a; cptr++; // this will increment current address of cptr by 1 byte *cptr=b;

Bitfield
If the variable is to take only two values 1 or 0, we need only single bit to store it. if the vaiable is to take 0 to 3,then two bit is sufficient to store these values. then why we sacrifies an entire 16 bits, when one or two bits are sufficient. the reason is C does not offer any one or two bit datatypes, but by using feature of 'bitfield', it is possible values of several variables can be pack in single byte for example, suppose there are four variable a,b,c, and d such that a can take any one of two values 0 or 1, b can take any value between 0 and 3, c can take any value between 0 and 7 and d can take any value between 0 and 15 we need only one bit to store value of a, 2 bits to store value of b, 3 bits to store value of c, 4 bits to store value of d. thus we need 10 bits all togather, which means we pack all information into a single integer, since an integer is 16 bits long. how to achiveve this using bit field shown in the following program in the following example, the colon in the declaration tell the compiler that we are talking about bitfields and the number after it tells how many bits to allot to the field. So in a single word we stored all four struct bit { unsigned a:1; Panimalar Engineering College

122

MC9212-Problem Solving and Programming Unit IV & V unsigned b:2; unsigned c:3; unsigned d:4; }; main() { struct bit x; x.a=1; x.b=3; x.c=7; x.d=15; clrscr(); printf("\nx.a=%d\tx.b=%d\tx.c=%d\tx.d=%d",x.a,x.b,x.c,x.d); getch(); } Explain the concept of pointer to the structure? Pointer can be created not only for the pre-defined data types, we can also create pointer to the user defined data type such as structure. The following code fragment demonstrate how to create structure pointer struct PhoneBook { char name[30]; long int phno; }; struct PhoneBook bk1, *ptr; ptr=&bk1; here bk1 in instance of PhoneBook, and ptr is pointer to the structure variable of PhoneBook and holding the address of bk1. now member of bk1 can be initialized and retrieved using pointer variable shown below: strcpy(ptr->name,RamKumar); strcpy(ptr->phno,324565); It is also possible; we can allocate memory for pointer to the structure variable at the runtime using malloc. The following program demonstrate the concept of allocating memory for structure variable at runtime to store multiple records #include<stdio.h> #include<conio.h> #define line printf("\n=============================================="); output How many Books ? 2

Panimalar Engineering College

123

input book info 1 ========================== Title ? Java Complete Reference

MC9212-Problem Solving and Programming Unit IV & V struct Books { char title[50],author[30],publication[50]; long price; }; main() { int n,i; struct Books *ptr; clrscr(); printf("\n How many Books ? "); scanf("%d",&n); ptr=(struct Books*)malloc(n*sizeof(struct Books)); for(i=0;i<n;i++) { clrscr(); printf("\ninput book info %d",i+1); line; printf("\n Title ? "); fflush(stdin); the 2 records are gets((ptr+i)->title); printf("\n Author ? "); gets((ptr+i)->author); printf("\n Publication ? "); gets((ptr+i)->publication); printf("\n Price? "); scanf("%ld",&(ptr+i)->price); } printf("\n press any key to display records....."); printf("\n the %d records are \n",n); line; printf("\ntitle\t\t author \t\tpublication\t\tprise"); line; for(i=0;i<n;i++) printf("\n%-20s %-20s %-20s %7ld",(ptr+i)->title,(ptr+i)->author,(ptr+i)>publication,(ptr+i)->price); line; getch(); } Panimalar Engineering College ================================================== title author publication prise ================================================== Java Complete Reference Rararaman PBP 400 The C Programming Kernighan PHI 235 =================================================

124

MC9212-Problem Solving and Programming Unit IV & V Write a program to demonstrate the functionality of linked list? The following program demonstrates how to create linked list, insert node in the front of the lined list, in the middle of the linked list and in the end of the linked list. Similarly this also demonstrate how to delete node or record from or record from linked list ( from front, middle and end
#include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h> #define line printf("\n======================================================") struct LinkedList { int data; struct LinkedList *next; }; struct LinkedList *start=NULL,*node,*tmp,*prev; void readData() { node=(struct LinkedList*)malloc(sizeof(struct LinkedList)); printf("\n\tInput Data : "); scanf("%d",&node->data); node->next=NULL; } void display() { if(start==NULL) printf("\n\t Linked list was empty..."); else { printf("\n Now linked list: "); tmp=start; while(tmp->next!=NULL) { printf("%d->",tmp->data); tmp=tmp->next; } printf("%d",tmp->data); } } void insert() { int opt=0,sdata; while(opt!=4) { clrscr(); line; printf("\n\t\tLinked List Insertion"); line; printf("\n\t1. Add Element in the Front");

Panimalar Engineering College

125

MC9212-Problem Solving and Programming Unit IV & V


printf("\n\t2. Add Element in between Existing Element"); printf("\n\t3. Add Element in the End"); printf("\n\t4. Back to Main Menu"); line; printf("\nSelect your option? "); line; gotoxy(30,10); scanf("%d",&opt); switch(opt) { case 1: readData(); if(start==NULL) start=node; else { node->next=start; start=node; } break; case 2: if(start==NULL) printf("\n while linked list was empty.this option not possible..."); else { display(); printf("\ninput data after which,you want to insert node?"); scanf("%d",&sdata); tmp=start; while(tmp->data!=sdata && tmp!=NULL) tmp=tmp->next; if(tmp==NULL) printf("\n insertion not possible. since search elements after which you want to insert not found...."); else { readData(); node->next=tmp->next; tmp->next=node; } } break; case 3: readData(); if(start==NULL) start=node; else { tmp=start; while(tmp->next!=NULL)tmp=tmp->next; tmp->next=node; }

Panimalar Engineering College

126

MC9212-Problem Solving and Programming Unit IV & V


break; case 4 : break; default: printf("\n invalid option. try again...."); } if(opt==1||opt==2||opt==3)display(); printf("\n\n\t press any key to continue...."); getch(); } } void delete() { int sdata,found=0; char ch; A: if(start==NULL) { printf("\n Deletion is not possible. since linked list is empty."); getch(); return; } clrscr(); line; display(); line; printf("\n enter data to delete : "); scanf("%d",&sdata); node=prev=start; do { found=0; if(sdata==node->data) { if(node==start) start=node->next; else prev->next=node->next; found=1; free(node); break; } prev=node; node=node->next; }while(node!=NULL); if(found) printf("\n node removed from linked list"); else printf("\n data not found to remove from linked list"); printf("\n Do you wish to delete one more node (Y/N)? "); fflush(stdin); ch=getchar(); if(tolower(ch)=='y') goto A;

Panimalar Engineering College

127

MC9212-Problem Solving and Programming Unit IV & V


} main() { int opt; while(1) { clrscr(); line; printf("\n\t\tLinked List Operations"); line; printf("\n\t1. Add Elements to the Linked List"); printf("\n\t2. Delete Element from the linked list"); printf("\n\t3. Display Elements in the linked list"); printf("\n\t4. Exit"); line; printf("\nSelect your option? "); line; gotoxy(30,10); scanf("%d",&opt); switch(opt) { case 1:insert(); break; case 2:delete(); break; case 3:display(); break; case 4:exit(0); default: printf("\n\t invalid option. try again..."); } getch(); } }

PSEUDO CODE / ALGORITHM Algorithm is defined as set of unambiguous precise stataements, which describe solution to the given problem Pseudo code is simply an English language like way of writing programming code. It is mush mere precise than a written description of process and much less precise than the actual codes that follows. Unlike programming code, pseudo code does not require exact syntax so the programmer is able to focus more on the bigger picture.This is much similar to algorithm E.G.: pseudo code that calculate bonus Repeat for all employees get salary from current record get deduction from expenses set net=salary-deduction if net 10000 Panimalar Engineering College

128

MC9212-Problem Solving and Programming Unit IV & V set bonus=10% of net else set bonus=5% of net end if end repeat

Flowcharts
Flow chart is a graphical way of illustrating the step in the program flow It uses one or more symbols connected by flow lines, to represent process & flow of program. It is an more easiest way of representing program flow than algorithms SOME OF KEY SYMBOLS INCLUDES 1. Termination symbol - It indicates start & stop of every algorithm

2. Input/output symbol it is used to represent get input from keyboard or display information into monitor 3. The decision symbol it is used to represent process of if, while, for control structure. It indicates the decision made by if then else statement. The program flow face one direction if it condition tested is true other wise flow takes another direction 4. manual Input symbol It is used to indicate read input from keyboard 5. display symbol it is used to display output only in the monitor

6. output symbol It indicates that information is to be printed on monitor or redirected to printer Two marks 1. what are the factors required for analysis of algorithm 2. describe the algorithm to find the biggest of three numbers 3. describe the need for array in problem solving 4. how prefixing and post fixing of increment operators to a variable affects the assignment statement 5. what will be the output of the follwing segment if n=-1 and n=0? x=y=2; if(n < 0 ) x = x -2; y = y +1; printf(%d %d,x,y); 6. what is pointer declaration illustrate 7. distinguish between r and rt mode in the context of files 8. design an algorithm for swapping two values with out using any temporary variables Panimalar Engineering College

129

MC9212-Problem Solving and Programming Unit IV & V 9. what is meant by modularity and what is its use 10. how can short integer, long integer and double precision arguments be indicated with in control string of a printf function 11. what are unary operators? How many operands are associated with a unary operator 12. describe two different ways to specify the address of an array elements? 13. what is the basic idea behind the linked list? 14. specify the use of fscanf ( ) and fgetc ( ) 15. what is the main overhead in using recursive functions 16. discuss about label in C language 17. what are the factors that contributes to the efficiency of an algorithm 18. give an algorithm for swapping two numbers 19. what do you understand by data type of a variable 20. write an alforithm to find the sum of the digits in a two digit number 21. what is the user of break statement 22. What is the difference between opening the file in w+ and a+ mode? 23. What is meant by selection? 24. describe the difference between way in which data file can be categorized in C 25. how does switch statement differ from nested if 26. how is an array of string represented in C 27. how is function definition distinguished from function call? Give an example 28. what are File I/O functions 29. list all dynamic memory allocation functions 30. what is o-notation 31. given two glasses marked as A and B. Glass A is full of raspberry drinks and glass B is full of lemonade. Suggest a way of exchanging the content of glasses A and B 32. in what way does switch statement differ from an if statement 33. what are trigraph? How are they useful? 34. how does structure differ from array? 35. write a limitations of using getchar and scanf function for reading strings 36. distincuish between malloc() and calloc() 37. what are the advantages of using macro definition in a program? 38. write down the output of following program main( ) { int v = 3 ; int *pv ; pv=&v ; printf( \n *pv=%d v=%d ,*pv, v); *pv = 0 ; printf( \n *pv=%d v=%d ,*pv, v); } 1. write detailed notes on top down design(8) 2. write a short notes on documentation of program, debugging program and programming testing (6) 3. how do you estinmate the efficienty of given tow alforithms(8) 4. explain the steps involved in analyzing an algorithms(8) Panimalar Engineering College

130

MC9212-Problem Solving and Programming Unit IV & V 5. design an algorithm that accepts as inputs a decimal number and convert it to the binary coded decimal (BCD) representation. In the BCD scheme each digit is represented by a 4-digit binary code (8) 6. design an algorithm that will find the GCD of n positive non-zero integers (8) 7. design and implement an algorithm that finds the smallest positive integers that has n or more divisors (8) 8. design an algorithm that finds the integer whose square is closed to but greater than the integer number input as data 9. write a program to find the square root of a quadratic equations(8) 10. write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7(8) 11. explain various input output operation with an example(8) 12. write a program that will read a string and rewrite it in the alphabetical order. For example the word STRING should be written as GINRST(10) 13. Write a program to illustrate the comparison of structure variable 14. explain the concept of addition and deletion in a doubly linked list with an example(12) 15. compare top-down and bottom-up design approach in solving a problem(10) 16. what are the steps in analyzing the algorithm? 17. write a short notes on: flow chart and pseudo code (6) 18. explain the counting algorithm with an example 19. design an algorithm to convert a decimal number to binary 20. Describe the significance of array techniques. Develop an algorithm to count the maximum and minimum integer and the number of times they occurs in an array of N integer 21. Write a program to multiply two square matrices and print the result 22. Discuss briefly about the relationship between array and pointer. Explain how an array is passed to a function with example(16) 23. Write a detailed note on dynamic memory allocation with an example (8) 24. What is linked list? Illustrate linked list with an example(8) 25. explain in detail about problem solving aspects(8) 26. given two variable of integer type a and b exchange their values without using a third temporary variable. Write an algorithm (6) 27. Explain the significance of array techniques(6) 28. explain about factoring methods and write an algorithm to find the greatest common divisor of two numbers (10) 29. explain with an example different looping statements (10) 30. write a program to generate the following table, with the result right justified as shown: ( 8) number number cubed 1 1 2 8 10 1000 31. describe different types of linked lists(6) Panimalar Engineering College

131

MC9212-Problem Solving and Programming Unit IV & V 32. with appropriate examples, explain how an algorithm is analyzed for best, worst and average cases for time and space (8) 33. explain various standard I/O function in C(7) 34. explain various File I/O in C(8) 35. Given a valid positive integer, where the center position is always zero. Write a program to check the integer before zero is exactly the reverse of the integer after zero. any invalid entry should be rejected(6) 36. Write a program that reads one line of text and then prints the same words in reverse order. Fro example, the input today is Tuesday would produce the output Tuesday is today (8) 37. given string s1 and s2 ( each of atmost 80 characters), write a pointer version program to concatenate them at the right or at the left depending on the given choice(8) 38. develop a text file in the name infile.txt and copy into another file outfile after squeezing out all blanks in the inflie.txt(8) 39. write a program to sort a list of names using arrays of pointers(10) 40. What is referential structure? How to generate a linked list using it(6) 41. write a program to find the product of two matrices(9) 42. briefly discuss about program verification(7) 43. write an algorithm to generate the Fibonacci series from n terms(9) 44. Write a c program to (i) create a linked list (ii) add an item to the list (iii) delete an item (iv) modify an item (v) display the content of the list(16) 45. explain how will you define pointer to function(7) 46. Write a C program for sorting a string array using pointers(9) 47. what is meant by algorithm? Write the algorithm to find the kth smallest element in an array and explain(16) 48. Write a program to print the given amount in words unto thousands. For example if we read 8765 the output should be eight thousand seven hundred and sixty five (16) 49. discuss various data types available in C(7) 50. write a program in C to generate the following series: (10) 1, 1, 1 2, 1 2 3, 1 2 3 4 5, 1 2 3 4 5 6 7 8 51. compare the functional macros and functions(6) 52. Develop a function in C which allocates memory locations using malloc ( ). The number of location to be allocated I s passed through first argument and the pointer to the allocated memory is returned through second argument(4) 53. write a program in C to reverse a string using pointer(7) 54. There are two file having the same structure of employee details. Write a program to merge these two files. Eliminate duplicate records(12) 55. What is recursion? Write a program to print Fibonacci series using recursive function(8) 56. Write a nested macro that givens the minimum of 3 values(4) 57. describe an algorithm to find the smallest integer in a set of integers(6) 58. write a function that reverses a list stored in one dimensional array and returns the reversed list in the same array(8) 59. Write down the various methods of initialization of array (8)

Panimalar Engineering College

132

You might also like