B.Sc., COMPUTER SCIENCE PROGRAMING 1 YEAR MAJOR PAPER - 1 FIRST YEAR NON SEMESTER 2020-2021

July-2020 (New Print)

150 Programming in C

MAJOR PAPER I PROGRAMMING IN C

UNIT – I

Evolution and Applications of C - Structure of a C program – Data types – Declarations – operators – Expressions – Type conversions – Built-in functions.

UNIT – II

Data Input and Output – Control statements: IF, ELSE-IF, GOTO, SWITCH, WHILE-DO, DO-WHILE, FOR, BREAK and CONTINUE.

UNIT – III

Functions: Defining and Accessing Arguments – recursive functions – storage classes – Arrays: Defining and processing Arrays – Multidimensional arrays – passing arrays to functions – Arrays and strings – String functions – String Manipulation.

UNIT – IV

Pointers – Pointer Declarations – Operations on pointers – pointers to functions – Pointer and strings – pointers and arrays – array of pointers – structures – structures and pointers – unions.

UNIT – V

Data files – Opening, closing and processing files – files with structures and unions – register variables – Bitwise Operations – Macros – Preprocessing.

Text Book:

“Programming in C” – E.Balagurusamy – Tata McGraw Hill Publications.

Books for Reference:

1. “Programming with C” – Byron S.Gottfried – Schaum’s outline series – Tata McGraw Hill Publications. 2. “The Sprit of C” – Mullish cooper – Schaum’s Outline Series – Tata McGraw Hill Publications. 3. “A first course in Programming with C” – T.Jeyapoovan, Vikas Publishing Hous Pvt. Ltd., New Delhi.

Programming in C

Table of Contents C PROGRAMMING LANGUAGE ...... 1 UNIT I ...... 1 1.1 EVOLUTION OF C ...... 1 1.1.1 Origin of C ...... 1 1.1.2 HISTORY OF C ...... 3 1.1.3 IMPORTANCE OF C ...... 4 1.2 APPLICATIONS OF C LANGUAGE ...... 5 1.2.1 USES ...... 5 1.2.2ADVANTAGES ...... 5 1.2.3 Facts about C ...... 6 1.2.4 Why to use C? ...... 6 1.3 STRUCTURE OF THE C PROGRAM ...... 7 1.3.1Programming Style ...... 8 1.3.2 Good Program Style: ...... 9 1.3.3Data types in C Language ...... 9 1.3.4 Modifiers ...... 11 1.3.5Qualifiers ...... 12 1.4 What are Arrays: ...... 13 1.4.1 Array Initialization ...... 14 1.5 Keywords: ...... 16 1.6 What is Operator? ...... 17 1.6.1 Arithmetic Operators: ...... 17 1.6.2 Logical (or Relational) Operators: ...... 18 1.6.3 Bitwise Operators: ...... 19 1.6.4 Assignment Operators: ...... 20 1.6.5 Misc Operators ...... 21 1.7 Constants: ...... 23 1.7.1 Defining Constants ...... 23 1.8 The enum ...... 24 1.9 Expressions : ...... 25 1.9.1 Evaluation of Expressions ...... 26 1.9.2 Rules for evaluation of expression ...... 27 1.10 Type conversions in expressions ...... 27 1.10.1 Implicit type conversion ...... 27

Programming in C

1.10.2 Explicit Conversion ...... 28 1.11 BUILT IN FUNCTIONS ...... 30 UNIT II ...... 33 2.1 MANAGING INPUT AND OUTPUT OPERATIONS ...... 33 2.1.1 UNFORMATTED I/O FUNCTIONS ...... 34 TO READ AND WRITE SINGLE CHARACTER ...... 34 getchar() ...... 34 2.1.2 FORMATTED I/O FUNCTIONS FORMATTED INPUT ...... 35 2.2 DECISION MAKING AND BRANCHING STATEMENT ...... 36 2.2.1 IF STATEMENT ...... 36 2.2.2 If …… else...... 37 2.2.3 Nested if ...... 38 2.2.4 else … if ladder ...... 39 2.3 SWITCH STATEMENT...... 41 2.4 GOTO STATEMENT ...... 43 2.5 LOOP STATEMENTS ...... 43 2.5.1 LOOP PROCESSING: ...... 44 2.5.2 TYPES OF LOOP ...... 44 Rules ...... 45 2.6 Jump Statements ...... 51 2.7 The Statement ...... 51 2.8 The continue Statement ...... 51 2.9 The break Statement...... 51 2.10 The return Statement ...... 52 Unit III ...... 52 3.1 Functions ...... 52 3.1.1 Built-in Functions ...... 53 3.1.2 Recursive Functions ...... 58 3.3 STORAGE CLASSES ...... 60 3.3.1 Automatic Storage class: ...... 61 3.3.2 Register storage class ...... 62 3.3.3 Static Storage class ...... 63 3.3.4 External Storage class ...... 64 3.4 ARRAY ...... 65 3.4.1 NEED FOR AN ARRAY: ...... 65

Programming in C

3.4.2 ONE DIMENSIONAL ARRAY ...... 66 3.4.3 TWO DIMENSIONAL ARRY ...... 67 3.5 String I/O in C programming ...... 69 3.5.1 C String-IO ...... 69 UNIT IV ...... 77 4.1 Pointers: ...... 77 4.1.1 Address in C ...... 77 4.1.2 CREATING A POINTER FOR THE STRING ...... 78 4.1.3 Array of strings ...... 81 4.2 Pointers and Arrays ...... 83 4.2.1 Pointer Arithmetic:...... 83 4.2.2 Using Pointer Arithmetic With Arrays: ...... 84 4.2.3 Passing Pointer to a Function ...... 85 4.3 DEFINING AND PROCESSING A STRUCTURE ...... 86 4.3.1 C Programming Structure ...... 86 4.3.2 Structure and Pointer ...... 89 4.3.3 Structure and Function ...... 90 4.4 UNION ...... 93 4.4.1 Defining a Union ...... 93 4.5 BIT FIELDS ...... 95 4.6 Enumeration ...... 97 UNIT V ...... 98 5.1 FILES ...... 98 5.1.1 Opening a file ...... 98 5.1.2 Closing a File ...... 99 5.1.3 Reading from file ...... 100 5.2 COMMAND LINE PARAMETERS ...... 100 5.3 Register Variables: ...... 102 5.4 BITWISE OPERATIONS ...... 103 5.5 MACROS ...... 107 5.5.1 Defining Macros through command line ...... 108 5.6 Introduction to Preprocessor ...... 111

Programming in C

PROGRAMMING IN C

UNIT I

1.1 EVOLUTION OF C 1.1.1 Origin of C

The C Programming Language was initially developed by Denis Ritchie using a system in 1972. This was varied and modified until a standard was defined by Brian Kernighan and Dennis Ritchie in 1978 in "The C Programming Language".

By the early 80's many versions of C were available which were inconsistent with each other in many aspects. This led to a standard being defined by ANSI in 1983. It is this standard this set of notes primarily addresses.

Martin Richard – BCPL (Basic Combined Programming Language)

Ken Thomson – B

Dennis Ritche – C ( Bell Laboratory – 1970s)

Martin Richards developed a high-level computer language called BCPL in the year 1967. The intention was to develop a language for writing an (OS). As you know an OS is software which controls the various processes in a computer system. This language was later improved by Ken Thompson and he gave it a new name B. The basic ideas about some topics such as arrays, etc., which were later inherited by C were developed in BCPL and B. In those days, the development of computers was in infancy. One of the serious constraints experienced while developing the language B was the small computer memory available at that time.

1

Programming in C

C is a general-purpose programming language which features economy of expression, modern control flow and data structures, and a rich set of operators. C is not a "very high level" language, nor a "big" one, and is not specialized to any particular area of application. But its absence of restrictions and its generality it more convenient and effective for many tasks than supposedly more powerful languages. The history of C programming language is quite interesting. C was originally designed for and implemented on the UNIX operating system on the DEC PDP-ll, by Dennis Ritchie. C is the result of a development process that started with an older language called BCPL. BCPL was developed by Martin Richards, and it influenced a language called B, which was invented by Ken Thompson. B led to the development of C in the 1970s

For many years, the de facto standard for C was the version supplied with the UNIX operating system. In the summer of 1983 a committee was established to create an ANSI (American National Standards Institute) standard that would define the C language. The standardization process took six years (much longer than anyone reasonably expected).

The ANSI C standard was finally adopted in December 1989, with the first copies becoming available in early 1990. The standard was also adopted by ISO (International Standards Organization), and the resulting standard was typically referred to as ANSI/ISO Standard C. In 1995, Amendment 1 to the C standard was adopted, which, among other things, added several new functions. The 1989 standard for C, along with Amendment 1, became a base document for Standard C++, defining the C subset of C++. The version of C defined by the 1989 standard is commonly referred to as C89.

C89 is the version of C in widest use, it is currently accepted by all C , and it forms the basis for C++.

During the 1990s, a new standard for C was being developed. It was the 1999 standard for C, usually referred to as C99. In general, C99 retained nearly all of the features of C89. The C99 standardization committee focused on two main areas: the addition of several numeric libraries and the development of some special-use, but highly innovative, new features, such as variable-length arrays and the restrictpointer qualifier. These innovations have once again put C at the forefront of computer language development. The C programming language is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. The UNIX operating system, the C , and essentially all UNIX applications programs have been written in C.

1.1.2 HISTORY OF C Over time, C began to be used in personal computers for developing software applications and other purposes

The first change (even if only a little) came when the American National Standards Institute (ANSI) formed a committee in 1983 to standardize C. After a review of the language, they modified it a little so that it was also compatible with other programs that preceded C. So the new ANSI standard came into being in 1989, and is known as ANSI C or C89. The International Organization for Standardization (ISO) has also contributed to the standardization of C.

2

Programming in C

Over time, C has evolved as it has added some significant features like memory management, functions, classes and libraries to its rich feature set. C is being used in some of the biggest and most prominent projects and products in the world. C has also influenced the development of numerous languages such as AMPL, AWK, csh, C++, C--,C#, Objective-C, Bit C, D, Go, Java, JavaScript, Julia, Limbo, LPC, Perl, PHP, Pike, Processing, Python, Rust, Seed7, Vala and Verilog. All of the applications of C are too numerous to be listed here, but some others include:

x Development of compilers, and spreadsheets x Computer and mobile games x Updating the UNIX kernel x Evaluating mathematical equations x Designing network devices

1.1.3 IMPORTANCE OF C

¾ C is a system Programming Language ¾ System programs can be created using C because it supports both the assembly language and high level language programming. Hence it is also called as middle level language. The unix operating system and C compiler are designed using C. 3

Programming in C

¾ C is application programming language ¾ Any application programs related to business and science can be created using C ¾ It is highly portable ¾ The software designed using C language is adaptable to different types of computer machine ¾ It is easy to code. ¾ C has a rich set of operators and built – in functions. Hence writing program code is easy ¾ C is a structured language. The code and data can be compartmentalized.

1.2 APPLICATIONS OF C LANGUAGE 1.2.1 USES ¾ C language is used for creating computer applications o Used in writing Embedded software ¾ Firmware for various electronics, industrial and communications products which use micro- controllers. ¾ It is also used in developing verification software, test code, simulators etc. for various applications and hardware products. ¾ For Creating Compiler of different Languages which can take input from other language and convert it into lower level machine dependent language. ¾ C is used to implement different Operating System Operations. UNIX kernel is completely developed in C Language. ¾ C is a system Programming Language ¾ System programs can be created using C because it supports both the assembly language and high level language programming. Hence it is also called as middle level language. The unix operating system and C compiler are designed using C. ¾ C is application programming language ¾ Any application programs related to business and science can be created using C ¾ It is highly portable ¾ The software designed using C language is adaptable to different types of computer machine ¾ It is easy to code ¾ C has a rich set of operators and built – in functions. Hence writing program code is easy ¾ C is a structured language ¾ The code and data can be compartmentalized.

1.2.2ADVANTAGES

C have the following advantages: Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. ¾ C is a general-purpose programming language. ¾ C is a high-level language that has the advantages of readability, maintainability, and portability. ¾ C is a very efficient language that allows you to control computer hardware and 4

Programming in C

peripherals. ¾ C is a small language that you can easily learn in a relatively short time. ¾ Programs written in C can be reused. ¾ Programs written in C must be compiled and translated into machine-readable code before the computer can execute them. • Many other programming languages, such as Perl, C++, and Java, have adopted basic concepts and useful features from the C language. Once we learn C, learning these other languages is much easier. • The ANSI standard for C is the standard supported by C

The C has now become a widely used professional language for various reasons. Easy to learn x Structured language x It produces efficient programs. x It can handle low-level activities. x It can be compiled on a variety of computer platforms.

1.2.3 Facts about C

C was invented to write an operating system called UNIX. x C is a successor of B language, which was introduced around 1970. x The language was formalized in 1988 by the American National Standard Institute. x (ANSI). The UNIX OS was totally written in C by 1973. Today, C is the most widely used and popular System Programming Language .x Most of the state-of-the-art software have been implemented using C .x Today's most ][popular OS and RBDMS MySQL have been written in C.

1.2.4 Why to use C?

C was initially used for system development work, in particular the programs that make up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: ¾ Operating Systems ¾ Language Compilers ¾ Assemblers ¾ Text Editors ¾ Print Spoolers ¾ Network Drivers ¾ Modern Programs ¾ Databases ¾ Language InterpreterS ¾ Utilities

5

Programming in C

