c programming for computing techniques

Post on 07-Apr-2017

21 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Problem Solving Problem Solving and and

C ProgrammingC Programming

Knowledge Level:Knowledge Level:Basic Basic

Icons used

Questions References

Key Concepts

A Welcome Break

Demo

Brain Teasers

Module Information

Module Description

After completing this Module participants will be able to , • Understand the concepts of problem solving and program design• Understand the need of programming languages and its features• Appreciate program design and components of program design• Understand the various elements of C programming language• Write effective programs using C Programming Language

Level Basic

Prerequisites N/A

Module Objective & Outline

Module Objective: After completing this Module participant will be able to,

– Understand the concepts of problem solving and program design– Understand the need of programming languages and its

features– Appreciate program design and components of program

design– Understand the various elements of C Programming

language– Write effective programs using C Programming Language

Module Objective & Outline

Module Flow:

4.Selection Structure

2.Programming

Language

3.Introduction

to C Programming

6.Arrays

AndStrings

1.Introduction

to Problem Solving

7.Introduction

toPointers

8.Functions

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 theprogram will take as input and what it will produce as output

Objective: After completing this Topic, you will be able to,

1. Understand various steps in program development2. Acquire problem solving skills3. 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

Defining the problem, also known as program analysis, involvesthe 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 outputthat 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 andthen calculate and output its area.

Compute the Area of a rectangle:Input : Width and LengthOutput : Area of rectangleProcess: 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 encounteredOutput : Sum of all the input numbersProcess: 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 andeffective operations that, when executed, will always produce a result andterminate 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

• Step1: Initialize Sum to be 0.

• Step2: Input New Number

• Step3: If new number is 0 go to step 6.

• Step4: Add the next number to sum.

• Step5: Go to Step2.

• Step6: 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 ChartA Flow Chart is a blue print or a logical diagram of the solution to aProblem.

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 executed. 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 all numbers in fibonacci sequences less than 200.

2. Draw a flow chart for the above problem3. Write an algorithm to find the total number of even integers in a

given list.

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 Language2. Appreciate Programming Language3. Understand types of Programming Language4. 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

1.0 Evolution of Computer

Introduction:This Topic gives an overview on computer evolution and and its history.

Objective: After completing this Topic, you will be able to understand,

1. Types of Computer2. History of Computer3. Typical Computer System

Types of Computer

• Types of Computers (based on size, speed and cost)– Mainframe Computer : – 1. A huge. 2. As Computer size decreases power increases. 3. Still used in large companies to describe the huge M/C processing millions

of transactions.

– Desktop Computer:– A pc that is not designed for portability, set in a permanent location. Offers more power, storage and versatility.

– Portable (notebook) Computers :– Note books, Laptops, Portable computer. That integrates the display, keyboard, a pointing device, processor, memory and hard drive in battery operated package. Size of hard cover book.

– Workstations:

– Desktop computer - Powerful cpu. Additional memory - Capabilities for performing special group of task like 3D graphics, game development.

– Supercomputer :

– Single computer systems or comprised of multiple high performance computers working in parallel as a single system. E.g. Cray super

computers.

History of computers

• History of Computers – Generation – Milestone.• The history of computer development is referred to as generation of

computers.• Each generation – Characterized by major technological development

that fundamentally changed the way the computers operate, resulting in smaller, cheaper, more powerful, more efficient and reliable devices.

– The First Generation (1945-55): Vacuum Tubes– The Second Generation (1955-65): Transistors– The Third Generation (1965-75): Integrated Circuits– The Fourth Generation (1975 - ): VLSIs– Beyond the Fourth Generation

History of Computer

• Zeroth Generation:(1642- )

- Mechanical computers. - French scientist Pascal – built the first calculating m/c – mechanical using gears and powered by a hand operated crank. - Could only do addition and subtraction. - 30 years later Baron Goltfried (Mathematician) – built another mechanical m/c – Multipy and divide as well. - 150 years – Charles Babbage (Professor of mathematics) – Designed

and built Difference Engine (since it used method of finite differences using

polynomials). - Mechanical device which adds and subtract and also designed to

compute tables of numbers for naval navigation.

- O/P method – results punched into copper engraver’s plate with a steel die – foreshadowing – punched cards – CD ROMS.

- It could run only one algorithm.

• Successor of this Babbage built (Entirely mechanical general purpose) – Analytical Engine.

• Contains four components: - The Store (Memory) – 1000 words of decimal digits, each used to hold variables and results. - The Mill (Computation unit) - Could accepts operands from store and then add, subtract, multiply or divide and finally returns the result to store. - Input section – Punched cards. - Output section – Punched cards and printers.

