Problem Solving and C Programming Flow diagram of

Problem Solving and C Programming

Flow diagram of Problem solving & C 1. Introduction to Problem Solving 6. Arrays And Strings 2. Programming Language 7. Introduction to Pointers 3. Introduction to C Programming 8. Functions 4. Selection Structure 9. Structures And Union 5. Control Statements 10. Files

1. 0 Introduction to Problem Solving Introduction: Designing a program means defining the logical flow of a program, what the program will take as input and what it will produce as output Objective: After completing this Topic, you will be able to, 1. 2. 3. Understand various steps in program development Acquire problem solving skills Learn the techniques of modular programming

Program Development The various steps involved in program development are, – – – – Analyzing or Defining the problem Developing a solution technique (Algorithm) Coding Documenting the problem Compiling and Running the program Testing and Debugging Maintenance

Analyzing or Defining the problem, also known as program analysis, involves the following tasks. – Specifying the input requirements – Specifying the output requirements – Specifying the processing requirements

Analyzing or Defining the problem Specifying the Input requirements: Specifying the input requirements is used to determine the inputs required and the source of the data. Specifying the output requirements: Specifying the output requirements is used to describe in detail the output that will be produced.

Analyzing or Defining the problem Specifying the processing requirements: Specifying the processing requirements is used to determine the processes for converting the input data in to output data. Example for problem definition: 1. Compute the Area of a rectangle Write a program, which will input the width and length of a rectangle and then calculate and output its area. Compute the Area of a rectangle: Input : Width and Length Output : Area of rectangle Process: Find solution technique, which converts input to output.

Analyzing or Defining the problem Example for problem definition: 2. Compute Sum of N numbers: • • Write a program, which will input a list of numbers until it encounters 0 and then output the sum. The above problem definitions very clearly and precisely defines what the problem are. The input, output and process for the above problem definitions can be as follows: Compute Sum of N numbers: Input : List of numbers until 0 is encountered Output : Sum of all the input numbers Process: Find solution technique, which converts input to output.

Modular Design Once the problem is defined clearly, several design methods can be considered. An important approach is Top-down program design. Top-Down program design is a structured design technique. It consists of the following steps. • Take a problem, divide it into smaller logical sub-problems, called as Modules. • Each module can have only one entry point and one exit point, so that the logic flow of the program is easy to follow. • When the program is executed, it must be able to move from one module to the next in sequence, until the last module has been executed. • Each module should be independent and should have a single function. • Each module should be of manageable size, in order to make the design and testing of the programmer easier.

Developing a Solution technique( Algorithm) An Algorithm is a step-by-step description of the solution to a problem. Def: An algorithm is defined as an “ordered sequence of well-defined and effective operations that, when executed, will always produce a result and terminate in a finite amount of time”. An algorithm must be, – Precise and unambiguous. – Give the correct solution in all cases. – Eventually end.

Developing a Solution technique( Algorithm) Example for an algorithm: The algorithm for the problem “Compute the Sum of N numbers”. Algorithm: Compute Sum • Step 1: Initialize Sum to be 0. • Step 2: Input New Number • Step 3: If new number is 0 go to step 6. • Step 4: Add the next number to sum. • Step 5: Go to Step 2. • Step 6: Report the Sum.

Developing a Solution technique( Algorithm) Testing an Algorithm: • The Boundary (or Extreme) Cases. How does the algorithm perform at the extremes of the valid cases, for example, finding elements at the very beginning or end of the list. • The Unusual Cases. What happens when we input data that violate the normal conditions of the problem or represent unusual condition? For example what happens if the key cannot be found in the list or we have given a list of length 0? • The Invalid Cases. How does the algorithm react for data are patently illegal are completely meaningless, such as list of length – 1? An algorithm should work correctly and produce meaningful results for any data. We call this foolproof programming.

Developing a Solution technique( Flow Chart) Flow Chart A Flow Chart is a blue print or a logical diagram of the solution to a Problem. The Symbols used in drawing a flow chart is given below

Developing a Solution technique( Flow Chart) START, END INPUT / OUTPUT COMPUTATION & ASSIGNMENT DECISION MAKING CONTROL FLOW CONTINUOUS PURPOSES

Coding • Writing the program is called Coding. • In this step, the logic that has been developed in the algorithm is used to actually write the program. • Using any programming language, the algorithm can be converted to coding.

Documenting the program • Documentation exists to assist in the understanding or use of a program. • Documentation comes in two forms - External documentation, which includes such things as reference manuals, algorithm descriptions, flowcharts, and project workbooks - Internal documentation, which is part of the source code itself (essentially, the declarations, statements, and comments).

Compiling and Running the program • Compiling is a process in which the source program instructions are translated into a form that is suitable for execution by the computer. • The compiler does the translation after examining each instruction for its correctness. The translation results in the creation of object code. If necessary, Linking is also done. • Linking is the process of putting together other program files and functions that are required by the program. • After compilation, the program can be e x e c u t e d. During execution, the executable object code is loaded into the computer memory and the program instructions are executed.

Testing • Testing is the process of executing a program with the deliberate intent of finding errors. • Some programmers use the terms “testing” and “debugging” interchangeably, but careful programmers distinguish between the two activities. • Testing is a means of detecting errors. Debugging is a means of diagnosing and correcting their root causes.

Debugging • Debugging is the process of identifying the root cause of an error and correcting it. • On some projects, debugging occupies as much as 50 percent of the total development time. • For many programmers, debugging is the hardest part of programming.

Maintenance • Programs require a continuing process of maintenance and modification to keep pace with changing requirements and implementation technologies. • Maintainability and modifiability are essential characteristics of real programs. • A program’s ability to be read and understood is an important prerequisite to its maintainability and modifiability. • You can make your program maintainable by: – dividing the program into modules – making sure that the program is well-documented – using symbolic constants

Summary • Program development life cycle involves analysis, algorithm development, coding, documenting, compiling and running, testing and debugging and maintenance. • An algorithm is a step-by-step description of the solution to a problem. Development of an algorithm involves many refinement process. • Top-Down program design involves dividing the problem into smaller logical sub-programs known as modules.

Test your understanding 1. Write an algorithm to find the total number of even integers in a given list. 2. Draw a flow chart for the above problem 3. Write an algorithm to find all numbers in fibonacci sequences less than 100. 4. Write an algorithm to find all numbers in prime sequences less than 200.

2. 0 Programming Language Introduction: A programming language is a vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. Objective: After completing this Topic, you will be able to, 1. Define Programming Language 2. Appreciate Programming Language 3. Understand types of Programming Language 4. Appreciate the development of Early Languages

What is a programming language? • • It is a vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. Usually refers to high-level languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal

