Programming with C

1. Introduction to Problem Solving Flow charts, Tracing flow charts, Problem solving methods, Need for computer Languages, Sample Programs written in C 2. C Language preliminaries: C character set, Identifiers and keywords, Data types, Declarations, Expressions, statements and symbolic constants 3. Input-Output: getchar, putchar, scanf, printf, gets, puts, functions. 4. Pre-processor commands: #include, #define, #ifdef 5. Preparing and running a complete C program 6. Operators and expressions: Arithmetic, unary, logical, bit-wise, assignment and conditional operators 7. Control statements: While, do-while, for statements, nested loops, if else, switch, break, Continue, and goto statements, comma operators 8. Storage types: Automatic, external, register and static variables. 9. Functions Defining and accessing, passing arguments, Function prototypes, Recursion, Library functions, Static functions 10. Arrays: Defining and processing, Passing arrays to a function, Multi dimensional arrays. 11. Strings Defining and operations on strings. 12. Pointers Declarations, Passing pointers to a function, Operations on pointers, Pointer Arithmetic, Pointers and arrays, Arrays of pointers function pointers. 13. Structures Defining and processing, Passing to a function, Unions, typedef, array of structure, and pointer to structure 14. File structures:
1

Definitions, concept of record, file operations: Storing, creating, retrieving, updating Sequential, relative, indexed and random access mode, Files with binary mode(Low level), performance of Sequential Files, Direct mapping techniques: Absolute, relative and indexed sequential files (ISAM) concept of index, levels of index, overflow of handling. 15. File Handling: File operation: creation, copy, delete, update, text file, binary file. Syllabus for MCA First Year Semester – I (with effect from the academic year 2007-2008) Term work/ Practical: Each candidate will submit a journal in which at least 12 practical assignments based on the above syllabus along with the flow chart and program listing will be submitted with the internal test paper. Test graded for 10 marks and Practical graded for 15 marks. List of Practical Two programs based on functions. Two programs based on pointers. Four programs based on Remaining portion eg. Control statements, Structures and Unions etc. Three programs based on Different File Operations (File Handling) References : 1. Mastering C by Venugopal, Prasad – TMH 2. Complete reference with C Tata McGraw Hill 3. C – programming E.Balagurusamy Tata McGray Hill 4. How to solve it by Computer : Dromey, PHI 5. Schaums outline of Theory and Problems of programming with C : Gottfried 6. The C programming language : Kerninghan and Ritchie 7. Programming in ANSI C : Ramkumar Agarwal 8. Mastering C by Venugopal, Prasad – TMH 9. Let Us C by kanetkar 10. An introduction to data structures with applications, Jean-Paul Trembly and Paul Sorenson, (2nd edition), 1884

2

Chapter 1 Contents • • • • • Flow charts Tracing flow charts

Introduction to Problem Solving

Problem solving methods Need for computer Languages Sample Programs written in C

Flow Chart A Flow Chart is a diagrammatic representation that gives a stepby-step solution to a given problem. A Flowchart is a common type of diagram that :
a. represents an algorithm or process,

b. showing the steps as boxes of various kinds, and
c. Shows their order by connecting these with arrows.

Data is represented in these boxes, and arrows connecting them represent flow / direction of flow of data. A flow chart can therefore be used to: 1. Define and analyze processes; 2. Build a step-by-step picture of the process for analysis, discussion, or communication; and 3. Define, standardize or find areas for improvement in a process

3

The most common flow chart symbols are: 1. Data: A parallelogram that indicates data input or output (I/O) for a process. 4 . Connector: A small. labeled. Process: A rectangular flow chart shape indicating a normal process flow step. 2. 5.Fig : A simple flowchart representing a process for dealing with a non-functioning TV Remote Flowchart Symbols Different flow chart symbols have different meanings. 3. circular flow chart shape used to indicate a jump in the process flow. Terminator: An oval flow chart shape indicating the start or end of the process. 4. Decision: A diamond flow chart shape indication a branch in the process flow.

6. A really simplistic flow chart showing the flow chart symbols described above can be seen below: START TERMINATOR PROCESS NO DECISIO N YES DATA DOCUMENT END TERMINATOR Need for Programming Languages 5 . Document: used to indicate a document or report (see image in sample flow chart below).