. Analytical Engine – Software – Ada Aeigusta Lovelace (worlds first programmer) – Programming language Ada is name in her honor.

First Generation(1945 – 1955)– Programs and data located in same memory.

– Assembly language was used to write programs.

– Vacuum Tube Technology for performing basic processing.

– Mercury delay line memory was used.

– Type writers as I/O devices.

– ENIAC – 18000 Vacuum tubes – 1500 relays – 30 tones – 140 kilowatts of power – 20 registers - 10 digit decimal number.

– EDSAC – 1949 – Von new man – Genius – Stored program concept – Memory 4096 words – 40 bits/word – 0’s & 1’s.

History of Computer

• History of Computer

Main Memory

(Programs and data for execution)

Instruction

Data

Central Processing Unit

(CPU)Progra

m Control

Data Processin

g

Programs, data, operator

commands

Input-output equipment

Secondary memory,

keyboard, printer etc.

History of Computer

• Second Generation (1955 – 1965)

– Transistor replaced vacuum tubes.– Magnetic core memories and magnetic storage devices were more widely

used.– High level language such as FORTRAN was developed.– Compilers were developed.– Separate I/O processors were developed along with CPU.– IBM became major manufacturer.

E.g. PDP1 – 4k of 18 bit words – 5 microseconds – cycle time. IBM 7090 – fastest at that time – 2 micro seconds – cycle time.

History of Computer

• Third Generation ( 1965-1975)

– Many transistors on a single chip (IC) enabled lower cost , faster processors and memory elements.

– IC memories replaced magnetic core memories.– Introduction of micro-programming (flexibility) , parallelism , pipelining.– Pipeline – multiple instructions – are at varies stages of instructions of

instruction cycle - simultaneously in different sections of the processor.– Parallelism - multiple units operate simultaneously.– Effective time sharing in operating system.– Development of Cache & Virtual memory.

History of computer

• Fourth Generation (1975-1996)

– Still advancement in IC technology (VLSI) that is Very Large Scale Integration.

– Microprocessor concept - Motorola, Texas Instruments were the major companies.

– Parallelism, Pipelining , Cache , Virtual Memories evolved to produce high performance.

– Computing systems of today.

Video Monito

rSecondar

y Memory

Keyboard

Communicatio

n Networ

k

Video Control

Hard Disk

ControlKeyboar

d Control

Network Control

IO expansion

slots

IO Devices

IO (local) Bus

Peripheral (IO) interface control unit

CPU

Cache

Microprocessor

Main Memory

System Bus

Bus Interface

Unit

A Typical Computer System

Evolution of Computer : Summary

The types of Computers are determined based on size, speed and cost.

The First Generation computer had Vacuum Tubes. The Second Generation computers had Transistors. The Third Generation computers had Integrated Circuits. The Fourth Generation computers had VLSIs.

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 micro-controllers, 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

• ALGOL60 was developed by an International committee in year the1960

• Combined Programming Language was developed at CambridgeUniversity 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 variablesmain function - Starting and ending point of executionUser 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 4int main( ){ int n1,n2,n3,n4; float total, avg; printf(“\n Please input 4 integer numbers”); scanf(“%d%d%d%d”, &n1,&n2,&n3,&n4); total = (n1+n2+n3+n4); avg = total / SIZE; printf(“\nThe following data was input: %d %d %d %d ”, n1, n2, n3, n4); printf(“\n The mean of the data is = %10.2f”, 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 for formatted output.

The C Compilation ModelThe 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 CompilerThe C compiler translates source code (user written program) to assembly code (Machine understandable code). The source code is received from the preprocessor.

• AssemblerThe 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 EditorIf 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

Keywords have standard, predefined meanings in C. These keywords can be used only for their intended purpose; They cannot be used as programmer-defined identifiers.

Some of the keywords are :

auto extern sizeofbreak float static etc.

Identifier

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 : sum01 net_pay

Invalid identifiers: 25Mark 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 - used to declare variables for storing character (textual) data.int - used to declare variables that store integer values.Float - used to declare variables that store real ( floating point )

values. double - used to declare variables that store double precision values.

Derived Data Types

• Derived data typesDerived 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) = 2 bytessizeof(char) = 1 bytesizeof(long) = 4 bytessizeof(short) = 2 bytessizeof(float) = 4 bytessizeof(double) = 8 bytessizeof(long double) = 10 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 – signed

Declaring and Initializing variables

• Declaring a VariableTo declare a variable in C, do:

var_data_type list variables;Examples:

int i,j,k;float x,y,z;char ch;

• Initializing a VariableYou can initialize a variable when you declare it.int total_score = 0;

Expression

ExpressionsExpression 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

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 ExpressionAn 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 ExpressionAn 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

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:

• ( ) [ ] -> . (Association left->right)• ! -(unary minus) sizeof (type cast) ++  - - ( Association right->left)• * / % (Association left->right)• + - (Association left->right)• < <= >= > (Association left->right)• == != (Association left->right)• && (Association left->right)• || (Association left->right)• ?: (Association right->left)• = += -= (Association right->left)• , (comma) (Association right->left)

Assignment Statements

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 - stringe.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 cannotbe 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 100#define pi 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

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)statement1;elsestatement2;