Why study Programming Language? • • • To improve a one’s ability to use programming languages effectively & efficiently To improve one’s ability to develop better & smarter algorithms To improve one’s knowledge on useful programming constructs To enable a better choice of programming languages which would tailor to one’s specific requirement. To make it easier to learn & design a new language

Types & Features • • Types – Numerical – Business – AI – System Features of a Good Programming Language – Clarity, Simplicity & Unity – Orthogonality – Support for abstraction – Portability – Cost of creation, execution and maintenance

Target Environments – – – Batch Interactive Embedded Portability Development

Summary • The choice of which language to use depends on the type of computer the program is to run on, what sort of program it is, and the expertise of the programmer. • The external environment supporting the execution of a program is termed its operating or target environment. • The environment under which a program is designed, coded, tested & debugged is called the host environment. • Target environments can be classified into 4 categories – - Batch processing - Interactive - Embedded systems and Programming environment

3. 0 Introduction to C Language • Objectives After completing this session you will be able to – Understand the structure of C Program – Understand the concepts of variables, constants and expressions – Understand the functions of Arithmetic, Relational and Logical Operators

Overview of C Language • C is a programming language that allows a software engineer to efficiently communicate with a computer. • It’s been used for a wide variety of programs including firmware for microcontrollers, operating systems, applications, and graphics programming.

Overview of C Language Some of the features of C Language are listed below: – Designed for top-down programming – Programs will be easier to design. – Designed for structure - Programs will be easier to read and understand. – Allows modular design – Makes it easier for you to debug. – C is much more flexible. – Low level (Bitwise) programming readily available – Pointer implementation - extensive use of pointers for memory, array, structures and functions.

History of C Language • ALGOL 60 was developed by an International committee in year the 1960 • Combined Programming Language was developed at Cambridge University in the year 1963. • Basic Combined Programming language was developed by Martin Richards at Cambridge University in 1967. • In 1970, B language was developed by Ken Thompson at Bell Labs. • In 1972, C language was developed by Dennis Ritchie at AT & T Bell labs.

Structure of C Program Preprocessor Area - This section is used to include files and define constants and macro functions. Function prototype - User defined functions prototype specification. Global Variables Declaration - This section is used to declare global variables main function - Starting and ending point of execution User defined functions - This section contains many user defined functions The structure of the User defined and main function is as follows: Return-type function-name(list of parameters) { Local Variables Declaration; Set of statements; return statement; }

Sample Program Example: 1 /* This program accepts four integers from the keyboard as input and calculate and print the average */ #include <stdio. h> #define SIZE 4 int main( ) { int n 1, n 2, n 3, n 4; float total, avg; printf(“n Please input 4 integer numbers”); scanf(“%d%d”, &n 1, &n 2, &n 3, &n 4); total = (n 1+n 2+n 3+n 4); avg = total / SIZE; printf(“n. The following data was input: %d %d ”, n 1, n 2, n 3, n 4); printf(“n The mean of the data is = %10. 2 f”, avg); return 0; }

Sample Program • Example: 2 /* Sample program */ main( ) { printf( “I Like C n'' ); } – C requires a semicolon at the end of every statement. – printf is a standard C function -- called from main. – n signifies new line character formatted output.

The C Compilation Model The C Compilation model describes the program development process in terms of language

The Preprocessor • The Preprocessor – The Preprocessor accepts source code as input and is responsible for – Removing comments – Interpreting special preprocessor directives denoted by #. • For example – #include -- includes contents of a named file. Files usually called header files. e. g • #include <math. h> -- standard library math file. • #include <stdio. h> -- standard library I/O file – #define -- defines a symbolic name or constant. Macro substitution. • #define MAX_ARRAY_SIZE 100

System Softwares • C Compiler The C compiler translates source code (user written program) to assembly code (Machine understandable code). The source code is received from the preprocessor. • Assembler The assembler creates object code. On a UNIX system you may see files with a. o suffix (. OBJ on MSDOS) to indicate object code files. • Link Editor If a source file references library functions or functions defined in other source files the link editor combines these functions (with main( )) to create an executable file. External Variable references resolved here also.

Character set and Keywords Character Set - C uses the uppercase letters A-Z, the lowercase letters a-z, the digits 0 -9 and special characters. Some of the special characters are ! * + “ < # ( = | { > % ) ~ ; } / etc. Keywords have standard, predefined meanings in C. These keywords can be used only for their intended purpose; They cannot be used as programmerdefined identifiers. Some of the keywords are : auto extern break float sizeof static etc.

Identifier • Identifier is a name given to any programming element like variables, constants, functions, statements. • It should start with a alphabet followed by the combinations of alphabets and digits. No special character is allowed except underscore( _ ). Valid identifiers : sum 01 net_pay Invalid identifiers: 25 Mark Student number #totalsalary

Variable and Data types Variable – A variable is an identifier that represents a value. The value represented by the identifier may be changed during the execution of the program. Data and Data Types – Data represent raw facts. – Data type indicated the type of value represented or stored. Data Type Defines – – – It also specifies the number of bytes to be reserved in memory The range of value can be represented Type of operation to be performed on data

Data Types Data types may be broadly classified into two types. – Primitive or Primary or Basic data types – Compound or Derived or User defined data types There are four basic primitive data types: char int Float double - used to declare variables for storing character (textual) data. - used to declare variables that store integer values. - used to declare variables that store real ( floating point ) values. - used to declare variables that store double precision values.

Derived Data Types • Derived data types are a combination of primitive data types. They are used to represent a collection of data. They are – – – Arrays Structure Unions Typedef Enumerated Pointers

Size of the Data types • Size of each data types (Machine Dependent) sizeof(int) sizeof(char) sizeof(long) sizeof(short) sizeof(float) sizeof(double) sizeof(long double) =2 =1 =4 =2 =4 =8 = 10 bytes bytes

Type Qualifiers • Type Qualifiers – Data Types can be augmented by additional information. – A number of qualifiers or modifiers may be assigned to these basic types to represent the number of bits utilized in memory • Some simple “type qualifiers” are listed below: – – short long unsigned

Declaring and Initializing variables • Declaring a Variable To declare a variable in C, do: var_data_type list variables; Examples: int i, j, k; float x, y, z; char ch; • Initializing a Variable You can initialize a variable when you declare it. int total_score = 0;

Expressions Expression is a combinations of language keywords, function calls, operators, and operands that evaluate to a value. There are three types of expressions, – Arithmetic Expressions – Relational Expressions – Logical Expressions

Arithmetic Expressions An expression which involves arithmetic operators, is Arithmetic Expression. The arithmetic operators available in C are, + Addition Subtraction * Multiplication / Division % Modulus

Relational Expression • Relational Expression An expression which involves relational operators, is Relational Expression. The Relational operators available in C , are < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to