1.3 STRUCTURE OF THE C PROGRAM

Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author and other details.

Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include directive.

Definition section: The definition section defines all symbolic constants such using the #define directive.

Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. main () function section: Every C program must have one main function section. This section contains two parts; declaration part and executable part

Declaration part: The declaration part declares all the variables used in the executable part.

Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the 6

Programming in C closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon.

Subprogram section: If the program is a multi-function program then the subprogram section contains all the user-defined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order.

1.3.1Programming Style ¾ Clarity

x The program should be clearly written.

x It should be easy to follow the program logic.

¾ Meaningful variable names

x Make variable/constant names meaningful to enhance program clarity.

x ‘area’ instead of ‘a’

x ‘radius’ instead of ‘r’

¾ Program documentation

x Insert comments in the program to make it easy to understand.

x Never use too many comments.

¾ Program indentation

x Use proper indentation.

x Structure of the program should be immediately visible. 1.3.2 Good Program Style: #include

/* FIND THE LARGEST OF THREE NUMBERS */ main() 7

Programming in C

{

int a, b, c;

scanf(“%d%d%d”, &a, &b, &c);

if ((a>b) && (a>c))

printf(“\n Largest is %d”, a);

else

if (b>c)

printf(“\n Largest is %d”, b);

else

printf(“\n Largest is %d”, c);

} 1.3.3Data types in C Language

Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we can use in our program. These data types have different storage capacities.

C language supports 2 different type of data types:

Primary data types: These are fundamental data types in C namely integer(int), floating point(float), character(char) and void.

Derived data types: Derived data types are nothing but primary data types but a little twisted or grouped together like array, structure, union and pointer.

Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can hold only integer values. Every variable which is used in the program must be declared as what data-type it is.

Primary data types in c

Integer type Integers are used to store whole numbers.

Size and range of Integer type on 16-bit machine:

8

Programming in C

Type Size(bytes) Range int or signed int 2 -32,768 to 32767 unsigned int 2 0 to 65535 short int or signed short int 1 -128 to 127 unsigned short int 1 0 to 255 long int or signed long int 4 -2,147,483,648 to 2,147,483,647 unsigned long int 4 0 to 4,294,967,295

Floating point type Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine Type Size(bytes) Range Float 4 3.4E-38 to 3.4E+38 double 8 1.7E-308 to 1.7E+308 long double 10 3.4E-4932 to 1.1E+4932

Character type Character types are used to store characters value.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range char or signed char 1 -128 to 127 unsigned char 1 0 to 255 int - data type int is used to define integer numbers.

{ int Count; Count = 5; } float - data type float is used to define floating point numbers.

{

float Miles;

Miles = 5.6;

9

Programming in C

} double - data type double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.

{ double Atoms; Atoms = 2500000; } char - data type char defines characters.

{ char Letter; Letter = 'x'; } 1.3.4 Modifiers

The data types explained above have the following modifiers.

x short x long x signed x unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:

short int <= int <= long int float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:

Type Bytes Range ------short int 2 -32,768 -> +32,767 (32kb) unsigned short int 2 0 -> +65,535 (64Kb) unsigned int 4 0 -> +4,294,967,295 ( 4Gb) int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 -128 -> +127 unsigned char 1 0 -> +255 float 4 double 8 long double 12

10

Programming in C

These figures only apply to today’s generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.

You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session.

Here is an example to check size of memory taken by various datatypes.

Int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); printf("sizeof(long long) == %d\n", sizeof(long long));

return 0; }

1.3.5Qualifiers

A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:

x The value of a variable can be changed. x The value of a variable must always be read from memory rather than from a register

Standard C language recognizes the following two qualifiers:

x const x volatile

The const qualifier is used to tell C that the variable value can not change after initialization. const float pi=3.14159;

Now pi cannot be changed at a later time within the program.

Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage

The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.

1.4 What are Arrays:

11

Programming in C

We have seen all basic data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration. int x[10];

The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:

Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index.

Arrays occupy consecutive memory slots in the computer's memory. x[0], x[1], x[2], ..., x[9]

If an array has n elements, the largest subscript is n-1.

Multiple-dimension arrays are provided. The declaration and use look like:

int name[10] [20]; n = name[i+j] [1] + name[k] [2];

Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns.

Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'.

Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).

main( ) { int n, c; char line[100]; n = 0; while( (c=getchar( )) != '\n' ) { if( n < 100 ) line[n] = c; n++; } printf("length = %d\n", n); } 1.4.1 Array Initialization

x As with other declarations, array declarations can include an optional initialization x Scalar variables are initialized with a single value x Arrays are initialized with a list of values

12

Programming in C

x The list is enclosed in curly braces int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};

The number of initializes cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializes by leaving the square brackets empty so these are identical declarations: int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};

An array of characters ie string can be initialized as follows: char string[10] = "Hello";

A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types

x Local Variables x Global Variables

Local Variables

x Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. x When a local variable is defined - it is not initialized by the system, you must initialize it yourself. x When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output

main() { int i=4; int j=10;

i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); }

if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; 13

Programming in C

printf("i is %d\n",i); }/* 'i' (value 100) dies here */

printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ }

This will generate following output i is 5 i is 100 i is 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;

You will see -- operator also which is called decrement operator and it decrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initialized automatically by the system when you define them!

Data Type Initialser

int 0

char '\0'

float 0

pointer NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

int i=4; /* Global definition */

main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); }

func() { int i=10; /* Local definition */

14

Programming in C

i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); }

This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and any reference to i will be to the global.

1.5 Keywords:

The following names are reserved by the C language. Their meaning is already defined, and they cannot be re-defined to mean anything else.

Auto Else long switch Break Enum register Case Extern return union Char Float short unsigned Const For signed void Continue goto sizeof volatile Default if static while Do int struct _Packed Double

While naming your functions and variables, other than these names, you can choose any names of reasonable length for variables, functions etc.

1.6 What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.

x Arithmetic Operators x Logical (or Relational) Operators x Bitwise Operators x Assignment Operators x Misc Operators

Lets have a look on all operators one by one.

1.6.1 Arithmetic Operators:

There are following arithmetic operators supported by C language:

15

Programming in C

Assume variable A holds 10 and variable B holds 20 then:

Show Examples

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by enumerator B / A will give 2

Modulus Operator and remainder of after an % B % A will give 0 integer division

Increment operator, increases integer value by ++ A++ will give 11 one

Decrement operator, decreases integer value by -- A-- will give 9 one

1.6.2 Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

Checks if the value of two operands is equal or == (A == B) is not true. not, if yes then condition becomes true.

Checks if the value of two operands is equal or != not, if values are not equal then condition (A != B) is true. becomes true.

Checks if the value of left operand is greater > than the value of right operand, if yes then (A > B) is not true. condition becomes true.

16

Programming in C

Checks if the value of left operand is less than < the value of right operand, if yes then condition (A < B) is true. becomes true.

Checks if the value of left operand is greater >= than or equal to the value of right operand, if (A >= B) is not true. yes then condition becomes true.

Checks if the value of left operand is less than <= or equal to the value of right operand, if yes (A <= B) is true. then condition becomes true.

Called Logical AND operator. If both the && operands are non zero then then condition (A && B) is true. becomes true.

Called Logical OR Operator. If any of the two || operands is non zero then then condition (A || B) is true. becomes true.

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is ! !(A && B) is false. true then Logical NOT operator will make false.

1.6.3 Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

17

Programming in C

There are following Bitwise operators supported by C language

Operator Description Example

Binary AND Operator copies a bit to the result & (A & B) will give 12 which is 0000 1100 if it exists in both operands.

Binary OR Operator copies a bit if it exists in | (A | B) will give 61 which is 0011 1101 either operand.

Binary XOR Operator copies the bit if it is set ^ (A ^ B) will give 49 which is 0011 0001 in one operand but not both.

Binary Ones Complement Operator is unary ~ (~A ) will give -60 which is 1100 0011 and has the effect of 'flipping' bits.

Binary Left Shift Operator. The left operands << value is moved left by the number of bits A << 2 will give 240 which is 1111 0000 specified by the right operand.

Binary Right Shift Operator. The left operands >> value is moved right by the number of bits A >> 2 will give 15 which is 0000 1111 specified by the right operand.

1.6.4 Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example

Simple assignment operator, Assigns = values from right side operands to left C = A + B will assign value of A + B into C side operand

Add AND assignment operator, It adds += right operand to the left operand and C += A is equivalent to C = C + A assign the result to left operand

Subtract AND assignment operator, It -= subtracts right operand from the left C -= A is equivalent to C = C - A operand and assign the result to left

18

Programming in C

operand

Multiply AND assignment operator, It multiplies right operand with the left *= C *= A is equivalent to C = C * A operand and assign the result to left operand

Divide AND assignment operator, It divides left operand with the right /= C /= A is equivalent to C = C / A operand and assign the result to left operand

Modulus AND assignment operator, It %= takes modulus using two operands and C %= A is equivalent to C = C % A assign the result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

bitwise exclusive OR and assignment ^= C ^= 2 is same as C = C ^ 2 operator

bitwise inclusive OR and assignment |= C |= 2 is same as C = C | 2 operator

Short Notes on L-VALUE and R-VALUE: x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

1.6.5 Misc Operators

There are few other operators supported by C Language.

Operator Description Example

19

Programming in C sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.

& Returns the address of an variable. &a; will give actaul address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

If Condition is true ? Then value X : Otherwise ? : Conditional Expression value Y

Operators Categories:

All the operators we have discussed above can be categorized into following categories:

x Postfix operators, which follow a single operand. x Unary prefix operators, which precede a single operand. x Binary operators, which take two operands and perform a variety of arithmetic and logical operations. x The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression. x Assignment operators, which assign a value to a variable. x The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associatively

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type) * & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

20

Programming in C

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

1.7 Constants:

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.

x Octal constants are written with a leading zero - 015. x Hexadecimal constants are written with a leading 0x - 0x1ae. x Long constants are written with a trailing L - 890L.

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows. '\n' newline '\t' tab '\\' backslash '\'' single quote '\0' null ( Used automatically to terminate character string )

In addition, a required bit pattern can be specified using its octal equivalent.

'\044' produces bit pattern 00100100.

21

Programming in C

Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.

A character is a different type to a single character string. This is important point to note.

1.7.1 Defining Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed.

The const keyword is to declare a constant, as shown below: int const a = 1; const int a =2;

Note:

x You can declare the const before or after the type. Choose one an stick to it. x It is usual to initialize a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.

#define TRUE 1 #define FALSE 0 #define NAME_SIZE 20

Here TRUE, FALSE and NAME_SIZE are constant

You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter.

The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completeness of this section it is is included here: void strcpy(char *buffer, char const *string) 1.8 The enum Data type enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example: enum colors {RED, YELLOW, GREEN, BLUE};

I've made the constant names uppercase, but you can name them which ever way you want.

Here, colors is the name given to the set of constants - the name is optional. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of

22

Programming in C the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3.

But you can assign values if you wanted to: enum colors {RED=1, YELLOW, GREEN=6, BLUE };

Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.

The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards.

You can name your constants in a weird order if you really wanted...

#include int main() { enum {RED=5, YELLOW, GREEN=4, BLUE};

printf("RED = %d\n", RED); printf("YELLOW = %d\n", YELLOW); printf("GREEN = %d\n", GREEN); printf("BLUE = %d\n", BLUE); return 0; } This will produce following results RED = 5 YELLOW = 6 GREEN = 4 BLUE = 5

1.9 Expressions :

x Expressions is a sequence of operators and operands that specifies computation of a value. An expressions may consist of single entity or some combination of such entities interconnected by one or more operators.

x All expression represents a logical connection that’s either true or false.

x Thus logical type expression actually represents numerical quantities.

In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. Some examples of expression are shown in the table given below. 23

Programming in C

A+b

3.14*r*r a*a+2*a*b+b*b

Algebraic Expression C Expression

a x b – c a * b – c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a * b / c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x / y + c

1.9.1 Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form Variable = expression; Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example of evaluation statements are x = a * b – c y = b / c * a z = a – b / c + d The following program illustrates the effect of presence of parenthesis in expressions. main () { float a, b, c x, y, z; a = 9; b = 12; c = 3; x = a – b / 3 + c * 2 – 1; y = a – b / (3 + c) * (2 – 1); z = a – ( b / (3 + c) * 2) – 1; printf ("x = %f",x); printf ("y = %f",y);

24

Programming in C

printf ("z = %f",z);

} output x = 10.00 y = 7.00 z = 4.00 Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / % Low priority + -

1.9.2 Rules for evaluation of expression

•First parenthesized sub expression left to right are evaluated. • If parenthesis are nested, the evaluation begins with the innermost sub expression. • The precedence rule is applied in determining the order of application of operators in evaluating sub expressions. • The associability rule is applied when two or more operators of the same precedence level appear in the sub expression. • Arithmetic expressions are evaluated from left to right using the rules of precedence. • When Parenthesis are used, the expressions within parenthesis assume highest priority. 1.10 Type conversions in expressions 1.10.1 Implicit type conversion C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic type conversion is know as implicit type conversion During evaluation it adheres to very strict rules and type conversion. If the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type. The following rules apply during evaluating expressions All short and char are automatically converted to int then 1. If one operand is long double, the other will be converted to long double and result will be long double. 2. If one operand is double, the other will be converted to double and result will be double. 3. If one operand is float, the other will be converted to float and result will be float. 4. If one of the operand is unsigned long int, the other will be converted into unsigned long int and result 25