• If the condition is true (nonzero), the first statement is executed, else the second statement is executed.

Form 3

if (expression)statement1;else if (expression)statement2;elsestatement3;

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:expression1 ? expression2: expression3

• It simply states:

if expression1 then expression2 else expression3

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;

Sample Program1 to illustrate nested if to find leap year.#include<stdio.h>main(){

int year;printf("Enter the year: ");scanf("%d", &year);if(year % 4 == 0)

if(year % 100 != 0)printf("%d is a leap year",year);

elseif(year % 400 == 0)

printf("%d is a leap year",year);else

printf("%d is not a leap year",year);else

printf("%d is not a leap year",year);return (0);

}

Sample program 2 Check a number for Armstrong (A number is Armstrong if it equals the sum of cubes of its digits)#include<stdio.h>main(){

int num, n, sum, r; clrscr();

printf("Enter a number for armstrong check\n\n");scanf("%d",&num);n = num;sum = 0;while(n != 0){

r = n % 10;sum += r * r * r;n = n / 10;

}if( sum == num)

printf("\n\n%d is an armstrong number\n",num);else

printf("\n\n%d is not an armstrong number\n",num);}

Sample program 3 to calculate commission #include<stdio.h>main()

{float commission, value;printf("Enter value of trade: ");scanf("%f",&value);

if (value < 2500.00)commission = 30.00 + 0.017 * value;

else if (value < 6250.00)commission = 56.00 + 0.0066 * value;

else if (value < 20000.00)commission = 76.00 + 0.0034 * value;

else if (value < 50000.00)commission = 100.00 + 0.0022 * value;

else if (value < 500000.00)commission = 155.00 + 0.0011 * value;

elsecommission = 255.00 + 0.0009 * value;

if ( commission < 39.00)commission = 39.00;

printf("commission: $%.2f\n",commission);return 0;

}

switch statement

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 item1: statement1; break;

case item2: statement2; 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++;

}

Sample program 4 Print number of days in a month #include<stdio.h>main(){

int month;clrscr();printf("Enter the month number 1 to 12\n");scanf("%d",&month);switch(month){case 1:case 3:case 5:case 7:case 8:case 10:case 12:/*This statement will be executed forall the above cases*/printf("\n31 days in month\n");break;

case 4:case 6:case 9:case 11:

/*This statement will be executed forall the above cases*/

printf("\n30 days in month\n");break;

case 2:printf("\n28 or 29 days in month\n");break;

default:printf("\nWrong Choice\n");break;

}}

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 (expression1; expression2; expression3)statement;

or {block of statements}

• expression1 initializes the counter variable; expression2 is the terminate test condition; expression3 is the modifier (which may be more than just simple increment);

for Statement

Example : for Statementmain(){ int x; for (x = 3; x > 0; x--) { printf("x=%d \n",x); } }

Output is x=3x=2x=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

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=%d\n",x); x--; }

}Output is

x=3x=2x=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:

dostatement;while (expression);

/* sin_series.c*/# include <stdio.h># include <math.h># define PI 3.14159void main(){int I,j,k;float fangle,fproduct,fsum,fradians;printf(“Enter the Angle :”);scanf(“%f”,&fangle);fradians =fangle*PI/180;fsum=fradians;for(i=3,k=1; i<=21; i+=2){fproduct=1;for(j=1; j<=i; j++)fproduct=fproduct*j;fsum=fsum+(pow(-1,k)*pow(fraduans,i))/fproduct;k+=1;}printf(“Sine Value of %5.2f=%8f\n”,fangle,fsum);}

/*Reverse.c*/# include <stdio.h># include <math.h>void main(){int n,d,s=0,t;clrscr();printf(“Enter a number : ”);scanf(%d”,&n);t=n;while(n!=0){d=n%10;s=(s*10)+d;n=n/10;}printf(“\n The Revers pf %d is %d”,t,s)getch();}

/*Determines the length of a message */#include<stdio.h>main(){char ch;int len=0;printf(“Enter a message : ”);ch=getchar();while (ch!=‘\n’) {len++;ch=getchar();}printf(“Your message was %d character(s) long. \n”, len);return 0;}