Logical Operators • Logical Expression An expression which involves logical operators, is Logical Expression. Logical operators are usually used with conditional statements. The logical operators are, && logical AND || logical OR ! logical NOT • Logical Operators && and || are binary operators(Which requires two Operands) • ! is a Unary Operator(Which requires one operand).

Order of Precedence – It is necessary to be careful of the meaning of such expressions as a+ b * c. – We may want the effect as either (a + b) * c or a + (b * c). All operators have a priority, and high priority operators are evaluated before lower priority ones. Operators of the same priority are evaluated from left to right, so that a - b – c is evaluated as ( a - b ) – c as you would expect.

Order of Precedence From high priority to low priority the order for all C operators is: • • • ( ) [ ] ->. ! -(unary minus) sizeof (type cast) ++ - * / % + < <= >= > == != && || ? : = += -= , (comma) (Association left->right) ( Association right->left) (Association left->right) (Association left->right) (Association right->left)

Assignment Statements • Assignment Statement is used to assign a value to a variable. In C, the assignment operator is “=”. • The left side of the “=” is always a variable whose address specifies where to store the data on the right side. e. g. x = y + z; this means, compute the value of y+z and store the result in the variable x. • However, x + 3 = y is not legal. x + 3 is an arithmetic expression; not a storage location. Here, x is a location value (storage location), y and z are the read values (right hand side variables values).

Multiple Assignment Statements C allows multiple assignment statements using =, for example: a = b = c = d = 3; . . . which is the same as, but more efficient than: a = 3; b = 3; c = 3; d = 3; This kind of assignment is only possible if all the variables types in the statement are the same.

Printing Out and Inputting Variables • Printing Out and Inputting Variables: C uses formatted output. The printf function has a special formatting character (%) -- a character following this defines a certain format for a variable: – %c -- characters – %d -- integers – %f – floats – %s - string e. g. printf(“%c %d %f”, ch, i, x); • scanf( ) is the function for inputting values to a data structure: Its format is similar to printf: e. g. scanf(“%c %d %f”, &ch, &i, &x);

Constants Constant it is a bit like a variable declaration except the value cannot be changed. • There are two types of constants. – – • Symbolic constants Constant variables, also called read-only variables. A symbolic constant is defined in the preprocessor area of the program and is valid throughout the entire program. The preprocessor #define is more flexible method to define constants in a program. A symbolic constant is defined as follows. For e. g. #define max #define pi 100 3. 14 Each reference to max in program will cause the value of 100 to be applied. This value cannot be changed by the program. Because there is no memory allocated for the symbolic constants.

Constants A constant variable is declared and initialized in the variable declaration section of the program and cannot be modified thereafter. The type of value stored in the constant must also be specified in the declaration. In C, we are using const as a keyword to declare constant variables. For example, an integer and float constants can be declared as follows: const int size = 100; const float pi=3. 14;

Typecasting • Typecasting: C provides a mechanism which allows the programmer to change the default data type of a given arithmetic expression. This is called typecasting. For e. g. float sum; sum = (int) (1. 5 * 3. 8); The type cast (int) tells the C compiler to interpret the result of (1. 5 * 3. 8) as the integer 5, instead of 5. 7. Because sum is of type float, the value stored will therefore be 5. 0.

Typecasting C provides two types of typecasting: • implicit - C compiler can converts the value of one data type into another by default. • explicit - User has to enforce the compiler to convert the one data type value to another data type value by using typecasting operator. [ (data type) expression ] Another two terms associated with type casting are : • Narrowing: Converting the higher data type value to lower data type value. • Widening : Converting the lower data type value to higher data type value. e. g. float to (int or char) - narrowing (char or int) to float - widening

Summary – C is a highly structured middle level language. – C program consists of collection of functions. – C supports four basic primitive data types int, char, float, double. – C has a rich set of operators namely arithmetic, relational and logic.

4. 0 Selection Structure • Objectives After completing this session you will be able to – Know the syntax of if statement and switch statement – Understand the function of ternary operator ? : – Write efficient programs using selection statements

if Statement if statement • The if statement allows us to put some decision-making into our programs. The if statement has the same function as other languages. It has three basic forms: Form 1 if (expression) statement ; • If the expression is evaluated as true (nonzero), the statement will be executed. If the expression is evaluated as false (0), the statement will not be executed. • If more than one statement are to be executed in the if condition, such statement must be enclosed within the curly braces.

if Statement Form 2 if (expression) statement 1; else statement 2; • If the condition is true (nonzero), the first statement is executed, else the second statement is executed. Form 3 if (expression) statement 1; else if (expression) statement 2; else statement 3;

if Statement Example 1 int x, y, w; main( ) { if (x > 0) { z = w; } else { z = y; } } Example 2 if(balance < 500) service_charge = 10; else service_charge = 2;

if Statement and ? : Operator(Ternary) Example 3 if( (student_cat = =’p’) && (age>21)) ++mature_student; Ternary Operator ( ? : ) • The ? : (ternary or conditional) operator is a more efficient form for expressing simple if statements. It has the following form: expression 1 ? expression 2: expression 3 • It simply states: if expression 1 then expression 2 else expression 3 For example to assign the maximum of a and b to c: c = (a>b) ? a : b; which is the same as: if (a>b) c = a; else c = b;

switch statement • The C switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups. switch (expression) { case item 1: statement 1; break; case item 2: statement 2; break; case itemn: statementn; break; default: statement; }

switch Statement Example switch (letter) { case ‘A’: case ‘E’: case ‘I’: case ‘O’: case ‘U’: number_of_vowels++; break; case ‘ ’ : number_of_spaces++; break; default : number_of_consonants++; }

Summary • if statement is a condition based decision making statement. • Ternary operator is more efficient form for expressing simple if statements • The C switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups.

5. 0 Control Statements Objectives After completing this chapter, you will be able to • Know the syntax and functions of for, while, and do-while statement • Know the usage of break and continue statement • Write Programs using control structures

for Statement • Looping statements allow the program to repeat a section of code any number of times or until some condition occurs. For example, loops are used to count the number of words in a document or to count the number of upper case characters in a line of text. for statement The C for statement has the following form: for (expression 1; expression 2; expression 3) statement; or {block of statements} • expression 1 initializes the counter variable; expression 2 is the terminate test condition; expression 3 is the modifier (which may be more than just simple increment);

for Statement Example : for Statement main() { int x; for (x = 3; x > 0; x--) { printf("x=%d n", x); } } Output is x=3 x=2 x=1

for Statement Different formats of for Statement • for (x=0 ; ((x>3) && (x<9)); x++) • for (x=0, y=4; ((x>3) && (y<9)); x++, y+=2) • for (x=0, y=4, z=4000; z ; z/=10)