Other languages..e.h> void main() { int a. although some languages. to express algorithms precisely. and were used to direct the behavior of machines such as Jacquard looms and player pianos. or as a mode of human communication.h> #include<conio. c = a + b: printf(“result of addition = %d”. } /* addition of 2 numbers */ #include<stdio. have a dominant implementation that is used as a reference. with many more being created every year. a=3. The earliest programming languages predate the invention of the computer.c. c=0.h> void main() { printf(“hello world”). mainly in the computer field. Some languages are defined by a specification document. Sample C Programs /*Hello world program*/ #include<stdio. as a sequence of commands. b.• • • • • • • • A programming language is an artificial language designed to express computations that can be performed by a machine.c). the C programming language is specified by an ISO Standard. Many programming languages have some form of written specification of their syntax (form) and semantics (meaning). use alternative forms of description. such as those that support functional programming or logic programming. b=4. Most programming languages describe computation in an imperative style. For example.h> #include<conio. Thousands of different programming languages have been created. such as Perl. } 6 . particularly a computer. i. Programming languages can be used to create programs that control the behavior of a machine.

~ * < : ` % > . 1. 2. *. ^ / ] . %(Mod) Special Characters: ( = ‘ \ ) ! “ blan k { $ & - } ? | _ [ . b.. Letters Digits Special Characters White Spaces White Spaces are ignored by the compiler until they are a part of string constant. B. # @ CONSTANTS & VARIABLES 7 . The character set in C Language can be grouped into the following categories. 8.z A. but are strictly prohibited while using between characters of keywords or identifiers. ……. 1.. 4. digit or symbols to represent information. /. 4.CHAPTER 2 C LANGUAGE PRELIMINARIES CONTENTS • • • • • • • C character set Identifiers and keywords Data types Declarations Expressions Statements Symbolic constants C CHARACTER SET A character denotes any alphabet. 5. 6. ……. 2. 7. Digits: 0. White Space may be used to separate words. 3.Z Arithmetic Operations: +. 3. 9 Alphabets: a. -.

Rs. O676 Hexadecimal integer constant is preceded by OX or Ox. Real Constants Real Constants consists of a fractional part in their representation. OXbcd. octal integers and hexadecimal integer. 2. 1. + 78 Some examples for invalid integer constants are 15 750. Integer constants are inadequate to represent quantities that vary continuously. Single Character Constants A Single Character constant represent a single character which is enclosed in a pair of quotation symbols. -3. +487. Spaces. 20. Some examples of octal integers are O26. Example of valid hexadecimal integers are OX2. Example of realconstants are 0. There are 3 types of integers namely decimal integer. Integer Constants Real Constants Single Character Constants String Constants Integer Constants An integer constant is a sequence of digits.0 Real Numbers can also be represented by exponential notation. 4. 435. The general form for exponential notation is mantissa exponent. C supports several types of constants. commas and non digit characters are not permitted between digits. Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or . they may contain alphabets from A to F or a to f.sign. O. 0. 3. -0. These quantities are represented by numbers containing fractional parts like 26. OX8C. The exponent is an integer number with an optional plus or minus sign. The alphabets A to F refers to 10 to 15 in decimaldigits.Constants A constant value is the one which does not change during the execution of a program. 562321.29. Example for valid decimal integer constants are 123. Example for character constants are 8 .97.0026.082. O347. 1000 Octal Integers constant consists of any combination of digits from 0 through 7 with a O at the beginning. The mantissa is either a real number expressed in decimal notation or an integer. Ox 1.000.

average1 IDENTIFIERS AND KEYWORDS Every word in C language is a keyword or an identifier/variable. No commas or blanks are allowed in it No special symbol other than an underscore can be used in it.'.. '. 9 . Ex. String Constants A string constant is a set of characters enclosed in double quotation marks. number.'5'. special character and blank space. "1234". Salary.?" Variables A variable is a value that can change any time. Keywords in C language cannot be used as a variable name. Example of variable names are Sun. It is a memory location used to store a data value. 'x'. "!.. classes. ' ' All character constants have an equivalent integer value which is called ASCII Values. Emp_name. The characters in a string constant sequence may be an alphabet. Variable names are case sensitive. A variable name should be carefully chosen by the programmer so that its use is reflected in a useful way in the entire program. Identifiers: • • • • • Identifiers are the names given to variables. "God Bless". Example of string constants are "VISHAL". methods and interfaces.. It must be a whole word and starts with either an alphabet or an underscore. They are case sensitive. number. They are specifically used by the compiler for its own purpose and they serve as building blocks of a c program..: marks grace sem1_rollno alpha Keywords: • Keywords are words that have special meaning to the C compiler.

Primary data type b. • C language data types can be broadly classified as a. There are many data types in C language. • A C programmer has to use appropriate data type as per his requirement. Derived data type c. C makes use of only 32 keywords or reserved words which combine with the formal syntax to the form the C programming language. Ex. User-defined data type DATA PRIMARY DATA SECONDARY DATA USER DEFINED CHAR INT FLOAT DOUBLE ARRAY FUNCTION POINTER STRUCTUR E UNION TYPEDEF ENUM Fig: Data Types in C Integer Data Type • • Integers are numbers without decimal point Integers are whole numbers with a range of values.: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Data types & Declarations In c. All keywords in C are written in lower case. the type of numbers or characters being used in the program. A keyword may not be used as a variable name. 10 .• • • • An identifier cannot have the same spelling and case as a C keyword. • These are data types. there are three types of data • In C language the system has to know before-hand. range of values are machine dependent.

C has three classes of integer storage namely short int. the range of an unsigned integer will be from 0 to 65535. long int num3. 2500. • Unlike signed integer.• Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is. -215 to +215-1). • To control the range of numbers and storage space. • The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space. int and long int. 100. unsigned integers are always positive and use all the bits for the magnitude of the number. Integer Data Type Memory Allocation: 11 . • A signed integer use one bit for storing sign and rest 15 bits for number. • A short int requires half the amount of storage than normal integer. Syntax: int <variable name>. • Therefore. short int num2. Example: 5. 6. • All three data types have signed and unsigned forms. int num1.

Floating Point Data Type Memory Allocation: Character Data Type • Character type variable can hold a single character and are declared by using the keyword char. both occupy 1 byte each. • Unsigned characters have values between 0 and 255. long double num3. When the accuracy of the floating point number is insufficient.Floating Point Data Type • The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. float num1. j. • As there are singed and unsigned int (either short or long). Syntax: char <variable name>. • The double is same as float but with longer precision and takes double space (8 bytes) than float. 3. 12 . S. • Floating point numbers are denoted by the keyword float. char ch = ‘a’. Syntax: float <variable name>.1254. b. but having different ranges. we can use the double to define the number. Example: a. • To extend the precision further we can use long double which occupies 10 bytes of memory space. signed characters have values from –128 to 127. double num2. g. Example: 9. in the same way there are signed and unsigned chars.125.

e. 13 . the expression is evaluated first and then replaces the previous value of the variable on the left hand side. • • • Variable is any valid C variable name. Algebraic Expression axb–c (m + n) (x + y) (m + n) * (x + y) C Expression a*b–c (ab / c) a*b/c Evaluation of Expressions • Expressions are evaluated using an assignment statement of the form Variable = expression. • In C every expression evaluates to a value i. • Some examples of C expressions are shown in the table given below.Arithmetic Expressions • An expression is a combination of variables constants and operators written according to the syntax of C language.. When the statement is encountered. every expression results in some value of a certain type that can be assigned to a variable. Example of evaluation statements are x=a*b–c y=b/c*a z = a – b / c + d. All variables used in the expression must be assigned values before evaluation is attempted.

h> void main() { printf(“hello world”). respectively. constant or keyword.h> # include <conio. • All statements are entered in small case letters. Thus . • C distinguishes between lowercase and uppercase letters in variable names. • However. } printf(“hello world”). no blank spaces are allowed within a variable. • The statements in a program must appear in the same order in which we wish them to be executed. and the syntax is #define NAME value Example : #define ANGLE_MIN 0 #define ANGLE_MAX 360 would define ANGLE_MIN and ANGLE_MAX to the values 0 and 360. 14 . which is out of sequence. Therefore a complete C program would comprise of a series of statements. Symbolic constants • C allows the definition of symbolic constants . That’s why it is often called a free-form language. • Example # include <stdio. is an statement that ends with a semicolon.Statements • Each instruction in a C program is written as a separate statement. acts as a statement terminator. • It is customary to use capital letters in defining global constants. unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement. • C has no specific rules for the position at which a statement is to be written. • Every C statement must end with a (semicolon) . • Blank spaces may be inserted between two words to improve the readability of the statement.names that will be replaced with their values when the program is compiled • Symbolic constants are defined before main().

and so on. Variable name = getchar(). Variable name is a valid ‘C’ variable. • There exists several functions in ‘C’ language that can carry out input output operations. # include < stdio. // assigns stdio-h header file to wer // Indicates the starting point of the 15 .h > program void main ( ) program. The scanf can also be used to achieve the function. • We can assign values to variable through assignment statements such as x = 5 a = 0 . Example program : # include < stdio.CHAPTER 3 INPUT-OUTPUT CONTENTS • • • • • • getchar() putchar() scanf() printf() gets() puts() • • One of the essential operations performed in a C language programs is to provide input values to the program and output the data produced by the program to a standard output device. that has been declared already and that possess the type char. Single character input output • • • The basic operation done in input output is to read characters from the standard input device such as the keyboard and to give output or writing it to the output unit usually the screen. These functions are collectively known as standard Input /Output Library. • For outputting results we have used extensively the function printf which sends results out to a terminal. Each program that uses standard input / output function must contain the statement. The getchar has the following form. • Another method is to use the Input then scanf which can be used to read data from a key board. The getchar function can be used to read a character from the standard input device.h > at the beginning.

h > void main ( ) { char s [80]. } String input and output • • • • • The gets function receives the string from standard input device while puts outputs the string to the standard output device. The puts function displays the contents stored in its parameter on the standard screen.h > // Inserts stdio. and fills the string with characters that are input from the keyboard till newline character is encountered. A string is an array or set of characters. putchar (in). printf (” The character we typed is = %c”. Example: # include < stdio. // character declaration of variable in. The standard form for the puts character is puts (str) Where str is a string variable. At the end function gets appends a null terminator as must be done to any string and returns. // message to user C = getchar () . Program shows the use of getchar function in an interactive environment. printf (” please enter one character”). The general form is putchar (variable name). // output } // Statement which displays value of C on // Standard screen. The function gets accepts the name of the string as a parameter. // get a character from key board and stores it in variable C. (That is till we press the enter key). // output ‘in’ value to standard screen.h header file into the Pgm void main ( ) // Beginning of main function. printf (“Type a string less than 80 characters:”).{ char C. { char in. 16 . displays the value stored in variable C to the standard screen. // variable declaration printf (“Type one character:”) . // assign the keyboard input value to in. // message to user in = getchar ( ) . C) . The standard form of the gets function is gets (str) Here "str" is a string variable. The putchar function which is analogous to getchar function can be used for writing characters one at a time to the output terminal. where variable is a valid C type variable that has already been declared Ex:putchar ( ). Example: #include < stdio.

• The control string specifies the field format which includes format specifications and optional number specifying field width and theconversion character % and also blanks. arg3 …………. • The format field is specified by the control string and the arguments arg1. To read the long integer data type we can use conversion specifier % ld & % hd for short integer. • The scanf function has the general form. &sum1.argn specifies the address of location where address is to be stored. arg2. The data type character d indicates that the number should be read in integer mode. Input values are generally taken by using the scanf function. If floating point numbers are assigned then the decimal or fractional part is skipped by the computer. • The general format for reading a integer number is %xd • Here percent sign (%) denotes that a specifier for conversion follows and x is an integer number which specifies the width of the field of the number that is being read. ……………. } Formatted Input For scanf: • The formatted input refers to input data that has been arranged in a particular format. &sum2). arg1. The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d the number 1342 will be cut to 134 and the remaining part is assigned to second variable sum2. If the values input are 175 and 1342 here value 175 is assigned to sum1 and 1342 to sum 2. The general format of specifying a real number input is 17 • . The field width specifier is optional. puts(s). tabs and newlines. scanf (“control string”. printf (“The string types is:”).gets (s). arg2. Input specifications for real number • Field specifications are not to be used while representing a real number therefore real numbers are specified in a straight forward manner using % f specifier. Example : scanf (“%3d %4d”. The conversion character % is followed by the type of data that is to be assigned to variable of the assignment. • The Blanks tabs and newlines are ignored by compiler.argn). Suppose the input data was follows 1342 and 175.

scanf (% f “. A simple program to illustrate the use of printf statement:#include < stdio. } Output: Hello! Welcome to IDOL. With the input data 321. &ch. 678 The values 321. • The simple statement such as printf (“Enter 2 numbers”). &c). 4. Example : scanf (“%C %15C”. Robert then a is assigned to ch and name will be assigned to Robert. nname): Here suppose the input given is a. The general format is % xc or %xs Where C and S represents character and string respectively and x represents the field width. 4. The address operator need not be specified while we input strings.76 is assigned to a . Example: scanf (“%f %f % f”.76. prompts the message enclosed in the quotation to be displayed.321.321 to b & 678 to C. &a. printf (“Welcome to the Institute of Distance & Open Learning!”). • It allows we to display information required to the user and also prints the variables we can also format the output and provide text labels. Printing One Line: printf(). Input specifications for a character. • The most simple output statement can be produced in C’ Language by using printf statement. If the number input is a double data type then the format specifier should be % lf instead of %f. 18 . &b. Single character or strings can be input by using the character specifiers.h > main ( ) { printf (“Hello!”). &variable).

It allows a variable number of arguments. %f – Print float value %g – Print using %e or %f whichever is smaller %o – Print actual value %s – Print a string %x – Print a hexadecimal integer (Unsigned) using lower case a – F %X – Print a hexadecimal integer (Unsigned) using upper case A – F %a – Print a unsigned integer. Example : printf (“Hello!\n”). There must be a conversion specifies after each variable. The variable includes all the variable to be printed in order they are to be printed. Conversion Strings and Specifiers: The printf ( ) function is quite flexible. The conversion string includes all the text labels. labels and sophisticated formatting of output. a new line character must be placed inside the quotation marks. Specifier Meaning %c – Print a character %d – Print a Integer %i – Print a Integer %e – Print float value in exponential form. variable list). If we wish to print the second message to the beginning of next line. OR printf (“\n Welcome to the Institute of Distance & Open Learning”).Both the messages appear in the output as if a single statement. %p – Print a pointer value %hx – hex short %lo – octal long %ld – long 19 . The general form of the printf ( ) function is printf (“conversion string”. escape character and conversion specifiers required for the desired output.

before the first function definition. #define UPPER 25 This statement is called ‘macro definition’ or more commonly. i <= UPPER . It is a program that processes our source program before it is passed to the compiler. i++ ) printf ( "\n%d".CHAPTER 4 PRE-PROCESSOR COMMANDS CONTENTS • #include • • #define #ifdef Introduction • • • • • • The C preprocessor is exactly what its name implies. Preprocessor commands (often known as directives) form what can almost be considered a language within C language. We would learn the following preprocessor directives here: (a) Macro expansion (b) File inclusion (c) Conditional Compilation Macro Expansion Example: #define UPPER 25 main( ) { int i . During preprocessing. i ) . The preprocessor offers several features called preprocessor directives. for ( i = 1 . But preprocessor is such a great convenience that virtually all C programmers rely on it. } In this program instead of writing 25 in the for loop we are writing it in the form of UPPER. which has already been defined before main( ) through the statement. 20 . the preprocessor replaces every occurrence of UPPER in the program with 25. just a ‘macro’. We can certainly write C programs without knowing anything about the preprocessor or its facilities. The directives can be placed anywhere in a program but are most often placed at the beginning of a program. Each of these preprocessor directives begin with a # symbol.

and that file can be included in every program we write. (b) There are some functions and some macro definitions that we need almost in all programs that we write. each containing a set of related functions. prototypes of console input/output functions are stored in the header file ‘conio. This command would look for the file goto. The preprocessor command for file inclusion looks like this: #include "filename" and it simply causes the entire contents of filename to be inserted into the source code at that point in the program It can be used in two cases: (a) If we have a very large program.c> .h extension. This directive causes one file to be included in another. the code is best divided into several different files. possibly because it contains statements which when included go to the head of our program. It is a good programming practice to keep different sections of a large program separate. For example prototypes of all mathematics related functions are stored in the header file ‘math. These commonly needed functions and macro definitions can be stored in a file.c" This command would look for the file goto. These files are #included at the beginning of main program file. 21 #include <goto.c in the specified list of directories only.h’. These are: #include "filename" #include <filename> The meaning of each of these forms is given below: #include "goto.h’. Actually there exist two ways to write #include statement. and so on. It is common for the files that are to be included to have a . This extension stands for ‘header file’.c in the current directory as well as the specified list of directories as mentioned in the include search path that might have been set up.File Inclusion The second preprocessor directive we’ll explore in this chapter is file inclusion. The prototypes of all the library functions are grouped into different categories and then stored in different header files. which would add all the statements in this file to our program as if we have typed them in.

instead of #ifdef the #ifndef directive is used. 3 and 4 would get compiled only if the macro OKAY has been defined. 2. if we want.Conditional Compilation We can. The #ifndef (which means ‘if not defined’) works exactly opposite to #ifdef. . #endif If macroname has been #defined. Here. statement 2 . Sometimes. . At a later date. main( ) { #ifdef OKAY statement 1 statement 2 statement 3 statement 4 #endif statement 5 statement 6 statement 7 } . if we want that these statements should also get compiled all that we are required to do is to delete the #ifdef and #endif statements. The above example if written using #ifndef. otherwise not. . which have the general form: #ifdef macroname statement 1 . and we have purposefully omitted the definition of the macro OKAY. would look like this: 22 . /* detects virus */ . statements 1. . statement 3 . have the compiler skip over part of a source code by inserting the preprocessing commands #ifdef and #endif. /* specific to stone virus */ . the block of code will be processed as usual.

It means than the overall program strategy should be set first and then proceed with the general logic of the program. function headings. Declare variables. • A program outline called pseudocode is made. 4. 3. b & c*/ /* Read values for a & b*/ /* calculate value of c*/ /*display the value of c */ } Writing a C program 23 . • Example: Addition of two numbers is given by C=A+B The steps required to write a program for adding two numbers is as follows: 1. A. starting and closing braces. It contains minimal program logic and more of program components such as header files. B & C Read values for A & B Add A & B. 2. store result in C Display the value of C Here is the program outline in the form of pseudocode /* Addition of two numbers*/ void main() { /* declare variables a.CHAPTER 5 PREPARING AND RUNNING A COMPLETE C PROGRAM Contents • • • • • • Planning a C program Writing a C program Writing a Program into the computer Compiling and executing Detecting Errors Debugging Techniques Planning a C Program • A C program should be written using a “top-down” approach. etc.

c. /*display the value of c */ } Writing a Program into the computer Now the next step is to compile and execute the program. /* initialize variable c */ scanf(“%d%d”. b. /* Read values for a & b*/ c = a + b. The process of Compilation and Execution is done in the software / Compiler.c 24 . usually a Borland Turbo C/C++ compiler is widely used. c. bscit.cpp”.&a.h> void main() { int a. Example: Filenames could be Addition.&b).c” extension and c++ programs by “. idol. The program can the typed and then executed in the compiler or it can be written in the compiler itself using its screen editor C programs are saved by the “.h> #include <conio. Example: /* Addition of two numbers*/ #include <stdio.c. /* calculate value of c*/ printf(“Result of Addition = %f”.c). /* declare variables a. Comment wer program wherever possible so that it reflects the program logic and makes it more readable A C program should not only execute successfully and give we results but also be readable and understandable. b & c*/ c = 0. Caution should be taken to make sure that the sequence of statements is correct. Example: calculating the value of c before reading the value of a & b is a common mistake • • • Use proper indentation wherever required because it is the key that will help we to understand wer program when it becomes too large.• • If the program strategy is well planned then this should be a very simple straightforward step.

or using the mouse directly click Compile in the menu bar. if not then the errors are listed line by line in a sequential order with a possible reason or mistake. undefined symbol. • If the compilation is successful then.Compiling and executing • • Now that the program is open in the compiler we are ready to compile it. we get a message “0 warnings & 0 errors”. • Once the program is successfully compiled and is found to be error free the next step is to execute it. It could be done either by using the key board shortcut CTRL + r. and are mostly detected when compiled. Compilation is the process that tests the programs for errors. or using the mouse to directly click on Run in the menu bar Detecting Errors All errors are difficult to be spotted before compiling. Compiling reveals the presence of syntactical or grammatical errors in a program and generates diagnostic messages Example: Common errors that are detected during compilation are Variable not defined. function prototype missing 25 . In our TC editor we can either use the keyboard shortcut Ctrl + c.

it means "assign the value of y to x. Its use in programming is somewhat different from its use in regular math. C has two unary mathematical operators and five binary mathematical operators. in a C program. on one or more operands." Instead. If we write x = y. the right side can be any expression. the form is as follows: variable = expression. all operands are expressions." In a C assignment statement. When executed. An operand is something that an operator acts on. and the left side must be a variable name. listed in Table below Table: C's unary mathematical operators. 26 . Mathematical Operators C's mathematical operators perform mathematical operations such as addition and subtraction. Thus. expression is evaluated. or action. and the resulting value is assigned to variable. The unary mathematical operators are so named because they take a single operand. it doesn't mean "x is equal to y. C operators fall into several categories: • The assignment operator • Mathematical operators • Relational operators • Logical operators The Assignment Operator The assignment operator is the equal sign (=). In C. C has two unary mathematical operators.Chapter 6 Operators and expressions Contents • • • • • • Arithmetic Unary Logical bit-wise assignment conditional operators Operators An operator is a symbol that instructs C to perform some operation.

Remember that = is the assignment operator. the increment and decrement operators modify their operand before it's used.Operator Increment Decrement Symbol ++ -- Action Increments the operand by one Decrements the operand by one Examples ++x. x++ --x. x has the value 11. y = ++x.1. the statements ++x. x = 10. They differ in terms of when the increment or decrement is performed: • When used in prefix mode. As an analogy. The operation performed is to add one to or subtract one from the operand. after the copy has been made. Subsequent changes to x. the following statements result in both y and x having the value 11. The value of x was assigned toy. we should note from above Table that either unary operator can be placed before its operand (prefix mode) or after its operand (postfix mode). • When used in postfix mode. In contrast. have no effect on y. and then its value is assigned to y. Binary Mathematical Operators C's binary operators take two operands. After these statements are executed. In other words. and y has the value 10. These two modes are not equivalent. y = x++. not with constants. not a statement of equality. think of = as the "photocopy" operator. --y. The statement y = x means to copy x into y. x-- The increment and decrement operators can be used only with variables. Look at these two statements: x = 10. are listed in Table below. The binary operators. y = y . which include the common mathematical operations found on a calculator. and then x was incremented.x is incremented. 27 . the increment and decrement operators modify their operand after it's used An example should make this clearer. are the equivalent of these statements: x = x + 1.

C's six relational operators are listed in Table below Operator Equal Greater than Less than Greater than or equal to Less than or equal to Not equal Symbo l == > < >= <= != Question Asked Is operand 1 equal to operand 2? Is operand 1 greater than operand 2? Is operand 1 less than operand 2? Is operand 1 greater than or equal to operand 2? Is operand 1 less than or equal to operand 2? Is operand 1 not equal to operand 2? Example x == y x>y x<y x >= y x <= y x != y Table: Relational operators in use. "Is x greater than 100?" or "Is y equal to 0?" An expression containing a relational operator evaluates to either true (1) or false (0). Operator Addition Subtraction Multiplication Division Modulus Symbo l + * / % Action Adds two operands Subtracts the second operand from the first operand Multiplies two operands Divides the first operand by the second operand Gives the remainder when the first operand is divided by the second operand Example x+y x-y x*y x/y x%y Relational Operators C's relational operators are used to compare expressions. asking questions such as.Table: C's binary mathematical operators. Expression How It Reads 5 == 1 Is 5 equal to 1? 5>1 Is 5 greater than 1? 5 != 1 Is 5 not equal to 1? (5 + 10) == (3 * 5) Is (5 + 10) equal to (3 * 5)? What It Evaluates To 0 (false) 1 (true) 1 (true) 1 (true) 28 .

false (0) otherwise (exp1 || exp2) True (1) if either exp1 or exp2 is true. we would write x += 5.Table: C's logical operators. depending on the true/false value of their operand(s). In more general notation. Using a compound assignment operator. because one operand is false True (1). Table below shows some actual code examples. because both operands are true True (1). For example. Table: Code examples of C's logical operators. because one operand is true False (0). 29 . Expression (5 == 5) && (6 != 2) (5 > 1) || (6 < 1) (2 == 1) && (5 == 5) !(5 == 4) What It Evaluates To True (1). which we can think of as a shorthand method of assignment. add 5 to x and assign the result to x. in other words. We could write x = x + 5. Expression What It Evaluates To (exp1 && exp2) True (1) only if both exp1 and exp2 are true. Operator Symbol AND && OR || NOT ! Example exp1 && exp2 exp1 || exp2 !exp1 Table: C's logical operators in use. false (0) only if both are false (!exp1) False (0) if exp1 is true. because the operand is false Compound Assignment Operators C's compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation. true (1) if exp1 is false We can see that expressions that use the logical operators evaluate to either true or false. the compound assignment operators have the following syntax (where op represents a binary operator): exp1 op= exp2 This is equivalent to writing exp1 = exp1 op exp2. or. say we want to increase the value of x by 5.

If exp1 evaluates to true (that is.. x *= y y -= z + 1 a /= b x += y / 8 y %= 3 It Is Equivalent To This x=x*y y=y-z+1 a=a/b x=x+y/8 y=y%3 The Conditional Operator The conditional operator is C's only ternary operator. The preceding statement could also be written like this: if (x > y) z = x. the entire expression evaluates to the value of exp2. we could write z = (x > y) ? x : y. The conditional operator can also be used in places we can't use an if statement. but the conditional operator is more concise. such as inside a single printf() statement: printf( "The larger value is %d".. If exp1 evaluates to false (that is. else z = y..We can create compound assignment operators using the five binary mathematical operators Table: Examples of compound assignment operators. to make z equal to the larger of x and y. nonzero). For example. Perhaps we've noticed that the conditional operator functions somewhat like an if statement. meaning that it takes three operands. the entire expression evaluates as the value of exp3. Its syntax is exp1 ? exp2 : exp3. The conditional operator can't be used in all situations in place of an if. the following statement assigns the value 1 to x if y is true and assigns 100 to x if y is false: x = y ? 1 : 100. zero). When We Write This.else construction. ((x > y) ? x : y) ). Likewise.. 30 .

These permit the programmer to access and manipulate individual bits within a piece of data. one’s complement of 65 means one’s complement of 0000 0000 0100 0001. One’s complement of 65 therefore would be. Operator ~ >> << & | ^ One’s Complement Operator On taking one’s complement of a number. showbits ( k ) .. Similarly. } } And here is the output of the above program. For example one’s complement of 1010 is 0101. all 1’s present in the number are changed to 0’s and all 0’s are changed to 1’s. Thus. j <= 3 . one’s complement of 1111 is 0000. printf ( "\nOne’s complement of %d is ".Bitwise Operators One of C’s powerful features is a set of bit manipulation operators. j ) . which is binary equivalent of 65.. for ( j = 0 . k = ~j . showbits ( j ) . j ) . j++ ) { printf ( "\nDecimal %d is same as binary ". k . 1111 1111 1011 1110 One’s complement operator is represented by the symbol main( ) { int j. Decimal 0 is same as binary 0000000000000000 One’s complement of 0 is 1111111111111111 Decimal 1 is same as binary 0000000000000001 One’s complement of 1 is 1111111111111110 Decimal 2 is same as binary 0000000000000010 One’s complement of 2 is 1111111111111101 Decimal 3 is same as binary 0000000000000011 One’s complement of 3 is 1111111111111100 31 Meaning One’s Complement Operator Right Shift Operator Left Shift Operator Bitwise AND Operator Bitwise OR Operator Bitwise XOR Operator .

showbits ( i ) . and for each bit shifted. j++ ) { k = i >>j . These blanks must be filled somehow. main( ) { int i = 5225. printf ( "\n%d right shift %d gives ". the only difference being that the bits are shifted to the left. printf ( "\nDecimal %d is same as binary ". i ) . Thus. Similarly. They are always filled with zeros. its right operand). 32 . j.Right Shift Operator The right shift operator is represented by >>. showbits ( k ) .. if the variable ch contains the bit pattern 11010111. j ) . i. a 0 is added to the right of the number. Decimal 5225 is same as binary 0001010001101001 5225 right shift 0 gives 0001010001101001 5225 right shift 1 gives 0000101000110100 5225 right shift 2 gives 0000010100011010 5225 right shift 3 gives 0000001010001101 5225 right shift 4 gives 0000000101000110 5225 right shift 5 gives 0000000010100011 Left Shift Operator This is similar to the right shift operator.. then. It needs two operands. ch >> 1 would give 01101011 and ch >> 2 would give 00110101. As the bits are shifted to the right. for ( j = 0 . ch >> 3 would shift all bits in ch three places to the right. For example. blanks are created on the left. k .e. } } The output of the above program would be. It shifts each bit in its left operand to the right. The number of places the bits are shifted depends on the number following the operator (i. j <= 5 . ch >> 5 would shift all bits 5 places to the right.

printf ( "\nDecimal %d is same as ". printf ( "\n%d left shift %d gives ". showbits ( k ) .. While operating upon these two operands they are compared on a bit-by-bit basis. k . } } The output of the above program would be. i ) . j ) .main( ) { int i = 5225. i. Decimal 5225 is same as binary 0001010001101001 5225 left shift 0 gives 0001010001101001 5225 left shift 1 gives 0010100011010010 5225 left shift 2 gives 0101000110100100 5225 left shift 3 gives 1010001101001000 5225 left shift 4 gives 0100011010010000 Bitwise AND Operator This operator is represented as &. showbits ( i ) .. j++ ) { k = i <<j . First bit 0 0 1 1 Second bit 0 1 0 1 Resultant bit 0 0 0 1 The example given below shows more clearly what happens while ANDing one operand with another. It is different than &&. j <= 4 . This operand when ANDed bitwise 1 0 1 0 1 0 1 0 With this operand yields 1 1 0 this result 1 0 0 Bitwise OR Operator 0 0 0 0 0 0 1 1 1 0 33 . The & operator operates on two operands. the logical AND operator. j. for ( j = 0 . The & operator operates on a pair of bits to yield a resultant bit. The second operand is often called an AND mask. Hence both the operands must be of the same type (either char or int).

when any one of the two bits or both the bits are 1. 11010000 Original bit pattern 00000111 OR mask ------------11010111 Resulting bit pattern Bitwise XOR Operator The XOR operator is represented as ^ and is also called an Exclusive OR Operator. The OR operator returns 1. A number XORed with another number twice gives the original number 34 . First bit 0 0 1 1 Second bit 0 1 0 1 Resultant bit 0 1 1 1 Using the Truth table confirm the result obtained on ORing the two operands as shown below. The truth table for the XOR operator is given below First bit 0 1 Second bit 0 1 Resultant bit 1 0 XOR operator is used to toggle a bit ON or OFF. The rules that govern the value of the resulting bit obtained after “OR”ing of two bits is shown in the truth table below.Another important bitwise operator is the OR operator which is represented as |. whereas XOR returns 1 only if one of the two bits is 1.

Chapter 7 Control statements Contents • While • do-while • for statements • nested loops • if else. continue and goto statements • comma operators The while Statement The while statement. 4. the while statement terminates. 35 . If condition evaluates to false (that is. and statement is a single or compound C statement. and execution passes to the first statement following statement 3. switch • break. If condition evaluates to true (that is. executes a block of statements as long as a specified condition is true. the following events occur: 1. zero). When program execution reaches a while statement. The while statement has the following form: while (condition) statement condition is any C expression. 2. The operation of a while statement. also called the while loop. nonzero). The expression condition is evaluated. the while statement terminates. and execution passes to the first statement following statement. Execution returns to step 1 Figure.

which executes a block of statements as long as a specified condition is true. The do.while statement./* Demonstrates a simple while statement */ #include <stdio.while Loop C's loop construct is the do.. while (count <= 20) { printf("%d\n". and statement is a single or compound C statement. condition is any C expression.... The structure of the do.. int main() { /* Print the numbers 1 through 20 */ count = 1...while loop.. 2. as is done by the for loop and the while loop. count++.. condition is evaluated. } Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 The do. If it's true..h> int count. the loop terminates 36 . The statements in statement are executed.while loop is as follows: do statement while (condition). } return 0. When program execution reaches a do. count).while loop tests the condition at the end of the loop rather than at the beginning. If it's false. execution returns to step 1. the following events occur: 1.

printf("\n1 . return selection.while loop are always executed at least once. &selection )... so the associated statements are not executed at all if the test condition is initially false.Change a record").h> int get_menu_choice( void ). In contrast.. printf("\n2 .Add a Record" ). printf("\nEnter a selection: " ). 37 . Example: /* Demonstrates a simple do.Quit").The statements associated with a do. return 0. scanf("%d". } int get_menu_choice( void ) { int selection = 0. }while ( selection < 1 || selection > 4 ). for loops and while loops evaluate the test condition at the start of the loop. printf("\n4 . printf("We chose Menu Option %d\n". printf("\n3 . This is because the test condition is evaluated at the end.. do { printf("\n" ). choice ). main() { int choice.Delete a record"). instead of the beginning. choice = get_menu_choice().while statement */ #include <stdio. of the loop. printf("\n" ).

Delete a record – Quit Enter a selection: 8 1 . initial is any valid C expression. x <10. the statements execute. Statement(s) are the C statements that are executed as long as the condition remains true. otherwise. It is usually an expression that increments a variable initialized bythe initial expression.Add a Record . It is usually a relational expression.Change a record 3 . It is usually an assignment statement that sets a variable to a particular value condition is any valid C expression. the C statement(s) in statement(s) are executed. x++) printf( "\nThe value of x is %d".} 1 2 3 4 . A for statement is a looping statement. increment is any valid C expression. If 99 is */ 38 .Quit Enter a selection: 4 We chose Menu Option 4 The for Statement for (initial.Add a Record 2 . Example: /*Obtains values from the user until 99 is entered */ int nbr = 0. If the condition is true. It can have an initialization. x ).Change a record . nbr != 99. the increment expression is evaluated. The for statement executes the initial expression first. and increment as parts of its command. Example: /* Lets user enter up to 10 integer values */ /* Values are stored in an array named value. The for statement then rechecks the condition and continues to loop until the condition is false. It then checks the condition. Example: /* Prints the value of x as it counts from 0 to 9 */ int x. test condition. the for statement terminates. for ( . Once the statements are completed. &nbr ). condition.Delete a record 4 . increment) statement(s). and execution passes to the first statement following statement(s). ) scanf( "%d". When condition evaluates to false (zero). for (x = 0.

35 ). ctr < 10 && nbr != 99. row > 0. This function takes two type intvariables. col > 0. main() calls draw_box() and passes the value 8 as the row and the value 35 as the column. int). int column ) { int col. the loop stops */ int value[10]. The first is why the local variable col was declared. The program has only one command to print an X. row--) { for (col = column. a function prototype for draw_box() is declared./* entered. return 0. value[ctr] = nbr. forming an 8*35 square. The 39 . we might see a couple things we don't readily understand. } void draw_box( int row. int ctr. In this listing. printf("\n"). row and column. which contain the dimensions of the box of Xs to be drawn. Looking closely at the draw_box() function.nbr=0. 280 Xs are printed on-screen. main() { draw_box( 8. for ( . 99 to quit "). &nbr). Nested for statements. } Nesting for Statements A for statement can be executed within another for statement. This is called nesting. ctr++) { puts("Enter a number. col--) printf("X"). scanf("%d". but it is nested in two loops. /* Demonstrates nesting two for statements */ #include <stdio. } } XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX When we run this program.h> void draw_box( int. for (ctr = 0.

statement2. In either case. If expression evaluates to true. statement is not executed. Statements in a C program normally execute from top to bottom. or block. } • • • • • • Example: Demonstrates if statements. how relational operators are used to make program control statements. The if statement is one of C's program control statements. Program control statements can cause other program statements to execute multiple times or to not execute at all. Both of these will become clearer after we look at the two for loops. are considered to comprise the complete if statement. In its basic form. they are not separate statements. Note that both the line if (expression) and the line statement.h> 40 . /* additional code goes here */ statementn. /* Demonstrates the use of if statements */ #include <stdio. depending on the circumstances. The if Statement • • • Relational operators are used mainly to construct the relational expressions used in if and while statements. we could write an if statement as follows: if (expression) { statement1. in the same order as they appear in wer source code file. A block can be used anywhere a single statement can be used. the if statement evaluates an expression and directs program execution depending on the result of that evaluation. execution then passes to whatever code follows the if statement. As defined earlier in this chapter. Therefore.second is why the second printf() was used. statement is executed. An if statement can control the execution of multiple statements through the use of a compound statement. a block is a group of two or more statements enclosed in braces. The form of an if statement is as follows: if (expression) statement. A program control statement modifies the order of statement execution. We could say that execution of statement depends on the result of expression. If expression evaluates to false.

&y). } Input an integer value for x: 100 Input an integer value for y: 10 x is greater than y Input an integer value for x: 10 Input an integer value for y: 100 x is smaller than y Input an integer value for x: 10 Input an integer value for y: 10 x is equal to y The else Clause An if statement can optionally include an else clause. if (x > y) printf("x is greater than y\n"). /* Test values and print result */ if (x == y) 41 . scanf("%d".h> int x. y. statement2 is executed. /* Test values and print result */ if (x == y) printf("x is equal to y\n"). If expression evaluates to true. return 0. statement1 is executed. else statement2. &y). Example: An if statement with an else clause. Both statement1 and statement2 can be compound statements or blocks.int x. if (x < y) printf("x is smaller than y\n"). scanf("%d". If expression evaluates to false. /* Demonstrates the use of if statement with else clause */ #include <stdio. scanf("%d". y. printf("\nInput an integer value for y: "). &x). printf("\nInput an integer value for y: "). main() { /* Input the two values to be tested */ printf("\nInput an integer value for x: "). &x). The else clause is included as follows: if (expression) statement1. scanf("%d". main() { /* Input the two values to be tested */ printf("\nInput an integer value for x: ").

If the first expression is not true. and the second is true. If the first expression is not true. else if (x > y) printf("x is greater than y\n"). Form 3 if( expression1 ) statement1.30. This is the most common form of the if statement. else statement2. is checked. else tax = . This is the if statement in its simplest form. If the first expression. the second expression. statement1 is executed. statement1 is ignored. } Input an integer value for x: 99 Input an integer value for y: 8 x is greater than y Input an integer value for x: 8 Input an integer value for y: 99 x is smaller than y Input an integer value for x: 99 Input an integer value for y: 99 x is equal to y The if Statement : Different forms Form 1 if( expression ) statement1. This is a nested if. statement2 is executed. If expression is not true. Only one of the three statements is executed. statement1 is executed. If expression is true. If both expressions are false. expression2. is true. Form 2 if( expression ) statement1. next_statement.0000 ) tax = .printf("x is equal to y\n"). otherwise.25. next_statement. statement2 is executed. else if( expression2 ) statement2. If expression is true. else printf("x is smaller than y\n"). expression1. else statement3. Example 1 if( salary > 45. 42 . next_statement. statement1 is executed before the program continues with the next_statement. return 0. statement3 is executed.

Example 2 if( age < 18 ) printf("Minor"); else if( age < 65 ) printf("Adult"); else printf( "Senior Citizen"); The switch Statement C's most flexible program control statement is the switch statement, which lets wer program execute different statements based on an expression that can have more than two values. Earlier control statements, such as if, were limited to evaluating an expression that could have only two values: true or false. To control program flow based on more than two values, we had to use multiple nested if statements, as shown in Listing 13.4. The switch statement makes such nesting unnecessary. The general form of the switch statement is as follows: switch (expression) { case template_1: statement(s); case template_2: statement(s); ... case template_n: statement(s); default: statement(s); } In this statement, expression is any expression that evaluates to an integer value: type long, int, or char. The switch statement evaluates expression and compares the value against the templates following each case label, and then one of the following happens: If a match is found between expression and one of the templates, execution is transferred to the statement that follows the case label. If no match is found, execution is transferred to the statement following the optional default label. If no match is found and there is no default label, execution passes to the first statement following the switch statement's closing brace.

Using the switch statement. /* Demonstrates the switch statement. */ #include <stdio.h> main() { int reply; puts("Enter a number between 1 and 5:"); scanf("%d", &reply); switch (reply) { case 1: puts("We entered 1."); 43

case 2: puts("We entered 2."); case 3: puts("We entered 3."); case 4: puts("We entered 4."); case 5: puts("We entered 5."); default: puts("Out of range, try again."); } return 0; } Enter a number between 1 and 5: 2 We entered 2. We entered 3. We entered 4. We entered 5. Out of range, try again. It looks as though the switch statement finds the first matching template and then executes everything that follows (not just the statements associated with the template). That's exactly what does happen, though. That's how switch is supposed to work. In effect, it performs a goto to the matching template. To ensure that only the statements associated with the matching template are executed, include a break statement where needed. Listing 13.6 shows the program rewritten with break statements. Now it functions properly. Correct use of switch, including break statements as needed. /* Demonstrates the switch statement correctly. */ #include <stdio.h> main() { int reply; puts("\nEnter a number between 1 and 5:"); scanf("%d", &reply); switch (reply) { case 0: break; case 1: { puts("We entered 1.\n"); break; } case 2: { puts("We entered 2.\n"); break; } case 3: 44

{ puts("We entered 3.\n"); break; } case 4: { puts("We entered 4.\n"); break; } case 5: { puts("We entered 5.\n"); break; } default: { puts("Out of range, try again.\n"); } } /* End of switch */ } Enter a number between 1 and 5: 1 We entered 1. Enter a number between 1 and 5: 6 Out of range, try again.

The break Statement The break statement can be placed only in the body of a for loop, while loop, or do...while loop. (It's valid in a switch statement too, but that topic isn't covered until later in this chapter.) When a break statement is encountered, execution exits the loop. The following is an example: for ( count = 0; count < 10; count++ ) { if ( count == 5 ) break; } Left to itself, the for loop would execute 10 times. On the sixth iteration, however, count is equal to 5, and the break statement executes, causing the for loop to terminate. Execution then passes to the statement immediately following the for loop's closing brace. When a break statement is encountered inside a nested loop, it causes the program to exit the innermost loop only. Example: Using the break statement. /* Demonstrates the break statement. */ 45

count++) { if (s[count] == `. displaying only those */ 46 . 11: 12: /* Input a line of text.. Following example uses the continue statement. 10: int ctr.h> char s[] = "This is a test string. printf("\nOriginal string: %s". or a do.1. */ 8: 9: char buffer[81].while loop.') { s[count+1] = `\0'. The statements between the continue statement and the end of the loop aren't executed. 15: gets(buffer). return 0. Example: Using the continue statement. 16: 17: /* Go through the string. a while loop. The continue Statement Like the break statement. Notice how this differs from the operation of a break statement. s[count]!='\0'. s). Modified string: This is a test string. */ 2: 3: #include <stdio. The operation of continue is also shown in Figure 13. for (count = 0.#include <stdio. */ 13: 14: puts("Enter a line of text:"). the next iteration of the enclosing loop begins immediately. It contains two sentences. } Original string: This is a test string..". } } printf("\nModified string: %s\n". 1: /* Demonstrates the continue statement. s). main() { int count. This program accepts a line of input from the keyboard and then displays it with all lowercase vowels removed. the continue statement can be placed only in the body of a for loop. When a continue statement executes.h> 4: 5: main() 6: { 7: /* Declare a buffer for input and a counter variable. It contains two sentences. break.

*/ for (ctr = 0. } return 0. /* If not a vowel. buffer[] holds the string that the user enters in line 15.18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: /* characters that are not lowercase vowels. control passes to the if statement. display it. The other variable. x <= 10. x ). an if statement in lines 26 through 28 checks the letter against lowercase vowels. For each letter in the loop. it does use a continue statement effectively. ctr. } The goto Statement 47 . The continue Statement continue. for( x = 1. increments through the elements of the array buffer[]. a continue statement executes. ctr++) { /* If the character is a lowercase vowel. /* Get next instance x */ printf( "\n%d". while the for loop in lines 20 through 34 searches for vowels. } Enter a line of text: This is a line of text Ths s ln f txt Although this isn't the most practical program. buffer[ctr] !='\0'. If there is a match. */ if (buffer[ctr] == `a' || buffer[ctr] == `e' || buffer[ctr] == `i' || buffer[ctr] == `o' || buffer[ctr] == `u') continue. Lines 9 and 10 declare the program's variables. which displays a single character onscreen. putchar(). sending control back to line 20. */ putchar(buffer[ctr]). printf("Printing only the even numbers from 1 to 10\n"). If the letter isn't a vowel. It causes the control of a program to skip the rest of the current iteration of a loop and start the next iteration. the for statement. continue is used inside a loop. Line 33 contains a new library function. Example int x. x++ ) { if( x % 2 != 0 ) /* See if the number is NOT even */ continue. loop back */ /* without displaying it. and line 33 is executed.

or branching. to the location specified by the goto statement.The goto statement is one of C's unconditional jump. 33: 34: end: . 1: /* Demonstrates the goto statement */ 2: 3: #include <stdio. for example). 12: scanf("%d". or branches. Take a look at Listing 13. When program execution reaches a goto statement. but they can be in different blocks. 32: puts("We entered something between 2 and 10. 8: 9: start: . execution immediately jumps.\n"). 25: goto end. 29: goto end.\n"). This statement is unconditional because execution always branches when a goto statement is encountered.3. 20: else 21: goto location2. 13: 14: if (n < 0 ||n > 10 ) 15: goto start. 35: return 0. 36: } Enter a number between 0 and 10: 1 We entered 1. 16: else if (n == 0) 17: goto location0. 30: 31: location2: .\n"). Enter a number between 0 and 10: 9 We entered something between 2 and 10. &n). statements. 22: 23: location0: . 26: 27: location1: . 28: puts("We entered 1. A goto statement and its target must be in the same function. a simple program that uses a goto statement. 10: 11: puts("Enter a number between 0 and 10: "). the branch doesn't depend on any program conditions (unlike if statements. 24: puts("We entered 0.h> 4: 5: main() 6: { 7: int n. 48 . Example: Using the goto statement. 18: else if (n == 1) 19: goto location1.

and then increments b: x = (a++ . If we want the label by itself on a line. We can form an expression by separating two subexpressions with a comma. which is on line 9. In certain situations. Otherwise. We can always write the needed code using C's other branching statements. When compiled. Using parentheses is necessary because the comma operator has low precedence. We can use goto to transfer execution both into and out of loops. The goto Statement goto location. function arguments. For example. the program checks on line 16 to see whether the number equals 0. DO use the logical operators && and || instead of nesting if statements. and so on. Because the ++ operator is used in postfix mode. The program executes the same logic for the value of 1 and all values between 2 and 10 as a whole. The result is as follows: Both expressions are evaluated. however. the program uses a goto statement on line 15 to go to start. A label statement consists of an identifier followed by a colon and a C statement: location: a C statement. The goto on line 25 sends control to end at the end of the program. serving to separate variable declarations. however. even lower than the assignment operator. such as a for statement.This is a simple program that accepts a number between 0 and 10. is that both the goto and the target must be in the same function. The target of a goto statement can come either before or after that statement in the code. As we'll learn in the next chapter. DO use (expression == 0) instead of (!expression). The Comma Operator The comma is frequently used in C as a simple punctuation mark. location is a label statement that identifies the program location where execution is to branch. They can be in different blocks. No programming task requires the goto statement. DON'T confuse the assignment operator (=) with the equal to (==) operator. There are two reasons:We don't need it. If the number isn't between 0 and 10. but we should never do this. If it does. with the left expression being evaluated first. a goto statement on line 17 sends control to location0 (line 23). these two expressions evaluate the same. then increments a. I strongly recommend that we never use the goto statement anywhere in wer programs. The only restriction. the first is more readable. In fact. as mentioned earlier. b++). we can follow it with the null statement (a semicolon by itself): location: . 49 . the value of b--before it is incremented--is assigned to x. the comma acts as an operator rather than just as a separator. the following statement assigns the value of b to x. which prints a statement on line 24 and executes another goto. The entire expression evaluates to the value of the right expression. the most common use of the comma operator is in for statements.

50 .

It is the variable’s storage class that determines in which of these two locations the value is stored. Life 51 . i. Automatic Storage Class The features of a variable defined to have an automatic storage class are as under: Storage Memory. There are four storage classes in C: (a) Automatic storage class (b) Register storage class (c) Static storage class (d) External storage class Let us examine these storage classes one by one. (b) What will be the initial value of the variable. Scope Local to the block in which the variable is defined. in which functions the value of the variable would be available.e. a variable name identifies some physical location within the computer where the string of bits representing the variable’s value is stored. i. Moreover. (c) What is the scope of the variable. which is often called a garbage value. external.e. Till the control remains within the block in which the variable is defined.Chapter 8 Storage types Contents: • Automatic.(i. register and static variables. (d) What is the life of the variable. the default initial value). Default initial value An unpredictable value. a variable’s storage class tells us: (a) Where the variable would be stored. how long would the variable exist. if initial value is not specifically assigned. From C compiler’s point of view. There are basically two kinds of locations in a computer where such a value may be kept— Memory and CPU registers.e.

main( ) { auto int i = 1 . Life A value stored in a CPU register can always be accessed faster than the one that is stored in memory. even though we have declared the storage class of i as register. i <= 10 . Local to the block in which the variable is defined.. { { { printf ( "\n%d ". i++ ) printf ( "\n%d". } Here. Therefore. if a variable is used at many places in a program it is better to declare its storage class as register. Not every type of variable can be stored in a CPU register.. Till the control remains within the block in which the variable is defined. A good example of frequently used variables is loop counters. i ) . i ) .Scope and life of an automatic variable is illustrated in the following program. 52 . Because the number of CPU registers are limited. } printf ( "%d". } } The output of the above program is: 111 Register Storage Class The features of a variable defined to be of register storage class are as under: Storage CPU registers. the variable works as if its storage class is auto. main( ) { register int i . for ( i = 1 . We can name their storage class as register. we cannot say for sure that the value of i would be stored in a CPU register. Default initial value Scope Garbage value. i ) . i ) . What happens in such an event. } printf ( "%d ". and they may be busy doing some other task.

if we use the register storage class for a float or a double variable we won’t get any error messages. In the above 53 . Because i is static. i=i+1. Value of the variable persists between different function calls. } increment( ) { static int i = 1 . It is never initialized again. Static Storage Class The features of a variable defined to have a static storage class are as under: Storage Default initial value Scope Memory. } Like auto variables. which require 4 and 8 bytes respectively. Their values persist. Local to the block in which the variable is defined. i ) . i is incremented to 2. this value persists. the current value of i (i. However. i is not re-initialized to 1. Zero. Life Example: main() { increment( ) . printf ( "%d\n". if the storage class is static then the statement static int i = 1 is executed only once. if the microprocessor has 16-bit registers then they cannot hold a float value or a double value. increment( ) . it is initialized to 1 only once. When increment( ) is called the third time. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3. on the contrary its old value 2 is still available. All that would happen is the compiler would treat the variables to be of auto storage class. 3) gets printed and once again i is incremented. During the first call to increment( ). If the control comes back to the same function again the static variables have the same values they had last time around. static variables are also local to the block in which they are declared. This current value of i (i. The next time increment( ) is called. The difference between them is that static variables don’t disappear when the function is no longer active. In short.For example. In the above example. increment( ) . irrespective of how many times the same function is called. i is static.e.e.

yet are available to all functions that care to use them. External variables are declared outside all functions. increment( ) . } increment( ) { i=i+1.External Storage Class The features of a variable whose storage class has been defined as external are as follows: Storage Default initial value Scope Life Memory. decrement( ) . not local. As long as the program’s execution doesn’t come to an end. i ) . } decrement( ) { i=i-1. printf ( "\non decrementing i = %d". Zero. Global. the value of i is available to the functions increment( ) and decrement( ) since i has been declared outside all functions. We can make a few ground rules for usage of different storage classes in different programming situations with a view to: 54 . increment( ) . that their scope is global. i ) . main( ) { printf ( "\ni = %d". Example: int i . decrement( ) . } The output would be: i=0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0 As is obvious from the above output. printf ( "\non incrementing i = %d". i ) .

which get used a number of times in a program. In fact most of the times we end up using the auto variables. there are very few CPU registers at our disposal and many of them might be busy doing something else. Make careful utilization of the scarce resources. − If we don’t have any of the express needs mentioned above. then use the auto storage class. because often it so happens that once we have used the variables in a function we don’t mind loosing them. A typical application of register storage class is loop counters. 55 . Declaring all the variables as extern would amount to a lot of wastage of memory space because these variables would remain active throughout the life of the program.(a) economise the memory space consumed by the variables (b) improve the speed of execution of the program The rules are as under: − Use static storage class only if we want the value of a variable to persist between different function calls. − Use register storage class for only those variables that are being used very often in a program. This would avoid unnecessary passing of these variables as arguments when making a function call. Reason is. − Use extern storage class for only those variables that are being used by almost all the functions in the program.

main( ) itself is a function and through it we are calling the function message( ). Cry. and the world smiles with we. 56 .. when we say that main( ) ‘calls’ the function message( ). whereas message( ) becomes the ‘called’ function. Example: main() { message( ) . sometimes it’s complex. printf ( "\nCry. Thus. it falls asleep while the message( ) function wakes up and goes to work. Sometimes the interaction with this person is very simple." ) . the control returns to main( ).... Every C program can be thought of as a collection of these functions.. Using a function is something like hiring a person to do a specific job. and we stop the monotony! Here. and the world smiles with we. When the message( ) function runs out of statements to execute. which comes to life again and begins executing its code at the exact point where it left off. We mean that the control passes to the function message( ).. } And here’s the output. main( ) becomes the ‘calling’ function. } message( ) { printf ( "\nSmile. and we stop the monotony!" ) . Smile.Chapter 9 Functions Contents • • • • • Defining and accessing Passing arguments Function prototypes Recursion Library functions Function: A function is a self-contained block of statements that perform a coherent task of some kind. The activity of main( ) is temporarily suspended.

The arguments are sometimes also called ‘parameters’. b and c through the keyboard and then output the sum of a. { 57 . y. b and c. However. } calsum ( x.From this program a number of conclusions can be drawn: − Any C program contains at least one function. c.When main( ) runs out of function calls. &b. − If a program contains only one function. − After each function has done its thing. then we must pass on these values to calsum( ). − Each function in a program is called in the sequence specified by the function calls in main( ). sum . in main( ) we receive the values of a. it must be main( ). then one (and only one) of these functions must be main( ). sum ) . scanf ( "%d %d %d". We have unknowingly used the arguments in the printf( ) and scanf( ) functions. /* Sending and receiving values between functions */ main( ) { int a. z . sum = calsum ( a. control returns to main( ). Consider the following program. the format string and the list of variables used inside the parentheses in these functions are arguments. the program ends. and once calsum( ) calculates the sum we must return it from calsum( ) back to main( ). − If a C program contains more than one function. printf ( "\nSum = %d". y. − There is no limit on the number of functions that might be present in a C program. because program execution always begins with main( ). If sum is to be calculated in calsum( ) and values of a. b. printf ( "\nEnter any three numbers " ) . b and c are received in main( ). z ) int x. the calculation of sum is done in a different function called calsum( ). &a. b. &c ) . Passing Arguments The mechanism used to convey information to the function is the ‘argument’. In this program. c ) .

(b) The variables a. whereas the variables x. However. y and z: calsum ( x. y. from the function main( ) the values of a. a. b . return ( y ) . // function call printf ( "\nSquare of %f is %f". b and c are called ‘actual arguments’. b and c are passed on to the function calsum( ).. the type. &a ) . y and z are called ‘formal arguments’. (2) It returns the value present in the parentheses after return. } And here is the output. b = square ( a ) .. // function prototype float a. y=x*x. by making a call to the function calsum( ) and mentioning a.. b and c in the parentheses: sum = calsum ( a. z ) int x. (c) The return statement serves two purposes: (1) On executing the return statement it immediately transfers the control back to the calling program. printf ( "\nEnter any number " ) . } float square ( float x ) // function definition { float y . to th3e calling program. scanf ( "%f". } And here is the output. Function Declaration and Prototypes main() { float square ( float ) . d=x+y+z.int d . 58 . y. In the above program the value of sum of three numbers is being returned. c ) . b ) . Any number of arguments can be passed to a function being called. return ( d ) .. In the calsum( ) function these values get collected in three variables x. z . order and number of the actual and formal arguments must always be same. b. Enter any three numbers 10 20 30 Sum = 60 There are a number of things to note about this program: (a) In this program.

i-. it is possible for the functions to call themselves. fact = factorial ( a ) . scanf ( "%d". fact ) . i .) f=f*i. A function is called ‘recursive’ if a statement within the body of a function calls the same function. main( ) { int a. the and that number. As we know. return ( f ) . For example. for ( i = x . This statement is often called the prototype declaration of the square( ) function. Hence this can be programmed using recursion.250000 The function square( ) must be declared in main( ) as float square ( float ) .. Example: Suppose we want to calculate the factorial value of an integer. Sometimes called ‘circular definition’.250000 number 2. before we try to write a recursive function for calculating factorial let us take a look at the non-recursive function for calculating the factorial value of an integer. } And here is the output. } factorial ( int x ) { int f = 1.. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for factorial. However. Enter any number 3 Factorial value = 6 59 . fact . recursion is thus the process of defining something in terms of itself. It means square( ) is a function that receives a float and returns a float. Recursion In C.5 is 6. We have done the prototype declaration in main( ) because we have called it from main( ). 4 factorial is 4 * 3 * 2 * 1. printf ( "Factorial value = %d". printf ( "\nEnter any number " ) . i >= 1 .Enter any Square of Enter any Square of number 1.5 1. Thus factorial of a number can be expressed in the form of itself.5 is 2.5 2. &a ) .

scanf(). in short.Library Functions A library function is a function that can be called by a program to perform some task. which comprise suites of functions that are loosely related in some way. but it is not part of the program itself. Typically library functions are collected together into libraries. An example might be a collection of functions that deal with dates and times and how they can be formatted or represented. 60 . Example : printf(). Libraries save programmers the bother of writing code to do the same tasks time and time again. libraries encourage code reuse.

As individual array element can be used anywhere that a normal variable with a statement such as g = grade [50]. which represent not a single value of grade but a entire set of grades. Any subscripts 0 to 49 are valid. The general form of declaration is: type variable-name[50]. More generally if I is declared to be an integer variable. Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades. (For this reason. Will take the value contained in the element number I of the grades array to 61 . we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number. In C we can define variable called grades. Declaration of arrays: Like any other variable arrays must be declared before they are used. The statement assigns the value stored in the 50th index of the array to the variable g. Each element of the set can then be referenced by means of a number called as index number or subscript. rather than as referring to the first element). such as int float or char and the size indicates the maximum number of elements that can be stored inside the array for ex: float height[50]. then the statement g=grades [I]. So height [0] refers to the first element of the array. In C the array elements index or subscript begins with number zero. The C language provides a capability that enables the user to define a set of ordered data items known as an array. The type specifies the type of the elements that will be contained in the array. it is easier to think of it as referring to element number zero. Declares the height to be an array containing 50 real elements.Chapter 10 Arrays Contents • • • Defining and processing Passing arrays to a function Multi-dimensional arrays.

The value 95 is stored into the element number 100 of the grades array. so if I were equal to 7 when the above statement is executed. the variable sum will then contain the total of first 100 values of the grades array (Assuming sum were set to zero before the loop was entered) In addition to integer constants. If low is equal to 1 and high were equal to 9. Just as variables arrays must also be declared before they are used. would reserve enough space for an array called values that could hold up to 10 integers. So if low and high were defined as integer variables. For example we can very easily sequence through the elements in the array by varying the value of the variable that is used as a subscript into the array.i < 100.assign it to g. Will sequence through the first 100 elements of the array grades (elements 0 to 99) and will add the values of each grade into sum. A value stored into an element in the array simply by specifying the array element on the left hand side of the equals sign. Refer to the below given picture to conceptualize the reserved storage space. The ability to represent a collection of related data items by a single array enables us to develop concise and efficient programs. So the for loop for(i=0. then the value of grades [7] would get assigned to g. integer valued expressions can also be inside the brackets to reference a particular element of the array. The declaration int values[10]. When the for loop is finished. then the statement next_value=sorted_data[(low+high)/2]. sum = sum + grades [i]. float.++i). would assign to the variable next_value indexed by evaluating the expression (low+high)/2. In the statement grades [100]=95. 62 . The C system needs this latter information in order to determine how much memory space to reserve for the particular array. then the value of sorted_data[5] would be assigned to the next_value and if low were equal to 1 and high were equal to 10 then the value of sorted_data[5] would also be referenced. char as well as maximum number ofelements that will be stored inside the array. The declaration of an array involves the type of the element that will be contained in the array such as int.

There is no convenient way to initialize only selected elements. The general form of initialization off arrays is: type array_name[size]={list of values}. Will declare the array size as a array of size 3 and will assign zero to each element if the number of values in the list is less than the number of elements. Initialization of arrays: We can initialize the elements in the array in the same way as the ordinary variables when they are declared.0}. For example the statement int counter[]={1. The initialization of arrays in c suffers two draw backs 1.values[0] values[1] values[2] values[3] values[4] values[5] values[6] values[7] values[8] values[9] The array values stored in the memory. for example the statement int number[3]={0. Will declare the array to contain four elements with initial values 1.0. in such cases the compiler allocates enough space for all initialized elements. 2.1}.h > void main( ) 63 . This approach works fine as long as we initialize every element in the array. The values in the list care separated by commas.1. The remaining elements will be set to zero automatically. then only that many elements are initialized.1. There is no shortcut method to initialize large number of elements. In the declaration of an array the size may be omitted. /* Program to count the no of positive and negative numbers*/ #include< stdio.

I++) scanf(“%d”. int m[10][20] . scanf(“%d”.5 and so on.I < n.5 Marks [2][2] 64 . Here the array has two subscripts.5 50.n.&n).&a[I]). One subscript denotes the row & the other the column.count_neg). for(I=0. printf(“Enter the elements of the arrayn”).count_pos). } printf(“There are %d negative numbers in the arrayn”.5 marks [2][0] Marks [2][1] Marks [0][2] 45.5 Marks [1][2] 60. else count_pos++.5 marks [1][0] Marks [1][1] 55.{ int a[50]. } Multi dimensional Arrays Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. for I=0.5 35. The declaration of two dimension arrays is as follows: data_type array_name[row_size][column_size]. printf(“Enter the size of the arrayn”).5 & second element is marks [0][1] and contains 40. The first element is given by marks [0][0] contains 35. marks [0][0] Marks [0][1] 40. Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19).count_neg=0. printf(“There are %d positive numbers in the arrayn”.count_pos=0. The first element of the matrix is m[0][0] and the last row last column is m[9][19] Elements of multi dimension arrays: A 2 dimensional array marks [4][3] is shown below figure.I++) { if(a[I] < 0) count_neg++.I < n.I.

n.&q). printf(“the sum of the matrix a and b is”).q. Similarly table is a four dimensional array containing 300 elements of floating point type.marks [3][0] Marks [3][1] Marks [3][2] Initialization of multidimensional arrays: Like the one dimension arrays.0}. 65 .{1. /* example program to add two matrices & store the results in the 3rd matrix */ #include< stdio. The general form of a multidimensional array declaration is: date_type array_name[s1][s2][s3]….i++) for(j=0.&a[i][j]). C allows arrays of three or more dimensions. for(i=0. printf(“enter the order of the matrixn”).1.j < q. The above statement can be equivalently written as int table[2][3]={{0.1.0.&p.[sn]. printf(“enter the elements of the matrix a”).j++) scanf(“%d”.j. clrscr().i++) for(j=0.h > void main() { int a[10][10]. The initialization is done row by row.b[10][10].&b[i][j]). Initializes the elements of first row to zero and second row to 1.1. Where s is the size of the ith dimension. scanf(“%d%d”.j++) scanf(“%d”.0. printf(“enter the elements of the matrix b”).p. 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces Example: int table[2][3]={0. for(i=0. The compiler determines the maximum number of dimension.0.j < n. float table[5][4][5][3].h > #include< conio. Survey is a 3 dimensional array declared to contain 180 integer elements. if(m==p && n==q) { printf(“matrix can be addedn”).1}.i < m.i. Some examples are: int survey[3][5][12].m.c[10][10].1}} By surrounding the elements of each row by braces.i < p..

c[5]. void main() { int a[5].h> #include<conio. } void dis(int d[].5).b[5]. } void read(int c[].j<i.j < n. printf("Enter the elements of first list \n"). for(j=0. but we are allowed to pass its address.i++) for(j=0.&c[j]). it would be enough to write a call like this: procedure (myarray).i < m.int i) { 66 . printf(“n”).j++) c[i][j]=a[i][j]+b[i][j].j++) printf(“%dt”. read(a. the following function: void procedure (int arg[]) accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as: int myarray [40]. } } Passing arrays to a function (as parameter) At some moment we may need to pass an array to a function as a parameter.int). #include<stdio. printf("The elements of first list are \n").5).int).i++) { for(j=0.j < n. dis(a. In practice this has almost the same effect and it is a much faster and more efficient operation. void dis(int *. For example.j++) scanf("%d".int i) { int j. an identifier and a pair of void brackets [].for(i=0. for(i=0. In C it is not possible to pass a complete block of memory by value as a parameter to a function. In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array.i.i < m. fflush(stdin).&a[i][j]).h> void read(int *.

j<i. } Output Enter the elements of first list 1 2 3 4 5 The elements of first list are 12345 67 . printf("\n").j++) printf("%d ". for(j=0.int j.d[j]).

Initializing Strings Following the discussion on characters arrays.’a’. 68 . Normally each character is stored in one byte.’a’. Any sequence or set of characters defined within double quotation symbols is a constant string. successive characters are stored in successive bytes. Reading string displaying strings Combining or concatenating strings Copying one string to another. The compiler takes care of string enclosed within a pair of a double quotes.’n’. characte r ASCII Code M 7 7 C 6 7 A 6 5 S 3 8 2 3 E 6 9 M 7 7 3 2 1 4 9 3 2 I 7 3 D 6 8 O 7 9 L 7 6 \ 0 0 The last character is the null character having ASCII value zero. Then the string month is initializing to January. Comparing string & checking whether they are equal Extraction of a portion of a string Strings are stored in memory as ASCII codes of characters that make up the string appended with ‘\0’(ASCII value of null). the initialization of a string must the following form which is simpler to one dimension array. The characters of the string are enclosed within a part of double quotes. char month1[ ]={‘j’.’r’. In c it is required to do some meaningful operations on strings they are: 1. 2. /*String.Chapter 11 Strings Contents • Defining and operations on strings. A string is a sequence of characters. 4.’y’}. The above string can be initialized char month1[]=”January”.’u’.c string variable*/ #include < stdio.h > main() { char month[15]. The compiler takes care of storing the ASCII codes of charactersof the string in the memory and also stores the null terminator in the end. 3. This is perfectly valid but C offers a special way to initialize strings. 5.

Example: char month[10].printf (“Enter the string”). printf (“The string entered is %s”. Reading Strings from the terminal: The function scanf with %s format specification is needed to read the character string from the terminal. A null character (\0) that has the ASCII value 0 terminates the string. The size determines the number of characters in the string name. It is one dimension array. } In this example string is stored in the character variable month the string is displayed in the statement. char address[100]. The general form of declaration of a string variable is char string_name[size]. The figure shows the storage of string January in the memory recall that \0 specifies a single character whose ASCII value is zero. The size of the array should be one byte more than the actual space occupied by the string since the complier appends a null character at the end of the string. A string variable is any valid C variable name & is always declared as an array. gets (month). Each character occupies a byte. printf(“The string entered is %s”. J A N U A R Y \0 Character string terminated by a null character ‘\0’. month”). month). 69 .

suppose if we type the string new york then only the string new will be read and since there is a blank space after word “new” it will terminate the string. String1=string2. To copy the chars in one string to another string we may do so on a character to character basis. For instance we cannot assign one string to another directly. It is also possible to use character constants in relational expressions for example ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter. is a valid statement. We cannot manipulate strings since C does not provide any operators for string. printf(“%d\n”. The format %s can be used to display an array of characters that is terminated by the nullcharacter for example printf(“%s”. We can represent a character as a interface by using the following method. X=’a’. Note that we can use the scanf without the ampersand symbol before the variable name.Example: char address[15]. The function getchar can be used repeatedly to read a sequence of successive single characters and store it in the array. scanf(“%s”. For example: String=”xyz”. When ever the system encounters the character data it is automatically converted into a integer value by the system. can be used to display the entire contents of the array name.x). where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII value ‘1’=56-49=7. A character digit can also be converted into its equivalent integer value suppose un the expression a=character-‘1’. The ASCIIvalue of ‘z’ is 122 the statement the therefore will assign 121 to variable x. scanf statement has a draw back it just terminates the statement as soon as it finds a blank space.name). Arithmetic operations can also be performed on characters for example x=’z’-1. Arithmetic operations on characters: We can also manipulate the characters as we manipulate numbers in c language.address). 70 . Are not valid. Writing strings to screen: The printf statement along with format specifier %s to print strings on to the screen. In many applications it is required to process text by reading an entire line of text from the terminal. Will display 97 on the screen.

The length does not include a null character. C library supports a large number of string handling functions that can be used to array out many o f the string manipulations such as: Length (number of characters in the string). printf(“\nNumber of characters in the string is=%d”. /*writr a c program to find the length of the string using strlen() function*/ #include < stdio. int length. length=strlen(name).h > void main() { char name[100].h > include < string. Which receives the value of length of the string. Where n is integer variable. } 71 . The function will assign number of characters 9 in the string to a integer variable length.We can also get the support of the c library function to converts a string of digits into their equivalent integer values the general format of the function in x=atoi(string) here x is an integer variable & string is a character array containing string of digits. Concatentation (adding two are more strings) Comparing two strings.h) C language recognizes that string is a different class of array by letting us input and output the array as a unit and are terminated by nullcharacter . String operations (string. • • • • • strlen() function: This function counts and returns the number of characters in a string. Syntax: n=strlen(string). Example length=strlen(“Hollywood”).h library header file in the program. gets(name). Substring (Extract substring from a given string) Copy(copies one string over another) To do all the operations described here it is essential to include string.length). printf(“Enter the string”).

From the above program segment the value of string1 becomes sribhagavan. strcpy(string1.”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’. This process is called concatenation. String1. & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.string2) string1 & string2 are character arrays.”Newyork”) will return zero because 2 strings are equal.”the”).”sri”). “the”) will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.string2) . The strcat()function joins 2 strings together. It takes the following form strcat(string1.string2). strcmp(“The”.”Bhagavan”). which returns a zero if 2 strings are equal. The syntax of strcmp() is given below: strcmp(string1. strcpy(string2. the string at string2 remains unchanged. will return 0. 72 . or a non zero number if the strings are not the same. strcpy() function C does not allow we to assign the characters to a string directly as in the statement name=”Robert”. strcmp function In c we cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most libraries however contain the strcmp() function. we add the characters of one string to the end of other string. Example strcmp(“THE”. strcmp() function This function is same as strcmp() which compares 2 strings but not case sensitive. Example strcpy(string1. When the function strcat is executed string2 is appended to string1. Instead use the strcpy() function found in most compilers the syntax of the function is illustrated below.strcat(string1. printf(“%s”. The string at str2 remains unchanged as bhagawan. String1 & string2 may be string variables or string constants. Example: strcmp(“Newyork”.string2). strcmp(“their”.strcat() function: when we combine two strings.

s1. For ex strrev(“program”). if(x!=0) {printf(“\nStrings are not equal\n”). printf(“\ns2=%s\t length=%d characters\n”. printf(“\ns3=%s\t length=%d characters\n”. For example: strupr(“idol”).l2). Syntax strupr(string). In the above example Robert is assigned to the string called name. } 73 . l2=strlen(s2). reverses the characters in a string into “margrop”. strcat(s1.s2).l2.s2).s2. For example: strlwr(“IDOL”) converts to Idol. strrev() function This function reverses the characters in a string. strcpy(Name. int x. syntax strlwr(string).l3.h > #include < string.Strcpy function assigns the contents of string2 to string1.”Robert”). will convert the string to IDOL.s3.s2).h > void main() { char s1[20]. /* Example program to use string functions*/ #include < stdio.s1.l1.s3[20].s2[20]. printf(“\ns1=%s\t length=%d characters\n”. l1=strlen(s1).l3). printf(“Enter the strings”).l1). strcpy(s3. x=strcmp(s1. } else printf(“\nStrings are equal”). strupr() function This function converts all characters in a string from lower case to uppercase. strlwr () function This function converts all characters in a string from uppercase to lowercase. Syntax strrev(string). scanf(“%s%s”. l3=strlen(s3).s1). string2 may be a character array variable or a string constant.

We start by specifying the type of data stored in the location identified by the pointer. ptr). Example: int *ptr. type * variable name. The asterisk tells the compiler that we are creating a pointer variable. Pointer declaration: A pointer is a variable that contains the memory location of another variable.Chapter 12 Pointers Contents • • • • • Declarations Passing pointers to a function Operations on pointers. Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable we want to point as in the following example: ptr=&num. Pointer Arithmetic Pointers and arrays Arrays of pointers function pointers In c a pointer is a variable that points to or references a memory location in which data is stored. This places the address where num is stores into the variable ptr. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Finally we give the name of the variable. /* A program to illustrate pointer declaration*/ main() { int *ptr. printf (“\n The sum pointer is %d”. The syntax is as shown below. printf (“\n Sum is %d\n”. ptr=sum. int sum. If num is stored in memory 21260 address then the variable ptr has the value 21260. } we will get the same result by assigning the address of num to a regular(non pointer) variable. sum=45. sum). The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 74 . float *string.

ptr2= ptr2. printf(“\nAddress of b %u”.b). ptr1=&a. 75 . then the following statements are valid. int a. While the value of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in *ptr=45. sum=sum+*p1. p1==p2 and p1!=p2 are allowed. z= 5* .ptr1). sum+=*p2. printf(“\nx=%d.b.h > main() { int ptr1. b=%d”. This means place the value 45 in the memory address pointer by the variable ptr.y.21260 but in the value stored in that memory location.y).a.y=%d”.*ptr1/ *ptr2 +30.ptr2. *p2= *p2 + 10..x.ptr2). a=30. ptr1=ptr1 + 70. this shows how we can change the value of pointer directly using a pointer and the indirection pointer. The usage of the pointers in a function definition may be classified into two groups. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include< stdio. And since this is the location of the variable num the value also becomes 45. y=*p1**p2. Sometimes only with a pointer a complex function can be easily represented and success. For example if p1 and p2 are properly declared and initialized pointers. ptr2=&b.x. etc. printf(“\na=%d. C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other.z. } Pointers and function: The pointer are very much used in a function declaration. Pointer expressions & pointer arithmetic: Like other variables pointer variables can be used in expressions. printf(“\na=%d.b). x=*ptr1+ *ptr2 –6. y=6*. b=%d”. printf(“\nAddress of a +%u”.a. We can also use short hand operators with the pointers p1+=. we can also compare pointers by using relational operators the expressions such as p1 >p2 . Since the pointer contains the address 21260 the value 45 is placed in that memory location.b=6.*p2/p1.

Call by value. y=30.q. Call by reference 2. Call by value: • We have seen that a function is invoked there will be a link established between the formal and actual parameters. q=q+q.y. } Call by Reference: When we pass address to a function the parameters receiving the address should be pointers. printf(“\n Value of a and b after function call =%d %d”.h > void main() { int x. • The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters. • A temporary storage is created where the value of actual parameters is stored.a.b). fncn(x. x=20. T • he formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value.a. { p=p+p. } fncn(p. • The corresponding formal parameter represents a local variable in the called function .q) int p. printf(“\n Value of a and b before function call =%d %d”. /* example of call by reference*? /* Include< stdio.y). The process of calling a function by using pointers to pass the address of the variable is known as call by reference. • The value of formal parameter may be changed in the body of the actual parameter. The function which is called by reference can change the values of the variable used in the call.b). /* Include< stdio.h > void main() 76 .1. • The current value of corresponding actual parameter becomes the initial value of formal parameter.

j+=. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses.ptr). printf(“Array element are”).ptr< (a+n). main( ) { int *arr[4] .b). arr[1] = &j . } fncn(p. } Pointer to arrays: an array is actually very much like pointer. arr[2] = &k .ptr++) printf(“Value of a[%d]=%d stored at address %u”.*ptr. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. printf(“Enter the array elements”). The difference is pointer is avariable and can appear on the left of the assignment operator that is lvalue. Since a pointer variable always contains an address. arr[3] = &l . The array name is constant and cannot appear as the left side of assignment operator. printf(“\nEnter the elements of the array\n”).&a[I]). arr[0] = &i . printf(“\n Value of a and b after function call =%d %d”. { *p=*p+*p.q.a. y=30. scanf(“%d”.I++) scanf(“%d”. m . x=20. *q=*q+*q.b).I< n. an array of pointers would be nothing but a collection of addresses. fncn(&x.&y). for(ptr=a.n.{ int x.j. /* array of integer pointers */ int i = 31.&n). 77 .a. All rules that apply to an ordinary array apply to the array of pointers as well. /* A program to display the contents of array using pointer*/ main() { int a[100]. k = 19. printf(“\n Value of a and b before function call =%d %d”.q) int p. int i.y. for(I=0. j = 5. l = 71. similarly there can be an array of pointers. } The way there can be an array of ints or an array of floats. I think a program would clarify the concept.

Here's a simple example. (*fp)(1).for ( m = 0 . #include <stdio. } 78 . float b). fp(2). /* or */ func(1. we declare a function returning a pointer: /* function returning pointer to int */ int *func(int a. Once we've got the pointer. m++ ) printf ( "%d ". say int func(int a. and simply put brackets around the name and a * in front of it: that declares the pointer.2). Because of precedence.h> void func(int). /* pointer to function returning int */ int (*func)(int a. float b). main() { void (*fp)(int). fp = func. a function name is turned into an address when it's used in an expression.2). } Pointer to Function A useful technique is the ability to have pointers to functions. } void func(int arg) { printf("%d\n". The second form has been newly blessed by the Standard. Their declaration is easy: write the declaration as it would be for the function. exit(EXIT_SUCCESS). we can assign the address of the right sort of function just by using its name: like an array. We can call the function using one of two forms: (*func)(1. if we don't parenthesize the name. * ( arr[m] ) ) . m <= 3 . arg). float b).h> #include <stdlib.

Defining & accessing Structure structure definition: struct tag_name { data type member1. The tag name can be used to define objects that have the tag names structure. char author[15]. The structure we just declared is not a variable by itself but a template for the structure. … … } Example: struct lib_books { char title[20]. These are members of the structures. Structure is a method of packing data of different types. data type member2. Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. float price. int pages. }. We can declare structure variables using the tag name any where in the 79 . If we need to use a collection of different data type items it is not possible using an array. the keyword struct declares a structure to holds the details of four fields namely title.Chapter 13 Structures Contents • • • • • • Defining and processing Passing to a function Unions typedef array of structure Pointer to structure Definition • • • • • A structure is a convenient method of handling a group of related data items of different data types. author pages and price. When we require using a collection of different data items of different data types we can use a structure. Each member may belong to different or same data type.

float price. } book1. book2. book1.book2.program.book3. char author[15]. structures do not occupy any memory until it is associated with the structure variable such as book1. book2. book3 declares book1.book3. int pages. struct lib_books book1. The tag name such as lib_books can be used to declare structure variables of its data type later in the program. The use of tag name is optional for example struct { … … … } book1. Giving values to members As mentioned earlier the members themselves are not variables they should be linked to structure variables in order to make them meaningful members. float price. each member is declared independently for its name and type in a separate statement inside the template. In such cases the structure assumes global status and all the functions can access the structure. struct lib_books. }.book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books.book2. is valid. The template is terminated with a semicolon. char author[15]. The complete structure declaration might look like this struct lib_books { char title[20]. A structure is usually defines before main along with macro definitions. int pages. 80 . For example the statement. While the entire declaration is considered as a statement.book2. the declaration struct lib_books { char title[20].book3 as structure variables representing 3 books but does not include a tag name for use in the declaration.book2. book3. We can also combine both template declaration and variables declaration in one statement. declares book1.

&new student.50.title. printf(“Enter the address of the student”). printf(“Age of student=%d\n”.”Balagurusamy”).book1. char name[20].”basic”).name).pages=250. printf(“Enter the student information”). char address[20]. printf(“Student information\n”).combination). printf(“student id_number=%d\n”.id_no).pages). printf(“Enter the name of the student”).&new student.newstudent. For example: Book1. We can use scanf statement to assign values like scanf(“%s”.author. scanf(“%d”.name). printf(“Enter the cmbination of the student”).price is the variable representing the price of book1 and can be treated like any other ordinary variable.The link between a member and a variable is established using the member operator ‘.address).age).&newstudent.& book1.&new student.address). scanf(“%s”. strcpy(book1.newstudent. scanf(“%d”. Or we can assign variables to the members of book1 strcpy(book1. /* Example program for using a structure*/ #include< stdio. scanf(“%s”. char combination[3]. int age. } 81 . printf(“student name=%s\n”.newstudent. }newstudent. printf(“Now Enter the student id_no”). book1. book1.combination). printf(“students combination= %s\n”.’ Which is known as dot operator or period operator.age).price=28.&new student.newstudent. scanf(“%d”.newstudent. scanf(“%d”.h > void main() { int id_no.id_no). printf(“student Address=%s\n”.file). printf(“Enter the age of the student”).

we don’t effect its corresponding argument. }. the name field to “kapildev”. char department[10]. /* pass only emp_id and name to display function*/ display(emp1. when we change structure parameter inside a function. 82 . the address field to “pes college” the field combination to “cse” and the age field to 19. structure names are not pointers. } /* function to display structure variables*/ display(e_no. “kapildev” “Pes college”.00}.”sampath”. As a result. 19. this initializes the id_no field to 12345. As for initialization goes structure obeys the same set of rules as arrays we initialize the fields of a structure by the following structure declaration with a list containing values for fileds as with arrays these values must be evaluate at compile time. static struct emp1={125.e_name) int e_no. which always point to the start of the array. Unlike array names however.h > void main() { int emp_id.e_name. char name[25]. # include < stdio.7500.”operator”. }. “Cse”. A structure may be passed into a function as individual member or a separate variable. float salary. Passing to a function We can pass structures as arguments to functions.emp_id.Initializing structure: Like other data type we can initialize structure when we declare them. A program example to display the contents of a structure passing the individual elements to a function is shown below.name).emp1. Example: struct student newstudent { 12345.

e_name). }. “sadanand”.name. } /*function to pass entire structure variable*/ display(empf) struct employee empf { printf(“%d%s.e_no. emp_id and name have been declared as integer and character array.salary). empf.%s. When we call the function display() using display(emp1.empf.emp1. Passing entire structure to functions: In case of structures having to having numerous structure elements passing these individual elements would be a tedious task. 7500.empf.name).{ printf(“%d%s”. char department[10].emp_id.department.%f”. /*sending entire employee structure*/ display(emp1).empf. we are sending the emp_id and name to function display(0). In such cases we may pass whole structure to a function as shown below: # include stdio. char name[25]. in the declaration of structure type.empid.00 }.h> { int emp_id. void main() { static struct employee emp1= { 12. float salary. it can be immediately realized that to pass individual elements would become more tedious as the number of structure elements go on increasing a better way would be to pass the entire structure variable at a time. “computer”. } Array of structure It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in 83 .

std[I].std[I]. #include< stdio.id_no. int I.I< n. char name[20]. char combination[3].age).I++) printf(“%d%s%s%s%d\n”.name. In such structures the declaration of the embedded structure must appear before the declarations of other structures. Each element is a structure that must be assigned corresponding initial values as illustrated below.I < n. char combination[3]. 84 .&std[I]. printf(“Enter the number of students”). } Structure within a structure: A structure may be defined as a member of another structure.id_no. printf(“ Enter Id_no. } struct info std[100].std[I]. for (I=0.combination. char address[20]. int age.name address combination age\m”).address. printf(“\n Student information”).std[I]. ”. scanf(“%d”. int month. char address[20].&n). char name[20].name.n. int age. for(I=0.std[I]. struct date { int day.&std[I].the college.age).std [I].I++) scanf(%d%s%s%s %d”. We need to use an array than single variables.h > { struct info { int id_no. We can define an array of structures as shown in the following example: structure information { int id_no. An array of structures can be assigned initial values just as any other array can.address.combinatio n.std[I]. } student[100].std[I].

Thus unions are used to observe memory. During accessing we should make sure that we are accessing the member whose value is currently stored. char name[20]. }oldstudent. • Like structures union can be declared using the keyword union as follows: union item { int m. char c.p code. However we can use only one of them at a time. • However the members that compose a union all share the same storage area within the computer’s memory whereas each member within a structure is assigned its own unique storage area.c are all valid member variables. float p. That is code. structure date def. }. int age. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. newstudent. This is because if only one location is allocated for union variable irrespective of size.int year. } code. the sturucture student constains another structure date as its one of its members. • • • • this declares a variable code of type union item. Unions • Unions like structure contain members whose individual data types may differ from one another. char combination[3]. • They are useful for application involving multiple members where values need not be assigned to all the members at any one time.m code. struct student { int id_no. structure date doa. The union contains three members each with a different data type. For example a statement such as 85 . char address[20].

typedef • • • • • A typedef declaration lets we define wer own identifiers that can be used in place of type specifiers such as int. The exception to this rule is if the typedef name specifies a variably modified type. When a different number is assigned a new value the new value supersedes the previous member’s value.code. but synonyms for the data types or combinations of data types they represent. printf(“%d”. typedef int LENGTH.78. Unions may be used in all places where a structure is allowed. and double.code. The structure WEIGHT can then be used in the following declarations: WEIGHT chicken. The names we define using typedef are not new data types. For example: typedef struct { int scruples. • • In effect a union creates a storage location that can be used by one of its members at a time. the properties of the defined object are exactly the same as if the object were defined by explicitly listing the data type associated with the identifier. In this case. Would produce erroneous result. height. union. The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure. int grains. The name space for a typedef name is the same as other identifiers. When an object is defined using a typedef identifier. width.m). it has block scope. whale. code. LENGTH length.m=456. or C++ class). typedef can be used to define a class type (structure.p=456. horse. } WEIGHT. 86 . cow. A typedef declaration does not reserve storage. int drams. float.

As such. we can index into 87 . The result is that no meaningful output occurs (probably) and this is to be expected. overflow of handling. requires random access since the application can read data from anywhere in the file in response to a query. relative and indexed sequential files (ISAM) concept of index. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. 1. paragraphs and pages from a textual document. fields and records belonging to a database. The file is broken down into a sequential string of records that share a common structure. A list is simply an open-ended single dimensional array of items. levels of index. Random access files work best for data we read and write in pieces A database file. Concept of record • • A good view of a file is as a list of records. updating Sequential. Sequential files are great for data we read or write all at once For example. Files are of two different forms: sequential files & random access files. as characters. on the other hand. creating. A file is simply a machine decipherable storage media where programs and data are stored for machine usage. so we can view a file as an array of records. which is generally a disk of some kind. The collection of bytes may be interpreted. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. or pixels from a graphical image. indexed and random access mode. Files with binary mode(Low level)p Performance of Sequential Files Direct mapping techniques: Absolute. Usually the text editor will read or write the entire file at once. a typical text fileis usually a sequential file.Chapter 14 File structures Contents • • • • • • Definitions concept of record file operations: Storing. words. Definition • • • A file is a collection of bytes stored on a secondary storage device. for example. lines. 2. relative. retrieving.

then the first record appears at byte offset zero in the file. the only difference is that a file doesn't have a "base address" in memory. Unless we have an array of offsets to each record in a variable-length file. the line feed character marks the end of each record. This calculation is quite simple. we'll adopt the line feed end of line marker.. Accessing records in a file containing variable-length records is problematic.we have the read the file sequentially from the start in order to locate a specific record in the file. these records do not all have to be the same length. we simply compute the zero-based offset of the record in the file. etc. If a sequential file does not use fixed length records then we say that the file uses variable-length records. Typical sequential files use one of two mechanisms: a length prefix or some special terminating value. Sequential files also consist of a list of records. it is quite possible to skip around to different records in a file.e. e. then the file must contain some kind of marker or other mechanism to separate the records in the file. A random access file is a list of records whose lengths are all identical (i. record number one. However.g. A text file is the best example of a sequential file that uses variablelength records. The principle difference between a sequential file and a random access file is the organization of the records and how easy it is to locate a specific record within the file. Other operating systems may use a different sequence. Using common file access operations. In a text file. This organization is virtually identical to that of an array of records in main memory. This will be much slower than accessing the file in 88 . Since we're working with Windows here. Text files use a special marker at the end of each record to delineate the records. If a sequential file uses variable-length records. Under Windows. and using some file I/O functions we will learn about a little later.• • • • • • • • • • • the file and select record number zero. the second record appears at byte offset n in the file.. record number two. Windows uses a carriage return/line feed sequence while the Mac OS uses a single carriage return. random access files require fixed length records). the third record appears at byte offset n*2 in the file. the only practical way to locate record n in a file is to read the first n-1 records. we use the same computation to locate an "element" of this list in the file as we would use to locate an element of an array in memory. These two schemes should sound quite familiar to those who have read the chapter on strings. If the record length is n bytes. a record corresponds to a single line of text. This is why variable-length files are sequential-access . The easiest file organization to understand is the random access file. etc. Character strings use a similar scheme to determine the bounds of a string in memory. we can quickly locate and manipulate any record in a random access file.

C supports a number of functions that have the ability to perform basic file operations. Writing data into a file 5. For example. If the average line length is around 60 characters. retrieving. To store a sequence of lines in a text file. can waste a tremendous amount of space on the disk. record sizes would have to be large enough to hold the longest possible input line. Opening a file 3. indexed and random access mode. especially as the files get larger or we create lots of files. Reading from a file 4. we would not use a variablelength record organization for files we need to access in a random fashion. Each record in the file will consume this many bytes even if the record uses substantially less data. This could be quite large. an empty line only requires one or a single byte (for the line feed character). Generally. Closing a file 89 . which include: 1. relative. This problem.a random access fashion. updating Sequential. then each line wastes an average of about 200 characters. • • File operations: Storing. Naming a file 2. After all. we can access records in a file with fixedlength records much more rapidly than files using the variablelength record organization. However. known as internal fragmentation. If the record size is 256 bytes. there is a cost to this: fixed-length records have to be large enough to hold the largest possible data object we want to store in a record. Performance • It would seem that fixed-length random access files offer all the advantages here. creating. for example. File organizations that use variable-length records generally don't suffer from this problem. then we're wasting 255 or 255 bytes for that blank line in the file.

It may be possible to access a file in an access method other than the "natural" one. The writing order defines the "natural" order of data. Possible file organizations are: 1) Sequential .Commonly used File operation functions in C: Function Name fopen() Fclose getc() putc() fprintf() fscanf() getw() Operation Creates a new file for use Opens a new existing file for use Closes a file which has been opened for use Reads a character from a file Writes a character to a file Writes a set of data values to a file Reads a set of data values from a file Reads a integer from a file putw() fseek() ftell() rewind() Writes an integer to the file Sets the position to a desired point in the file Gives the current position in the file Sets the position to the begining of the file File organization and access methods are separate but related concepts. in simple cases the data will reside on the disk in consecutive locations.The info in file can be accessed only in the order it was written. organization refers to the internal structure. 90 . access method is an "allowed method" to read/write from/to the file.

The system buffers file accesses and let's we read a specified number of bytes at a time. 91 . 4) Direct .2) Relative .First data item is at the start of the file.The real hardware address. and contain "indexes". they are recorded on a magnetic media. this gives an offset from the file's beginning. 7) Byte stream . 2) By physical/logical/virtual block number . Standard FORTRAN 77 doesn't require that indexed files are to be implemented. the system supports accesses to the "mapped" main memory as if they were accesses to the file's data.First one or more indexes are consulted (in a complex process). but in order to conserve physical memory it is paging it in and out as necessary. other items follow one after the other. Relative files are just like arrays [of structures]. lists of "pointers" to these cells arranged by some order. and the system will calculate the offset. not necessarily of the same size. but instead of residing in main memory. number of the track and number of the sector. 5) Keyed .This is the serial number of the required disk block ("atomic" unit of disk area).The file is a sequence of equal-sized "data cells". they yield the address of the data item. we can access any "cell" we want using its serial number.The operating system creates an association between the data in the file and a part of the main memory.Data item location is calculated from its serial number and the constant "cell size". but some vendors supply this nice extension. the three variants are different numbering methods. Access methods are classified by the way they find the location of the data on the disk: 1) By physical address . 3) Sequential . composed of three components (at least): the number of the magnetic head used. 6) Memory mapping . 3) Indexed . We can think of this process as if the system copied all of the file contents to a large array residing in main memory.The file is made of "data cells".

A record is a sequence of data bytes together with control information about the record's size and maybe some attributes. To have any structure in a file. system and application programs accessing the file must adopt some convention that has to respected by all programs. characterized by the way they implement file I/O: Byte-oriented file systems In this type of file-system. The unit of I/O operations is one or more record(s).--------------. Having all records in a file share the same type.----------Sequential + + + Direct ? + ? Keyed + Physical address + + + By block number + + + Memory mapping + + + Byte stream + + + The two basic types of file-systems ----------------------------------There are two major types of file-systems. by system routines we call in order to perform file I/O. a file is considered as a sequence of bytes. For example. Record-oriented file systems In these file-systems a file is a sequence of records of the same type. ISAM ISAM (Indexed Sequential Access Method) is a file management system developed that allows records to be accessed either sequentially (in the order they were entered) or randomly (with an index). This structure is imposed by consistently interpreting the data and control information kept in the records.Compatibility of different organizations and access methods: Access \ Organization Sequential Relative Indexed ----------------------------. a line-feed (ASCII 10) character in a file containing text may denote an end-of-line. • 92 .-----------. makes it reasonable to use files and records terms interchangeably. the operating system supplies routines that can read/write a specified number of bytes.

the last name field would be the key. a name index may order employees alphabetically by last name. For an alphabetical index of employee names. • A key is specified in each index.• Each index defines a different ordering of the records. 93 . based on the information being sought. while a department index may order employees by their department. An employee database may have several indexes. • For example.

Chapter 15 File Handling Contents • File operation: creation, copy, delete, update, text file, binary file

Creating a file and output some data In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type. /* Program to create a file and write some data the file */ #include <stdio.h> #include <stdio.h> main( ) { FILE *fp; char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %d\n", stuff, index); fclose(fp); /* close the file before ending program */ } • The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. • It means that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type. • The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if we so desire. It is enclosed in double quotes. For this example we have chosen the name TENLINES.TXT. • This file should not exist on wer disk at this time. If we have a file with this name, we should change its name or move it because when we execute this program, its contents will be erased. If we dont have a file by this name, that is good because we will create one and put some data into it.
94

We are permitted to include a directory with the file name. The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character “\\” must be written twice. • For example, if the file is to be stored in the \PROJECTS sub directory then the file name should be entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case.

Reading (r) • When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that we desire to append additional data to the data already in an existing file. • Most C compilers have other file attributes available • Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program. Example: Here is a small program that reads a file and display its contents on screen. /* Program to display the contents of a file on screen */ #include <stdio.h> void main() { FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); } Writing (w) When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. Example: Here is the program to create a file and write some data into the file. #include <stdio.h> int main()
95

{ FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0; } Appending (a) When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. Example: Here is a program that will add text to a file which already exists and there is some text in the file. #include <stdio.h> int main() { FILE *fp file = fopen("file.txt","a"); fprintf(fp,"%s","This is just an example :)"); /*append some text*/ fclose(fp); return 0; } Outputting to the file • The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. • The only real differences are the new function names and the addition of the file pointer as one of the function arguments. • In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. • The remainder of the statement looks like, and in fact is identical to, the printf statement. Closing a file • To close a file we simply use the function fclose with the file pointer in the parentheses.
96

/* repeat until EOF (end of file) */ } fclose(fp). • The file pointer is simply a tool that we use to point to a file and we decide what file it will point to. If it doesn’t. it is not necessary to close the file because the system will close all open files before returning to DOS. and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it. and reopen it for reading. } • In this program we check to see that the file exists. that is where wer output will be. some data definitions. else { do { c = getc(fp). When we run it. Compile and run this program. /* display it on the monitor */ } while (c != EOF). we execute the main body of the program. they should agree! Do not erase the file named TENLINES. Reading from a text file Now for our first program that reads from a file. if (fp == NULL) printf("File doesn't exist\n"). but it is good programming practice to close all files in spite of the fact that they will be closed automatically.• Actually. and if it does. funny = fopen("TENLINES. look at wer directory for a file named TENLINES. or we could use a different one. and open it again for appending.TXT and type it. #include <stdio. If the file does not exist. etc. 97 . Each time we open it. char c. Compare the output with that specified in the program. /* get one character from the file */ putchar(c). • We can open a file for writing. we print a message and quit. "r"). in this simple program. because that would act as a reminder to we of what files are open at the end of each program. • After running it. we will not get any output to the monitor because it doesnt generate any. This program begins with the familiar include. close it.h> main( ) { FILE *fp.TXT". then close it. we will use it in some of the other examples in this section. the system will set the pointer equal to NULL which we can test. we could use the same file pointer.TXT yet.

This is a very frustrating problem to try to find. it would be a good exercise to change the name of TENLINES. so we can use a char variable for this purpose. printf("Argument Missing ! Press key to exit. #include<stdio. 21. 10. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that. because C usually returns a minus one for an EOF – which an unsigned char type variable is not capable of containing. 17. The program can never find the EOF and will therefore never terminate the loop. } 16. Be sure to change the name back because we are still not finished with TENLINES. { 20. 13. so it will return a 255 for a minus one in C. fs = fopen(arr[1]. There is a problem that could develop here if we happened to use an unsigned char however. exit(0). char ch. { 12. getch(). 5."). { 7. #include<stdlib.TXT. getch(). we have the potential for one of the most common and most perplexing problems of programming in C.*ft.h> 2."). #include<conio. if(arg!=3) 11. printf("Cannot open source file ! Press key to exit. void main(int arg. clrscr()."r"). 18.h> 4. • The file is then closed and the program is terminated. Copy a File 1. • An unsigned char type variable can only have the values of zero to 255. FILE *fs. if(fs==NULL) 19.• The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. 9.h> 3. 8.char *arr[]) 6. 15. • After we compile and run this program and are satisfied with the results.TXT and run the program again to see that the NULL test actually works as stated. 14. At this point. 98 . • The variable returned from the getc function is a character. • This is easy to prevent: always have a char or int type variable for use in returning an EOF.

37. exit(0). getch(). fclose(fs). 24. 40. exit(0). fclose(ft). } printf("File copied succesfully!"). It takes file name from “main()” function’s character array pointer argument. fclose(fs). 23. } while(1) { ch = getc(fs). 34. 36.g. not for beginners. First argument is an integer argument in the main function which stores the number of parameters provided at the runtime. 41. 31. as we can see. Line – 5: This line is starting of the main function which accepts two arguments or parameters. } Code Explanation This is an advanced kind of program. 27. 48. 33. 38. If “fopen()” function can open file successfully then returns pointer else returns NULL. if(ch==EOF) { break."w"). If argument is less than 3 or greater than 3. Second argument in main function is a character array pointer. 42. then it will show error message. 28. 39. 43. 26. 45. We are checking this. first is file name and second is file opening mode. In our program it has to be 3 (e. Line – 10-15: These line will check whether user has provided 3 arguments or not. 25.22. } else putc(ch. 46. To serve this purpose we will use “fopen()” function. Line – 7: This line declares two file pointer variables which we will need in our program. if(ft==NULL) { printf("Cannot copy file ! Press key to exit. 29. One file pointer variable will be used to read file and another will be used to write to file. 44. function. } ft = fopen(arr[2]. This is for those who have idea of file handling.ft). 30. program_name source_file destination_file). 35. pointer array etc. which store the arguments. if file 99 ."). 47. Line – 17-23: In these lines we will open source file in read mode. 32. This function requires two arguments.

All text file functions and types in C come from the stdio library. so we need to close both of them. Line – 34-43: As we can see here we have declared an infinite while loop and the loop continues until end of file is reached. If fopen() function returns NULL then we need to close source file stream and exit program. and we need only one source for input information and one sink for output information. we have used the library function remove() which deletes the file HELLO. Line – 25-32: In this block of code we are trying to create a new file.txt") == -1) perror("Error in deleting a file").txt. So we need to open this file in write mode.is not found or file cannot be accessed due to security restriction then there is no need to execute program further. There are six different I/O commands in <stdio.txt. In line 42 we are writing character stored in ch variable to new file (ft file pointer) with the help of “putc()” function. It also takes file name from “main()” function’s character array pointer argument. getch().h> #include <conio. the function perror() prints the error message on the console. } Text Files Text files in C are straightforward and easy to understand. When we need text I/O in a C program. we can rely on stdin (standard in) and stdout (standard out). The “gets()” function reads character from given stream and stores character in ch variable then increments file pointer to next character.h> that we can use with stdin and stdout: printf . Example : Deleting the File #include <stdio. In case if the file will not be deleted. Delete a file in C We can see in the given example that we want to remove the file HELLO. Because we are using two file pointer.prints formatted output to stdout 100 .h> void main() { if (remove("HELLO. Line – 46-47: These two lines contain two same functions whose job is to clearing the stream buffer and closing the stream buffer. For this. We can then use input and output redirection at the command line to move different information streams through the program.

getchar .opens a text file fclose . When we press CTRL-D. use the text file functions in stdio: fopen . we might need to open a specific file and read from or write to it.h> void main() { char s[1000]. then returns a 0 so that the while loop ends. suppose we want to count the characters in a file.reads a string from stdin putc . It waits for input from stdin.closes a text file feof .reads formatted input from a file 101 .h> #include <string. For example. the contents of the file named filename will be used instead.prints a string to stdout gets . Now.prints a character to stdout getc. The gets function reads a line until it detects eof. } Enter this code and run it. Likewise. we can type the following: xxx < filename Instead of accepting input from the keyboard. We can achieve the same result using pipes: cat < filename | xxx We can also redirect the output to a file: xxx < filename > out This command places the character count produced by the program in a text file named out. Sometimes. int count=0. the ability to redirect I/O is very powerful. We might want to manage several streams of input or output or create a program like a text editor that can save and recall data or configuration files on command. we see a count of the number of characters in stdout (the screen).prints formatted output to a file fscanf . maybe we want to create a program that reads from stdin and counts the number of characters: #include <stdio. printf("%d\n".detects end-of-file marker in a file fprintf .reads a character from stdin The advantage of stdin and stdout is that they are easy to use. In that case. If we compiled the program to an executable named xxx. while (gets(s)) count += strlen(s). so type a few lines. press CTRL-D to signal end-of-file (eof).reads formatted input from stdin puts . When we are done.count).scanf . we need to use a text file directly. For example.

Instead. which is stored in the variable f. The fprintf statement should look very familiar: It is just like printf but uses the file pointer as its first parameter."%d\n". This is a destructive write mode. f=fopen("out". The fopen command returns a pointer to the file.x). return 0. for(x=1."w"). f will contain NULL. for read.prints a character to a file fgetc . This variable is used to refer to the file.fputs . int x. and append). which means that if out does not exist it is created. open it with r mode. It then returns a file pointer that we use to access the file. In general. fscanf will not handle it correctly. write.reads a string from a file fputc . w. The following code demonstrates the process of reading a file and dumping its contents to the screen: 102 . If the file cannot be opened for some reason. suppose we want to open a file and write the numbers 1 to 10 in it. It opens a file for a specified mode (the three most common are r.prints a string to a file fgets . } The fopen statement here opens a file named out with the w mode.h> #define MAX 10 int main() { FILE *f. The fclose statement closes the file when we are done. use fgets to read in each line and then parse out the pieces we need. if (!f) return 1. x<=MAX. fclose(f).reads a character from a file Text Files: Opening We use fopen to open a file. Text Files: Reading To read a file. and a. We could use the following code: #include <stdio. x++) fprintf(f. but if it does exist it is destroyed and a new file is created in its place. it is not a good idea to use fscanf for reading: Unless the file is perfectly formatted. For example.

if (!f) return 1. but it can point to any byte location in the file. or seek to any structure in the file. Any write operation writes to the currently pointed-to structure and moves the pointer down one structure. We can change the contents of a structure anywhere in the file at any time. while (fgets(s. 2. They are also permanent and always available. Because the structures in a binary file are on disk. • C thinks of everything in the disk file as blocks of bytes read from disk into memory or read from memory onto disk. Any read operation reads the currently pointed-to structure and moves the pointer down one structure. char s[1000]. We therefore have to keep track of things. • This file concept supports the concept of a file pointer.h> int main() { FILE *f. • When the file is opened. which provides random access as in an array.#include <stdio. everything has to be converted back and forth to text. The following program illustrates these concepts: 103 . In a text file. } Binary Files Binary files are very similar to arrays of structures. Binary files have two features that distinguish them from text files: 1. except the structures are in a disk file rather than in an array in memory.f)!=NULL) printf("%s". f=fopen("infile". the pointer points to record 0 (the first record in the file). fclose(f)."r"). C uses a file pointer. we can create very large collections of them (limited only by wer available disk space). The only disadvantage is the slowness that comes from disk access time. • C supports the file-of-structures concept very cleanly. and this takes time. write a structure.1000. Once we open the file we can read a structure. • Binary files also usually have faster read and write times than text files. because a binary image of the record is stored directly from memory to disk (or vice versa). We can jump instantly to any structure in the file. Seek moves the pointer to the requested record. return 0.s).

sizeof(struct rec). if (!f) return 1. /* use fseek to read the 10 records in reverse order */ f=fopen("junk".1. } fclose(f).#include <stdio.x=i. printf("%d\n". if (!f) return 1.SEEK_SET). }.f). i--) { fseek(f. /* create the file of 10 records */ f=fopen("junk". printf("\n").y. printf("%d\n".x).i<=10.f). /* read the 10 records */ f=fopen("junk". if (!f) return 1.1. for (i=9.r."r"). 104 .h> /* random record description . struct rec r. FILE *f.sizeof(struct rec)."r"). */ int main() { int i.r.j. i>=0.i<=10.x). fwrite(&r. fread(&r.sizeof(struct rec)*i. /* writes and then reads 10 arbitrary records from the file "junk".could be anything */ struct rec { int x. for (i=1.f). i++) { r. } fclose(f). i++) { fread(&r.z.sizeof(struct rec)."w"). for (i=1.1.

f). fseek(f. fwrite(&r.SEEK_CUR). } fclose(f).sizeof(struct rec)*3.i<=10. for (i=1."r+").r. 105 . fseek(f. printf("%d\n".sizeof(struct rec).SEEK_SET). if (!f) return 1. i++) { fread(&r. fread(&r.sizeof(struct rec). /* use fseek to read 4th record.0. but we can use any structure description we want. We can see that fopen and fclose work exactly as they did for text files. printf("\n"). i++) { fread(&r.f)."r").} fclose(f).SEEK_SET). for (i=0.r.x).1.f). if (!f) return 1. printf("%d\n".sizeof(struct rec). fseek(f. /* read the 10 records to insure 4th record was changed */ f=fopen("junk".1. } In this program.SEEK_SET).sizeof(struct rec).f). a structure description rec has been used.sizeof(struct rec)*3.i<5."r"). } fclose(f).x=100. printf("\n"). /* use fseek to read every other record */ f=fopen("junk". printf("\n"). if (!f) return 1.1. fseek(f. change it. fclose(f).sizeof(struct rec). return 0. and write it back */ f=fopen("junk".1. r.x).

but moves the block of bytes from memory to the file. The fwrite function works the same way. says to read 12 bytes • • • • (the size of rec) from the file f (from the current location of the file pointer) into memory address &r. SEEK_END moves the pointer from the end of the file (so we must use negative offsets with this option). it then seeks back because the read displaced the pointer. • Several different options appear in the code above. the line fread(&r. and changes a field. The file variable • Thus. The number of blocks to read d. The fseek function moves the file pointer to a byte in the file. The fread function takes four parameters: a.The new functions here are fread.f). A memory address b. Generally. which allows records to be changed. fwrite and fseek. This opens the file for reading and writing. It would be just as easy to read 100 blocks from disk into an array in memory by changing 1 to 100. note the section where the file is opened with r+ mode. The code seeks to a record. One block of 12 bytes is requested. In particular. 106 . and writes the change back.1. We can use three options when seeking: • SEEK_SET • SEEK_CUR • SEEK_END SEEK_SET moves the pointer x bytes down from the beginning of the file (from byte 0 in the file). reads it.sizeof(struct rec). • SEEK_CUR moves the pointer x bytes down from the current pointer position. The number of bytes to read per block c. we move the pointer in sizeof(struct rec) increments to keep the pointer at record boundaries.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.