Programming in C will be unsigned long int. 5. If one operand is long int and other is unsigned int then a. If unsigned int can be converted to long int, then unsigned int operand will be converted as such and the result will be long int...... b. Else Both operands will be converted to unsigned long int and the result will be unsigned long int. 6. If one of the operand is long int, the other will be converted to long int and the result will be long int. 7. If one operand is unsigned int the other will be converted to unsigned int and the result will be unsigned int. 1.10.2 Explicit Conversion Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion. Consider for example the calculation of number of female and male students in a class female_students Ratio = ------male_students Since if female_students and male_students are declared as integers, the decimal part will be rounded off and its ratio will represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below. Ratio = (float) female_students / male_students The operator float converts the female_students to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the fractional part of the result. The process of such a local conversion is known as explicit conversion or casting a value. The general form is (type_name) expression Operator precedence and associatively

Each operator in C has a precedence associated with it. The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these levels. The operators of higher precedence are evaluated first. The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as associatively property of an operator. The table given below gives the precedence of each operator.

Order Category Operator Operation Associativity

1 Highest precedence ( ) Function call L ? R [ ] Left to Right ? : : .

26

Programming in C

2 Unary ! Logical (NOT) R ? L ~ Bitwise 1’s complement Right -> Left + Unary plus - Unary minus ++ Pre or post increment - - Pre or post decrement & Address * Indirection Size of Size of operant in bytes

3 Member Access .* Dereference L ? R ?* Dereference

4 Multiplication * Multiply L ? R / Divide % Modulus

5 Additive + Binary Plus L ? R - Binary Minus

6 Shift << Shift Left L ? R >> Shift Right

7 Relational < Less than L ? R <= Less than or equal to > Greater than >= Greater than or equal to

8 Equality == Equal to L ? R != Not Equal to

9 Bitwise AAND & Bitwise AND L ? R

10 Bitwise XOR ^ Bitwise XOR L ? R

11 Bitwise OR | Bitwise OR L ? R

12 Logical AND && Logical AND L ? R

14 Conditional ? : Ternary Operator R ? L

27

Programming in C

15 Assignment = Assignment R ? L *= Assign product %= Assign reminder /= Assign quotient += Assign sum -= Assign difference &= Assign bitwise AND ^= Assign bitwise XOR |= Assign bitwise OR <<= Assign left shift >>= Assign right shift

16 Comma , Evaluate L ? R

1.11 BUILT IN FUNCTIONS: There are several different types of functions in C. So far, we have used one type of function – the built-in C functions, like printf( ) and scanf( ). These functions are part of the C programming language.

Another type is called a user-defined function. This is a function which the programmer creates and uses in a C program. We will learn how to create these functions in this part of the tutorial.

We can also distinguish between functions which return values and those which don’t — like void main( ). Technically speaking, all functions return values, but in C we can choose to eliminate this process by using void. So far, we have not used our main( ) function to return any values, so we voided it and let the body functions, like printf( ) return values.

A function which return values produces some result — like printing text on the screen, or scanning a variable, etc. Let’s examine the different types of functions, so we can understand them better.

Built-in Functions

C has many built-in functions that you can use in your programs. So far we have learned 15 built-in functions: main( ) printf( ) scanf( ) gets( ) puts( ) strcpy( )

28

Programming in C strlen( ) strcmp( ) stricmp( ) strcat( ) strstr( ) isalpha( ) isdigit( ) isupper( ) islower( )

If you can’t remember how to use each of these functions, go back and review the previous sections of this tutorial.

User-Defined Functions

If you have a special set of instructions that aren’t in a built-in function, you can create a user-defined function.

C - Built-in Library Functions String Manipulation Functions

x char *strcpy (char *dest, char *src); Copy src string into dest string. x char *strncpy(char *string1, char *string2, int n); Copy first n characters of string2 to stringl . x int strcmp(char *string1, char *string2); Compare string1 and string2 to determine alphabetic order. x int strncmp(char *string1, char *string2, int n); Compare first n characters of two strings. x int strlen(char *string); Determine the length of a string. x char *strcat(char *dest, const char *src); Concatenate string src to the string dest. x char *strncat(char *dest, const char *src, int n); Concatenate n chracters from string src to the string dest. x char *strchr(char *string, int c); Find first occurrence of character c in string. x char *strrchr(char *string, int c); Find last occurrence of character c in string. x char *strstr(char *string2, char string*1); Find first occurrence of string string1 in string2. x char *strtok(char *s, const char *delim) ; Parse the string s into tokens using delim as delimiter.

29

Programming in C

Memory Management Functions

x void *calloc(int num elems, int elem_size); Allocate an array and initialise all elements to zero . x void free(void *mem address); Free a block of memory. x void *malloc(int num bytes); Allocate a block of memory. x void *realloc(void *mem address, int newsize); Reallocate (adjust size) a block of memory.

Buffer Manipulation

x void* memcpy(void* s, const void* ct, int n); Copies n characters from ct to s and returns s. s may be corrupted if objects overlap. x int memcmp(const void* cs, const void* ct, int n); Compares at most (the first) n characters of cs and ct, returning negative value if csct. x void* memchr(const void* cs, int c, int n); Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found. x void* memset(void* s, int c, int n); Replaces each of the first n characters of s by c and returns s. x void* memmove(void* s, const void* ct, int n); Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.

Character Functions

x int isalnum(int c); The function returns nonzero if c is alphanumeric x int isalpha(int c); The function returns nonzero if c is alphabetic only x int iscntrl(int c); The function returns nonzero if c is a control character x int isdigit(int c); The function returns nonzero if c is a numeric digit x int isgraph(int c); The function returns nonzero if c is any character for which either isalnum or ispunct returns nonzero. x int islower(int c); The function returns nonzero if c is a lower case character. x int isprint(int c); The function returns nonzero if c is space or a character for which isgraph returns nonzero. x int ispunct(int c); The function returns nonzero if c is punctuation x int isspace(int c); The function returns nonzero if c is space character x int isupper(int c); The function returns nonzero if c is upper case character x int isxdigit(int c); The function returns nonzero if c is hexa digit

30

Programming in C

x int tolower(int c); The function returns the corresponding lowercase letter if one exists and if isupper(c); otherwise, it returns c. x int toupper(int c); The function returns the corresponding uppercase letter if one exists and if islower(c); otherwise, it returns c.

Error Handling Functions

x void perror(const char *s); produces a message on standard error output describing the last error encountered. x char *strerror(int errnum ); returns a string describing the error code passed in the argument errnum.

------

UNIT II

2.1 MANAGING INPUT AND OUTPUT OPERATIONS x Input means to feed data into a program. x Output means to display data on screen, printer, or in any file. x C programming provides a set of built-in functions to read the input and to output the data on the computer screen. These functions are present in Standard I/O library. Hence to read and write, #include is used. x I/O functions can be classified as, o Unformatted I/O functions : These do not allow formatted input or output. e.g. getch(), getche(), getchar(), gets, putch(), putchar(), puts() o Formatted I/O functions : These allow the input read from the keyboard or the output displayed on the screen to be formatted as per the requirements. e.g. scanf(), printf()

2.1.1 UNFORMATTED I/O FUNCTIONS

READING AND WRITING A CHARACTER The getchar() and putchar() functions are used to read and write a character respectively.

The gets() and puts() functions are used to read and write a line of text respectively.

TO READ AND WRITE SINGLE CHARACTER getchar() x The getchar() function reads any character keyed in. x It can be numbers, characters, special symbols, enter key, tab key etc. x This function reads only single character at a time. 31

Programming in C

Syntax, Variable = getchar(); A character is read from the keyboard and it is assigned to the variable. putchar() x The putchar() function writes a character on the screen. x This function puts only single character at a time. Syntax, putchar(variable); The value of the variable is printed on the screen Example: void main( ) { char c; printf( "Enter a character :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); } Output: Enter a character : y You entered: y

To read and write a line of text gets() x The only way to accept a line of text from the keyboard including with spaces is gets(). x Syntax, gets(str); where str Æ an array of char, i. e., a character string.

x It reads characters into str until newline character (Enter key) is encountered and appends a null character to the end of the string puts() x puts() is used to display a line of text on the screen x syntax, puts(str); where str Æ string variable Example: #include void main( ) { char str[100]; printf( "Enter a line of text :"); gets( str ); printf( "\nYou entered: ");

32

Programming in C puts( str ); } Output Enter a line of text : this is test You entered: This is test

2.1.2 FORMATTED I/O FUNCTIONS FORMATTED INPUT

These functions allow us to supply the input in a fixed format and let us obtain the output in the specified form. scanf() and printf() fall under this category. scanf() scanf() function is used to read character, string, numeric data from keyboard

syntax, scanf( “control string”,&var1,&var2….&varn); where control string Æ is in the form, %[width][modifiers]type % Æ conversion character width Æ maximum number of characters to be read modifiers Æ used along with data type type Æ data type & Æ a pointer which is used to point to the variable. Var Æ list of variables Eg: scanf ( "%d %f %c", &c, &a, &ch ) ;

Control string %d Æ to read integer data %ld Æ long integer %hd Æ short integer %oi Æ decimal, hexa decimal or octal %o Æ octal %x Æ hexa decimal %f, %e, %g Æ floating point data %ws, %wc Æ character or string

Rules: 1. Do not include escape sequences in the format string. printf() ptintf() function is used to print character, string, numeric data, symbols on the screen. syntax, printf ( "control string", list of variables ) ; where the format string can contain : x Characters that are simply printed as they are 33

Programming in C

x Conversion specifications that begin with a % sign x Escape sequences that begin with a \ sign

The syntax of scanf() looks like : scanf ( "format string", list of addresses of variables ) ;

2.2 DECISION MAKING AND BRANCHING STATEMENT Normally, the program code is executed sequentially one by one. Decision making and branching statement transfers the control from one line to another line, based on some condition and the execution continues from there. 2.2.1 IF STATEMENT x if statement is a conditional control statement. x Based on some condition(Boolean value of an expression), it executes one block of statements, ignoring another block of statements There are 4 types of if statement. 1. if 2. if ….. else 3. Nested if 4. else .. if ladder if Syntax

if (condition) { Statement Block

}

Next Statement

Mode of Execution On executing the if statement x The condition is checked. x If it is true, the statement block is executed and comes to the next statement. x If it is false, it comes to the next statement ignoring the statement block Example Program //Biggest among 2 - simple if #include void main() { int a,b; scanf("%d%d",&a,&b);

34

Programming in C if(a>b) { printf("A is big"); Æ if statement goto aa; } printf("B is big"); aa: }

2.2.2 If …… else Syntax Flowchart

if (condition) cond { StatementTrue Statement Block False Statement True Statement Block Block Block }

else Next statement { False Statement Block } Next Statement Mode of Execution On executing the if – else statement, x The condition is checked. x If it is true, the Statement Block 1 is executed,( ignoring Statement Block 2 and comes to the next statement.) x If it is false, the Statement B lock 2 is executed, (ignoring Statement Block 1 and comes to the next statement.) Eg: //Biggest among 2 - if-else #include void main() { int a,b; scanf("%d%d",&a,&b); if(a>b) printf("A is big"); else Æ if..else printf("B is big"); }

35

Programming in C

2.2.3 Nested if

If, an if statement contains another if block inside it, then it is known as Nested if statement. Syntax Flowchart

Cond1 if (condition1)

Statement Block3Block if(condition2) Cond2 { Statement Block1 Statement Block 1 Statement Block2 }

else Next statement

{

Statement Block 2 } else { Statement Block3 } Next Statement

Mode of Execution On executing the nested if statement, x The condition1 is checked. If it is true, Condition2 is checked. If condition1 and 2 are true Statement Block1 is executed, (ignoring Statement Block 2 and Statement Block3 and comes to the Next Statement). x if condition1 is true and Condition2 is false, Statement Block2 is executed, (ignoring Statement Block 1 and Statement Block3 and comes to the Next Statement.) x If condition1 is false, the Statement B lock3 is executed, (ignoring Statement Block 1 and Statement Block2 and comes to the Next Statement). Ex //Biggest among 3 - Nested if #include void main() { int a,b,c; scanf("%d%d%d",&a,&b,&c); 36

Programming in C if(a>b) if(a>c) printf("A is big"); Æ Nested if else if (b>c) printf("B is big"); else printf("C is big"); }

2.2.4 else … if ladder If an else part of a if statement contains another series of if block inside it, then it is known as else…if ladder. Syntax Flowchart

if (condition1)

Statement Block { Cond1 Statement Block 1 } Statement Block2 else if (condition2) { Next statement Statement Block 2 } Statement Block1 else if(condition3) Cond2 { Statement Block3 } else { Default Block } Next Statement

Mode of Execution On executing the else.. if ladder statement, x The condition1 is checked. If it is true, Statement Block1 is executed (and comes to the Next Statement.)

37

Programming in C x if condition1 is false, Condition2 is checked. If it is true Statement Block2 is executed (and comes to the Next Statement.) x Hence it continues. The Statement Block corresponding to the true condition is executed. If all the conditions are false, the Default Block is executed and comes to the Next Statement. Ex: #include void main() { int x; scanf("%d",&x); if(x==1)printf("one"); else if (x==2) printf("Two"); else if (x==3) printf("Three"); Æ else if ladder else printf("Out of range"); Æ default statement }

Rules 1. The condition should be a valid relational or logical expression eg: if(a>b && c5) Æ valid

2. The condition should return true or false eg: if(a>b && c5) Æ valid

3. If a statement block contains one statement, { … } are optional eg: if(a>b) if(a>b)