while Statement • The while statement is used when the program needs to perform repetitive tasks. The while statement has the form: while (expression) statement;

while Statement Example int x=3; main() { while (x>0) { printf("x=%dn", x); x--; } } Output is x=3 x=2 x=1

while Statement • Because the while loops can accept expressions, not just conditions, the following are all legal: while (x--); while (x = x+1); while (x += 5); • Using this type of expression, only when the result of x--, x=x+1, or x+=5, evaluates to 0 will the while condition fail and the loop be exited. • We can go further still and perform complete operations within the while expression: while (i++ < 10); while ( (ch = getche( )) != ‘q’) putchar(ch);

do while Statement The do-while statement C's do-while statement has the form: do statement; while (expression);

do while Statement Example: int x = 3; main( ) { do { printf("x=%dn", x--); }while (x>0); } Output is x=3 x=2 x=1

break and continue Statements break and continue • C provides two commands to control how we loop: break continue - exit form loop or switch. skip 1 iteration of loop. • Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.

break and continue Statements while (scanf( “%d”, &value ) = = 1 && value != 0) { if (value < 0) { printf(``Illegal valuen''); break; /* Abandon the loop */ } if (value > 100) { printf(``Invalid valuen''); continue; /* Skip to start loop again */ } /* Process the value read */ /* guaranteed between 1 and 100 */. . . . ; } /* end while value != 0 */

Summary • Looping allows the program to repeat a section of code any number of times or until some condition occurs • for statement is used to repeat a set of statements specified number of times • while and do. . while statements are repetitive control structures, that are used to carry out conditional looping

6. 0 Arrays and Strings Objectives After completing this chapter, you will be able to • Give a brief overview of arrays and strings • Explain the memory layout of single and multi dimensional arrays • List the merits and de-merits of arrays

Arrays Introduction • Array is one of the simplest data structure in computer programming. • Arrays hold a fixed number of equally sized data elements, generally of the same data type.

Introduction to Arrays • Arrays are a data type that are used to represent a large number of homogeneous values, that is values that are all of the one data type. • The data type could be of type char, in which case we have a string. • The data type could just as easily be of type int, float or even another array. • Example : int my_array[] = {1, 23, 17, 4, -5, 100}; The elements in the Array are always stored in consecutive memory locations.

Memory Organization for an array The Memory organization of an integer array A of 5 elements is Shown below A 1 2 100 102 3 4 5 104 106 108

Multi Dimensional Arrays • The elements of an array can themselves be arrays. • The following example declares and creates a rectangular integer array with 10 rows and 20 columns int a[][] = new int[10][20]; for (int i = 0; i < a. length; i++) { for (int j = 0; j < a[i]. length; j++) { a[i][j] = 0; } } • The elements are accessed as a[i][j]. This is a consistent notation since a[i][j] is element j of the array a[i].

Advantages & Limitations Advantages • Arrays are, – – Simple and easy to understand Contiguous allocation Fast retrieval because of its indexed nature No need for the user to be worried about the allocation and de-allocation of arrays Limitations • If you need m elements out of n locations defined, – n-m locations are unnecessarily wasted if n>m or – an error occurs if m>n named out of bounds error.

Strings • Strings are sequences of characters. • Strings are just character arrays with a few restrictions. One of these restrictions is that the special character ‘ ’ (NULL) is used to indicate the end of a string. • For example, the following defines a string of 5 characters: char name[5]; int main( ) { name[0] = ‘A’; name[1] = ‘R’; name[2] = ‘U’; name[3] = ‘N’; name[4] = ‘ ’; return 0; }

Strings • C doesn’t allow one array to be assigned to another, so we can’t write an assignment of the form. name = “ARUN”; /* illegal*/ • Instead we must use the standard library function strcpy to copy the string constant into the string variable. strcpy(name, “ARUN”); • To print a string we use printf with a special %s control character: printf(“%s”, name);

Strings There are several standard routines that work on string variables. Some of the string manipulation functions are, strcpy(string 1, string 2); - copy string 2 into string 1 strcat(string 1, string 2); - concatenate string 2 onto the end of string 1 strcmp(string 1, string 2); - 0 if string 1 is equals to string 2, < 0 if string 1 is less than string 2 >0 if string 1 is greater than string 2 strlen(string) - get the length of a string. strrev(string) - reverse the string and result is stored in same string.

Strings The standard character string input functions are, scanf(“%s”, string_name); gets(string); The standard character string output functions are, printf(“%s”, string); puts(string);

Summary • The simplest type of data structure is a linear array • An array can be defined as a collection of homogenous elements, in the form of index/value pairs, stored in consecutive memory locations. An array always has a predefined size and the elements of an array are referenced by means of an index / subscript. • An array can be of more than one dimension. There are no restrictions to the number of dimensions that we can have. • Arrays of Characters are called as Strings

7. 0 Introduction to Pointers Objective After completing this chapter you will be able to • • Understand Pointers Compare Pointers and Arrays Understand Character Pointers List the advantages and limitations of Pointers

Introduction to Pointers • What is a pointer? The C programming language provides a special mechanism for passing variables to functions that is a little unintuitive, but extremely powerful. C provides two operators, & and *, which allow you to pass a variable instead of its value. • Example: main() { int x = 7 ; int *px ; /* px is a pointer to an integer */ px = &x ; /* px gets the address of x */ printf( "%dn" , x ) ; /* show the value of x */ printf( "%dn" , &x ) ; /* show the address of x */ printf( "%dn" , *px ) ; /* show the value of what px points to */ }

Pointer Arithmetic • • Pointer Addition or subtraction is done in accordance with the associated data type. – Integer => adds 4 for every increment – Char => adds 1 for every increment – float => adds 4 for every increment Example int * ptr , i=5; ptr= &i; ptr ++; let ptr = 1000 (location of i) now ptr = 1001 but it is 1004 or +4 (integers) ++*ptr or (*ptr)++ => increments the value of i by 1 *ptr++ • => increments the address of i by 1 ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i. e. 4 for an integer)

Pointers and Arrays • The address of the 1’st element of an array is represented by its name • Example int a[5] ; a => &a[0] a+1 => &a[0] + 1 (a+i) ; i varies from 0 to 4 ; traverses through the address of each element in the array ‘a’ a+i a+i a+i (i=0) => (i=1) => (i=2) => (i=3) => (i=4) => &a[0] &a[1] &a[2] &a[3] &a[4]

Pointers and Arrays • In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name, thus in our code where we wrote: – – int *ptr, my_array[]={10, 20, 30, 40 }; ptr = &my_array[0]; we can write: ptr = my_array; • ptr is a variable, my_array is a constant. That is, the location at which the first element of my_array will be stored cannot be changed once my_array[] has been declared • We cannot write – my_array = ptr; – Or – my_array++;