/*Determines the length of a message */#include <stdio.h>main(){int len=0;printf(“Enter a message : ”);while (getchar() != ‘\n’) len++;printf(“Your message was %d character(s) long. \n”, len);return 0;}

BREAK

for (d=2; d<n; d++) if (n%d==0) break;if (d<n) printf(“%d is divisible by %d \n”, n, d);else printf(“%d is prime\n”, n);

for (;;) { printf(“Enter a number (enter 0 to stop) : ”); scanf(“%d”, &n); if (n==0) break; printf(“%d cubed is %d\n”, n, n*n*n);}

while (. . . ) { switch (. . . ) { . . . break; . . . }}

CONTINUE

n=0;sum=0;while (n<10) { scanf(“%d”, &i); if (i==0) continue; sum += I; n++; /* continue jumps to here */)}

n=0;sum=0;while (n<10) { scanf(“%d”, &i); if (i==0) { sum += I; n++; }}

• Flowchart

statement

expressionfalse

Exit

True

Entry

do while Statement

Example:int x = 3;main( ){ do { printf("x=%d\n",x--); }while (x>0);

}Output is

x=3x=2x=1

• Examples• #include<stdio.h>• Main()• {• Int digit =0;• Do• Printf(“%d\n”,digit++);• While(digit<=9);• }

• Do• {• printf(“x=“);• Scanf(“%s,&x);• Sum+=x;• ++count;• } while(count<=n)• Average = sum/n;• Printf(“\n the average is %f \n”,average);• }

break and continue Statements

break and continue

• C provides two commands to control how we loop:

break - exit form loop or switch.continue - 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 Statementswhile (scanf( “%d”, &value ) = = 1 && value != 0)

{ if (value < 0) { printf(``Illegal value\n'');

break; /* Abandon the loop */

} if (value > 100) {

printf(``Invalid value\n''); continue;

/* Skip to start loop again */ }

/* Process the value read *//* guaranteed between 1 and 100 */....;....;} /* end while value != 0 */

Summary

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.

• Array declaration int A[5] where int – data type, A – array name, [5] – size of array.

• Array indices begin with ‘0’.

• 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[0] A[1] A[2] A[3] A[4]1 2 3 4 5

100 102 104 106 108

A

Array initialization : int A[5]=[100,102,104,106,108];

Size can be omitted if the no of initializations are know.

Accessing array elements: To access an array element, specify the array name followed by the

square brackets enclosing an integer called array index.

A[0] – access first element.A[1] – access second element.

Warning: “c” does not check the validity of subscript when you use arrays.

Main(){ int A[40]; A[50] = 11; A[50]++;}

No error message is generated but incorrect result is obtained.

• Name of the array:

Float lan[50];

Name of the array ‘lan’.

When used without subscript it refers to the first element of array.

• Array subscripts can be expressions too, which evaluate to a constant.

e.g. A[c+30];

“For “ loops used extensively for array processing

example 1: write a program to read an array and print.

#include<stdio.h>Void main(){ int I,a[10];For(i=0;i<10;i++) scanf(“%d”,&a[i]);For(i-0;i<10;i++)Printf(“\n %d”,a[i]);}

Example2: write a program to read integer number and copy it another array.

Void main(){Int I,a[10],b[10];For(i=0;i<10;i++) scanf(“%d”,&a[i]);/* copying into array b */For(i=0;i<10;i++) b[i]=a[i];For(i=0;i<10;i++)Printf(“%d %d \n”,a[i],b[i]);}

Example3: write a program to read 10 values and sum these 10 values and print.

Void main(){Int I,a[10],sum=0;/* reading */For(i=0;i<10;i++){ scanf(“%d”,&a[i]); sum=sum+a[i]; }Printf(“sum of the 10 values %d”,sum);}

Example4: write a program to read 10 values and store it in another array in reverse order.

Void main(){Int I,a[10],b[10];For(i=0;i<10;i++) scanf(“%d”,&a[i]);For(i=0;i<10;i++)B[i]=a[9-i];For(i=0;i<10;i++) printf(“\n a[%2d]=%2d b[%2d]= %2d”,i+1,a[i],i+1,b[i]);}

Two dimensional arrayExample : A class of 10 students scoring marks in 10 subjects.

Subjects Student sub1 sub2 sub3 ……… sub10S1S2S3..S10Int mark[10][10] The mark of s2 in sub1 can be represented as mark[2][1].‘C’ allows us to define such table items using two dimensional arrays.Horizontal line is called ‘row’ and vertical line is called ‘column’.