printf(“a is big”); Æ valid {

printf(“a is big”);

} Æ valid

4. If a statement block contains more than one statement, { …. } are must eg: if(a>b) if(a>b)

printf(“hai”); {

printf(“a is big”); Æ invalid printf(“hai”);

printf(“a is big”); Æ valid

}

38

Programming in C

5. Every statement inside a statement block is separated by a semicolon. eg: if(a>b) { printf(“hai”); printf(“a is big”) Æ invalid } 2.3 SWITCH STATEMENT A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Syntax,

switch(expression) { case value-1: block-1; break; case value-2: block-2; break; case value-3: block-3; break; case value-4: block-4; break; default: default-block; break; } Mode of Execution:

x The expression is evaluated. x The value is matched with the case value x If match occurs, that statement block is executed until break statement is reached and comes to the next statement x If no match occurs, the default block is executed Rules: x The expression used in a switch statement must have an integral value x Any number of case statements are allowed within a switch. x Each case is followed by the value to be compared to and a colon. x The constant value for a case must be the same data type as the variable in the switch. x It must be a constant or a literal.

39

Programming in C

x If no break appears, the flow of control will fall through to subsequent cases until a break is reached. x A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. 2.4 GOTO STATEMENT A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function. NOTE í 8VH RI goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them. Syntax

The syntax for a goto VWDWHPHQWLQ&LVDVIROORZVí goto label; .. . label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement. EXAMPLE: int main() { int age; Vote: printf("you are eligible for voting");

NoVote: printf("you are not eligible to vote");

printf("Enter you age:"); scanf("%d", &age); if(age>=18) goto Vote; else goto NoVote;

return 0; }

40

Programming in C

2.5 LOOP STATEMENTS x Loop statement are used to repeat a sequence of statements until a specified condition is met (true) x A loop statement consists of 2 segments. o Control statement: It tests the condition and directs the repetition of the loop. o Body of the loop : The statements that are to be repeated if the condition is met. x There are 2 categories of loop. 1.entry controlled loop: The condition is checked at the beginning of the loop Eg: while loop, for loop 2. exit –controlled loop: The condition is checked after executing the body of the loop eg: do… while loop 2.5.1 LOOP PROCESSING: x Setting and initializing a condition variable. x Testing of the condition. x Executing the body of loop. x Updating the condition variable. x Repeat step2-4 until the condition is true. 2.5.2 TYPES OF LOOP C provides 3 loop statements i. while loop ii. do… while loop iii. for loop

WHILE LOOP: While loop is used where the number of repetition is not known before the loop begin execution. It is an entry – controlled loop. The condition is checked before executing the body of the loop. A condition variable is used to change the condition from true to false to stop the loop. It is also called as sentinel-controlled loop or indefinite repetition loop. Syntax: while (condition) { Body of the loop } Next statement

Mode of execution : On seeing the while statement x The condition is checked x If it is true , the body of the loop is executed and the loop repeats. 41