Pointers and 2 -D Arrays • In a 2 -D array each row may be thought of as an 1 -D array • When a 2 -D array is declared in the following way, – my_array[10][5]; • The expression (my_array + 0) gives the address of the 0 th element of the 2 -D array • The expression *(my_array + 0) gives the base address of 0 th 1 -D array • The expression *(*(my_array + 0) gives the value of the element my_array[0][0]

Character Pointers • Character pointer is a pointer, which is capable of holding the address of a character variable. Suppose if we have a character array declared as char name[30] = {“Data Structures”}; • If we need to store the address of this array we need a character pointer declared as follows char *p = NULL; • Once the pointer is declared we need to assign the address of the array to this pointer. i. e. p = name; • Now issue the following printf statements and check the output printf(“character output = %cn”, *p); printf(“String output = %s”, p);

Character Pointers • We know that when we refer to a pointer with the indirection operator we refer to the content of the address pointed by the pointer. The above printf statements will product the output as follows: character output = D String output = Data Structures • The reason for the output produced by the second printf statement is because of the %s format specifier, which will print the string till it encounters a ‘ ’ character.

malloc() function • malloc( ) is the function used for memory allocation in C. malloc() takes one argument that is the number of bytes to allocate. Suppose P is a pointer then int *p; p = (int *)malloc(sizeof(int)); • The above assignment will allocate memory for holding an integer value. • The system allocates memory from the heap and not from the stack. • For freeing the allocated memory the function used is, free(<pointer variable>);

Advantages of Pointers • It gives direct control over memory and thus we can play around with memory by all possible means. For example we can refer to any part of the hardware like keyboard, video memory, printer, etc directly. • As working with pointers is like working with memory it will provide enhanced performance • Pass by reference is possible only through the usage of pointers • Useful while returning multiple values from a function • Allocation and freeing of memory can be done wherever required and need not be done in advance

Limitations of Pointers • If memory allocations are not freed properly it can cause memory leakages • If not used properly can make the program difficult to understand • its values need to be stored somewhere. It is the nature of the pointers value that is new.

Summary SUMMARY • A pointer is a datatype whose value is used to refer to ("points to") another value stored elsewhere in the computer memory. Obtaining the value that a pointer refers to is called dereferencing the pointer. • Pointers are variables that can hold the address of another variable • Pointer addition and subtraction involves incrementing/ decrementing pointer depending upon the associated data type • The difference between arrays and pointers is array name is a fixed pointer, whereas a pointer can point to any element of an array

8. 0 Functions Objectives After completing this chapter you will be able to • • • Understand the utility of user-defined functions Define and Invoke functions Define Methods of passing data among Functions Define Function proto-types Pass arguments to main( ) functions through Command-line arguments • Understand the usage of auto, static, and extern storage qualifiers • Understand the concept of Recursion • Write Programs with efficient, concise functions

Need for functions Need for the Functions As, programs become more complex and large, several problems arise. Most common are • Algorithms for solving more complex problems become more difficult and , hence difficult to design • Even if algorithms are known, its implementation becomes more difficult because the size of the program is longer • As programs become larger and complex, debugging and testing becomes more difficult. • As programs become larger and complex, more documentation is required to make the program understandable for people who will use and maintain the program

Functions Defining a Function In C, a program is a collection of well defined and interrelated functions. The general form of a function is as follows return-type function(type arg 1, type arg 2, …. . ) { local variables Declaration; executable statement 1; executable statement 2; : : return(expression); }

Functions Example 1: Function for finding the biggest of two integers int find_big(int a, int b) { if ( a > b) return a; else return b; }

Functions Invoking a Function • The user-defined functions are accessed from a function simply by its name and actual arguments / parameters enclosed with in parentheses. • These actual arguments are used to pass values formal arguments defined in the function. • When the function call is encountered, the control is transferred to the called function. • The formal arguments are copied by actual arguments and the execution of the function is carried out. • When the return statement is executed or last statement has finished its execution, the control is transferred back to the place of function call in the calling function.

Functions Example Program for finding biggest of two integers using the function void main( ) { int num 1, num 2, big; scanf(“%d%d”, &num 1, &num 2); big=find_big(num 1, num 2); printf(“ The biggest is : %d “, big); } int find_big(int a, int b) { if ( a > b) return a; else return b; }

Local and Global Variables • The variables declared inside a function are local to that function. It can be accessed only with in that function. Memories for the local variables are allocated only when the function is invoked and deallocated when the control returns to the calling function. These variables are also known to be automatic variables. • The variables declared outside of all function are global variables. These global variables are visible to all functions.

Local and Global Variables Example : Usage of Global Variables int a; /* Global variable */ float b; /* Global variable */ void main() { int c; /* Local variable*/ a=10; b=1. 2; c= 20; fun( ); printf(“ %d “, a); /* prints 20 */ } void fun() { a+=10; }

Passing arguments to a function Passing arguments to a Function • The mechanism used to pass data to a function is via argument list. There are two approaches to passing arguments to a function. These are – Call by Value – Call by Reference

Call by Value Example Program that illustrates Call by Value mechanism void main() { int a, b; a=10; b=20; swap(a, b); /* passing the values of a and b to c and d of swap function*/ printf(“%d %d”, a, b); /* Prints 10 20 */ } void swap(int c, int d) { int temp; temp = c; c = d; d = temp; } /* Function used to swap the values of variables c and d */

Call by Reference • In this approach, the addresses of actual arguments are used in the function call. The formal arguments should be declared as Pointer variables. • This approach is of practical importance while passing arrays and structures among functions and also for passing back more than one value to the calling function.

Call by Reference Example : Program that illustrates Call by Reference mechanism void main() { int a, b; a=10; b=20; swap(&a, &b); /* passing the addresses of a and b to c and d of swap function*/ printf(“%d %d”, a, b); /* Prints 20 10 */ } void swap(int *c, int *d) { int temp; temp = *c; *c = *d; *d = temp; }

Function Prototyping • Function prototype is a function declaration that specifies the return type and data types of the arguments. • A function prototype/declaration informing the compiler the number and data types of arguments to be passed to the function, and the data type of the value returned by the called function. • Prototype for the function find_big int find_big(int, int); • Prototype for the swap function written void swap(int *, int*); • Usually prototypes appear at the beginning of a Program.

Storage Classes • Every variable in C possesses a characteristic called storage class. The Storage class defines two characteristics of a variable. Its Life time Its visibility or scope • Life time: The life time of a variable is the length of time, it retains a value in memory • Visibility: Visibility or Scope of a variable refers to those parts of a program which will be able to recognize it.

Storage Classes • The storage class precedes the variable’s declaration and tells the compiler how the variable should be stored in memory. C supports following four storage classes: • • Auto Static Extern Register • If the storage class is omitted at declaration, it is assumed of type auto storage class.

auto storage class auto Storage Class • Stored in Memory • If not initialized in the declaration statement, their initial value is unpredictable value often called garbage value • Local (visible) to the block in which the variable is declared. If the variable is declared with in a function, then it is only visible to that function. • It retains its value till the control remains in that block. As the execution of the block/function is completed, it is cleared and its memory destroyed.

auto Storage Class Example: Program illustrating auto variables void main( ) { fun( ); } void fun( ) { auto int b = 20; /*Auto (Local) variable to fun() */ b++; printf( “ Calling Fun( ) : %d n“, b); } The output of the above program is as follows Calling Fun( ) : 21

Static Storage Class • Stored in Memory • If not initialized in the declaration, it is initialized to zero. • Local(Visible) to the block in which the variable is declared. If the variable is declared inside a function, then it is visible to that function. But, if the variable is declared outside the function, then it is visible to all functions following its declaration. • It retains its value between different function calls. That is, when for the first a function is called, a static variable is created with initial value zero, and in subsequent calls it retains its present value.

Static Storage Class Example : Program illustrating Static variables void main( ) { fun( ); } void fun( ) { static int b = 20; /*Static variable to fun( ) */ b++; printf( “ Calling Fun( ) : %d n“, b); }

Static Storage Class • The output of the above program is as follows Calling Fun( ) : 21 Calling Fun( ) : 22 Calling Fun( ) : 23

Register Storage Class • Stored in Processor registers, if register is available. If no register is available, the variable is stored in memory, and works as if its storage class is auto. • If not initialized in the declaration, the variable is initialized to zero. • Local(Visible) to the block in which the variable is declared. If the variable is declared inside a function, then it is visible to that function. But, if the variable is declared outside the function, then it is visible to all functions following its declaration. • It retains its value till the control remains in that block. As the execution of the block/function is completed, it is cleared and its memory destroyed.

Extern Storage Class • The Scope of external variables is global. External variables are declared outside all functions, usually in the beginning of the program file. As all the function will be defined after these variables declaration, these variables are visible to all functions of the program. • This storage class is useful for a multi files program. • Stored in memory • If not initialized in the declaration, it is initialized to zero.

Extern Storage Class Example Program File a. c int val; /*Global */ void main( ) { scanf(“ %d “, &val); compute( ); printf(“ %d “, val); } Program File b. c void compute( ) { extern int val; val++; } /*This implies that, the variable val is defined in another file*/

Recursion • If a function is having a self-reference, it is recursion. In order that the function should not continue indefinitely, a recursive function must have the following properties: - There must be certain criteria, called base criteria, for which a function does not call itself. - Each time, when a function calls itself, it must be close to the base criteria. That is, it uses an argument(s) smaller than the one it was given at previous reference.

Recursion Example Illustrative examples of Recursive function Factorial Function : n! = n * (n-1)! Base Criteria is 0! =1 int factorial( int n) { if(n = = 0) return 1; else return( n* factorial(n-1)); }

Command Line Arguments Command line arguments • The main( ) function can receive arguments from the command line. These arguments, which are used sent data to main( ) function are known as command line arguments • The command-line arguments are accepted by the main() function through special parameters namely argc and argv. Their declarations are as follows: void main ( int argc, char *argv[]) { : } • argc provides a count of the number of command line argument • argv is an array of character pointer of undefined size that can be thought of as an array of pointer to strings, which are command line strings.

Command Line Arguments • Example : Program illustrating command line arguments void main( int argc, char* argv[]) { int i; printf(“n Total Number of Arguments = %d”, argc); for( i = 0; i < argc; i++) printf(“n. Argument number %d = %s”, i , argv[i]); } • Assume that this program is stored in a file test. c and got compiled. Now, in the operating system prompt if we type a command as test one two three four

Command Line Arguments Then the result will be Number of Arguments Argument number 0 Argument number 1 Argument number 2 Argument number 3 Argument number 4 = = = 5 test one two three four

Functions and Arrays Single dimensional arrays can be passed to functions as follows: float find_average(int size, float list[]) { int i; float sum=0. 0; for (i=0; i<size; i++) sum+=list[i]; return(sum/size); } Here the declaration float list[] tells C that list is an array of float. Note we do not specify the dimension of the array when it is a parameter of a function.

Functions and Arrays Multi-dimensional arrays can be passed to functions as follows: void print_table(int xsize, int ysize, float table[][5]) { int x, y; for (x=0; x<xsize; x++) { for (y=0; y<ysize; y++) printf("t%f", table[x][y]); printf("n"); } } Here float table[][5] tells C that table is an array of dimension N*5 of float. Note we must specify the second (and subsequent) dimension of the array BUT not the first dimension.

Function Pointer • A function in C has an address and it can be pointed using a pointer • A function pointer is declared in the following way, int (*func_ptr) (); • The address of a function is assigned to a function pointer in the following way, – – int display(); int (*func_ptr) (); func_ptr = display; (*func_ptr) (); // invokes the function display

Summary • A function facilitates Reusability and Procedural abstraction • Function Proto-type is a model of a function. • The Command-line arguments argv and argc are used to pass arguments to a main() function. • The storage qualifiers auto, static, register and extern are used for memory management of variables. • Recursive functions are used to solve complex problems but recursive in nature.

9. 0 Structures and Unions Learning Objectives After the completion of this module, you will be in a position to • Understand the concepts of Structures and Unions • Understand the applications of Structure and Unions • Write Programs for processing structures and Unions

Structures Structure • A Structure is a group of data items of different data types held together in a single unit. • It is used to represent an entity, which is described with a set of attributes. • For example, an employee is represented by the attributes employee code (an Integer number), employee’s name (a character array), Department Code ( an Integer number), Salary( a Floating point number) and so forth.

Structures Declaring a Structure and its Variables The syntax for declaring a structure is as follows struct-name { type variable-name, . . . . ; type variable-name, . . . . ; : : type variable-name, . . . . ; }struct-variable, struct-variable. . . ;
![Structures Example struct employee_type { int code; char name[20]; int dept_code; float salary; } Structures Example struct employee_type { int code; char name[20]; int dept_code; float salary; }](http://slidetodoc.com/presentation_image_h2/3d6661b761b6f9bed324b0078fffd688/image-139.jpg)
Structures Example struct employee_type { int code; char name[20]; int dept_code; float salary; } emp 1, emp 2; • Here, employee_type is a Tag. The fields inside this structure are code, name, dept_code and salary. The variables of the type emplyee_type are emp 1 and emp 2.

Structures • By using the structure tag, other variables, function arguments can be declared as follows struct-name var 1, var 2, . . . ; • For example, we can define a variables of type employee_type as follows struct employee_type emp 1, emp 2;

Structures Accessing Structure Elements • The elements/fields of a structure variable are accessed using dot operator ‘. ’. The syntax for accessing a members of a structure variable is variable. field • For example, to access a fields of a variable emp 1, emp 2 defined in the above example , we can use the dot operator as follows emp 1. code emp 1. name emp 1. dept_code emp 1. salary emp 2. code emp 2. name emp 2. dept_code emp 2. salary

Structures Initializing Structures • Like simple variables and arrays, structure variables can also be initialized at the time of declaration. The format used is quite similar to initialize an array. Example struct stud_type { int rollnum; char name[20]; int semester; float avg; }; struct stud_type stud 1={1001, ”Aldina”, 1, 90. 78}, stud 2={1002, “Raja”, 1, 79. 28};
![Structures Array of Structures Example struct stud_type { int rollnum; char name[20]; int semester; Structures Array of Structures Example struct stud_type { int rollnum; char name[20]; int semester;](http://slidetodoc.com/presentation_image_h2/3d6661b761b6f9bed324b0078fffd688/image-143.jpg)
Structures Array of Structures Example struct stud_type { int rollnum; char name[20]; int semester; float avg; }; struct stud_type stud[50];

Structures • In the above example, stud is an array that consists of 50 structure of type stud_type. To access the 0 th structure, we can do it as follows, stud[0]. rollnum stud[0]. name stud[0]. semester stud[0]. avg

Pointers and Structures • As we can use pointers with other types, we can also use pointers for structure variables. We can declare pointer to a student structure as follows struct stud_type *ptr; • In this declaration, ptr is a pointer type variable, which can hold an address of a variable of the type stud_type.
![Structures Example struct stud_type { int rollnum; char name[20]; int semester; float avg; }; Structures Example struct stud_type { int rollnum; char name[20]; int semester; float avg; };](http://slidetodoc.com/presentation_image_h2/3d6661b761b6f9bed324b0078fffd688/image-146.jpg)
Structures Example struct stud_type { int rollnum; char name[20]; int semester; float avg; }; struct stud_type stud={1001, ”Aldina”, 1, 98. 23}, *ptr ; • In this example a structure variable stud is defined and initialized. The pointer variable ptr is declared. • Now to make ptr to point to the structure stud, we can write as ptr = &stud; • After this assignment, the structure stud can be accessed through the pointer ptr. The notation for referring a field of a structure pointed by a pointer is as follows (*pointer). field (OR) pointer -> field • So, We can access the fields of a stud through a pointer ptr as follows Printf(“ %d %s %d %f “, ptr->rollnum, ptr->name, ptr->sem, ptr->avg);

Structures Nested Structure • Just as there can be arrays of arrays, there can be a structure that contains other structures. This can be a powerful tool to create complex data types. Example struct date { int day; int month; int year; };
![Structures struct employee_type { int code; char name[20]; struct date doj; int dept_code; float Structures struct employee_type { int code; char name[20]; struct date doj; int dept_code; float](http://slidetodoc.com/presentation_image_h2/3d6661b761b6f9bed324b0078fffd688/image-148.jpg)
Structures struct employee_type { int code; char name[20]; struct date doj; int dept_code; float salary; }emp 1, emp 2; • In this example, if we want to access the year of joining of an employee of emp 1, then we can do so by writing emp 1. doj. year

Unions • As like structures, Union is also used to group data fields of different type, but unlike structures all data fields are sharing a common memory. • That is, a union permits a section of memory to be treated as a variable of one type on one occasion, and as a different variable of a different type on a another occasion. • The syntax for declaring a union, declaring variables of union type, accessing elements of union is identical to that of structures. Union differs from structure in storage and in initialization.

Unions Example union u_type { char var 1; int var 2; float var 3; double var 4; }u_var;

Union of Structures • There can be structures with in unions and unions with in structures. The following block of code illustrates union of structures. Example struct employee_type { int code; char name[20]; int dept_code; float salary; };
![Union of Structures struct stud_type { int rollno; char name[20]; int age; float avg; Union of Structures struct stud_type { int rollno; char name[20]; int age; float avg;](http://slidetodoc.com/presentation_image_h2/3d6661b761b6f9bed324b0078fffd688/image-152.jpg)
Union of Structures struct stud_type { int rollno; char name[20]; int age; float avg; }; union person { struct employee_type e 1; struct stud_type s 1; }ex;

Union of Structures • In the above example, the union makes the structure variables e 1 and s 1 to share a common memory space. • That is, the user can use either e 1 or s 1, but not both at the same time. The elements of this union of structures are accessed using dot operator as follows. ex. e 1. salary

typedef Statement Defining New Data Types using typedef • typedef can also be used with structures. The following creates a new type agun which is of type struct gun and can be initialised as usual: typedef struct gun { char name[50]; int magazinesize; float calibre; } agun; agun arnies={"Uzi", 30, 7}; • Here gun still acts as a tag to the struct and is optional. • agun is the new data type. arnies is a variable of type agun which is a structure.

Enumerated types Enumerated Types • Enumerated types contain a list of constants that can be addressed in integer values. • We can declare types and variables as follows. enum days {mon, tues, . . . , sun} week; enum days week 1, week 2; • As with arrays first enumerated name has index value 0. So mon has value 0, tues 1, and so on. week 1 and week 2 are variables. • We can also override the 0 start value: enum months {jan = 1, feb, mar, . . . , dec}; Here it is implied that feb = 2 etc.

Summary • Structures are used to group different types of data, and to represent any real-time entity • Union is similar to structures but, memory is shared by the members • typedef is used to define a new data type

Chapter 10. Files Learning Objectives After completing this chapter, you will be able to • Understand the concepts of files • Understand the basic operations of file • Understand the functions of Preprocessor directives

Files Overview of Files • A file is collection of related data stored on hard disks or an auxiliary storage device such as magnetic tape or disk. Files can be accessed using Library Functions or System Calls of Operating System. • The files accessed through the library functions are called streamoriented files and the files accessed with system calls are known as system oriented files.

Files • Based on internal storage representation of files we can have two types of files. - Text file - Binary file Text File: • The I/O stream can be a text stream or binary stream. A text stream is a sequence of text. In a text stream, each line consists of zero or more characters, terminated with new line character. Binary File: • A binary stream is a sequence of bytes. In a binary stream, it represents raw data without any conversion. For example, the new line character ‘n’ is not mapped to carriage return while using the binary streams.

Files • In C, FILE is a structure that holds the description of a file and is defined in stdio. h. Processing Files The Processing of files involves the following steps : - Opening a File - Reading from or writing into a File - Closing the File

Files • Standard Input/output • Standard I/O is the easiest and most commonly used way of performing file I/O in C language. The Standard I/O in C provides variety of functions to handle files. It supports the following ways of reading from and writing into file. - Character I/O - String I/O - Formatted I/O - Block I/O

Files Mode r w a Purpose Open for reading, the file must already exist. Open for writing. If the file exists, the content will be vanished Opening for append. Writing at the end of file. If the file does not exist, it will be created r+ Open for both reading and writing. The file must exist already w+ Open for both reading and writing. If the file exists already the content will be vanished. a+ Open for reading and appending. If the file does not exist, it will be created rb Same as mode “r”, but for binary file wb Same as mode “w”, but for binary file.

Files Example : Program segment that opens a file. FILE *fptr; fptr = fopen(“test. dat”, “w”); if ( fptr = = NULL) { printf(“ n File open failed n”); exit( 1); } else printf(“n The file is opened successfully for Writingn”);

Files Closing a File • When a program has finished with reading/writing of a file, it must be closed. This task is done by the library function fclose, which is defined in stdio. h. fclose(fptr); where fptr is a file pointer associated with the file, which is to be closed.

Files Character I/O • Using character I/O, one character(byte) can be written to or read from a file at a time. The functions putc and getc are used to write and read a byte respectively from/to a file. The syntax of putc is as follows putc(ch, fptr); • This function writes the character ch into a file pointed by the file pointer fptr. This fptr may be stdout, which represents standard output device , Screen, as a file. • The syntax of function getc is as follows ch =getc(fptr); where ch is a character variable and fptr is a file pointer. This function read a next character from the file and it is returned. The fptr may be stdin, which represents a standard input device, keyboard as a file. The EOF is end of file status flag, which is true if end of file is reached, otherwise false.

Files Example : Program for reading a line from the keyboard and writing into a file. #include <stdio. h> main( ) { FILE *fptr; char ch; fptr = fopen( “test. dat”, “w”); while( (ch=getc(stdin))!=’r’) putc( ch, fptr); fclose(fptr); }

Files Example : Program for reading characters from a file and writing to the screen until end of file. #include <stdio. h> main( ) { FILE *fptr; char ch; fptr = fopen( “test. dat”, “r”); while( (ch=getc(fptr))!=EOF) putc( ch, stdout); fclose(fptr); }

Files String Input/Output • C language is also providing functions for reading and writing data in the form of string from/to a file. The functions namely fgets( ) and fputs( ). These functions are analogous to gets( ) and puts( ), which are used to read a string from a keyboard and write a string into a screen. The syntax for writing a string into a file is as follows fputs(str, fptr); where, str is a array of characters, fptr is file pointer. This function will write the string str into a file pointed by fptr. • The syntax for reading a string from the file is as follows fgets(str, n, fptr); where str is a array of characters, where the string read from a file is stored, n is a maximum length of the string to be read, and fptr is a file pointer. This function will read a string terminated by null, new line character or up to the length of n, from a file pointed by fptr and stores it in the array str. This function returns NULL when we reach end of file.

Strings Formatted Input/Output • • We can read from or write to a file in a formatted manner using fscanf and fprintf functions. These functions are analogous to scanf and printf functions. The syntax for the fprintf which writes a formatted data into a file is as follows. fprintf( fptr, format-string, variable-list); This function will write the contents of the variables in the variable-list into file pointed by fptr according to the format specifier specified in format string. Each variable in the variable-list should have format specifier in the format-string. The syntax for the fscanf which reads a formatted data from the file is as follows fscanf( fptr, format-string, addresses-list); This function will read the formatted data from the file pointed by fptr, as specified by the format specifiers in format-string and stores in the variables, whose addresses are given in addresses-list.

Files Random Access • In C, it is possible to directly access any byte or data item, which is stored in any part of file directly. This is achieved by manipulating the file pointer. File pointer is pointing a byte in the file. • When the file is opened in read mode, the file pointer is pointing to the first byte or data item. After reading a byte/data item the file pointer is moved to next byte/data item. • In order to read/write anywhere in a file, C is providing a function fseek( ) for placing a file pointer in a place where read/write operation need to be done. fseek( ) function The syntax of fseek( ) function is as follows fseek( fptr, offset, from_where) • Where fptr is a file pointer, offset is a long integer that specifies the number of bytes by which a file pointer is to be moved and third argument from_where specifies from which position, the offset need to be measured.

Files Statement fseek(fp, 0 L, 0); fseek(fp, 0 L, 2); fseek(fp, 10 L, 0); fseek(fp, 10 L, 1); fseek(fp, -10 L, 2); Meaning Move the file pointer to the beginning. Move the file pointer to the end of file. Move after 10 bytes from the beginning. Move after 10 bytes from the current Move backward 10 bytes from the eof. • The function fseek() returns 0, when the operation is successful, otherwise returns -1.

Files ftell( ) function • This function will return a long integer that specifies the relative current position of the file pointer. The syntax is as follows ftell(fptr); • The following program fragment is used to find the size of a file name “test. dat”. fptr = fopen(“test. dat”, ”r”); fseek(fptr, 0 L, 2); size = ftell(fptr); • • rewind( ) function This function will place a file pointer to the beginning of a file. The syntax of this function is as follows rewind(fptr); This is equivalent to a fseek( ) function with the arguments fseek(fptr, 0 L, 0); •

C Preprocessor The C Preprocessor • The ``preprocessor'' is a translation phase that is applied to your source code before the compiler proper gets its hands on it. Each preprocessor directive is identified by the # (pound sign) at the beginning of a line. • File inclusion: inserting the contents of another file into your source file, as if you had typed it all in there. • Macro substitution: replacing instances of one piece of text with another. • Conditional compilation: Arranging that, depending on various circumstances, certain parts of your source code are seen or not seen by the compiler at all.

C Preprocessor File inclusion • It is also called header files. • Examples: • #include <stdio. h> #include "allconstants. h"

C Preprocessor Macro substitution • Macro substitution takes a fixed character sequence and substitutes it with another character sequence Example #define MAX 1000 We use the string MAX in our source code, and we define it once within the source code. The preprocessor substitutes the integer value 1000 for every instance of this string within the source code. It is efficient (for code execution and for memory allocation).

C Preprocessor Conditional compilation • It essentially provides a way of defining a variable, such that based on the variable's value, a specific set of (source) code is or is not compiled into the resulting object code. • Code must often be different (do different things) to be correct when executing under different operating systems. • When compiled for a target system (meaning that the operating system is defined) only the code intended specifically for that system is compiled in. • This makes the code more general, and able to be compiled for more operating systems.

Summary • File is a collection of related data stored on auxiliary storage device. • The I/O operations performed over a file are, fopen, fclose, putc, getc, fprintf, fscanf, fread, fwrite. • Preprocessor directives performs textual substitution in the source code.
- Slides: 177