Matrix processing using arrays:A value in a matrix is represented using two subscripts Ai,j - refers to the value of ith row, jth columnExample: Write a program to add tw0 matrics.Void main(){Int I,j,a[10][10],b[10][10],c[10][10];Printf(“enter the values of the matrix A”);For(i=0;i<10;i++) for(j=0;j<10;j++) { scanf(“%d”,&a[i][j]); scanf(“%d”,&b[i][j]);}

For(i=0;i<10;i++) { for(j=0;j<10;j++) { c[i][j]=a[i][j]+b[i][j]; printf(“%d”,c[i][j]); }Printf(“\n”); }}

Example write a program to multiply two matrices.

#include<stdio.h>#include<conio.h>void main(){int m=0,n=0,o=0,p=0,i,j,k,a[10][10],b[10][10],c[10][10];clrscr();

printf("enter the size of a");scanf("%d%d",&m,&n);printf("enter the size of b");scanf("%d%d",&o,&p);printf("enter the elements of A");for(i=1;i<=m;i++){for(j=1;j<=n;j++){scanf("%d",&a[i][j]);}}printf("enter the elements of B");

for(i=1;i<=n;i++){for(j=1;j<=p;j++){scanf("%d",&b[i][j]);}}for(i=1;i<=n;i++){for(j=1;j<=p;j++){c[i][j]=0;for(k=1;k<=n;k++){c[i][j]+=a[i][k]*b[k][j];}}}

for(i=1;i<=n;i++){for(j=1;j<=p;j++){printf("%d\t",c[i][j]);}printf("\n");}getch();}

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 columnsint 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 ‘\0’ (NULL) is used to indicate the end of a string.

• String constant does not have an integer value ‘A’- A – 65 “A” = A \0 – no integer value.

• 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] = ‘\0’;return 0;

}

Declaring string:Generate form or syntax of declarationChar variable-name[size];Datatype identifier sizeof the identifier

Eg.Char acname[10],acbook[20];Acname ---array size is 10 , 9 characters and a null character.

Initializing string:Char acname [7] = “gandhi”;This is equivalent to Char acname[] = {‘g’,’a’,’n’,’d’,’h’,’i’,’\0’};

This first method \0 is automatically inserted where as in the second method user has to specify it.

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

The standard character string input functions are,

scanf(“%s”, string_name);gets(string);

• Ampersand (&) is not needed.• It is an error to use an ampersand.• The %s option uses a blank space as a delimiter,since it considers

character seperated by a blank space as two strings.• Gets() for reading string from user,it overcomes the disadvantage

of scanf().• Gets() can read any length of string with any number of blank

spaces and tabs. It terminates when an enter key is pressed.

The standard character string output functions are,

printf(“%s”,string);puts(string);

Strings

There are several standard routines that work on string variables.Some of the string manipulation functions are,

strcpy(string1, string2); - copy string2 into string1

strcat(string1, string2); - concatenate string2 onto the end of string1

strcmp(string1,string2); - 0 if string1 is equals to string2, < 0 if string1 is less than string2

>0 if string1 is greater than string2

strlen(string) - get the length of a string.

strrev(string) - reverse the string and result is stored in same string.

Using putchar and puts function:Char ch = ‘A’;Putchar(ch);The function putchar() prints one character

Putchar(ch); == printf(“%c”,ch);

Puts() prints the value of string variable str and then moves the cursor to the beginning of the next line on the screen.

String compare:

Strcmp(string1,string2);It returns’0’ if equal.It returns ’- ve’ value is string 1 is alphabetically above.It returns ‘+ve’ value if string2 is alphabetically below.

String copy :Strcpy(string1,string2)String2 gets copied into string1.String1 is overwritten.String1 should be large enough to receive string2.

Program to copy string2 to string1.

#include<stdio.h>#include<string.h>Void main(){Char str1[25],str2[25];Printf(“enter the string”);Gets(str2);Strcpy(str1,str2);Printf(“source string is %s”,str2);Printf(“copied string ios %s:,str1);}

Program to count length of string excluding null character.

#include<stdio.h>#include<string.h>

Void main(){Char acstr[25];Printf(“enter a string”);Gets(acstr);Printf(“the length of the string is %d”,strlen(scstr));}

Program to reverse a string.

#include<stdio.h>#include<string.h>