Programming in C x The body of the loop is executed as long as the condition is true x It the condition is false, it comes to the next statement. Eg: i= 1; while (i<=5) { printf ( “All is well\n”); i++; } Rules 1. The condition should be a valid relational or logical expression which results in true or false Eg: While (a>b) valid While 9i<=5 && a<=10) valid While (5) valid 2. Every statement inside the body of the loop should be terminated by a semicolon (;) Eg: while (i void main () { int i= 1,n; print f ( “ enter the range\n”); scan f (“%d”,&n); print f (“natural numbers \n”); while (i<=n) { print f (“%d\n”,i);

42

Programming in C

i++; } }

Do… while statement: Dob… while loop is used where the numbers of repetition is not known before the loop begins execution. It is an entry – controlled loop. The condition is checked before executing the body of the loop. A condition variable is used to change the condition from true to false to stop the loop. It is also called as sentinel – controlled loop or indefinite loop. Syntax: do { Body of the loop } While (condition); Next statement

Mode of executing : On seeing the do .. while statement, x The body of the loop is executed irrespective of the condition x Then it checks for the condition. x It is true the body of the loop is (executed again) repeated x The body of the loop is executed is true. x If the condition is false , it comes to the next statement I=0; Eg: do { Print f ( “all is well\n”); I++; } While (i<5=)

Rules 1. The condition should be a valid relational or logical expression which results in true or false Ehg: { … … … } While (a

2. Every statement in side the body of the loop should be terminated by a semicolon (;) Eg: Do

43

Programming in C

{ Print f ( “all is well \n”) valid I++ }

3. If the body of the loop contain more then one statement {3 braces are must otherwise it is optional Eg:

Do { …. …. …. While(…); Do Print f (“all is well\n”); While(a

Do { I++; While (I<=n);

For loop: For loop is used where the numbers of expectation is exactly known before the loop begin

Execution. It is an entry - controlled loop in the condition is checked at the beginning of

the loop it is also know as counter controlled loop or definite repetition loop , it uses a control variable known as counter must be initiated , tested and updated for the designed loop operation.

Syntax:

For ( control variable initialization, condition ; update control variable)

{

Body of the loop

}

Next statement

Mode of execution:

On seeing the for statement,

Control variable initialized it is also known as loop variable. 44

Programming in C

Next the condition is checked.

It is true, the body of the loop is executed .

Updates the control variable

Again checks the condition , execute the body of the loop is repeated with its condition is false.

If the condition is false , it comes to the next statement.

Eg:

For (i=1; i<=3;i++)

Print f (“all is well\n”)

Rules

Any number of initialization can be done in the initiazation section

If there is more initialization , they are separated by comma

For (i=1,s=o,by=x; i

{

….

….

}

The condition should be an relational or logical expression which results in true or false

Or logical expression which results in true or false.

For(i=1; i

If the body of the loop contains more than one statement , it is enclosed with{} otherwise braces

{3 are optional

EG:1 FOR (I=1;I

{

Print f (“hai\n”);

Print f ( “all is well\n”);

} 45

Programming in C

Eg 2:

for (i=1; i<=n;i++ )

print f (“all is well\n”); valid

Declaration of variable can be done in initialization section.

Eg:

For (int i=1, s=o; i

{

….

….

}

I and s are declared as i

5.update control variable section increments or decrements the contro variable.

EG:

FOR (I=1; I < =n ; i++) valid

For (i=1; i>n ; i..) valid

6.Every statement in the body of the loop should be terminated by a semicolon.

Eg

for (i=1;i<=n; i++)

{

Print f (”hai\n”) in valid

Print f ( “all is well \n”); valid

}

7. the update section can have more than one expression

Eg:

For (i=1; i<=n; i++, st=i)

8. there should be only one condition in the condition section

For (i=1; i<=n, j<=m; i++) 46

Programming in C

9. the testing condition is not limited to the loop control variable it can test other variable

Eg: for (i=1; i<=20 && sum <100; +++i) valid

Loop control other variable

Variable

10. expression can be used in initialization and increment section.

Eg: for (x= (m+n)/2; x>o; x=x/2) valid

Initialization update section

Section

11 one or more section can be omitted in a statement

Eg: for (; m ! =100;)

12. the sections can be left blank but semicolon repeating section is must

Eg: for (m!=10) in valid.

13. if the test condition is not present it is an infinite loop.

Eg: for (i=1; i++) infinite loops

2.6 Jump Statements

Jump statements cause an unconditional jump to another statement elsewhere in the code. They are used primarily to interrupt switch statements and loops.

The jump statements are the goto statement, the continue statement, the break statement, and the return statement, which are discussed in the following sections.

2.7 The goto Statement

The goto statement unconditionally transfers program control to a labeled statement, where the label identifier is in the scope of the function containing the gotostatement. The labeled statement is the next statement executed. The goto statement has the following syntax: goto identifier;

Care must be taken when branching into a block by using the goto statement, because storage is allocated for automatic variables declared within a block when the block is activated. When a goto statement branches into a block, automatic variables declared in the block are not initialized.

47

Programming in C

2.8 The continue Statement

The continue statement passes control to the end of the immediately enclosing while , do , or for statement. The continue statement has the following syntax: continue; The continue statement is equivalent to a goto statement within an iteration statement that passes control to the end of the loop body. For example, the following two loops are equivalent: while(1) while(1) { { ...... goto label_1; continue; ...... label_1: ; ; } }

The continue statement can be used only in loops. A continue inside a switch statement that is inside a loop causes continued execution of the enclosing loop after exiting from the body of the switch statement.

2.9 The break Statement

The break statement terminates execution of the immediately enclosing while , do , for , or switch statement. Control passes to the statement following the loop body (or the compound statement of a switch statement). The break statement has the following syntax: break; which uses a break statement within a switch statement. 2.10 The return Statement

The return statement terminates execution of a function and returns control to the calling function, with or without a return value. A function may contain any number of return statements. The return statement has the following syntax: return expression(opt);

If present, the expression is evaluated and its value is returned to the calling function. If necessary, its value is converted to the declared type of the containing function's return value.

A return statement with an expression cannot appear in a function whose return type is void . For more information about the void data type and function return types

If there is no expression and the function is not defined as void , the return value is undefined. For example, the following main function returns an unpredictable value to the operating system:

48

Programming in C main ( ) { return; }

Reaching the closing brace that terminates a function is equivalent to executing a return statement without an expression.

------

Unit III

3.1 Functions There are several different types of functions in C. So far, we have used one type of function – the built-in C functions, like printf( ) and scanf( ). These functions are part of the C programming language.

Another type is called a user-defined function. This is a function which the programmer creates and uses in a C program. We will learn how to create these functions in this part of the tutorial.

We can also distinguish between functions which return values and those which don’t — like void main( ). Technically speaking, all functions return values, but in C we can choose to eliminate this process by using void. So far, we have not used our main( ) function to return any values, so we voided it and let the body functions, like printf( ) return values.

A function which return values produces some result — like printing text on the screen, or scanning a variable, etc. Let’s examine the different types of functions, so we can understand them better. 3.1.1 Built-in Functions C has many built-in functions that you can use in your programs. So far we have learned 15 built-in functions: main( ) printf( ) scanf( ) gets( ) puts( ) strcpy( ) strlen( ) strcmp( ) stricmp( ) strcat( ) strstr( ) isalpha( ) isdigit( ) isupper( )

49

Programming in C islower( )

If you can’t remember how to use each of these functions, go back and review the previous sections of this tutorial.

User-Defined Functions

If you have a special set of instructions that aren’t in a built-in function, you can create a user-defined function. Here are the steps: give your function a name that isn’t already used in C (by built-in functions, types of variables, keywords, etc.) create a function header, which contains three things: a. the type of variable (int, char, double, etc.) that the function will produce (return) b. the name of the function, which can be one or more words (but put underscores _ or Capital Letters connecting these words, because no spaces are allowed) c. the parameters of the function, which are the names and types of variables inside your function create a function body, which contains the operations to be completed when you call the function to run

Function Header

Here is an example of a function header: int Square(int num)This function expects an integer variable, so we begin with int.

Then we type a space followed by the name of the function, Square.

Next, we put the parameters in parentheses: (int num).

Function Body

Now we can add variables and functions to create a function body:

{ return (num * num);

}

This function calculates the square of num, which is num * num. This function returns the value of num * num.

Location and Call

To use this function, we must write it before void main( ) or after void main( ). We don’t want to write it inside void main( ), since Square( ) is a function separate from main( ).

50

Programming in C

#include int Square(int num)

{ return (num * num);

}

Inside void main( ), we must call the function Square( ) to run. This means triggering the function to activate. This involves three things: a variable equal to the value returned from the function the name of the function the variable passed to the function

Here is an example: void main( )

{ int num; int total; total = Square(num);

}

The Square Function

#include int Square(int num)

{ return (num * num);

}void main( )

{ int num; int total; printf(“Type a number: “); scanf(“%d”, &num);

51

Programming in C total = Square(num); printf(“Your number squared is %d.”, total);

}

Using main( ) Plus Two More Functions

You can create more than one function in a C program. Each function will need its own return statement and its own variable to store the returned value. Here is an example:

#include int Thirteen(int born)

{ return (born + 13);

}int Nineteen(int born)

{ return (born + 19);

}void main( )

{ int born; int teen1; int teen2; printf(“What year were you born? “); scanf(“%d”, &born); teen1 = Thirteen(born); teen2 = Nineteen(born); printf(“You were a teenager from %d to %d.”, teen1, teen2);

}

Let’s analyze this program step-by-step:

#include int Thirteen(int born)

{

52

Programming in C return (born + 13);

} This is the first function:Thirteen, which uses the passed variable born. This function returns a value of born + 13. int Nineteen(int born)

{ return (born + 19);

} This is the second function:Nineteen, which uses the passed variable born. This function returns a value of born + 19. void main( )

{ int born; int teen1; int teen2; In the main( ) function, declare three variables: the passed variable the variable to store the returned value from the first function the variable to store the returned value from the second function printf(“What year were you born? “); scanf(“%d”, &born); Ask the viewer to enter a value, then scanf it. teen1 = Thirteen(born); teen2 = Nineteen(born); Pass the variable to each function, and store the returned value in our two variables. printf(“You were a teenager from %d to %d.”, teen1,teen2);

} //Print the result. 3.1.2 Recursive Functions

Those functions which are called by themselves are called Recursive functions. It means that the same function is called again within itself. The function itself becomes the calling function of it. Control is cycled within the function until a break point is reached in the program.

Non-Recursive Function

These functions are called only once from the calling function.

53

Programming in C

Eg: /* Write C programs that use both recursive and non-recursive functions To find the factorial of a given integer.*/

#include< stdio.h> #include< conio.h> unsigned long factrec(int ); unsigned long factnrec(int ); void main() { int a; unsigned long f1,f2; clrscr(); printf("\n\n\t\tENTER VALUE OF A: "); scanf("%d",&a); f1=factrec(a); f2=factnrec(a); printf("\n\n\nFACTORIAL OF %d USING RECURSIVE FUNCTION IS: %d\n",a,f1); printf("\nFACTORIAL OF %d USING NON-RECURSIVE FUNCTION IS : %d",a,f2); getch(); } /* RECURSIVE FUNCTION*/ unsigned long factrec(int x) { if(x<=1) return 1; else return x*factrec(x-1); } 28 /* NON-RECURSIVE FUNCTION*/ 29 unsigned long factnrec(int x) 30 { 31 int i; 32 unsigned long f=1; 33 if(x<=1) 34 return 1; 35 54

Programming in C

else 36 { 37 for(i = 1; i <= x; i++) 38 f=f*i; 39 } 40 return f; 41 } 42 OUTPUT: ENTER VALUE OF A: 6 FACTORIAL OF 6 USING RECURSIVE FUNCTION IS: 720 FACTORIAL OF 6 USING NON-RECURSIVE FUNCTION IS : 720

Important Note:

A function declared globally i.e, outside the main( ) function can be used by any other function in the program. Any C program contains atleast one function, which is nothing but the main( ). There is no limit on the number of functions that might be present in a C program. Each function in a program is called in the sequence specified by the function calls in main( ). A function can be called from another function, but a function cannot be defined in another function. Variables declared in the main( ) function and called functions are different. So, same Same variable names can be used in main( ) and called functions.

3.3 STORAGE CLASSES Variables in C language are not only data types but are also of storage class. They provide information about locality and visibility of variables. Depending upon the declaration of variables they are of two types. Global variables: These are the variables which are declared before the main function and they can be used in any function with in the program. Local variables: These are the variables which are declared with in the main function and they can be used with in that function only. EX: int d; void main() { char c,e; }

55

Programming in C

In the above example variable d is globally declared and can be used in any function where as c and e are declared locally and can be used with in that function only. Storage classes To fully define a variable one needs to mention not only its ‘type’ but also its ‘storage class’. In other words, not only do all variables have a data type, they also have a ‘storage class’. We have not yet mentioned storage classes yet, though we have written several programs in C.We were able to get away with this because storage classes have defaults. If we don’t specify the storage class of a variable in its declaration, the compiler will assume a storage class depending on the context in which the variable is used. Thus variables have certain default storage classes. From C compiler’s point of view, a variable name identifies some physical location within the computer where the string of bits representing the variable’s value is stored. There are basically two kinds of locations in a computer where such a value may be kept: Memory and CPU registers. It is the variable’s storage class that determines in which of these two locations the value is stored. Moreover, a variable’s storage class tells us: (a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically assigned (i.e. the default initial value). (c) What is the scope of the variable i.e. in which functions the value of variable would be available. (d) What is the life of the variable i.e. how long would the variable exist. There are four storage classes available in ‘C’: Automatic Storage class. Register Storage class. Static Storage class. External Storage class.

3.3.1 Automatic Storage class: The features of a variable defined to have an automatic storage class are as under: Storage : Memory Default initial value : unpredictable value which is often called a garbage value. Scope : Local to the block in which the variable is defined. Life : Till the control remains within the block in which the Variable is defined. Keyword : Auto The variables are declared inside a function block are automatic variables. A variable declared inside a function block without a storage class name, by default is an auto variable. Example: program that shows the default values of automatic variables. main () { auto int i,j; printf("\n %d %d",i ,j); } The output of the above program would be …. 1432 2313 Where 1432 and 2313 are the garbage values of i and j. When you run this program you may get different values, since garbage values are unpredictable. So always make it a point that you initialize the automatic variables properly, otherwise you are likely to get unexpected results. 56

Programming in C

Example: program that shows the scope and lifetime of an automatic variable. main() { auto int =1; { auto int i=2; { auto int i=3; printf( "\n %d",i); } printf("%d", i); } printf( "%d", i); }

The output of the above program would be: 3 2 1

Explanation: In the above program the compiler treats the three i’s as totally different variables, since they are defined in different blocks. Once the control comes out of the innermost block the variable i with the value 3 is lost, and hence the i in the second printf () refers to i with value 2. Similarly, when the control comes out of the next innermost block, the third printf () refers to the i with value 1. 3.3.2 Register storage class The features of a variable defined to be of register storage class are as under: Storage : CPU registers. Default initial value : unpredictable value which is often called a garbage value. Scope : Local to the block in which the variable is defined. Life : Till the control remains within the block in which the Variable is defined. Keyword : register. We can also keep some variables in the CPU registers instead of memory. The keyword register tells the compiler that the variable list followed by it is kept on the CPU registers, since register access is faster than the memory access. So, the variables that are declared with storage class register are known as register variables. Example: main() { register int i; for(i=1 ; i<=10; i++ ) printf( " %d ", i); }

In the above example the space for variable i will be allocated in registers.

57

Programming in C

Here, even though we have declared the storage class of i as register, we cannot say for sure that the value of i would be stored in a CPU register. Why? Because the number of CPU registers are limited (14 in case of a micro computer), and they may be busy doing some other task. What happens in such a event…. the variable works as if its storage class is auto. We cannot use register storage class for all types of variables. For example, the following declarations are wrong: register float a; register long c; register double a; This is because CPU registers in a microcomputer are usually 16 bit registers and therefore cannot hold a float value or a double value, which require 4 and 8 bytes respectively for storing a value. However, if you use the above declarations you won’t get any error messages. All that would happen is the compiler would treat the variables to be of auto storage class. 3.3.3 Static Storage class

The features of a variable defined to have a static storage class are as under: Storage : Memory. Default initial value : Zero. Scope : Local to the block in which the variable is defined. Life : Value of the variable persists between different function Calls. Keyword : static. The static variable may be of an internal or external type, depending upon where it is declared. If declared outside the function of the body it will be static global. In case it is declared in the body or block it will be auto variable. A static variable is initialized only once, it is never reinitialized. Example: program that shows the difference between automatic and static storage classes. main () main() { { increment (); increment(); increment (); increment(); increment (); increment(); } } increment () increment () { { auto int i=1; static int i=1; printf ( "%d \n", i); printf( " %d\n", i); i=i+1; i=i+1; } }

The output of the programs would be: 1 1 1 2 1 3

58

Programming in C

Explanation: In the above example, when variable i is auto, each time increment () is called it is re- initialized to one. When the function terminates, i vanishes and its new value of 2 is lost. The result: no matter how many times we call increment (), i is initialized to 1 every time. On the other hand if i is static, it is initialized to only one once. It is never initialized again. During the first call to increment (), i is incremented to 2.Because I is static, the value persists. The next time increment () is called, i is not re-initialized to 1.On the contrary its old value 2 is still available. This current value of (i.e. 2) gets printed and then i=i+1 adds 1 to i to get a value of 3. When increment () is called third time, the current value of i (i.e. 3) gets printed and once again i is incremented. In short if storage class is static then the statement static int i=1 is executed only once irrespective of how many times the same function is called. 3.3.4 External Storage class

The features of a variable whose storage class has been defined as external as follows: Storage : Memory. Default initial value : Zero. Scope : Global. Life : As long as the program’s execution doesn’t comes to end. Keyword : extern. The variables that are available to all the functions i.e. from entire program they can be accessed are known as external or global variables. External variables are declared outside the function body. In case both external and auto variables are declared with the same name, in a program the first priority is given to the auto variable. In this case external variable is hidden. Example: program that shows the default value, scope and life time of a global variable.

#include< stdio.h> #include< conio.h> int i ; void main() { extern int i; printf( "\n i=%d", i ); increment(); increment(); decrement(); decrement(); } increment() { i=i+1; printf("\n On incrementing i= %d", i); } decrement() { i=i-1; printf("\n On decrementing j= %d", j);

59

Programming in C

}

The output of the above program would be: i=0 On incrementing i=1 On incrementing i=2 On decrementing j=1 On decrementing j=0 Explanation: In the above output it is clear that the value of i is available to l the functions increment() and decrement() since i is declared outside all the functions.

3.4 ARRAY 3.4.1 NEED FOR AN ARRAY:

To store marks of 100, 100 variables are declared as m0,m1, m2 …..m99, get data for 100 variables individually and processing. While programming, declaring and processing more number of variable is impossible. To overcome this problem arrays are used. An array variable m can be declared with size 100 and marks are stored in m0, m1, m2 … m99.

ARRAY:

x An array is a fixed size, consecutive memory location, collection of related data items that share a common name and each individual element is referred by its index or subscript. x Arrays are used to process large amount of data. x It is a derived data type in C

There are 3 types of array 1. One dimensional array 2. Two dimensional array 3. Multi dimensional array

3.4.2 ONE DIMENSIONAL ARRAY

x An array with only one subscript is known as one dimensional array or single subscripted variable x A list of data can be stores in one dimensional array

60

Programming in C

DECLARING ONE DIMENSIONAL ARRAY

Array must be declared before they are used so that the compiler can allocate space for them in memory. To declare an array, specify x the type of elements stored in an array and x the number of consecutive memory location. Syntax, data_typearray_name [array_size]; where, data_type Æ valid C data type array_name Æ name of the array array_size Æ maximum size of an array. Array size is a non – zero integer Eg: int a[20]; Declares an array ‘a’ with size 20 It holds integer data

INITIALIZATION OF ONE DIMENSIONAL ARRAY

Array can be initialized in 2 ways 1. initialization 2. Run time initialization

COMPILE TIME INITIALIZATION

Initializing an array at the time of declaration is called compile time initialization. Syntax, data_typearray_name [array_size] = { list of values to store in the array }; Eg: int a[5] = {1000, 200, 500, 300, 100}; Rules: 1. Number of values stored in the array <= array size. Eg :int a[3] = { 10, 20, 30, 40, 50 } Æ invalid 2. Size of an array can be omitted. Array becomes big enough to hold data. Eg: inta[] = { 10, 20, 30, 40, 50 } Æ valid. a is an array of size 5

RUN TIME INITIALIZATION Array can be assigned a value while running Eg: c[2] = 30 Æ valid. Array at position 2 is assigned 30 for (i=1; i<=n;i++) scanf(“%d”, &c[i]); Æ valid. assigning values one by one

// Program to illustrate One Dimension Array – Reading and printing one dimensional array

61

Programming in C

3.4.3 TWO DIMENSIONAL ARRY

Two dimensional array is an array of one dimensional array. The two dimensional array can be viewed as matrix or table form It consists of rows and columns DECLARING TWO DIMENSIONAL ARRY 2D array can be declated as Syntax, data_typearray_name[row_size] [column_size]; where, data_type Æ valid C data type array_name Æ name of the array array_size = row size x column size The 1st index is the row and the 2nd index is the columns within the row Eg: int a[2] [3]; Declares an array ‘a’ with size 2 x 3 = 6 It holds integer data 2D array are stored as Col[0] col[1] col[2] Row[0] a[0][0] a[0][1] a[0][2] Row[1] a[1][0] a[1][1] a[2][1]

INITIALIZATION OF TWO DIMENSIONAL ARRAY Array can be initialized in 2 ways 1. Compile time initialization 2. Run time initialization COMPILE TIME INITIALIZATION Initializing an array at the time of declaration is called compile time initialization. Syntax, data_typearray_name [array_size] = { list of values to store in the array }; Eg: int a[5][5] = {1000, 200, 500, 300, 100}; Rules: 1. Number of values stored in the array <= array size(row size x column size). Eg :int a[2][3] = { 10, 20, 30, 40, 50, 60, 70 }; Æ invalid 2. The initialization is done row by row each row is separated by a comma Eg: inta[2][3] = { {1,2,3},{4,5,6} }; Æ valid 3. The first index is optional but the 2nd index is must. Eg: inta[][3] = { {1,2,3},{4,5,6} }; Æ valid 4. If the values are missing, they are automatically set to zero. Eg: inta[2][3] = { {1,2},{4} };

62

Programming in C

RUN TIME INITIALIZATION 2D Array can be assigned a value while running Eg: c[2][2] = 30 Æ valid. Array at position 2,2(2nd row 2nd column) is assigned 30 eg: for(i=1; i<=m;i++) for (j=1;j<=n;j++) scanf(“%d”, &c[i] [j]); Æ valid. Assigning values one by one

//Program to illustrate 2D Array. String is an array of characters. In this guide, we learn how to declare strings, how to work with strings in C programming and how to use the pre-defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one string to another & perform various string manipulation operations. We can perform such operations using the pre-defined functions of “string.h” header file. In order to use these string functions you must include string.h file in your C program.

String Declaration string declaration in C

Method 1: char address[]={'T', 'E', 'X', 'A', 'S', '\0'};

Method 2: The above string can also be defined as – char address[]="TEXAS"; In the above declaration NULL character (\0) will automatically be inserted at the end of the string.

What is NULL Char “\0”? '\0' represents the end of the string. It is also referred as String terminator & Null Character.

3.5 String I/O in C programming 3.5.1 C String-IO

Read & write Strings in C using Printf() and Scanf() functions

#include #include int main() { /* String Declaration*/ char nickname[20];

printf("Enter your Nick name:");

63

Programming in C

/* I am reading the input string and storing it in nickname * Array name alone works as a base address of array so * we can use nickname instead of &nickname here */ scanf("%s", nickname);

/*Displaying String*/ printf("%s",nickname);

return 0; } Output:

Enter your Nick name:Negan Negan Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions

#include #include int main() { /* String Declaration*/ char nickname[20];

/* Console display using puts */ puts("Enter your Nick name:");

/*Input using gets*/ gets(nickname);

puts(nickname);

return 0; } C – String functions

C string-functions

C String function – strlen

Syntax:

64

Programming in C size_t strlen(const char *str) size_t represents unsigned short It returns the length of the string without including end character (terminating char ‘\0’).

Example of strlen:

#include #include int main() { char str1[20] = "BeginnersBook"; printf("Length of string str1: %d", strlen(str1)); return 0; } Output:

Length of string str1: 13 strlen vs sizeof strlen returns you the length of the string stored in array, however sizeof returns the total allocated size assigned to the array. So if I consider the above example again then the following statements would return the below values. strlen(str1) returned value 13. sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main function).

C String function – strnlen

Syntax: size_t strnlen(const char *str, size_t maxlen) size_t represents unsigned short It returns length of the string if it is less than the value specified for maxlen (maximum length) otherwise it returns maxlen value.

Example of strnlen:

#include #include int main() { char str1[20] = "BeginnersBook"; printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30)); printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10)); return 0; } Output: 65

Programming in C

Length of string str1 when maxlen is 30: 13 Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string length was 13 it returned only 10 because the maxlen was 10.

C String function – strcmp int strcmp(const char *str1, const char *str2) It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Example of strcmp:

#include #include int main() { char s1[20] = "BeginnersBook"; char s2[20] = "BeginnersBook.COM"; if (strcmp(s1, s2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; } Output: string 1 and 2 are different C String function – strncmp int strncmp(const char *str1, const char *str2, size_t n) size_t is for unassigned short It compares both the string till n characters or in other words it compares first n characters of both the strings.

Example of strncmp:

66

Programming in C

#include #include int main() { char s1[20] = "BeginnersBook"; char s2[20] = "BeginnersBook.COM"; /* below it is comparing first 8 characters of s1 and s2*/ if (strncmp(s1, s2, 8) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; } Output: string1 and string 2 are equal C String function – strcat char *strcat(char *str1, char *str2) It concatenates two strings and returns the concatenated string.

Example of strcat:

#include #include int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; } Output:

Output string after concatenation: HelloWorld C String function – strncat char *strncat(char *str1, char *str2, int n) It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be appended at the end of the concatenated string.

67

Programming in C

Example of strncat:

#include #include int main() { char s1[10] = "Hello"; char s2[10] = "World"; strncat(s1,s2, 3); printf("Concatenation using strncat: %s", s1); return 0; }

Output:

Concatenation using strncat: HelloWorld

C String function – strcpy char *strcpy( char *str1, char *str2) It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Example of strcpy:

#include #include int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I’m gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; } Output:

String s1 is: string 2: I’m gonna copied into s1 C String function – strncpy char *strncpy( char *str1, char *str2, size_t n) size_t is unassigned short and n is a number. Case1: If length of str2 > n then it just copies first n characters of str2 into str1. Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several terminator chars(‘\0’) to accumulate the length of str1 to make it n. 68

Programming in C

Example of strncpy:

#include #include int main() { char first[30] = "string 1"; char second[30] = "string 2: I’m using strncpy now"; /* this function has copied first 10 chars of s2 into s1*/ strncpy(s1,s2, 12); printf("String s1 is: %s", s1); return 0; }

Output:

String s1 is: string 2: I’m C String function – strchr char *strchr(char *str, int ch) It searches string str for character ch (you may be wondering that in above definition I have given data type of ch as int, don’t worry I didn’t make any mistake it should be int only. The thing is when we give any character while using strchr then it internally gets converted into integer for better searching.

Example of strchr:

#include #include int main() { char mystr[30] = "I’m an example of function strchr"; printf ("%s", strchr(mystr, 'f')); return 0; }

Output: f function strchr C String function – Strrchr char *strrchr(char *str, int ch) It is similar to the function strchr, the only difference is that it searches the string in reverse order, now you would have understood why we have extra r in strrchr, yes you guessed it correct, it is for reverse only.

69

Programming in C

Now let’s take the same above example:

#include #include int main() { char mystr[30] = "I’m an example of function strchr"; printf ("%s", strrchr(mystr, 'f')); return 0; } Output: function strchr Why output is different than strchr? It is because it started searching from the end of the string and found the first ‘f’ in function instead of ‘of’.

C String function – strstr char *strstr(char *str, char *srch_term) It is similar to strchr, except that it searches for string srch_term instead of a single char.

Example of strstr:

#include #include int main() { char inputstr[70] = "String Function in C at BeginnersBook.COM"; printf ("Output string is: %s", strstr(inputstr, 'Begi')); return 0; } Output:

Output string is: BeginnersBook.COM You can also use this function in place of strchr as you are allowed to give single char also in place of search_term string.

3UHYLRXV1H[W

Comments

Prit Kaur says JUNE 27, 2016 AT 9:12 AM Explanation of every function is very clear and described in a easy way. its very good for understanding practical examples for students /beginners.Its humble request to explain more string functions in the article. 70

Programming in C

Reply Marcello Missiroli says MARCH 21, 2017 AT 12:32 PM

The first program has an error. You should not call scanf with &nickname as an argument, since nicknama is already an address. This is also pointed out by the compiler string.c:11:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=] scanf(“%s”, &nickname);

------

UNIT IV

4.1 Pointers:

Pointers are powerful features of C and (C++) programming that differentiates it from other popular programming languages like: Java and Python.

Pointers are used in C program to access the memory and manipulate the address.

4.1.1 Address in C

Before you get into the concept of pointers, let's first get familiar with address in C.

If you have a variable var in your program, &var will give you its address in the memory, where & is commonly called the reference operator.

You must have seen this notation while using scanf() function. It was used in the function to store the user inputted value in the address of var.

A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier.

x There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators. x When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable. x When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.

Here is an example to understand what I have stated above.

71

Programming in C

#include int main() { int my_variable = 6, other_variable = 10; int *my_pointer;

printf("the address of my_variable is : %p\n", &my_variable); printf("the address of other_variable is : %p\n", &other_variable);

my_pointer = &my_variable;

printf("\nafter \"my_pointer = &my_variable\":\n"); printf("\tthe value of my_pointer is %p\n", my_pointer); printf("\tthe value at that address is %d\n", *my_pointer);

my_pointer = &other_variable;

printf("\nafter \"my_pointer = &other_variable\":\n"); printf("\tthe value of my_pointer is %p\n", my_pointer); printf("\tthe value at that address is %d\n", *my_pointer);

return 0; }

This will produce following result. the address of my_variable is : 0xbfffdac4 the address of other_variable is : 0xbfffdac0 after "my_pointer = &my_variable": the value of my_pointer is 0xbfffdac4 the value at that address is 6 after "my_pointer = &other_variable": the value of my_pointer is 0xbfffdac0 the value at that address is 10 4.1.2 CREATING A POINTER FOR THE STRING

Creating a string

In the following example we are creating a string str using char character array of size 6. char str[6] = "Hello";

The above string can be represented in memory as follows.

Each character in the string str takes 1 byte of memory space.

72

Programming in C

Creating a pointer for the string

The variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address.

So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr will point at the string str.

In the following code we are assigning the address of the string str to the pointer ptr. char *ptr = str;

We can represent the character pointer variable ptr as follows.

The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000.

Accessing string via pointer

To access and print the elements of the string we can use a loop and check for the \0 null character.

In the following example we are using while loop to print the characters of the string variable str.

#include int main(void) {

// string variable

char str[6] = "Hello";

// pointer variable

char *ptr = str;

// print the string

while(*ptr != '\0') {

printf("%c", *ptr);

// move the ptr pointer to the next memory location

ptr++;

}

return 0;

}

73

Programming in C

Using pointer to store string

We can achieve the same result by creating a character pointer that points at a string value stored at some memory location.

In the following example we are using character pointer variable strPtr to store string value.

#include int main(void) {

// pointer variable to store string

char *strPtr = "Hello";

// temporary pointer variable

char *t = strPtr;

// print the string

while(*t != '\0') {

printf("%c", *t);

// move the t pointer to the next memory location

t++;

}

return 0;

}

Note! In the above code we are using another character pointer t to print the characters of the string as because we don't want to lose the starting address of the string "Hello" which is saved in pointer variable strPtr.

In the above image the string "Hello" is saved in the memory location 5000 to 5005.

The pointer variable strPtr is at memory location 8000 and is pointing at the string address 5000.

The temporary variable is also assigned the address of the string so, it too holds the value 5000 and points at the starting memory location of the string "Hello".

4.1.3 Array of strings We can create a two dimensional array and save multiple strings in it.

For example, in the given code we are storing 4 cities name in a string array city. char city[4][12] = {

"Chennai", 74

Programming in C

"Kolkata",

"Mumbai",

"New Delhi"

};

We can represent the city array as follows.

The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city array and we are only using 33 bytes.

We can save those unused memory spaces by using pointers as shown below. char *cityPtr[4] = {

"Chennai",

"Kolkata",

"Mumbai",

"New Delhi"

};

In the above code we are creating an array of character pointer cityPtr of size 4 to store the name of the four cities.

We can represent the array of pointers as follows.

The above array of pointers can be represented in memory as follows.

The cityPtr pointer variable is allocated the memory address 8000 to 8007. Assuming integer address value takes 2 bytes space. So, each pointer gets 2 bytes.

Name of the cities are saved in locations 1000, 2000, 3000 and 4000.

Accessing values pointed by array of pointers

To access and print the values pointed by the array of pointers we take help of loop as shown in the following example.

#include int main(void) {

// array of pointers

char *cityPtr[4] = {

"Chennai",

75

Programming in C

"Kolkata",

"Mumbai",

"New Delhi"

};

// temporary variable

int r, c;

// print cities

for (r = 0; r < 4; r++) {

c = 0;

while(*(cityPtr[r] + c) != '\0') {

printf("%c", *(cityPtr[r] + c));

c++;

}

printf("\n");

}

return 0;

}

Output:

Chennai

Kolkata

Mumbai

New Delhi

In the above code we are using the r variable to access each row of the pointer. And we are using the c variable to access each character in a selected row. 4.2 Pointers and Arrays

The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example:

76

Programming in C

char *y; char x[100]; y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of

y = &x[0]; y = x;

Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following:

*(y+1) gives x[1] *(y+i) gives x[i] and the sequence

y = &x[0]; y++; leaves y pointing at x[1].

4.2.1 Pointer Arithmetic:

C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:

int x = 5, *ip = &x;

ip++;

On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.

Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.

4.2.2 Using Pointer Arithmetic With Arrays:

Arrays occupy consecutive memory slots in the computer's memory. This is where pointer arithmetic comes in handy - if you create a pointer to the first element, incrementing it one step will make it point to the next element.

#include int main() { int *ptr; 77

Programming in C

int arrayInts[10] = {1,2,3,4,5,6,7,8,9,10};

ptr = arrayInts; /* ptr = &arrayInts[0]; is also fine */

printf("The pointer is pointing to the first "); printf("array element, which is %d.\n", *ptr); printf("Let's increment it.....\n");

ptr++;

printf("Now it should point to the next element,"); printf(" which is %d.\n", *ptr); printf("But suppose we point to the 3rd and 4th: %d %d.\n", *(ptr+1),*(ptr+2));

ptr+=2;

printf("Now skip the next 4 to point to the 8th: %d.\n", *(ptr+=4));

ptr--;

printf("Did I miss out my lucky number %d?!\n", *(ptr++)); printf("Back to the 8th it is then..... %d.\n", *ptr);

return 0; }

This will produce following result:

The pointer is pointing to the first array element, which is 1. Let's increment it..... Now it should point to the next element, which is 2. But suppose we point to the 3rd and 4th: 3 4. Now skip the next 4 to point to the 8th: 8. Did I miss out my lucky number 7?! Back to the 8th it is then..... 8.

4.2.3 Passing Pointer to a Function

In this example, we are passing a pointer to a function. When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.

Try this same program without pointer, you would find that the bonus amount will not reflect in the salary, this is because the change made by the function would be done to the local variables of the function. When we use pointers, the value is changed at the address of variable

78

Programming in C

#include void salaryhike(int *var, int b) { *var = *var+b; } int main() { int salary=0, bonus=0; printf("Enter the employee current salary:"); scanf("%d", &salary); printf("Enter bonus:"); scanf("%d", &bonus); salaryhike(&salary, bonus); printf("Final salary: %d", salary); return 0; } Output:

Enter the employee current salary:10000 Enter bonus:2000 Final salary: 12000 Example 2: Swapping two numbers using Pointers

This is one of the most popular example that shows how to swap numbers using call by reference.

Try this program without pointers, you would see that the numbers are not swapped. The reason is same that we have seen above in the first example.

#include void swapnum(int *num1, int *num2) { int tempnum;

tempnum = *num1; *num1 = *num2; *num2 = tempnum; } int main( ) { int v1 = 11, v2 = 77 ; printf("Before swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2);

/*calling swap function*/ 79

Programming in C

swapnum( &v1, &v2 );

printf("\nAfter swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2); } Output:

Before swapping: Value of v1 is: 11 Value of v2 is: 77 After swapping: Value of v1 is: 77 Value of v2 is: 11

4.3 DEFINING AND PROCESSING A STRUCTURE 4.3.1 C Programming Structure Structure is an user defined data type available in C that allows to combine data items of different kinds. Structures are used to represent a record. Structure is the collection of variables of different types under a single name. Eg: Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book –Title, Author, Subject, Book ID Structure Definition in C Keyword struct is used for creating a structure. Syntax of structure struct structure_name { data_type member1; data_type member2; . data_type memeber; }; We can create the structure for a person as mentioned above as: struct person { char name[50]; int cit_no; float salary; }; This declaration above creates the derived data type struct person. Structure variable declaration When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as: struct person

80

Programming in C

{ char name[50]; int cit_no; float salary; };

Inside main function: struct person p1, p2, p[20]; Another way of creating sturcture variable is: struct person { char name[50]; int cit_no; float salary; }p1 ,p2 ,p[20]; In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created. Accessing members of a structure There are two types of operators used for accessing members of a structure. 1. Member operator(.) 2. Structure pointer operator(->) Any member of a structure can be accessed as:structure_variable_name.member_name Suppose, we want to access salary for variable p2. Then, it can be accessed as: p2.salary

Example of structure Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot) #include struct Distance{ int feet; float inch; }d1,d2,sum; Void main(){ printf("1st distance\n"); printf("Enter feet: "); scanf("%d",&d1.feet); /* input of feet for structure variable d1 */ printf("Enter inch: "); scanf("%f",&d1.inch); /* input of inch for structure variable d1 */ printf("2nd distance\n"); printf("Enter feet: "); scanf("%d",&d2.feet); /* input of feet for structure variable d2 */ printf("Enter inch: "); scanf("%f",&d2.inch); /* input of inch for structure variable d2 */ sum.feet=d1.feet+d2.feet; 81

Programming in C

sum.inch=d1.inch+d2.inch; if (sum.inch>12){ //If inch is greater than 12, changing it to feet. ++sum.feet; sum.inch=sum.inch-12; } printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); } Output

1st distance Enter feet: 12 Enter inch: 7.9 2nd distance Enter feet: 2 Enter inch: 9.8 Sum of distances= 15'-5.7" 4.3.2 Structure and Pointer

Pointers can be accessed along with structures. A pointer variable of structure can be created as, struct name { member1; member2; . };

Inside function struct name *ptr; Here, the pointer variable of type struct name is created. Structure's member through pointer can be used in two ways: 1. Referencing pointer to another address to access memory 2. Using dynamic memory allocation Consider an example to access structure's member through pointer. #include struct name{ int a; float b; }; int main(){ struct name *ptr,p; ptr=&p; /* Referencing pointer to memory address of p */ printf("Enter integer: "); scanf("%d",&(*ptr).a); printf("Enter number: "); 82

Programming in C

scanf("%f",&(*ptr).b); printf("Displaying: "); printf("%d%f",(*ptr).a,(*ptr).b); return 0; } In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed. Structure pointer member can also be accessed using -> operator. (*ptr).a is same as ptr->a (*ptr).b is same as ptr->b Accessing structure member through pointer using dynamic memory allocation To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file. Syntax to use malloc() ptr=(cast-type*)malloc(byte-size) Example to use structure's member through pointer using malloc() function. #include #include struct name { int a; float b; char c[30]; }; int main(){ struct name *ptr; int i,n; printf("Enter n: "); scanf("%d",&n); ptr=(struct name*)malloc(n*sizeof(struct name)); /* Above statement allocates the memory for n structures with pointer ptr pointing to base address */ for(i=0;ic,&(ptr+i)->a,&(ptr+i)->b); } printf("Displaying Infromation:\n"); for(i=0;ic,(ptr+i)->a,(ptr+i)->b); return 0; } Output

Enter n: 2 Enter string, integer and floating number respectively: Programming 2 83

Programming in C

3.2 Enter string, integer and floating number respectively: Structure 6 2.3 Displaying Information Programming 2 3.20 Structure 6 2.30 4.3.3 Structure and Function

In C, structure can be passed to functions by two methods: 1. Passing by value (passing actual value as argument) 2. Passing by reference (passing address of an argument) Passing structure by value A structure variable can be passed to the function as an argument as normal variable. If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function. Write a C program to create a structure student, containing name and roll. Ask user the name and roll of a student in main function. Pass this structure to a function and display the information in that function. #include struct student{ char name[50]; int roll; }; void Display(struct student stu); /* function prototype should be below to the structure declaration otherwise compiler shows error */ int main(){ struct student s1; printf("Enter student's name: "); scanf("%s",&s1.name); printf("Enter roll number:"); scanf("%d",&s1.roll); Display(s1); // passing structure variable s1 as argument return 0; } void Display(struct student stu){ printf("Output\nName: %s",stu.name); printf("\nRoll: %d",stu.roll); } Output

Enter student's name: Kevin Amla Enter roll number: 149 Output

84

Programming in C

Name: Kevin Amla Roll: 149

Passing structure by reference

The address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function. Write a C program to add two distances(feet-inch system) entered by user. To solve this program, make a structure. Pass two structure variable (containing distance in feet and inch) to add function by reference and display the result in main function without returning it. #include struct distance{ int feet; float inch; }; void Add(struct distance d1,struct distance d2, struct distance *d3); int main() { struct distance dist1, dist2, dist3; printf("First distance\n"); printf("Enter feet: "); scanf("%d",&dist1.feet); printf("Enter inch: "); scanf("%f",&dist1.inch); printf("Second distance\n"); printf("Enter feet: "); scanf("%d",&dist2.feet); printf("Enter inch: "); scanf("%f",&dist2.inch); Add(dist1, dist2, &dist3);

/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference */ printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch); return 0; } void Add(struct distance d1,struct distance d2, struct distance *d3) { /* Adding distances d1 and d2 and storing it in d3 */ d3->feet=d1.feet+d2.feet; d3->inch=d1.inch+d2.inch; if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */ d3->inch-=12; ++d3->feet; } 85

Programming in C

} Output

First distance Enter feet: 12 Enter inch: 6.8 Second distance Enter feet: 5 Enter inch: 7.5 Sum of distances = 18'-2.3"

Explanation In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e., address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If any change is made in d3 variable, effect of it is seed indist3 variable in main function.

4.4 UNION A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. 4.4.1 Defining a Union The union statement defines a new data type with more than one member for your program. The format of WKHXQLRQVWDWHPHQWLVDVIROORZVí union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type QDPHG'DWDKDYLQJWKUHHPHPEHUVLIDQGVWUí union Data { int i; float f; char str[20]; } data; Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the

86

Programming in C maximum space which can be occupied by a character string. The following example displays the total memory size occupied by the above uQLRQí #include #include union Data { int i; float f; char str[20]; }; void main( ) { union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data)); } When the above code is compiled and executeGLWSURGXFHVWKHIROORZLQJUHVXOWí Memory size occupied by data : 20 Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use XQLRQVLQDSURJUDPí #include #include union Data { int i; float f; char str[20]; }; int main( ) { union Data data;

data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str);

return 0; } WheQWKHDERYHFRGHLVFRPSLOHGDQGH[HFXWHGLWSURGXFHVWKHIROORZLQJUHVXOWí data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming 87

Programming in C

Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main SXUSRVHRIKDYLQJXQLRQVí #include #include union Data { int i; float f; char str[20]; }; void main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i);

data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); } :KHQWKHDERYHFRGHLVFRPSLOHGDQGH[HFXWHGLWSURGXFHVWKHIROORZLQJUHVXOWí data.i : 10 data.f : 220.500000 data.str : C Programming Here, all the members are getting printed very well because one member is being used at a time.

4.5 BIT FIELDS

Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, DVIROORZVí struct { unsigned int widthValidated; unsigned int heightValidated; } status; This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of the variables. The C programming language offers a better way to utilize the memory space in such situations. If you are using such variables inside a structure then you can define the width of a variable which tells the C compiler that you are going to use only those number of bytes. For example, the above structure can be re- written as IROORZVí struct {

88

Programming in C

unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status; The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to store the values. If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4 bytes. However as soon as you have 33 variables, it will allocate the next slot of the memory and it will start using 8 bytes. Let us check the following example to understand tKHFRQFHSWí #include #include /* define simple structure */ struct { unsigned int widthValidated; unsigned int heightValidated; } status1;

/* define a structure with bit fields */ struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2; void main( ) { printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2)); return 0; } When the above code is compiled and exHFXWHGLWSURGXFHVWKHIROORZLQJUHVXOWí Memory size occupied by status1 : 8 Memory size occupied by status2 : 4 Bit Field Declaration The declaration of a bit-ILHOGKDVWKHIROORZLQJIRUPLQVLGHDVWUXFWXUHí struct { type [member_name] : width ; }; 7KHIROORZLQJWDEOHGHVFULEHVWKHYDULDEOHHOHPHQWVRIDELWILHOGí Elements Description type An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int, or unsigned int. member_name The name of the bit-field. width The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type. The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a ZLGWKRIELWVDVIROORZVí struct { 89

Programming in C

unsigned int age : 3; } Age; The above structure definition instructs the C compiler that the age variable is going to use only 3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to do so. Let us try the following H[DPSOHí #include #include struct { unsigned int age : 3; } Age; int main( ) { Age.age = 4; printf( "Sizeof( Age ) : %d\n", sizeof(Age) ); printf( "Age.age : %d\n", Age.age );

Age.age = 7; printf( "Age.age : %d\n", Age.age );

Age.age = 8; printf( "Age.age : %d\n", Age.age ); } When the above code is compiled it will compile with a warning and when executed, it produces the IROORZLQJUHVXOWí Sizeof( Age ) : 4 Age.age : 4 Age.age : 7 Age.age : 0