Void main(){Char acstr[29];Printf(“enter the string:”);Gets(acstr);Printf(“the reversed string is %s”,strrev(acstr);}

Program to convert into lower case

#include<stdio.h>#include<string.h>

Void main(){Char acstr[25];Printf(“enter the string”);Gets(acstr);Printf(“the case changed string is %s”,strlwr(acstr));• }

Program to sort a list of string alphabetically

#include<stdio.h>#include<string.h>Void main(){Int I,n=0;Char x[10][12];Printf(“enter a string on separate lines\n \n”);Printf(“type END when finished \n\n”);/* read in the list*/Do{Printf(“string %d:”,n+1);Scanf(“%s”,x[n]);}while (strcmp(x[n++],”END”);

?* adjust value of n */N--;/*reorder list of strings*/Reorder(n,x);/*display the reorder list of strings*/Printf(“\n\n reorder list of strings\n”);For(i=0;i<n;++i) Printf(“\n string %d :%s”,i+1,x{i]);}

Void reorder(int n,char x[][12]){Char temp[12];Int I,item;For(item=0;item<n-1;++item) For(i=item+1;i<n;i++) If(strcmp(x[item],x[i]>0) { Strcpy(temp,x[item]); Strcpy(x[item],x[i]); Strcpy(x[i],temp); } return; }

Program to compare two strings.

#include<stdio.h>#include<string.h>Void main(){Char acstr[25],accmp[25];Int inum;Printf(“enter a string :”);Gets(acstr);Printf(“enter the second string”);Gets(accmp);Inum=strcmp(acstr,accmp);If(inum == 0)Puts(“strings are equal”);Else if(inum>0) puts(“string %s greater than string %s”,acstr,accmp);Else puts(“string %s is greater than string %s”,accmp,acstr);}

Summary

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

Introduction to Pointers

Objective

After completing this presentation you will be able to

• Understand Pointers• Compare Pointers and Arrays• Understand Character Pointers• List the advantages and limitations of Pointers

Introduction to Pointers

• Every program and data occupies memory space.

• Every variable occupies one or more bytes. The address of the first byte is the address of the variable.

• Although address are represented by numbers their range of values may differ from that of integer.

• Hence they cannot be stored in ordinary integer variables and they need to be stored in special variable called pointer variable.

• In other words pointers is nothing more than an address and pointer variable is a just a variable that can store an address.

Declaring pointer variable

• int *p;• Same as any other declaration except for the ‘*’ .• This * indicates that p is a pointer variable capable of pointing to object

of type int.• Pointer variable can appear alongside other variable.

• Example: int I,j,a[10],*p,*q; float a,b,*r; char *w; There are no restrictions on what the referenced type may be.

Address & indirection operators• These are two operators designed specifically for use with pointers.• & - address operator to find the address of variable.• * - indirection operator helps to gain access to the object that the

pointer points to.• If p is ppinter then *p represents object to which ‘p’ is currently pointing.

Address operator:Like any other variable it is crucial to initialize a pointer variable before we

use it.

int I,*p; p= &I;

int I,*p = &I; is also valid.

Indirection operator

• One pointer variable is initialized( points to an object) we can use indirection operator to access what is stored in the object.

• int i = 10, *p = &I;• printf(“%d \n”, *p);

Eg j=*&i; same as j=i; p=&i; i=10; printf(“%d\n),i); printf(“%d\n”,*p); prints 10

*p = 20; printf(“%d\n”,i); printf(“%d\n”,*p); prints 20

Pointer assignment

• C allows the use of assignment operator to copy pointers provided they are of same type.

• Eg int i,j,*p,*q;• p=&i; q=p; both p and q points to the same variable.• *p=1; value can be assigned to i either *p or *q.• *q = 2; • p=&i; q=&j;• *p=2;• *q=*p;

Pointers as arguments

• A variable supplied as an argument in a function call is protected against change when ‘c’ passes arguments by value.

• If we need the function to be able to modify the variable we should pass by reference and this is accomplished using pointers.

• Eg decompose – A function which separates the integer and fractional part of a floating pointer number.

• Void decompose(float x, int * ,float *);• Main()• { -----; ------; decompose(3.14159, &i, &f); ----;}

• Void decompose(float x,int *int-part,float *float-part)• {• * int-part = (int) x;• * float-part = x - *int-part;• }Examples:

main() { int x = 7 ; int *px ; /* px is a pointer to an integer */ px = &x ; /* px gets the address of x */ printf( "%d\n" , x ) ; /* show the value of x */ printf( "%d\n" , &x ) ; /* show the address of x */ printf( "%d\n" , *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; let ptr = 1000 (location of i) ptr ++; 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 (i=0) => &a[0]a+i (i=1) => &a[1]a+i (i=2) => &a[2]a+i (i=3) => &a[3]a+i (i=4) => &a[4]

Finds the largest and smallest elements in an array.

• include<stdio.h>• define n 10• void max-min(int a[], int n, int *max, int *min);• main()• {• int b[n], i, big, small;• printf(“enter %d numbers”,n);• for(i=0;i<n;i++)• scanf(“%d”,&b[i];• max-min(b,n,&big,&small);• printf(“largest : %d \n”,big);• printf(“smallest:%d\n”,small);• return 0;• }

• Void max-min(int a[], int n, int * max, int *min)• {• int i;• * max = * min = a[0];• for(i=1;i<n;i++){• if(a[i] > *max)• * max = a[i];• Else if(a[i] < * min)• *min=a[i];• }• }

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 0th element

of the 2-D array• The expression *(my_array + 0) gives the base address of 0th 1-D

array• The expression *(*(my_array + 0) + 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 outputprintf(“character output = %c\n”, *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 ‘\0’ 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 arg1, type arg2, …..){

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 num1, num2, big; scanf(“%d%d”, &num1, &num2); big=find_big(num1,num2); 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

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 ValueCall 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) /* Function used to swap the values of variables c and d */ { int temp; temp = c; c = d; d = temp; }

Call by Reference

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

Passing arrays to functions

• Passing one dimensional array : Length of array is left unspecified.

• Eg int f ( int a[]) /* no length specified*/• {• }• Length is passed as an additional argument since function has no

way of knowing the size.

• int sum-array(int a[],int n)• {• int i,sum=0;• for(i=0;i<n;i++) • sum+=a[i];• Return sum;• }

• Protype:• int sum-array( int [], int );

• Call:• Main()• {• int b[len], total;• …. total = sum-array(b,len);• ….• }• A function has no way to check the actual size of array we can

exploit this fact by telling the function to process lesser no of elements in the array.

• B[100] – can hold 100.• Still by specifying n to be 50 it can add first 50 elements and ignore

the rest.

• Two dimensional array only first dimension can be omitted out second cannot be omitted.

• Int sum-array( int a[][len],int n)• {• int i,j,sum=0;• for(i=0;i<n;i++)• for(j=0;j<len;j++)• sum+=a[i][j];• return sum;• }• Here are observe than a two dimensional array cannot be passed

with an arbitrary number of column. This can be addressed using pointers.

Function Prototyping

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 writtenvoid swap(int *, int*);

• Usually prototypes appear at the beginning of a Program.

Storage Classes

Storage Classes

• Every variable in C possesses a characteristic called storage class. The Storage class defines two characteristics of a variable.

Its Life timeIts 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 ClassExample: Program illustrating auto variables

void main( ){ fun( ); fun( ); 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( ) : 21Calling Fun( ) : 21Calling Fun( ) : 21

Static Storage Class

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 variablesvoid main( ){ fun( ); fun( ); 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( ) : 21Calling Fun( ) : 22Calling Fun( ) : 23

Register Storage Class

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

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.cvoid compute( ){ extern int val; /*This implies that, the variable val is defined in another

file*/ val++; }

Recursion

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

Execution of the factorialn = fact(3);

• Step1: fact(3) - finds that 3 is not less than or equal to 1, so it calls fact(2).

• Step2: fact(2) – which finds that 2 is not less than or equal to 1, so it calls fact(1).

• Step3: fact(1) – which finds that 1 is less than or equal to 1, so it returns 1, causing

• fact(2) to return 2*1=2,causing• fact(3) to return 3*2=6.

Write a program to generate fibonacci series using recursive function.

#include<stdio.h>Void fibo(int,int,int);Void main(){Int i=-1,j=1,k=0;Printf(“\n enter the number of terms in the fibonacci series”);Scanf(“%d”,&k);Printf(“\n the fibonacci series is …\n”);Fibo(k,I,j);}

Void fibo(int k,int I,int j){If(k==0) exit(0);Printf(“%d”,i+j);Fibo(--k,j,i+j);}

Execution of the above program

k I j print 5 -1 1 0 4 1 0 1 3 0 1 1 2 1 1 2 1 1 2 3 0

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 argumentsvoid main( int argc, char* argv[])

{ int i; printf(“\n Total Number of Arguments = %d”,argc); for( i = 0; i < argc; i++)

printf(“\nArgument 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 beNumber of Arguments = 5Argument number 0 = testArgument number 1 = oneArgument number 2 = twoArgument number 3 = threeArgument number 4 = four

Functions and Arrays

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. Notewe 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

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 struct-name

{ type variable-name, variable-name,........;

type variable-name, variable-name,........; type variable-name, variable-name,........;

::

type variable-name, variable-name,........; }struct-variable, struct-variable...... ;

Structures

Example struct employee_type

{ int code; char name[20]; int dept_code; float salary; } emp1, emp2;

• 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 emp1 and emp2.

Structures

• By using the structure tag, other variables, function arguments can be declared as follows

struct struct-name var1, var2, .....;

• For example, we can define a variables of type employee_type as follows

struct employee_type emp1, emp2;

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 emp1, emp2 defined in

the above example , we can use the dot operator as follows emp1.code emp1.name emp1.dept_code emp1.salary emp2.code emp2.name emp2.dept_code emp2.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 stud1={1001,”Aldina”, 1, 90.78}, stud2={1002, “Raja”,

1,79.28};

Structures

Array of StructuresExample 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 0th structure, we can do it as follows,

stud[0].rollnum stud[0].name stud[0].semester stud[0].avg

Pointers and Structures

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.

StructuresExample 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 asptr = &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 salary;}emp1,emp2;

• In this example, if we want to access the year of joining of an employee of emp1, then we can do so by writing

emp1.doj.year

Unions

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

int var2; float var3; double var4;

}u_var;

Union of Structures

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 person {

struct employee_type e1; struct stud_type s1;

}ex;

Union of Structures

• In the above example, the union makes the structure variables e1 and s1 to share a common memory space.

• That is, the user can use either e1 or s1, but not both at the same time. The elements of this union of structures are accessed using dot operator as follows.

ex.e1.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 week1, week2;

• As with arrays first enumerated name has index value 0. So mon has value 0, tues 1, and so on. week1 and week2 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

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 stream-oriented 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 Purpose

r Open for reading, the file must already exist.w Open for writing. If the file exists, the content will be vanisheda Opening for append. Writing at the end of file. If the file does not exist, it will be createdr+ Open for both reading and writing. The file must exist alreadyw+ 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 createdrb Same as mode “r”, but for binary filewb 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 Writing\n”);

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 followsch =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 writethe string str into a file pointed by fptr.

• The syntax for reading a string from the file is as followsfgets(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( ) functionThe 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 Meaning fseek(fp, 0L, 0); Move the file pointer to the beginning. fseek(fp, 0L, 2); Move the file pointer to the end of file. fseek(fp, 10L, 0); Move after 10 bytes from the

beginning. fseek(fp, 10L, 1); Move after 10 bytes from the current

fseek(fp, -10L, 1); Move backward 10 bytes from the current

fseek(fp, -10L, 2); 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 followsftell(fptr);

• The following program fragment is used to find the size of a file name “test.dat”.fptr = fopen(“test.dat”,”r”);fseek(fptr, 0L, 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 followsrewind(fptr);

• This is equivalent to a fseek( ) function with the arguments fseek(fptr, 0L, 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).

• There are different forms of macro substitution. The most common forms are

• -- Simple macro substitutions.• -- Argumented macro substitution.• -- Nested macro substitution.

Simple macro substitution: # define COUNT 100 # define FALSE 0 # define Subjects 6 # define TEST if(x>y) # define AND # define PRINT printf (“very good”)

The preprocessor would translate this line to if(x>y) printf(“very good”);

• Macros with arguments:- Permit us to define more complex and more useful form of replacements #define identifier(f1,f2,…,fn) stringOccurrence of a macro with arguments is known as macro call. A simple

macro with arguments is #define CUBE(x) X*X*XIf the following statement appears in the program Volume = CUBE(side) then the preprocessor would expand this

statement to be Volume= (side * side* side);Consider the following statement Volume = CUBE(a+b); would be same

as Volume = (a+b *a+b * a+b); Which obviously produce incorrect result.

• Nesting of macros:-

We can also use one macro in the definition of another macro. That is they may be nested.

#define M 5#define N M+1#define square(x) (x * x)#define CUBE(x) (square(x) * (x))

Un defining macro:-A macro can be undefined using the statement #undef identifier Useful

when we want to restrict the definition only to appear in a particular part of the program.

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.

#if directive & #endif directive• #if directive syntax # if constant-expression#endif directive syntax #endifWhen the preprocessor encounters the #if directive, it evaluates the constant

expression. If the value of the expression is zero, the lines between #if and #endif will be removed from the program during preprocessing. Other wise those lines will be included in the program execution.

E.g. #define DEBUG 1Void main() {----#if DEBUGPrintf(“value of i=%d”,i);Printf(“value of j= %d”,j);#endif

The #ifdef and #ifndef directives

• The #ifdef directive tests whether an identifier is currently defined as a macro #ifdef identifier

#endif

#ifdef

Summary

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.

Congratulations!Congratulations!You have successfully You have successfully

completedcompleted

Problem Problem Solving & C Solving & C

ProgrammingProgramming

top related