4.6 Enumeration An enumeration is a user-defined data type consists of integral constants and each integral constant is give a name. Keyword enum is used to defined enumerated data type. enum type_name{ value1, value2,...,valueN }; Here, type_name is the name of enumerated data type or tag. And value1,value2,....,valueN are values of type type_name. By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value. // Changing the default value of enum elements enum suit{ club=0; diamonds=10; hearts=20; spades=3; };

90

Programming in C

Declaration of enumerated variable Above code defines the type of the data but, no any variable is created. Variable of type enum can be created as: enum boolean{ false; true; }; enum boolean check; Here, a variable check is declared which is of type enum boolean. Example of enumerated type #include enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday}; int main(){ enum week today; today=wednesday; printf("%d day",today+1); return 0; } Output 4 day You can write any program in C language without the help of enumerations but, enumerations helps in writing clear codes and simplify programming.

UNIT V

5.1 FILES In C programming, file is a place on disk where a group of related data is stored. Why files are needed? When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands. There are large numbers of functions to handle file I/O in C language. File Operations 1. Creating a new file 2. Opening an existing file 3. Reading from and writing information to a file 4. Closing a file Working with file While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program. FILE *ptr; 5.1.1 Opening a file Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is: 91

Programming in C

The fopen() function is used to create a new file or to open an existing file. General Syntax : *fp = FILE *fopen(const char *filename, const char *mode); Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file. ptr=fopen("fileopen","mode")

For Example: fopen("E:\\cprogram\program.txt","w");

/* E:\\cprogram\program.txt is the location to create file. "w" represents the mode for writing. */ Here, the program.txt file is opened for writing mode. Opening Modes in Standard I/O File Mode Meaning of Mode During Inexistence of file r Open for reading. If the file does not exist, fopen() returns NULL. w Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a Open for append. i.e, Data is added to end of file. If the file does not exists, it will be created. r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL. w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a+ Open for both reading and appending. If the file does not exists, it will be created. 5.1.2 Closing a File The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose(). fclose(ptr); //ptr is the file pointer associated with file to be closed. The Functions fprintf() and fscanf() functions. The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE Writing to a file #include int main() { int n; FILE *fptr; fptr=fopen("C:\\program.txt","w"); if(fptr==NULL){ printf("Error!"); exit(1); } printf("Enter n: "); scanf("%d",&n); fprintf(fptr,"%d",n);

92

Programming in C

fclose(fptr); return 0; } This program takes the number from user and stores in file. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open that file, you can see the integer you entered. Similarly, fscanf() can be used to read data from file. 5.1.3 Reading from file

#include int main() { int n; FILE *fptr; if ((fptr=fopen("C:\\program.txt","r"))==NULL){ printf("Error! opening file"); exit(1); /* Program exits if file pointer returns NULL. */ } fscanf(fptr,"%d",&n); printf("Value of n=%d",n); fclose(fptr); return 0; } If you have run program above to write in file successfully, you can get the integer back entered in that program using this program.

5.2 COMMAND LINE PARAMETERS

It is possible to pass some values from the command line to your C programs when they are executed. These values are calledcommand line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and WDNHDFWLRQDFFRUGLQJO\í #include int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else {

93

Programming in C

printf("One argument expected.\n"); } } When the above code is compiled and executed with single argument, it produces the following result. $./a.out testing The argument supplied is testing When the above code is compiled and executed with a two arguments, it produces the following result. $./a.out testing1 testing2 Too many arguments supplied. When the above code is compiled and executed without passing any argument, it produces the following result. $./a.out One argument expected It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argcis set at 2. You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by SXWWLQJLQVLGHGRXEOHTXRWHVí #include int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result. $./a.out "testing1 testing2" Program name ./a.out The argument supplied is testing1 testing2

5.3 Register Variables:

A register is a small data storage location inside the processor, most of the time registers are used to hold memory locations, arithmetic/logical instructions etc. Registers can hold up to 64-bit data depending upon the processor.

94

Programming in C

C provides six operators for bit manipulation.[1]

Symbol Operator & bitwise AND | bitwise inclusive OR ^ bitwise XOR (exclusive OR) << left shift >> right shift ~ bitwise NOT (one's complement) (unary) Bitwise AND &[edit] bit a bit b a & b (a AND b) 0 0 0 0 1 0 1 0 0 1 1 1 The bitwise AND operator is a single ampersand: &. It is just a representation of AND which does its work on the bits of the operands rather than the truth value of the operands. Bitwise binary AND does the logical AND (as shown in the table above) of the bits in each position of a number in its binary form. For instance, working with a byte (the char type):

11001000 & 10111000 ------= 10001000 The most significant bit of the first number is 1 and that of the second number is also 1 so the most significant bit of the result is 1; in the second most significant bit, the bit of second number is zero, so we have the result as 0. [2]

Bitwise OR |[edit] bit a bit b a | b (a OR b) 0 0 0 0 1 1 1 0 1 1 1 1 Similar to bitwise AND, bitwise OR only operates at the bit level. Its result is a 1 if one of the either bits is 1 and zero only when both bits are 0. Its symbol is | which can be called a pipe.

11001000 | 10111000 ------= 11111000 [2]

Bitwise XOR ^[edit] bit a bit b a ^ b (a XOR b) 96

Programming in C

0 0 0 0 1 1 1 0 1 1 1 0 The bitwise XOR (exclusive or) performs a logical XOR function, which is equivalent to adding two bits and discarding the carry. The result is zero only when we have two zeroes or two ones.[3] XOR can be used to toggle the bits between 1 and 0. Thus i = i ^ 1 when used in a loop toggles its values between 1 and 0.[4]

11001000 ^ 10111000 ------= 01110000 Bitwise NOT ~ / ones' complement (unary)[edit] bit a ~a (complement of a) 0 1 1 0 The ones' complement (~) or the bitwise complement gets us the complement of a given number. Thus we get the bits inverted, for every bit 1 the result is bit 0 and conversely for every bit 0 we have a bit 1. This operation should not be confused with logical negation !.

~ 11001000 ------= 00110111 Shift operators[edit] There are two bitwise shift operators. They are

Right shift (>>) Left shift (<<) Right shift >>[edit] The symbol of right shift operator is >>. For its operation, it requires two operands. It shifts each bit in its left operand to the right. The number following the operator decides the number of places the bits are shifted (i.e. the right operand). Thus by doing ch >> 3 all the bits will be shifted to the right by three places and so on.

Example:

If the variable ch contains the bit pattern 11100101, then ch >> 1 will produce the result 01110010, and ch >> 2 will produce 00111001. Here blank spaces are generated simultaneously on the left when the bits are shifted to the right. When performed on an unsigned type, the operation performed is a logical shift, causing the blanks to be filled by 0s (zeros). When performed on a signed type, the result is technically undefined and compiler dependent,[5] however most compilers will perform an arithmetic shift, causing the blank to be filled with the sign bit of the left operand.

Right shift can be used to divide a bit pattern by 2 as shown: 97

Programming in C

i = 14; // Bit pattern 00001110 j = i >> 1; // here we have the bit pattern shifted by 1 thus we get 00000111 = 7 which is 14/2 Right shift operator usage[edit] Typical usage of a right shift operator in C can be seen from the following code.

Example:

#include void showbits(unsigned int x) { for(int i = (sizeof(int) * 8) - 1; i >= 0; i--) { (x & (1u << i)) ? putchar('1') : putchar('0'); } printf("\n"); } int main() { int j = 5225; printf("%d in binary \t\t ", j); /* assume we have a function that prints a binary string when given a decimal integer */ showbits(j);

/* the loop for right shift operation */ for (int m = 0; m <= 5; m++) { int n = j >> m; printf("%d right shift %d gives ", j, m); showbits(n); } return 0; }

The output of the above program will be

5225 in binary 00000000000000000001010001101001 5225 right shift 0 gives 00000000000000000001010001101001 5225 right shift 1 gives 00000000000000000000101000110100 5225 right shift 2 gives 00000000000000000000010100011010 5225 right shift 3 gives 00000000000000000000001010001101 5225 right shift 4 gives 00000000000000000000000101000110 5225 right shift 5 gives 00000000000000000000000010100011 Left shift <<[edit]

98

Programming in C

The symbol of left shift operator is <<. It shifts each bit in its left-hand operand to the left by the number of positions indicated by the right-hand operand. It works opposite to that of right shift operator. Thus by doing ch << 1 in the above example we have 11001010. Blank spaces generated are filled up by zeroes as above.

Left shift can be used to multiply an integer by powers of 2 as in int i = 4; /* bit pattern equivalent is binary 100 */ int j = i << 2; /* makes it binary 10000, which multiplies the original number by 4 i.e. 16 */ A simple addition program Example[edit] The following program adds two operands using AND, XOR and left shift (<<).

#include int main() { unsigned int x = 3, y = 1, sum, carry; sum = x ^ y; // x XOR y carry = x & y; // x AND y while (carry != 0) { carry = carry << 1; // left shift the carry x = sum; // initialize x as sum y = carry; // initialize y as carry sum = x ^ y; // sum is calculated carry = x & y; /* carry is calculated, the loop condition is evaluated and the process is repeated until carry is equal to 0. */ } printf("%u\n", sum); // the program will print 4 return 0; } Bitwise assignment operators[edit] C provides a compound assignment operator for each binary arithmetic and bitwise operation (i.e. each operation which accepts two operands). Each of the compound bitwise assignment operators perform the appropriate binary operation and store the result in the left operand.[6]

The bitwise assignment operators are as follows:

Symbol Operator &= bitwise AND assignment |= bitwise inclusive OR assignment ^= bitwise exclusive OR assignment <<= left shift assignment >>= right shift assignment

99

Programming in C

5.5 MACROS

A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the preprocessor directive, #define.

The advantage of using macro is the execution speed of the program fragment. When the actual code snippet is to be used, it can be substituted by the name of the macro. The same block of statements, on the other hand, need to be repeatedly hard coded as and when required.

The disadvantage of the macro is the size of the program. The reason is, the pre-processor will replace all the macros in the program by its real definition prior to the compilation process of the program.

Lets understand the concept of macros using some example codes.

Defining Macros without values

The most basic use of macros is to define them without values and use them as testing conditions. As an example, lets look at the following piece of code :

#include #define MACRO1 #define MACRO2 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined\n"); #endif #ifdef MACRO2 // test whether MACRO2 is defined... printf("\nMACRO2 Defined\n"); #endif return 0; }

So, the above code just defines two macros MACRO1 and MACRO2. As clear from the definition, the macros are without any values Inside the main function, the macros are used only in testing conditions. Now, if we look at the output, we will see :

$ ./macro MACRO1 Defined MACRO2 Defined

Since both of the macros are defined so both the printf statements executed.

100

Programming in C

Now, one would question where are these testing macros used. Well, mostly these type of testing macros are used in a big project involving many source and header files. In such big projects, to avoid including a single header more than once (directly and indirectly through another header file) a macro is defined in the original header and this macro is tested before including the header anywhere so as to be sure that if the macros is already defined then there is no need to include the header as it has already been included (directly or indirectly).

5.5.1 Defining Macros through command line.

Another use of testing macros is where we want to enable debugging (or any other feature) in a code while compilation. In this case, a macro can be defined through compilation statement from command line. This definition of macro is reflected inside the code and accordingly the code is compiled.

As an example, I modified the code used in example of the last section in this way :

#include #define MACRO1 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined\n"); #endif

#ifdef MACRO2 // test whether MACRO2 is defined... printf("\nMACRO2 Defined\n"); #endif return 0; }

So now only MACRO1 is defined While MACRO2 is also being used under a condition. If the above program is now compiled and run, we can see the following output :

$ ./macro MACRO1 Defined

So we see that since only MACRO1 is defined so condition related to MACRO1 executed. Now, if we want to enable or define MACRO2 also then either we can do it from within the code (as shown in first example) or we can define it through the command line. The command for compilation of the code in that case becomes :

$ gcc -Wall -DMACRO2 macro.c -o macro and now if we run the code, the output is :

101

Programming in C

$ ./macro MACRO1 Defined MACRO2 Defined

So we see that MACRO2 got defined and hence the printf under the MACRO2 condition got executed.

Macros with values As discussed in the introduction, there are macros that have some values associated with them. For example : #define MACRO1 25 So, in the above example, we defined a macro MACRO1 which has value 25. The concept is that in the preprocessing stage of the compilation process, the name of this macro is replaced with macros value all over the code. For example :

#include #define MACRO1 25 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined with value [%d]\n", MACRO1); #endif return 0; } So in the code above, a value of 25 is given to the macro MACRO1. When the code above is run, we see the following output :

$ ./macro MACRO1 Defined with value [25]

So we see that the macro name (MACRO1) was replaced by 25 in the code.

Defining macros with values from command line

Not only the macros can be defined from command line (as shown in one of the sections above) but also they can be given values from command line. Lets take the following example :

#include int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined with value [%d]\n", MACRO1); #endif return 0; }

In the code above, the macro MACRO1 is being tested and its value is being used but it is not defined anywhere. Lets define it from the command line :

102

Programming in C

$ gcc -Wall -DMACRO1=25 macro.c -o macro $ ./macro MACRO1 Defined with value [25] So we see that through the command line option -D[Macroname]=[Value] it was made possible. Macros with piece of code as their values As discussed in the introduction part, macros can also contain small piece of code as their values. Those piece of code which are very small and are being used repetitively in the code are assigned to macros. For example :

#include #define MACRO(x) x * (x+5) int main(void) { #ifdef MACRO // test whether MACRO1 is defined... printf("\nMACRO Defined...\n"); #endif int res = MACRO(2); printf("\n res = [%d]\n", res); return 0; }

So, In the code above we defined a parameterized macro that accepts a value and has a small piece of code associated with it. This macro is being used in the code to calculate value for the variable ‘res’.When the above code is compiled and run, we see :

$ ./macro MACRO Defined... res = [14] So we see that a parameterized macro (that has a small piece of code logic associated with it) was used to calculate the value for ‘res’.

5.6 Introduction to Preprocessor The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre- processing before the actual compilation. We'll refer to the C Preprocessor as CPP. A program which processes the source code before it passes through the compiler is known as preprocessor. The commands of the preprocessor are known as preprocessor directives. It is placed before the main(). It begins with a # symbol. They are never terminated with a semicolon. Preprocessor Directives The preprocessor directives are divided into four different categories which are as follows:

103

Programming in C

1. Macro expansion There are two types of macros - one which takes the argument and another which does not take any argument. Values are passed so that we can use the same macro for a wide range of values.

Syntax: #define name replacement text

Where, name – it is known as the micro . replacement text – it is known as the macro expansion.

A macro name is generally written in capital letters. If suitable and relevant names are given macros increase the readability. If a macro is used in any program and we need to make some changes throughout the program we can just change the macro and the changes will be reflected everywhere in the program. Example : Simple macro

#define LOWER 30 void main() { int i; for (i=1;i<=LOWER; i++) { printf("\n%d", i); } }

Example : Macros with arguments

#define AREA(a) (3.14 * a * a) void main() { float r = 3.5, x; x = AREA (r); printf ("\n Area of circle = %f", x); } Some of the predefined macros which are readily available are as follows:

Macro Description ___LINE___ It contains a current line number as a decimal constant. ___FILE___ It contains the current filename as a string literal. ___DATE___ It shows the current date as a character literal in the “MMM YYYY” format. ___TIME___ It shows the current time as a character literal in “HH:MM:SS” format. ___STDC___ It is defined as 1 when the compiler complies with the ANSI standard. 104

Programming in C

___TIMESTAMP___ It is a sing literal in the form of “DDD MM YYYY Date HH:MM:SS”. It is used to specify the date and time of the last modification of the current source file.

2. File inclusion

The file inclusion uses the #include. Syntax: #include filename

The content that is included in the filename will be replaced at the point where the directive is written. By using the file inclusive directive, we can include the header files in the programs. Macros, function declarations, declaration of the external variables can all be combined in the header file instead of repeating them in each of the program. The stdio.h header file contains the function declarations and all the information regarding the input and output.

There are two ways of the file inclusion statement: i) #include “file-name” ii) #include

If the first way is used, the file and then the filename in the current working directory and the specified list of directories would be searched. If the second way, is used the file and then the filename in the specified list of directories would be searched. 3. Conditional compilation The conditional compilation is used when we want certain lines of code to be compiled or not. It uses directives like #if, #elif, #else, #endif

Syntax

#if TEST <= 5 statement 1; statement 2; #else statement 3; statement 4; #endif

If there are a number of conditions to be checked we can use the #elif instead of #else and #if.

3. Miscellaneous directive There are some directives which do not fall in any of the above mentioned categories.

There are two directives: i) #undef : This directive is used in relation to the #define directive. It is used to undefined a defined macro. 105

Programming in C ii) #pragma : It is a specialized and rarely used directive. They are used for turning on and off certain features.

Summary of preprocessor directives

Following table will show you various directives that we have studied in this chapter:

Directives Description #define It substitutes a preprocessor macro. #include It inserts a particular header file from another file. #undef A preprocessor macro is undefined. #ifdef It returns true if the macro is defined. #ifndef It returns true if the macro is not defined. #if It tests if the compile time condition is true. #else It is an alternative for #if. #elif It has #else and #if in one statement. #endif The conditional preprocessor is ended. #error It prints the error message on stderr. #pragma It issues special commands to the compiler by using a standardized method.

106