Top Banner
Chapter 1 Overview of “C” The root of all modern programming language is ALGO, it is introduced in 1960. ALGO gave the new concept of the structure programming. Subsequently varies languages are announced. In 1967 Martin Richards developed a language called BCPL( Basic Combined Programming Language) . In 1970, Ken Thompson created a language using many features of BCPL and it simply called B language. Both BCPL and B was “type less” system programming language. C language was developed by Dennis Ritchie at the Bell Laboratories in 1972. C language uses many features of the ALGO, BCPL and B Languages. It also added new concepts of the “data type” and many powerful features. Unix operating system is totally coded in C language.
260

C presentation book

Sep 13, 2014

Download

Education

c language full information on it and it is like book it is very halpful to lurn c language
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: C presentation book

Chapter 1 Overview of “C”

• The root of all modern programming language is ALGO, it is introduced in 1960. ALGO gave the new concept of the structure programming. Subsequently varies languages are announced.

• In 1967 Martin Richards developed a language called BCPL( Basic Combined Programming Language) .

• In 1970, Ken Thompson created a language using many features of BCPL and it simply called B language.Both BCPL and B was “type less” system programming language.

• C language was developed by Dennis Ritchie at the Bell Laboratories in 1972. C language uses many features of the ALGO, BCPL and B Languages. It also added new concepts of the “data type” and many powerful features. Unix operating system is totally coded in C language.

Page 2: C presentation book

• In 1983 American National Standard Institute (ANSI) appoint a technical committee to define a standard of C.

• The committee approved a version of c in December 1989 which is now known as ANSI C

• It was the approved by the International Standards Organization (ISO) in 1990.This version of the c is also referred as C89

Importance of the C language:• It is Robust Language. It’s rich set of bit in function and

operator can be used to write any complex program.

• The C Compiler combines the features of the assembly language and high level language so it is suitable for both system software and business package.

Page 3: C presentation book

• Programs written in C languages are very efficient and fast because of its variety of data types and powerful operators.

• There are several inbuilt functions which is used to build any program.

• There are 32 keywords in C Which is used to make the program.

• C is highly portable language.

• C language is suitable for structure programming. This modular structure makes program debugging, testing and maintenance easier.

• The ability to extend itself. It means we can add our own functions into the c library

Page 4: C presentation book

Sample Program for C language to print hello.

/* Write the Program to Print the Hello */

#include<stdio.h>#include<conio.h>void main(){

clrscr();printf (“Hello world”);getch();

}Alt + f9 -> To compile the programCtrl + f9 -> To run the program

Page 5: C presentation book

Basic Structure of the c program:

Documentation Section

Link Section

Definition Section

Global Declaration Section

Main () Function Section

{

Declaration Part

Executable Part

}Sub Program Section

Function 1

Function 2 etc..

Page 6: C presentation book

Executing a C Program :

• Executing a Program C Involves a Series of Steps :• Creating a Program• Compile the Program• Linking the Program with functions that are needed from

the C library• Executing the Program

Page 7: C presentation book

Enter the Program Code

Compile Program with Compiler

Syntax Error

Link with System Library

Execute Object Code

Generate the Output

No

Yes

Edit the Source Program

Executable Object Code

Object Code

Page 8: C presentation book

Chapter : 2 Constants, Variable and Data Types

Introduction :-The Sequence of the Instruction written to perform specific task is called the Program.

This Instructions are formed using special symbols and words according to some rigid rule is known as syntax rules.

Every Instruction must be written according to the syntax rule of the languages.

Like any other languages C languages has its vocabulary and grammar. They are follow up for making the program.

In this Chapter we will discuss about various constants, variables and data types are used in C Programming.

Page 9: C presentation book

Character Set :• Character Set is the set of the character.• This characters are used to form the word, numbers and

expression.• The characters in the c are grouped into the following

categories.

LettersDigitsSpecial charactersWhite Spaces.

Letters : Uppercase A…Z, Lowercase a…zDigits : All decimal digits 0 to 9Special Character : ,(comma) .(period) ; (semicolon)

: (colon), & (ampersand), # (number sign) etc.White spaces : Blank Space, Horizontal Space, New Line.

Page 10: C presentation book

Trigraph Characters:

• Many Non – English Keywords don’t support all the characters mentioned in character set.

• ANSI C Introduce the concept “trigraph” Sequences to enter special character that are not available on some keyboard.

• Each trigraph sequence consists of three characters (two question mark followed by a character)

Trigraph Sequence Translation??= # nubersign??( [ left bracket??) ] right bracket??< { left braces??> } Right braces

Page 11: C presentation book

C Tokens:Smallest Individual units are known as C Tokens.There are six types of the C Tokens.

• Keywords• Identifiers• Constants• String• Special Symbols• Operators.

Keywords:• Every C word is classified as either keyword or identifier. • All keywords have fixed meanings and you can not change

its meanings. • Keywords serve as a basic building blocks for program

statement. ANSI C supports 32 keywords that are listed in ANSI C book.

Page 12: C presentation book

Ex: int, float, double, extern, static, auto, continue, if, goto short, long etc. are the keywords

Identifiers:• Identifiers refer to the names of variables, functions and

arrays.• These are user defined names and consists of sequence of

letters and digits.• Both uppercase and lowercase letters are permitted to

make the identified but generally lowercase letters are used to make the variable.

Rules for Identifiers:• First character must be alphabet• Must not contain white space• Only first 31 characters are significant• Can not use keyword as a identifier

Page 13: C presentation book

Constants:Constants referred as a fixed value that don't change during the execution of the program.

C Support Several types of constants:

Constants

Numeric ConstantsInteger constantsReal Constants

Character ConstantsSingle Character ConstantsString Constants

Page 14: C presentation book

Integer Constants:

An integer constants refers as a sequence of digits.There are three types of integer constants.

• Decimal Integer• Octal Integer• Hexadecimal

Decimal Integer : It consists of 0-9 digits, preceded by an optional – or

+ sign.Valid example of decimal integer are :123 , -321, 0 , 654321, +78

Embedded spaces, comma and non digit characters are not permitted between digits.15 750, 20,000, $1000 are Illegal

Page 15: C presentation book

Octal Integer: An Octal Integers consists of digits 0-7 with a leading 0.Ex:037, 0, 0435, 0551

Hexadecimal Integer:A sequence of digits preceded by 0x or OX is considered as Hexadecimal Integer.Hexadecimal Integer includes 0 to 9 digits and A to F letters.Ex: 0x9, 0x9F, OXbcd etc are valid.

Real Constants:Integer numbers are inadequate to represent quantities such as distance, heights, temperature, price and so on. These quantities are represented by a number containing fractional parts like 12.32. Such numbers are called real constants

Page 16: C presentation book

These numbers having a whole number followed by a decimal digits.ex: 0.85, -0.75, 85.45, +241.54It is possible to omit the digit before the decimal digit and after the decimal digit.ex: 215., .23 , -.71 , +54.

A real number may also be expressed in exponential (Scientific) notation.

General form : mantissa e exponent

The mantissa is either a real number or integer number.Exponent is an integer number with + or – sign.The letter e separating mantissa and exponent can be written either in lowercase or in uppercase letter.

Page 17: C presentation book

ex : 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiple by 102

75000 written as 7.5E4 or 7.5E+4-0.00038 written as -3.8e-4

Comma, White space and dollar space is not permitted in digits.25,0.000 , 7.1 e 4 , 1.5 E 2.5 (exponent must be an integer),$255.

Single character constants:A single character constant contains a single character enclosed with a pair of single quotation mark (‘ ’).

ex: ‘5’, ‘x’, ‘;’ , ‘ ’

Note that character constant ‘5’ is not same as number 5.character constant have a integer value known as ASCII value

Page 18: C presentation book

ex : printf (“%d”, ‘a’) would print the number 97.printf(“%c”, ‘97’) would print the letter a.

String Constants :A String Constant is a sequence of characters enclosed in double quotation mark.

ex: “Hello” , “1987”, “Well Done”, “X”Note : A single String constant does not have an equivalent integer value, while a character constant has an equivalent integer value.

Backslash character constant:Backslash character constant are used in output function.

ex: ‘\n’ – new line, ‘\t’ – horizontal tab, ‘\’’-single quote etc.

Page 19: C presentation book

VARIABLE :A variable is a data name that may be used to store a data value.Unlike constants that remain unchanged during the execution of the program, a variable may take different value at different time.

Rules to declare a variable :• They must begin with letter• variable length must be 31 character significant.• Both lowercase and uppercase letters are distinct. ex Total and

total are not same• It should not be a keyword• White space, Dollar sign are not allowed.

ex: John, delhi, First_tag, int_type ---- validPrice$, char, group one, 123, 25th, (area) ------- Invalid

Page 20: C presentation book

Declaration of Variable:

Syntax : data_type v1,v2,v3….vn ;where v1,v2..vn are different variable name.

Ex: int count;int number, total;double ratio;float price;char c;where int, double, float and char are data type.

Assign Value to a Variable :Assignment operator (=) is used to assign value to a variable.Ex: price = 12.50; ratio = 12.2345; number=12;

c=‘a’;

Page 21: C presentation book

Data Types:C language is rich in its data types:

ANSI C support three classes of data types.1. Primary Data Type2. Derived Data Type3. User-Defined Data Type.

Page 22: C presentation book

Primary Data Type :

Integral Type

Integer CharacterSigned

int

short int

Long int

Unsigned

unsigned int

unsigned short int

unsigned Long int

char

signed char

unsigned char

Floating Point Type

float double long double void

Page 23: C presentation book

All C compiler support five fundamental data types, namely integer(int), character(char), floating point(float), double-precision floating point(double) and void.

Integer types:

• Integers are whole numbers with a range of values supported by a particular machine.

• There are signed integer and unsigned integer. Signed integer uses one bit for sign and 15 bits for magnitude of the number. Unsigned integers are always positive. It does not contain any bit for sign so that it occupies all the bit for the magnitude of the number. (Note : For 16 bit machine)

• By using equation -2n to +2n-1 we can find out the range of the number. Where n is the number of bits.

Page 24: C presentation book

• To provide some control over the range of number and storage space, C has three classes of integer storage, namely short int, int and long int in both signed and unsigned forms.

Size and Range of Data Type on a 16-bit machine.

Type size(bits) Range

int or signed int 16 -215 to 215 -1 unsigned int 16 0 to 216-1short int or 8 -27 to 27 -1 signed short int unsigned short int 8 0 to 28 -1long int or 32 -231 to 231 -1 signed long intunsigned long int 32 0 to 232 -1

Page 25: C presentation book

Floating Point Types:

• Floating point numbers are stored in 32 bits (on all 16bit and 32 bit machines) with 6 digits of precision.

• Floating point numbers are defined in C by the keyword float.• When the accuracy provided by float is not sufficient double

data type is used. It uses 64 bits giving a precision of 14 digits.

• When you want to extend more precision you can use the long double data type. it uses 80 bits

Type size(bits) Rangefloat 32 3.4E-38 to 3.4E+38double 64 1.7E-308 to

1.7E+308long double 80 3.4E-4932 to

1.1E+4932

Page 26: C presentation book

Void Types :• Void type has no values.• Void type does not return any values.

Character Type:• Character type data type is char.• It’s storage is 8bit to store a bit.• The qulifier signed and unsigned explicitly applied on

character type

Type size (bits) rangechar or signed char 8 -27 to 27 -1 unsigned char 8 0 to 28 -1

Page 27: C presentation book

Note :Integer constants by default represent int data type. We can override this default by specifying unsigned or long after the number (by appending U or L).ex:Literal Type value+111 int 111-222 int 22245678U unsigned int 45,678-56789L long int 56,789987654UL unsigned long int 9,87,654

similarly floating point constants by default it will take double data type. To override we must append f or F for float type and l or L for long double type.ex: Literal Type value1.234 double 1.234-1.2f float -1.21.23456789L long double 1.23456789

Page 28: C presentation book

/* Program To Show the declaration, assignments and values stored in varies types of variables */

#include<stdio.h>#include<conio.h>void main(){

float x; double q ; unsigned k ; int m =5431; long int n = 1234567890;x=1.234567890000; q= 1.0 ; k=54321;

printf(“%d”, m); printf(“%ld\n”, n); printf(“%f\n”, x);printf(“%lf”,x); printf(“%lf\n”,q); printf(“%u”,k);

}

Page 29: C presentation book

Defining Symbolic Constants:Those constants which are repeatedly used in the programs

are defined as a symbolic constants.

Because of Symbolic constants we can solve problems like:1. Problem in modification of the program2. Problem in understanding the program

Syntax:#define symbolic_name value_of_constant

Ex:#define PI 3.14#define MAX 200#define PASS_MARK 50

Page 30: C presentation book

Rules to define the symbolic constants:

• Symbolic names are written in Capital letters to visually distinguish them from the normal variables.

• No blank space between the pound sign ‘#’ and the word define is permitted.

• ‘#’ must be the first character in the line.• A blank space is required between #define and symbolic

name.• #define statement must not end with a semicolon• Assignment operator is not used to assign a value to the

symbolic name.• A statement can define only one name

Invalid define statement:#define X=2.5, # define MAX 10, #define N 25; , #define PI , R 3.14 , #define PRICE$ 100

Page 31: C presentation book

Declaring a variable as constant:Syntax:const data_type variable_name = value ;

Ex:const int class_size=40;

Using const keyword we can made any variable’s value constant and because of that we cant change the value of that variable during the execution time.

Declaring a variable as volatile:Qualifier volatile that could be used to tell explicitly the compiler that a variable’s value may be changed at any time by some external source.

Syntax:volatile int date.

Page 32: C presentation book

User-Defined Type Declaration:• Using typedef keyword we can define our own user defined

data type.

Syntax:typedef type identifier;

Ex:typedef int marks;marks sub1,sub2;

• Another user defined data type is enum (enumeration) which can be used to declare variable that can have one of the values enclosed within the braces (Known as enumeration constants)

• The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants.

Page 33: C presentation book

Syntax:enum identifier {value1, value2, value3,….,valueN};

Example:enum day {Monday, Tuesday,……..,Sunday};enum day week_st, week_end;week_st = Monday;week_end = Friday;If(week_st == Tuesday)week_end = Saturday;

• enum day {Monday=1,Tuesday,….., Sunday};Here Monday = 1 constant value so the remaining constants are assigned value that increase successively by 1.

• Declaration combined as follow:enum day {Monday,…..,Sunday} week_st, week_end;

Page 34: C presentation book

Read data from keyboard:Using Scanf function we can read data from the keyboard.

Syntax:

scanf(“control string”,&variable1,&variable2);.

Page 35: C presentation book

Chapter 3 Operators and Expression

C support a rich set of built in operator.

• An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

C operators are classified into following categories:

• Arithmetic operator• Relational operator• Logical operator• Assignment operator• Increment and Decrement operator• Conditional operator• Bitwise operator• Special operator.

Page 36: C presentation book

Arithmetic operator:+(Addition), -(Subtraction), *(Multiplication), /(Division) , %(Modulat Division). All this are arithmetic operators.

ex:a-b a+ba*b a/ba%b -a*b

Here a and b are variables and are known as operands.Note : Modular operator can not be used in the floating point operation.

Arithmetic operator has three types:(1) Integer Arithmetic(2) Real Arithmetic

(3) Mixed mode Arithmetic

Page 37: C presentation book

Integer Arithmeic:When both the operands in a arithmetic expressions are integer, the expression is called an integer expression, and the operation is called integer arithmetic.

If a and b both are integer than for a=14 and b=4 we have following results:a – b = 10a + b = 18a * b = 56a / b = 3 (Decimal part truncated)a % b = 2 (remainder of division)

During integer division,if both the operands are of the same sign,the result is truncated towards the zero. If one of them is negative, the direction of truncation is implementation dependent. That is,

6/7 = 0 and -6/-7 = 0

Page 38: C presentation book

Similarly during modular division, the sign of the result is always the sign of the first operand (dividend). That is

-14%3 = -2 -14%-3 = -2

14%-3 = 2

Ex : /* Program to convert a given number of days into months and days*/main()

{int month, day;clrscr();scanf(“%d”,&day);month = day/30;day = day%30;printf(“Month = %d Days = %d”, month,day);getch();

}

Page 39: C presentation book

Real Arithmetic :An arithmetic expression involving only real operands is called real arithmetic. A real operands may assume values either in decimal or exponential notation.

If x,y,z are floats, then we will have:x = 6.0/7.0 = 0.85713y = -2.0/3.0 = -0.666667

the operator % can not be used with real operands.

Mixed Mode Arithmetic:When one of the operand is real and the other is integer, the expression is called the mixed mode arithmetic expression. If either operand is real type then only real operation is performed and the result is always a real number. Thus

15/ 10.0 = 1.5where as

15/10 = 1

Page 40: C presentation book

Relational operators:Whenever you want to compare two entities at that time you can use the Relational operator.

An expression containing a relational operator is known as relational expression.

C Support six type of the relational operators:

operator Meaning< less than<= is less than or equal to> greater than>= is greater than or equal to== is equal to!= is not equal to

Relational operators are generally used in the decision making statements like if and while and it returns value true and false

Page 41: C presentation book

Ex: 4.5 <= 10 truea+b == c+d true if equal else false10< 7+5 true-35 >= 0 false

Logical Operators:Logical operators are generally used when you want to test more than one condition.

There are three types of the logical operator:Logical And &&Logical Or ||Logical Not !

Ax expression of this kind, which combines two or more relational expressions, is termed as a logical expression or a compound relational expression.

Page 42: C presentation book

Truth Table:

Op-1 Op-2 value of the expressionop-1 && op-2 op1 || op2

1 1 1 11 0 0 10 1 0 10 0 0 0

Example :if(age > 55 && salary < 1000)if(number < 0 || number > 100)

Assignment Operators:Assignment operators are used to assign the result of an expression to a variable. We have seen the usual assignment operator ‘=’. In addition c has a ‘shorthand’ assignment operators of the form.

Page 43: C presentation book

Syntax:v op = exp

Where v is a variable, exp is an expression and op is a c binary arithmetic operator.

Is equivalent to :V = v op (exp)

Ex: x+=1 is equivalent to x= x+1

Statement with simple Statement with shorthand Assignment operator operator.a=a+1 a+=1a=a-1 a-=1a=a*(n+1) a*=n+1

Use of the shorthand assignment operator:1. Left hand side need not to be repeated so easier to write2. Statement is easier to read3. Statement is more efficient.

Page 44: C presentation book

Increment(++) and Decrement(--) Operator:

++ operator add 1 to the operand, while –- subtracts 1. Both are unary operator and takes the both form.

++m or m++--m or m--

We generally used this statement in the for and while loop.

++m and m++ both are different thing when they are used in the expression.For m=5;

Y= ++m In this case value of y and m would be 6Y= m++ In this case vale of y would be 5 and m would be 6.

Increment and decrement statement is used in the complex statement:M= n++ -j +10 but old value of the n is incremented after the evaluation of

the equation

Page 45: C presentation book

#include<stdio.h>#include<conio.h>void main(){ int n,k,m; clrscr(); k=1,m=2; n= k++ + m; printf("%d",k); printf("%d",n); getch();}

Output:k=2, n=3

Page 46: C presentation book

Conditional operator:

Conditional operator is also called the “ternary operator”.Syntax:exp1 ? exp2 : exp3

Ex:a = 10;b = 15;

X = (a>b) ? a : b;

Its same asif (a > b)

x = a;else

x = b;

Page 47: C presentation book

Bitwise Operator :• Whenever you want to manipulate your data at that time you can use the

Bitwise operator.• These operators are generally used to testing the Bits, or shifting them left

or right.• Bitwise operator can not be applied to float or double.

• List of the Bitwise operators and their meanings are as follow.

Operator Meaning

& bitwise AND| bitwise OR^ bitwise exclusive OR<< shift left>> shift right

Page 48: C presentation book

Special Operator :• C Support some special operator like comma, and sizeof operator.

Comma Operator :Comma Operator can be used to link the related expression together.Ex:

Value = (x=10, y=5, x+y);

In for loop.

A list of expressions are evaluated from left to right direction.Ex:for(n=1,n<=10;n++);

The sizeof Operator:Sizeof operator is a compile time operator. It returns number of bytes occupied by the operand. The operand may be a variable, constant or a data type.

Page 49: C presentation book

Ex:m = sizeof(sum);n = sizeof(long int);

Page 50: C presentation book

#include<stdio.h>#include<conio.h>void main(){ int a,b,c,d; clrscr(); a=15, b= 10; c= ++a - b; // value of a is increamented before use in expression printf("a=%d b=%d c=%d\n", a,b,c); d= b++ + a; // value of b is increament after use in expression printf("\na = %d b = %d d = %d",a,b,d); printf("\n a/b = %d",a/b); printf("\n a%b = %d",a%b); printf("\n a*=b = %d", a*=b); printf("%d\n", (c>d) ? 1:0); printf(“%d”,sizeof(int)); getch();}

Output :

a=16 b=10 c=6a = 16 b = 11 d = 26a/b = 1a%b = 5a*=b = 17602

Page 51: C presentation book

ARITHMETIC EXPRESSION :An arithmetic expression is a combination of variables, constants, and operators arranged as per the syntax of the language.

Example :

Algebric Exprssion C Expression

a x b – c a * b – c(m+n)(x+y) (m+n) * (x+y)ab/c a*b/c 3x2 +x +1 3*x*x + x + 1

EVALUATION OF EXPRESSION :Syntax : variable = expression;

Ex: x = a * b – c; z = a – b / c – d;

Page 52: C presentation book

Precedence of Arithmetic operators:

High Priority : * / %Low Priority : + -

#include<stdio.h>#include<conio.h>void main(){

float a,b,c,x,y,z;clrscr();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 y = %f z = %f", x,y,z);getch();

}Output : x =10.000000 , y = 7. 000000 , z = 4. 000000

Page 53: C presentation book

Rules for Evaluation Expression :

• First, parenthesized sub expression from left to right are evaluated

• If parentheses are nested, the evaluation begins with the innermost sub expressions

• The associativity rule is applied when two or more operator of the same precedence level appear in sub expression.

• The precedence rule is applied to determine the order of operator in evaluating expression.

• Arithmetic operators are evaluated left to right using the rules of precedence

• When parentheses are used, the expressions within parentheses assume highest priority.

Page 54: C presentation book

Type Conversion in Expression :

There are two types of the type conversions:

Implicit Type Conversion Explicit Type Conversion

Implicit Type Conversion :

• When data value automatically convert from one type to another type is called the Imlicit type conversion.

• If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds.

Ex: #include<stdio.h>#include<conio.h>void main(){ int a,b; float c; a= 12,b=13; c= a+b; // automatic type conversion printf("%f",c); getch();}

/* Output 25.00000 */

Page 55: C presentation book

Explicit Type Conversion :

When a process of the conversion done manually of locally then this process is called the explicit type conversion process or casting operation.

Syntax : (type_name) expression :

Ex:x = (int) 7.5; a = (int) 21.3 / (int)4.5b= (double) sum /n y = (int) (a+b);z = (int) a + b;

#include<stdio.h>#include<conio.h>void main(){ float a,b; int c; clrscr(); a=12,b=13; c= (int) (a+b); // Type Conversion float to int printf("%f",c); getch();}

/* Output 25 */

Note : whenever you try to convert higher data type to lower type your result will be loss.

Page 56: C presentation book

Chapter : 4 Managing Input Output Operation

Reading a character :

Using getchar() function you can get a single character from the screen.

Syntax:Variable_name = getchar();

Ex: char name;name = getchar();

Writing a character :

Using putchar() function you can print the character which is stored in the variable on to the output screen.

Syntax: putchar(variable_name);

Ex: char answer; answer = ‘y’

putchar (answer);

Page 57: C presentation book

Character Functions:

• C Support many character functions. These character functions contained in the file ctype.h and therefore the statement#include<ctype.h> must be include in the program to access this character function.

Character set functions:isalnum(c) - Is c an alphanumeric characterisalpha( c ) - Is c an alphabetic characterisdigit( c) - Is c a digit.islower( c ) - Is c lower case letterisupper( c ) - Is c Upper Case letterisspace( c ) - Is c a white space character.ispunct( c ) - Is c a punctual mark

toupper() - convert lowercase argument into uppercase letter and function tolower() – convert uppercase letter into the lowercase letter.

Page 58: C presentation book

Example :

/* Write the Program To Convert uppercase to lowercase and lowercase letter to uppercase letter */

#include<stdio.h>#include<conio.h>void main(){ char alpha; clrscr(); printf("Enter a alphabet :"); alpha = getchar();

if(islower(alpha))putchar(toupper(alpha));

elseputchar(tolower(alpha));

getch();}

Page 59: C presentation book

Chapter 5 : Decision Making and Branching

if statementswitch statementConditional operator statementgoto statement

All the above statements are known as decision – making statement. These statements ‘control’ the flow of the execution, they are also known as control statements.

Decision Making with If statement :If statement used to control the flow of the execution.

Syntax: if(test_expression) { statement-block;

} statement-x;

If test_expression condition is true execute the statement_block statements.

Page 60: C presentation book

Ex:#include<stdio.h>#include<conio.h>void main(){ int a,b,c,d; float ratio; clrscr(); scanf(“%d %d %d %d”,&a,&b,&c,&d); if(c-d != 0) { ratio = (float) (a+b)/(float) (c-d); printf(“Ratio = %f\n”,ratio);

}getch();}

Page 61: C presentation book

The If….Else Statement :The if…else statement is an extension of the if statement. It is generally used whenever

you want to execute the condition’s true and false part.

Syntax :If(test_expression){ true- block statements;}else{ false – block statements;}statement – x;

If test_expression condition is true execute the true-block statements else execute thefalse – block statements.

Page 62: C presentation book

Ex:#include<stdio.h>#include<conio.h>void main(){ int a,b; clrscr(); scanf(“%d %d”, &a, &b); if (a>b) printf(“A is bigger than B : %d”,a); else printf(“B is bigger tha A : %d”,b); getch();}

Page 63: C presentation book

Nesting of If…Else statements:

When a series of decisions are involved, we may have to use more than one if…else statements in a program in nested form is called the nesting of if…else statements.

Syntax:if(test_condition 1){

if(test_condition 2) {

statement – 1;}else{

statement – 2;}

}else{

statement – 3;}Statement – x;

Page 64: C presentation book

Ex:

#include<stdio.h>

#include<conio.h>

void main()

{

float a,b,c; clrscr();

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

if(a>b){

if(a>c)

printf(“%f\n”,a);

else printf(“%f\n”,c);

}

else

{if(c>b)

printf(“%f\n”,c);

else

printf(“%f\n”,b);}

getch();

}

Page 65: C presentation book

Else If Ladder:

When we want to take multiple decision, putting ifs together. This construction is known as the else..if ladder.

Syntax:

if (Condition 1)

statement – 1;

else if (condition 2)

statement – 2;

else if (condition 3)

statement – 3;

……..

…….

else

default statement;

Statement x;

The conditions are evaluated from the top to downwards. As soon as a true condition is

found, the statement associated with it is executed and the statement is transferred to

the statement x.When all the condition become false default statement will be executed.

Page 66: C presentation book

#include<stdio.h>#include<conio.h>void main(){ int s1,s2,total; float per; clrscr(); printf("Enter Marks for s1 & s2 :"); scanf ("%d %d",&s1,&s2); total = s1+s2; printf("\n\nTotal Mark is : %d",total); per=(float)(total*100/2); printf("\n\nPercentage is :%f",per); printf("\n\nClass of the Student :"); if(per>79) printf("Honours:"); else if(per>59)

printf("First"); else if(per>39); printf("Second");

getch(); }

Page 67: C presentation book

The Switch Statement :When one of the many alternative is to be selected, we can use an if statementto control the selection. However the complexity of such program increases when thenumber of the alternative increases.

C has a built in multiway decision statement known as switch. The switch statement tests the value of a given variable against a list of case value andwhen a match is found, a block of statement associated with that case is executed.

Syntax:switch(expression){ case value-1:

block-1break;

case value-2:block-2break;

……….. default:

default-blockbreak;

}

Page 68: C presentation book

• The expression is an integer or character expression. Value1, value2 are constants and are known as case label.

• There is no need to put braces around these blocks.• When switch is executed, the value of the expression is successfully compared against

the Values value1, value2…. If the case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.

• break statement exit the control from the switch case and transfer the control after the switch case statement.

• The default is an optional case, when present, it will be executed if the value of the expression does not match with any of the case values.

Rules for switch statement:• Case label must be integer or character.• Case label must be unique.No two case labels can have the same value.• Case label must end with colon.• The break statement is optional.• The default label is optional.• There can be at most one default label.• The default may be placed any where but usually placed at the end• It is permitted to nest switch statement.

Page 69: C presentation book

#include<stdio.h>#include<conio.h>void main(){ int s1,s2,total,index; float per; clrscr(); printf("Enter Marks for s1 :");

scanf ("%d",&s1);printf("Enter Marks for s2 :");scanf ("%d",&s2);

total = s1+s2;printf("\n\nTotal Mark is : %d",total); per=(float)(total*100/2); printf("\n\nPercentage is :%f",per);printf("\n\nClass of the Student :");index=(int)(per/10);

Page 70: C presentation book

switch(index) {

case 10:case 9:case 8:

printf("Honour");break;

case 7:case 6:

printf("First");break;

case 5:case 4:

printf("Second");break;

default: printf("Grade not displayed");

}

getch(); }

Page 71: C presentation book

Go TO Statement :

C support go to statement to branch unconditionally from one point to another in theprogram.

Although it may not be essential to use the goto statement in a highly structuredlanguage like C. There may be occasions when the use of goto might be desirable

The goto requires a label to identify the place where the branch is to be made. Label is valid variable name and must be followed by a colon.

Label is placed before the statement where control is to be transferred.

goto label; label:…….. Statement;…….. ……….…….. ……….label: ……….Statement; goto label;

[Forword Jump] [Backward Jump]

Page 72: C presentation book

Backward Jump. If a label is before the statement goto, a loop will be formed and some statements will beExecuted repeatedly. Such a jump is known as Backward Jump.

Forward Jump:If the label is placed after the goto label, some statements will be skipped and the jump isknown as a forward jump.

Page 73: C presentation book

Ex:#include<stdio.h>#include<conio.h>#include<math.h>

void main(){

float x,y;clrscr();read:scanf(“%f”,&x);if(x<0){

printf(“This is a Negative value”); goto read;

}else{

y=sqrt(x)printf(“Suare root of %f is %f ”,x,y);

}goto read;

getch();}Note : Infinite loop will be occurred because of the above case.

Page 74: C presentation book

Solution of the infinite loop in goto statement :Ex:#include<stdio.h>#include<conio.h>#include<math.h>

void main(){

float x,y; int count;clrscr();read:scanf(“%f”,&x);if(x<0){

printf(“This is a Negative value”); goto read;

}else{

y=sqrt(x)printf(“Suare root of %f is %f ”,x,y);

}count++;if(count <= 5)

goto read;

printf(“\n End of the computation”);

getch();}

Page 75: C presentation book

Chapter : 6 Decision Making and Looping

What is looping?A sequence of statements are executed until some condition for termination of the loopare satisfied is called looping.

There are two types of the looping.(a) Entry controlled loop(b) Exit controlled loop

Entry controlled loop : In this looping first condition will be checked and then Body of the statements are executed is called the entry controlled loop.

Exit controlled loop: In this looping first body of the statements are executed and then condition will be checked is called the exit controlled loop.

Page 76: C presentation book

Test Condition ?

Body of the loop

Body of the loop

Test condition ?False

True

False

True

(a) Entry Controlled loop(b) Exit Controlled loop

Page 77: C presentation book

The c language provides for three constructs for performing loop operation.

• The while statement• The do statement• The for statement.

The while statement :

The while is an entry controlled loop statement.

Syntax:

while (test condition){

Body of the loop;

}

Here while is a key word.

The test condition is evaluated and if the condition is true, the body of the loop is

executed. After the execution of the body, the test condition is once again evaluated andif it is true, the body is executed once again.

Note : Braces is needed if the body contains more than one statements.

Page 78: C presentation book

Ex://program:-9 to find the sum of first 100 natural nos:

#include<stdio.h> #include<conio.h> void main() {

int i,sum;clrscr();i=0; sum=0;while(i<=100){

sum = sum + i;i++;

}printf("\nSummation of first 100 is : %d",sum);getch();

}

Hw : Write the program to find the summation of first five no’s square.

Page 79: C presentation book

Do…While statement :

Do…while statement is exit controlled loop.

Syntax:

do{

Body of the loop;}while (test condition);

It first executes the body of loop then evaluates the test condition. If the condition is true,the Body loop is executed again and again until the condition become false.

After the while statement there is a semicolon in do..while statement.

If first time condition become false, though it executes the body of the loop once.

Page 80: C presentation book

/* Find the factorial of any number */#include<stdio.h>#include<conio.h>void main(){

int n, fact=1;clrscr();printf("Enter the number :");scanf("%d",&n);if(n<0)

printf("\n factorial of negetive number is not possible :");else if(n==0)

printf("Factorial of 0 is 1\n");else{

do{

fact *= n;n--;

}while(n>0);printf("Factorial of the given no. is : %d", fact);

}getch();}

Page 81: C presentation book

For Loop:The for loop is another entry control loop that provides a more concise loop control structure.

Syntax :

for( initialization; test-condition ; increment or decrement) { Body of the loop }

Initialization: In Initialization part you can initialize the variable. Such as i=0.

Test-Condition: The value of the control variable is tested using the test – condition. Test condition is relational expression, such as i<10 that determines when loop will exit. If the condition is true body of the loop is executed otherwise the loop is terminated.

Increment or Decrement : When the Body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is incremented or decremented.

Page 82: C presentation book

Ex:

/* Program to Display 0 to 9 */

#include<stdio.h>#include<conio.h>void main(){

int x;for(x=0; x<=9 ; x++){

printf(“%d”,x);}

printf(“\n”);}

Page 83: C presentation book

/* Program to Display 9 to 0 */

#include<stdio.h>#include<conio.h>void main(){

int x;for(x=9; x>=0 ; x--){

printf(“%d”,x);}

printf(“\n”);}

Page 84: C presentation book

Additional features of the for loop :

More than one variable can be initialized at a time in the for statement. Ex: p=1;

for (n=0; n<17; n++)is equivalent tofor(p=1,n=0; n<17; n++)

Increment or Decrement section also has more than one statement.Ex: for(n=1, m=50; n<=m; n++, m--)

{p=m/n;printf(“%d %d %d\n”, n,m,p);

} The test condition may have any compound relation.

Ex: sum=0; for(i=1; i<20 && sum < 100; i++){

sum = sum +i;printf(“%d %d\n”, i, sum);

}

Page 85: C presentation book

It is also permissible to use expression in the assignment statements of initialization andincrement sections.

Ex: for( x=(m+n)/2; x>0; x= x/2)

Another feature of the for loop is that one or more section can be omitted, if necessary.Ex: m=5;

for( ; m != 100 ;){

printf(“%d\n”, m);m++;

}Note : If test condition is not present, the for statement sets up an “infiniteloop” such loop can be broken using break and goto statements in the loop.

We can set up the time delay loops using the null statement as follow:for(j=1000; j>0; j--) ;

This loop is executed 1000 times without producing any output; it simply causes time delay.

The Body of the loop contains only a semi colon, known as null statement.

Note : The c compiler does not give any error message if we place semicolon by mistake at the end of a for statement..

Page 86: C presentation book

Nesting of for loop:

Nesting of for loops, that is one for statement within another for statement.

Ex:for ( i=1 ; i< 10; i++){

for ( j=1; j != 5; j++ ){

………..…………

}……………..…………….}

Note : ANSI C allow up to 15 levels of nesting.

Inner loopOuter loop

Page 87: C presentation book

/* Program to display the output on the screen */

#include<stdio.h>#include<conio.h>void main(){ int i,j,n; clrscr(); printf("Enter the value of i :"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<=i;j++) { printf("*"); } printf("\n"); }

getch();}

Page 88: C presentation book

/*

Enter the value of n : 4

**********

*/

Page 89: C presentation book

Jumps in Loops :

There are two statements break and continue are used to performing operationjumps in loops.

break statement :

When the break statement is encountered inside a loop, the loop is immediately exitedand the program continues with the statement immediately following the loop. When theloops are nested, the break would only exit from the loop containing it. That is break willexit only a single loop.

Syntax : break;

Since a goto statement can transfer the control to any place in a program . Another important use of goto is to exit from deeply nested loops when an error occurs.

Page 90: C presentation book

for (……..)

{

for (……….)

{

if (condition) break;

}

----------

}

while (……..)

{

………………..

………………..

if (condition)

break;

………………

}

do

{

………………..

………………..

if (condition)

break;

………………

} while(….) ;

for (……..)

{

………………..

………………..

if (error)

break;

………………

}

Exit loopExit loop

Exit loop

Exit loop

Page 91: C presentation book

continue statement :

The use of the continue statement is to skip the following statements and continue with the next iteration.

Syntax : continue;

Unlike the break which causes the loop to be terminated, the continue as the name implies, causes the loop to be continued with the next iteration after skipping anystatements in between.

In while and do loops, continue causes the control to go directly to the test condition andthen do continue the iteration process.

In the case of for loop increment section of the loop is executed before the test – condition is evaluated.

Page 92: C presentation book

for (……..)

{

for (……….)

{

if (condition) continue;

}

----------

}

while (……..)

{

………………..

………………..

if (condition)

continue;

………………

}

do

{

………………..

………………..

if (condition)

continue;

………………

} while(….) ;

for (……..)

{

………………..

………………..

if (error)

continue;

………………

}

Exit loop

Page 93: C presentation book

#include<stdio.h>#include<conio.h>#include<math.h>void main(){ int count,negative; float no,sqroot; printf("Enter 9999 To Stop\n"); count=0; negative=0; while(count<=20) {

printf("\nEnter a number :");scanf("%f",&no);if(no==9999)

break; //Break statement

Page 94: C presentation book

if( no < 0 ){

printf("\nNumber is negative"); negative++; continue; // continue statement

} sqroot = sqrt(no); printf("Numer = %f\n Square root = %f\n\n",no,sqroot); count++; }

printf("\nNumber of item done = %d\n",count);printf("\nNegative item = %d\n",negative);

}

Page 95: C presentation book

Chapter 7 : Arrays

Defination of Array : An array is a sequences collection of the realated data items that share a common name.

An array is a derived data type.

There are mainly three types of the array:

• One – Dimentional arrays• Two – Dimentional arrays• Multidimentional arrays

Page 96: C presentation book

One – Dimentional Arrays:

A list of items can be given one variable name using only one subscript and sucha variable is called a single subscripted variable or a one dimentional array.

Syntax:type variable-name[size];

The type specifies the type of the element that will be contained in the array, such as int,float or char.

Ex: If we want to represent a set of five numbers say, (35,40,20,57,19) by an array variable number, then we may declare the vaiable number as follows.

int number[5];

And the computer reserves five storage location as shown below:

Number[0]

Number[1]

Number[2]

Number[3]

Number[4]

Page 97: C presentation book

The value to the array element can be assigned as follow:

Number[0] = 35 ;Number[1] = 40 ;Number[2] = 20 ;Number[3] = 57 ;Number[4] = 19

This would case the array number to store the value as shown below:

Note : C performs no bound checking and, therefore, care should be exercised to ensure that the array indices are within the declared limits.

Number[0]

Number[1]

Number[2]

Number[3]

Number[4]

35

40

20

57

19

Page 98: C presentation book

Same way,float height[50];

Declares the height to be an array containing 50 real elements. Any subscript to0 to 49 are valid.

• Any references to the arrays outside the declared limits would not necessarily cause an error. Rather, it might result in unpredictable program results.

• The size should be either integer constant or symbolic constant.

The C language treats character string simply as array of characters. The size ina character string represents the maximum number of characters that the stringcan hold.

char name[10] ;

Declare name as a character array variable that can hold a maximum of 10 characters.Suppose we read the following string constant into the string variable name.

“WELL DONE”

Page 99: C presentation book

Each character of the string is treated as an element of the array name and is stored in the memory as follows:

• Character string terminates with an additional null character. Thus name[10] holds the null character ‘\0’. When declaring character array, we must allow one extra space for the null chararcter.

‘W’

‘E’

‘L’

‘L’

‘ ’

‘D’

‘O’

‘N’

‘E’

‘\0’

Page 100: C presentation book

INITIALIZATION OF ONE – DIMENTIONAL ARRAYS:

After an array is declared, its element must be initialized. Otherwise, they willcontain “garbage”. An array can be initialized at either of the following stages:

At compile timeAt run time

CompileTime Initialization:

Syntax:

Type array-name[size] = {list of values};

The value in the list are separed by commas. Ex: int number[3] = {0,0,0} ;

Will declare the variable number as an array of size 3 and will assign zero toeach element. If the number of values in the list is less than the number of elements, then only that many elements will be initialized. The remaining elements will be set tozero automatically

Page 101: C presentation book

float total[5] = { 0.0 , 15.75 , -10};

Will initialize the first three elements to 0.0, 15.75 and -10.0 and the remainingtwo elements to zero

The size may be omitted. In such cases, the compiler allocate enough spaces forall initialized elements.

Ex: int counter[] = {1,1,1,1}

Counter array contain four element with initial value 1.

Character array may be initialized similar manner.char name[] = {‘R’, ‘A’, ‘M’, ‘\0’};

Is equivalent to :char name[] = “RAM”;

If we have more than the declared size, the compiler will produce an error. That is thestatement.

int number[3] = {10, 20, 30, 40} ; will not work. It is illegal in C.

Page 102: C presentation book

Run Time Initialization :

An array can be explicitly initialized at run time. This approach is usually appliedfor initializing large arrays.

Ex:for(i=0; i<100 ; i++){

if (i < 50 ) sum[i] = 0.0;else

sum[i] = 1.0; }

In the above case the first 50 elements are initialized to zero while theremaining elements are initialized to 1.0 are run time.

We can also use a read function such as scanf to initialize an array.Ex: int x[3];

scanf (“%d %d %d”, &x[0], &x[1], &x[2] ) ; Will initialize array elements with the values entered through the kwyboard.

Page 103: C presentation book

/* program:-22 write a C proragm to arrange the accepted numbers in ascending order and descending order: */

#include<stdio.h>#include<conio.h>

void main(){ int i,j,ans,n,temp=0, no[20]; clrscr(); printf("Enter the requirement:="); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the no:-"); scanf("%d",&no[i]); } printf("Enter the your choice ascending=1&descending=2:="); scanf("%d",&ans);

Page 104: C presentation book

for(i=0;i<n;i++) { for(j=i;j<n;j++) { if(ans==1)

{ if(no[i]>no[j])

{ temp=no[i]; no[i]=no[j]; no[j]=temp; }

} else

if(no[i]<no[j]) {

temp=no[i]; no[i]=no[j]; no[j]=temp; }

} printf("%d",no[i]); printf("\n"); } getch();}

Page 105: C presentation book

TWO – DIMENTIONAL ARRAYS:

If you want to store data into table or matrix form at that time you can use thetwo dimentional array.

Ex:ITEM 1 ITEM2 ITEM 3

SALES MAN 1 310 275 365SALES MAN 2 210 190 325SALES MAN 3 405 235 240SALES MAN 4 260 300 380

The table discussed above can be define as :v[4][3] where 4 Rows and 3 columns.

Declaration of two dimentional array:

Syntax : data_type array-name[rowsize][colsize];

Page 106: C presentation book

Memory representation of the two dimentional array for v[4][3] .

column 0column 1column2

[0][0] [0][1] [0][2]

Row 0

[1][0] [1][1] [1][2]

Row 1

[2][0] [2][1] [2][2]

Row 2

[3][0] [3][1] [3][2]

Row 3

310 275 365

325

2400

365275

235

19010

405

310

Page 107: C presentation book

INITIALIZING TWO DIMENTIONAL ARRAY:

Ex: int table[2][3] = {0,0,0,1,1,1};

Initialize elements of the first row to 0 and second row to 1. The initialization isdone row by row.

The above statement can be equivalent written as :int table[2][3] = {{0,0,0},{1,1,1}};

We can also initialize a two dimensional array in the form of a matrix as shown below:int table[2][3] = {

{0,0,0},{1,1,1}

} ; When the array is completely initialized with all values, we need not specify the size of thefirst dimension. That is, the statement is permitted.

int table[][3] = {{0,0,0} ,{1,1,1)

};

Page 108: C presentation book

If the value is missing in an initializes, they are automatically set to zero. Ex: int table[2][3] ={

{1,1} ,{2}

} ;Will initialize the first two elements of the first row to one, the first element of the secondrow to two and all other elements to zero.

When all the elements are initialized to zero, the following short cut method may be used.int m[3][5] = { 0, 0 };

or

int m[3][5] = { {0} , { 0} };

Page 109: C presentation book

//program30 : addition of two matrix#include<stdio.h>#include<conio.h>void main(){

int i,j,n,m,a[10][10],b[10][10],m1,n1;clrscr();

printf("Enter No of Rows for first matrix:");scanf("%d",&n);

printf("Enter No of columns for first Matrix:");scanf("%d",&m);

printf("Enter No of Rows for second matrix:");scanf("%d",&n1);

printf("Enter No of columns for second Matrix:");scanf("%d",&m1);

Page 110: C presentation book

if(m!=m1 || n!=n1) printf("Sum not Possible.");

else{

for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("Give value of a[%d][%d]:",i+1,j+1); scanf("%d",&a[i][j]); } }

for(i=0;i<n1;i++) { for(j=0;j<m1;j++) { printf("Give value of b[%d][%d]:",i+1,j+1); scanf("%d",&b[i][j]); } }

Page 111: C presentation book

printf("First Matrix:\n"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("%d ",a[i][j]); } printf("\n");

}printf("Second Matrix\n");

for(i=0;i<n1;i++) { for(j=0;j<m1;j++) {

printf("%d ",b[i][j]); } printf("\n"); } printf("After Sum New Matrix\n");

for(i=0;i<n1;i++) { for(j=0;j<m1;j++) {

printf("%d ",a[i][j]+b[i][j]); } printf("\n"); }}getch();

}

Page 112: C presentation book

MULTIDIMENTIONAL – ARRAY :

C allows array of three or more dimensions.

Syntax:

type array_name [s1] [s2] [s3]……………[sn] ;

Where si is the size of the ith dimentions.

Some ex: int survey [3] [5] [12] ;float table [5] [4] [5] [3] ;

Survey is a three dimensional array while table is four dimensional array.

Survey contain 180 integer value. Table contain 300 element for floating type.

Ex:int survey[3][5][12];

In this first index denotes year, second city and third month. The array surveyRepresent a survey of rainfall during the last three years from January toDecember in five cities.

Page 113: C presentation book

Month

City1 2 12…………………………

………1

5

……

……

YEAR 1

Month

City1 2 12…………………………

………1

5

……

……

YEAR 2

----

----

---

YEAR 3

Page 114: C presentation book

Dynamic Array:

In C it is possible to allocate memory at the run time to the Array is called theDynamic Array.

Dynamic arrays are created using what are known as pointer variable and memory management function like malloc, calloc and realloc.

The process of allocating memory at compile time is known as static memory allocation and the array that receive static memory allocation is called the

staticarray.

Page 115: C presentation book

Chapter : 8 Handling of character String:

What is a String :

String is a group of character array.

Any group of character defined between double quotation mark is a constant string.

Ex: printf(“Hello How are you”);

output : Hello How are you

If you want to included double quotes with string than also it is possible.

Ex: printf(“\”Hello How are you”\”); output : “Hello How are you”

Page 116: C presentation book

• Declaring and Initialising String Variable : A String Variable is always declared as an array :

Syntax : char string_name[size]; Where size determines the number of character

in the string. size should be maximum number of the

character + 1. because When the compiler assigns the

character string to character array . It automatically supplies null character (“\0”) at the end of the string.

Ex: char city[10]; char name[30];

Page 117: C presentation book

• Initialization of string variable :

char array may be initialized when they are declared.

you can initialized char array with two form:

char city[9] = “New York”; char city[9] = {‘N’, ‘e’, ‘w’, ‘ ’, ‘Y’, ‘o’, ‘r’, ‘k’,’\0’ };

Page 118: C presentation book

C also permit us to initialise character array without specifying the number of elements.

In such cases, the size of the array will be

determined automatically,based on the number of the elements initialised.

Ex: char string[] = {‘G’,’O’,’O’,’D’,’\0’};

It defines the string as five elements array.

Page 119: C presentation book

• Reading String from terminal : You can read the string using scanf function

with %s format specification. Ex: char address[15]; scanf(“%s”,address); (& sign is not included before address)

The problem with the scanf function is that it terminates its input on the first white space it finds.

Ex: If input string is New York in address that address array included only New. After New, string will be terminated.

Page 120: C presentation book

If we want to to read the entire line “New York” then we may use two character

array of appropriate sizes. That is, scanf(“%s %s”,adr1,adr2); Where adr1 assign “New” and adr2 assigns

“York”.

Page 121: C presentation book

• Reading a line of Text: Program to read a line of text from terminal : #include<stdio.h> void main() { char line[81],character; int c=0; do { character = getchar(); line[c] = character; c++; } while(character != ‘\n’); c=c-1; line[c] = ‘\0’ ; printf(“\n %s \n”,line)}Output : programming in C is interesting. Programming in C is interesting.

Page 122: C presentation book

• Copying one string to another string

We can copy one string to another string using character by character basis.

We can’t assign one string to another string directly.

Ex: string = “ABC”; string1 = string2;

is not possible in C.

Page 123: C presentation book

program to copying one string to another string :

#include<stdio.h> void main() { char str1[80],str2[80]; int i; printf(“Enter the String\n”); scanf(“%s”,str2); for(i=0; str2[i] != ‘\0’; i++) str1[i] = str2[i]; str1[i] = ‘\0’; printf(“%s\n”,str1); printf(“No.of characters=%d\n”,i); }

Page 124: C presentation book

• Writing string to screen : We have used printf function with %s format to print

the string to the screen. Ex: printf(“%s”,name); Used to display the entire contents of the array

name. Features of the %s format specification : (1) When the field width is less than the length of the

string than the entire string is printed. (2) The integer value on the right side of the decimal

point specifies the number of character to be printed. Ex: %10.4s specifies 4 character printed . (3) When the number of character to be printed is

specified by zero,nothing is printed. Ex: %10.0s (4) The minus sign in the specification causes the

string to be printed left side. Ex: %-10.4s 4 character printed left side.

Page 125: C presentation book

• Another nice features for printing output is: printf(“%*.*s\n”,w,d,string); prints the first d characters of the string in the

field width of w.

Write the program for writing string using %s format : void main() { char country[15] = “United Kingdom” printf(“%15s \n”,country); printf(“%5s \n”,country); printf(“%15.6s \n”,country); printf(“%-15.6s \n”,country); printf(“%15.0s \n”,country); printf(“%0.3s \n”,country);}

Page 126: C presentation book

• Output :• United Kingdom• United Kingdom• United• United

• Uni

Page 127: C presentation book

• Write the program to print the output:

void main() { int c , d; char string[] = “Cprogramming”; for(c=0;c<=11;c++) { d=c+1; printf(“%-12.*s \n”,d,string); } printf(“\n\n”); for(c=11;c>=0;c--) { d=c+1; printf(“%-12.*s \n”,d,string); } }

Page 128: C presentation book

• OUT PUT :CCpCprCproCprog………………..Cprogramming

CprogrammingCprogramminCprogrammiCprogrammCprogramCprograCprogr……..….C

Page 129: C presentation book

• Arithmetic operation on characters : To write a character in integer

representation , we may write it as an integer.

Ex: int x; x = ‘a’; printf(“%d\n”,x); it will display number

97 on the screen.

It is also possible to perform arithmetic operation on the character constants and variable.

Ex: x = ‘z’ – 1 Ascii value of z is 122 so x will be store 121.

Page 130: C presentation book

• The C library provides a function which converts string of digits into their integer value.

Ex: number = “1988”; year = atoi(number);

String Handling function : There are mainly four types of string

handling function: 1. strcat() – Concatenation of two string 2. strcmp() – Compares two string 3. strcpy() – copies one string over another

string 4. strlen() – finds the length of the string.

Page 131: C presentation book

• Strcat() : - Using this function you can concat two string:

syntax : strcat(string1,string2); where string1 and string2 both are character

array. string2 is appended to string1 by removing

null character at the end of string1. Ex: str1 = “Very \0” str2 = “Good\0” str3 = “Bad\0”

Strcat(str1,str2); - output : Very Good\0

Page 132: C presentation book

• It also allows to concat three string together Ex: strcat(strcat(str1,str2),str3); output : Very GoodBad

strcmp() : This function compares two string If both are equal then it return 0 value and if they are not equal then it will return numeric difference between the nonmatching character.

Ex: strcmp(“their”,”there”); will return numeric difference between ASCII “i”and”r”.

Page 133: C presentation book

• strcpy () : using this function we can copy contents of one string to contents of another string.

syntax : strcpy(str1,str2); strlen() : This function is used to find the

length of the string. n = strlen(string); where n is an integer variable.

Page 134: C presentation book

• Examples of string handling function : #include<stdio.h> #include<string.h> void main() { char s1[20],s2[20],s3[20]; int x,l1,l2,l3; printf(“Enter two string constants\n”); scanf(“%s %s”,s1,s2); x=strcmp(s1,s2); if(x != 0) { printf(“Strings not equal”); strcat(s1,s2); } else printf(“strings are equal”) ; strcpy(s3,s1); l1 = strlen(s1); l2=strlen(s2) ; l3 = strlen(s3); printf(“s1 = %s length=%d character\n”,s1,l1); }

Page 135: C presentation book

• Table of string : When you want to store a set of strings in

table form than it is possible using two dimensional character array.

Ex: student[30][15] A character array student[30][15] may be

used to store a list of 30 names,each of the length not more than 15 characters.

Page 136: C presentation book

• Write a program that would sort a list of names in alphabetical order. #define ITEMS 5 #define MAXCHAR 20 void main(){ char string[ITEMS][MAXCHAR],dummy[MAXCHAR]; int i=0,j=0; printf(“Enter names:”); while(i<ITEMS) scanf(“%s”,string[i++]); for(i=1;i<ITEMS;i++) { for(j=1;j<=ITEMS-i;j++) { if(strcmp(string[j-1],string[j])>0) { strcpy(dummy,string[j-1]); strcpy(string[j-1],string[j]); strcpy(string[j],dummy); }}Printf(“\n Alphabetical order”);for(i=0;i<ITEMS;i++) printf(“%s”,string[i]);}

Page 137: C presentation book

• Write the program to count the number of character,word and spaces in line :

#include<stdio.h> void main()

{char line[81],ctr;

int i,c,end=0,character=0,words=0,line=0; while(end==0)

{ c=0;

while((ctr=getchar()) != ‘\n’) line[c++] = ctr; line[c] = ‘\0’;

if(line[0]=‘ ’) break;

else{ words++; for(i=0;line[i] != ‘\0’;i++)

continue :

Page 138: C presentation book

if(line[i] == ‘ ’ || line[i] == ‘\t’)

words++; } /* counting lines and characters */ lines = lines +1; characters = characters + strlen(line); } printf(“Number of lines = %d\n”,lines); printf(“Number of words = %d\n”,words); printf(“Number of character = %d”,characters);}

Page 139: C presentation book

• Chapter - 9 User Defined Function:

• C Functions can be classified into two category :

1. Library function. 2. User defined function. Difference between library and user defined

function : library function is inbuilt function while user defined function is developed by user.

Ex : printf and scanf are library function

while main() is an user defined function

Page 140: C presentation book

• Need for user defined function : main is a user defined function.It is possible

to write entire code in main function but it leads a number of problems.

The program becomes to large and complex,

so the task of maintaining,debugging and testing is become difficult.

If a program is divided into function parts then each parts may be individually coded and finally combined into single units. These subprogram is called function.

And it is easier to understand, to debug code and test.

Page 141: C presentation book

• Benefits of function: 1. It facilitates top - down modular

programming. 2. The length of source code is reduced by

using function at appropriate place. 3. It is easy to locate and isolate faulty

function for further investigation. 4. A function can be used by many other

programs.

Page 142: C presentation book

• Forms (Syntax) of function : return_type function_name(argument list) { local variable declaration; executable statements; …………. …………. return( expression); }• By default return_type of function is int• void should not return any value.

Page 143: C presentation book

• Ex:1 #include<stdio.h>

#include<conio.h> void main() { void printline(); // prototype printline(); // calling function printf("This is a function program\n"); printline(); } void printline() //called function { int i; for(i=1;i<40;i++) printf("-"); printf("\n"); }

Page 144: C presentation book

Ex:2 #include<stdio.h> #include<conio.h> void printline() //called function { int i; for(i=1;i<40;i++) printf("-"); printf("\n"); } void main() { //does not required to declare prototype printline(); // calling function printf("This is a function program\n"); printline(); }

If you declared UDF before the main function than it should not required to declare prototype.

Page 145: C presentation book

Category of the function :

There are three categories of the function :

1. Function with no arguments and no return value

2. Function with arguments and no return value.

3. Function with arguments and with return value

Page 146: C presentation book

• Function with no arguments and no return value : This function can not contain any arguments and any

return value. Ex: #include<stdio.h> void mul() { int j,k,mul; scanf(“%d”,&j); scanf(“%d”,&k); mul = j * k;

printf(“%d”,mul); }

void main() { mul(); }

Page 147: C presentation book

Function with arguments and no return value :

This function contain arguments but does not return value. #include<stdio.h> #include<conio.h> void main() { void mul(int,int); int j,k; clrscr(); scanf("%d %d",&j,&k); mul(j,k); getch(); } void mul(int l,int m) { int mul; mul = l * m; printf("%d",mul); }

Page 148: C presentation book

• Function with arguments and with return value :Ex:#include<stdio.h> #include<conio.h> void main() { int mul(int,int); int j,k,multipli; clrscr(); scanf("%d %d",&j,&k); multipli=mul(j,k); printf("%d",multipli); getch(); } int mul(int l,int m) { int mul; mul = l * m; return(mul); }

Page 149: C presentation book

• Recursion : Recursion is a process where a function calls

itself. Ex: main() { printf(“This is an example of recursion “); main(); } output :This is an example of recursionThis is an example of recursion ……..Execution will be continue indefinitely

Page 150: C presentation book

• Ex: Write the program to find the factorial of the given no. using the recursion :

#include<stdio.h>#include<conio.h>factorial(int no){ int fact; if(no==1) return(1); else fact=no*factorial(no-1); return(fact);}void main(){int no;clrscr();printf("Enter the number");scanf("%d",&no);factorial(no);getch();}

Page 151: C presentation book

• Output :• Enter No : 3 fact=3*factorial(2) = 3*2*factorial(1) = 3*2*1 =6

Function with arrays :Syntax : functionname(arrayname,size)

Ex : largest(a,n)Where largest is a function name, a is an array

name and n is a size of an array

Page 152: C presentation book

• Ex: Find the maximum no: float largest(float a[],int n) { int i ; float max; max = a[0]; for(i=1;i<n;i++) if(max < a[i]) max = a[i]; return(max); } main() { float largest[float [],int n]; float value[4]={2.5,-4.75,1.2,3.67} printf(“%f\n”,largest(value,4)); }

Page 153: C presentation book

• The scope and lifetime of variables in function :

In C there are four types of storage classes : 1. Autoamatic storage classes 2. External variables 3. Static variables. 4. Register variables

Automatic variables : Automatic varibles declared inside a

function in which they are utilized. so, automatic variables are private to that

function.

Page 154: C presentation book

• Automatic variables are referred as a local variable or internal variable.

• So you can declare this variable in more than one function without any confusion.

• Ex: main() { int number ; }

You can also declared explicitly with auto keyword

Ex: main() { auto int number ; }

Page 155: C presentation book

• External variable :• variables that are both active and alive

throughout the entire program is known as external variable.It is also called global variable.

• unlike local varibles global variables can be accessed by any function in the program.

• Ex: int number; main() { ……… } fun1() { …….. } fun2() { …….. }

Page 156: C presentation book

• Static variables: static variables declared using static keyword. Ex: static int number; Static variables are initialised only once during the

execution of the program. static variables are generally used to retain values

between function calls. Ex: main() { int i; for(i=0;i<=3;i++) stat(); } stat() { static int x=0; x++ ; printf(“%d\n”,x) }

Page 157: C presentation book

• Register Variables : Register Variables are generally used to

store variable register so you can access that variable very fast than store in the memory.

you can create your register variable using register keyword.

Ex: register int x;register variables are generally used in looping.

Page 158: C presentation book

Chapter - 10 Structure and Unions

• Structures : Structure is nothing but group of dataitems

of different type with a single name.

Define structure : struct book_name { char title ; char author; int pages ;

float prices; }; struct book_name book1,book2,book3;

Page 159: C presentation book

• Second method to defining structure is :

struct book_name { char title ; char author; int pages ;

float prices; } book1,book2,book3;

You can defined structure globally as well as locally. when you defined structure outside the main its

called global declaration of structure. when you declared structure inside the main its called

local declaration of structure.

Page 160: C presentation book

#include<stdio.h>#include<conio.h>#include<string.h>#define l 2void main(){ int i,j; struct stud { int rno; char nm[50]; char add[50]; char ct[50]; int ph; }s; clrscr();

Page 161: C presentation book

printf("Give Roll No:"); scanf("%d",&s.rno); printf("Give Name:"); scanf("%s",s.nm); printf("Give Address:"); scanf("%s",s.add); printf("Give City:"); scanf("%s",s.ct); printf("Give Phone No:"); scanf("%d",&s.ph); printf("Roll No:%d\n",s.rno); printf("Name:%s\n",s.nm); printf("Address:%s\n",s.add); printf("City:%s\n",s.ct); printf("Phone No:%d\n",s.ph); getch();}

Page 162: C presentation book

• Initialization of structure variable : First method to initialise structure : main()

{ struct st_record { int weight; float height; }; struct st_record stud1 = {60,80.5}; struct st_record stud2 = {53,170}; }

Page 163: C presentation book

Second method to initialise structure : struct st_record { int weight; float height; } stud1={60,80.5}; /* you also initialise stud2 globally by

separating comma */ main()

{struct st_record stud2 = {60,80.5};

}

Page 164: C presentation book

Arrays of structure :// Program No:40#include<stdio.h>#include<conio.h>#include<string.h>#define l 3void main(){ int i,j; struct stud { int rno; char nm[50]; char add[50]; char ct[50]; int ph; }s[l]; clrscr();

Page 165: C presentation book

for(i=0;i<l;i++) { printf("Give Roll No:"); scanf("%d",&s[i].rno); printf("Give Name:"); scanf("%s",s[i].nm); printf("Give Address:"); scanf("%s",s[i].add); printf("Give City:"); scanf("%s",s[i].ct); printf("Give Phone No:"); scanf("%d",&s[i].ph); } for(i=0;i<l;i++) { printf("Roll No:%d\n",s[i].rno); printf("Name:%s\n",s[i].nm); printf("Address:%s\n",s[i].add); printf("City:%s\n",s[i].ct); printf("Phone No:%d\n",s[i].ph); } getch();}

Page 166: C presentation book

// Program No:41#include<stdio.h>#include<conio.h>#include<string.h>#define l 3#include<stdlib.h>void main(){ char ch[50]=""; int i,j; struct crt { int arg; char nm[50]; char tnm[50]; }s[l]; clrscr();

Page 167: C presentation book

for(i=0;i<l;i++) { printf("Give Name:"); scanf("%s",s[i].nm); printf("Give Name of Team:"); scanf("%s",s[i].tnm); printf("Give Average:"); scanf("%d",&s[i].arg); } for(i=0;i<l;i++) { if(strcmp(s[i].tnm,ch)!=0) { strcpy(ch,s[i].tnm); printf("%s team list\n",ch); for(j=i;j<l;j++) {

if(strcmp(s[j].tnm,ch)==0) { printf("%s\n",s[j].nm); printf("%d\n",s[j].arg); }}

} } getch();}

Page 168: C presentation book

• Array within structure : void main() { struct marks { int sub[3]; int total ; }; struct marks student[3] =

{45,67,81,0,75,53,69,0,57,36,71,0}; int i,j; for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { student[i].total += student[i].sub[j]; } }

Page 169: C presentation book

printf(“display student total\n\n”) for(i=0;i<=2;i++) printf(“student[%d] %d”,i+1,student[i].total)

}

Structure within structure : Structure within a structure means nesting of structures.

Ex: the following structure defined to store information about the salary of employees.

struct salary { char name[20] ; char department[20]; int basic_pay; int houserent_allowance; int city_allowance ; int medical_allowance; }

Page 170: C presentation book

• Now we can group all the items related to allowance together and declare them under a structure .

struct salary {

char name[20] ; char department[20];

int basic_pay; struct

{ int houserent_allowance; int city_allowance ; int medical_allowance; } allowance ; }

Page 171: C presentation book

• The salary structure contains a member named allowance which itself is a structure with three members.the members contained in the inner structure can be reffered as :

employee.allowance.dearness employee.allowance.house_rent employee.allowance.city It is not allowed directly accessed ex: employee.allowance (actual member is

missing) employee.house_rent (inner structure

variable is missing)

Page 172: C presentation book

• An inner structure can have more than one variable name.

Ex: struct salary { char name[20]; char department[10]; struct { int city_allowance; int houserent_allowance; int medicle_allowance; } allowance,arears;

* We can also use tag name to define inner structures.

Page 173: C presentation book

struct pay { int city_allowance; int houserent_allowance; int medicle_allowance; }; struct salary { char name[20]; char department[10]; struct pay allowance; struct pay arrears; }; struct salary employee;

Page 174: C presentation book

• Structure and function : There are three method by which the values of a

structure can be transferred from one function to another function.

1. pass each member of the structure as an actual argument of the function.This method is

inefficient when structure size is very large. 2. passing of a copy of the entire structure to the

called function.since function working on the copy of the structure,any changes to structure members within the function are not reflected in the original structure. therefore it is necessary for the function to return the entire function to the called function. All compiler does not support this method.

Page 175: C presentation book

3. using pointer to pass the structure as an arguments. In this case address location of the structure is passed to the called function.the function can access indirectly the entire structure and work on it. This method is more efficient than other two method.

The general format of sending a copy of the structure to the called function.

data_tye function_name(struct_type st_name)

{ ……………. ……………. return(expression); }

Page 176: C presentation book

• Program to illustrate the method of sending an entire structure as a parameter to a function.

#include<stdio.h>#include<conio.h>struct stores{ char name[20]; float price; int quantity;

};struct stores update(struct stores product,float p,int q){ product.price = product.price + p; product.quantity=product.quantity + q; return(product);}

Page 177: C presentation book

float mul(struct stores stock){ return(stock.price * stock.quantity);}void main(){float p_increament , q_increament , value;struct stores item = {"ABC",25.34,12};printf("price increament and quantity increament\n");scanf("%f %d",&p_increament,&q_increament);/*------------------------------------------------*/item = update(item,p_increament,q_increament);/* ----------------------------------------------- */printf("update values of item\n\n");printf("Name : %s",item.name);printf("Price : %f",item.price);printf("Quantity : %d",item.quantity);

/*----------------------------------------- */value = mul(item);/*------------------------------------------*/printf("value of the item = %f",value);}}

Page 178: C presentation book

• Union : Unions are concepts borrowed from structures

therefore follow the same syntax as structures.

Difference between structure and unions : In structures each member has its own storage

locations, whereas all members of the unions use the same storage locations.This implies that a union may contain many members at a time but it can handle only one member at a time.

In unions the compiler allocates a piece of storage that is large enough to hold the largest variable type in the union.

Page 179: C presentation book

Ex: Unions Example#include<stdio.h>#include<conio.h>union item{ int m; int x; int c;}code;void main(){ code.m=10; code.x = 15; printf("%d",code.m); printf("%d",code.x);}

/* Output : 15 15 */

Page 180: C presentation book

• Using unary operator sizeof() you can know the size of structure.

• Bit Fields :integer fields of size 16 bits to store data. There are occasions where data items require much less than 16 bits space. In such cases, we waste memory space. This is possible using small bit fields. The bit field is a set of bits whose size can be from 1 to 16 bits in length. A word can be divided into a number of bit fields.

the name and size of the bit fields are defined using a structure.

Page 181: C presentation book

• General format to define bit fieldth : struct tag_name { data_type name1 : bit_length;

data_type name2 : bit_length;data_type name3 : bit_length;………………………………………..data_type nameN : bit_length;

}

Where data_type is either int , unsigned int and bit – length specified number of bits used for specified name. The bit length is decided by the range of values to be stored

Page 182: C presentation book

• There are several specific points to be observer :1. The first field always starts with the first bit of the

word. 2. A bit field cannot overlap integer boundaries.the

sum of lengths of all fields in a structure should not be more than the size of a word.In case,it is

more,the overlapping field is automatically forced to the beginning of the next word. 3. there can be unnamed field declared with size.

unsigned : length ; It provides padding within the word.

4. there can be unused bits in a word.5. we cannot take the address of a bit field variable.this means we cannnot use scanf function and pointer in the bit field. 6. Bit fields cannot be arrayed.7. Bit fields should be assigned values that are within the range of their size. If we try to assign larger value than unpredicted result generated

Page 183: C presentation book

• Ex: struct personal

{unsigned sex : 1

unsigned age : 7unsigned m_status : 1unsigned childeren : 3

unsigned : 4 } emp;

Range :

Bit field Bit-length Rangesex : 1 0 or 1age : 7 0 or 127 m_status : 1 0 or 1childeren : 3 0 to 7

Note : we cannot use scanf to read values into a bit field.we may have to read into a temporary variable and then assigns its value to the bit field.

Page 184: C presentation book

Chapter-11 POINTERS

What is a pointer ? A pointer is nothing but a variable that contains the

address which is a location of the another variable in memory.

Benefits of using the pointer :1. A pointer enables us to access a variable that is

defiend outside the function.2. Pointer are more efficient in handling data table.3. Pointer reduces the length and complexity of the

program.4. The use of pointer array to character string results

in saving of datastorage space in memory.

Page 185: C presentation book

• Declaring and initialising pointers :

syntax :

data_type *pt_name ;

this tells the compiler three things about the variable pt_name.

1. * tells the compiler that the variable pt_name is a pointer variable.2. pt_name needs a memory location.3. pt_name points to a variable of type data_type.

Page 186: C presentation book

• Ex: int quantity=179 ;int *p;

p=&quantity; quantity variable 179 value

5000 Address

p=&quantity; using this statement you can store the address of the variable quantity to the pointer variale p.

Note : you can know the address of variable using %u format specification.

You can’t assign an absolute address to a pointer variable directly.

Ex: p = 5000; It is not possible

Page 187: C presentation book

• Accessing variables using pointers.void main()

{int x,y, *ptr;

x=10; ptr=&x;

y = *ptr;printf(“Value of x is %d\n\n”,x);printf(“%d is stored at address %u\n”, x, &x);printf(“%d is stored at address %u\n”, *&x, &x);printf(“%d is stored at address %u\n”, *ptr, &x);printf(“%d is stored at address %u\n”, y, &*ptr);printf(“%d is stored at address %u\n”,ptr,&ptr);

printf(“%d is stored at address %u\n”, y, &y);

*ptr=25;printf(“\n Now x = %d\n”,x)

}

Page 188: C presentation book

• Output: Value of X is 10 10 is stored at address 410410 is stored at address 410410 is stored at address 410410 is stored at address 41044104 is stored at address 410610 is stored at address 4108

Now x = 25

Page 189: C presentation book

• Pointers expression :void main()

{int a,b,*p1,*p2, x, y, z ;a =12; b = 4; p1=&a; p2 = &b;x = *p1 * *p2 – 6;y = 4* - *p2 / *p1 + 10;printf(“Address of a = %u\n”,p1);printf(“Address of b=%u\n”,p2);printf(“\n”);Printf(“a=%d, b=%d\n”,a , b); printf(“x=%d , y=%d\n”,x,y);*p2 = *p2 + 3 ; *p1 = *p2 – 5 ; z= *p1 * *p2 – 6 ;printf(\n a = %d , b = %d “, a ,b);printf(“z = %d\n”, z);

}

Page 190: C presentation book

Out put :- Address of a = 4020Address of b =4016a = 12 b=4x=42 y=9a=2 b=7 z=8

Pointer increments and scale factor :p1++ will cause the pointer p1 points to the next value of its type. Ex :- if p1 is an integer pointer with the initial value say 2800,then after the operations p1=p1+1,the value of p1 will be 2802,not 2801

when we increment pointer its value is increased by the length of the data type that it points to.This length is called scale factor.

Page 191: C presentation book

• Pointer and Arrays :-

When an array is declared,the compiler allocates a baseAddress and sufficient amount of storage to contains allThe elements of the array in memory location.

Base address is the location of the first element of thearray

int x[5] = {1,2,3,4,5}

Suppose the base address of x is 1000 and assuming that Each integer requires 2 bytes,the five elements stored as Follows :

Element x[0] x[1] x[2] x[3] x[4]Value 1 2 3 4 5Address 1000 1002 1004 1006 1008

So, base address is,x = &x[0] = 1000

Page 192: C presentation book

• If we declare p as integer pointer, then we can make the pointer p to point to the array x by the following statements.

p = x or p = &x[0]Now we can access every element of x using p++ to move from one element to another.

p = &x[0] (=1000)p+1 = &x[1] (=1002)p+2 = &x[2] (=1004) p+3 = &x[3] (=1006)

p+4 = &x[4] (=1008)

Page 193: C presentation book

/***PRGRAMM FOR N NUMBER ELEMENT SUM******/#include<stdio.h>main(){

int x[10],i,*p,n,sum=0;printf("enter the N:");scanf("%d",&n);printf("enter the the data:\n");for(i=0;i<n;i++){scanf("%d",&x[i]);}p = x;for(i=0;i<n;i++){printf("\n%d",*p);sum=sum + *p;p++;}printf("\nsum=%d",sum);

}

Page 194: C presentation book

2,0 2,3

P

P + 1

0 1 2 3 4

0

1

2

3

*(p+2)

p+2

P = pointer to first row

P+I = pointer to ith row

*(p+i) = pointer to first element in the ith row

*(p+i)+j = pointer to jth elements

*(*(p+i)+j)=value stored in the cell(i,j)

*(p+2) + 3

Page 195: C presentation book

/*** PROGRAMM FOR SUM OF N NUBER ELEMENT*****/#include<stdio.h>main(){

int x[10][10],i,j,n,sum=0;clrscr();printf("enter the N:");scanf("%d",&n);printf("enter the the data:\n");for(i=0;i<n;i++){for(j=0;j<n;j++){scanf("%d",&x[i][j]);}

Page 196: C presentation book

`for(i=0;i<n;i++){for(j=0;j<n;j++){printf("\n%d",*(*(x+i)+j));sum=sum + *(*(x+i)+j);}}printf("\nsum=%d",sum);

} getch(); }

Page 197: C presentation book

/* program for double dimention matrix */#include<stdio.h>main(){ int a[5][5],r; clrscr(); scanf("%d",&r); rea(a,r); writ(a,r);}

rea(int (*p)[5], int r){ int i,j; for(i=0;i<r;i++) for(j=0;j<5;j++) { printf("Enter the element data for (%d,%d) : ",i+1,j+1); scanf("%d",*(p+i)+j); }}

Page 198: C presentation book

writ(int (*p)[5], int r){ int i,j; for(i=0;i<r;i++) { for(j=0;j<5;j++) printf("%d",*(*(p+i)+j)); printf("\n"); }}

Page 199: C presentation book

• Pointer and character string :-In c, a constant character string always represents a pointer to that string. And therefore you can directly write char *name;name = “DELHI”these statements will declare name as a pointer to character and assign to name the constant character string “Delhi”.

but remember that this type of assignment does not apply on character arrays.

char name[20];name = “DELHI”

one important use of pointer is handling of a table of string.following is the array of string.char name[3][25];this say that table containing three names ,each with a maximum length of 25 characters. So total storage requirement for the name table are 75 bytes

Page 200: C presentation book

• We know that individual string may be equal length.therefore instead of making each row a fixed number of characters,we can make it a pointer to a string of varying length.

char *name[3] = { “New Zealand”,

“Australia”,“India”

}Where name to be an array of three pointers to a character,each pointer points to a particular name.

name[0]=“New Zealand”,name[1]=“Australia”,name[2]=“India”

This declaration allocates only 28 bytes.

The character arrays with the rows of varying length are called ragged array.

Page 201: C presentation book

/****PROGRAMM FOR STRING PRINT USING POINTER ****/#include<stdio.h>main(){

char name[10],*ptr;clrscr();printf("enter the name => ");scanf("%s",name);ptr=name;printf("\n");while(*ptr != '\0'){printf("%c",*ptr);ptr++;}

getch(); }

Note : if we want to directly assign string constant then we have to make name as character pointer.char *name ; name = “Delhi”

Page 202: C presentation book

• Pointer and function :When we pass addresses to a function,the parameter receiving the addresses should be pointers.The process of calling a function using pointer to pass the address of variable is known as call by reference. The function which is called by ‘reference’ can change the value of the variable used in the call.

Ex: main(){

int x=20;;change(&x);printf(“%d\n”,x);

}change(int *p){

*p = *p + 10}

Page 203: C presentation book

Thus call by reference provides the mechanism by which the function can change the stored value.

Ex: /***PROGRAM FOR EXCHANGING THE VALUE*****/#include<stdio.h>main(){int a,b;printf("enter the number");scanf("%d %d",&a,&b);printf("\t\t\nA=%d B=%d\n\n",a,b);swap(&a,&b);printf("\t\t\nA=%d B=%d",a,b);}swap(int *p ,int *q){int t;t=*p;*p=*q;*q=t;}

Page 204: C presentation book

• POINTERS AND STRUCTURES :We know that name of an array stands for address of the zeroth elements.the same thing is true for names of arrays of structure variable.

Ex: struct inventory{

char name[30];int number;float price;

} product[2],*ptr;

here product as an array of two elements and ptr as pointer to data objects of the type struct inventory.

ptr = product ;

would assign the address of the zeroth element of product to ptr. That is the pointer ptr points to the product[0].It’s members can be accessed using the following notation.

Page 205: C presentation book

• ptr -> nameptr->numberptr->price

-> : this symbol is called arrow operator and is made up of minus sign and greater than sign.

When pointer ptr is incremented by one.it is made to point to the next record i.e. product[1].

we can also use notation (*ptr).number to access the member number.Parantheses around *ptr are necessary because the member operator “.” has a higher precedence than the operator *.

Note : precedence is necessary in structure.ex: ++ptr -> count : increment counter (++ptr)->counter :- increment pointer.

Page 206: C presentation book

• Ex: pointer to structure variable :struct invent{

char *name[20];int number;float price;

} product[3] , *ptr ;void main(){

for(ptr=product ; ptr < product + 3 ; ptr++)scanf(“%s %d %f”,ptr->name,&ptr->number,&ptr->price);

ptr=product;

for(ptr=product ; ptr < product + 3 ; ptr++)printf(“%s %d %f”,ptr->name,ptr->number,ptr->price);

}

Page 207: C presentation book

• Pointer to function :A pointer which points to a function is called function to a pointer.

syntax: type (*fptr)();

Ex: double (*p1)() , mul();p1=mul;

where p1 points to a function mul. Now to the function mul we can use pointer p1 instead of mul function.

To call the function mul, we may now use the pointer p1 with the list of parameters.that is

(*p1)(x,y)is equivalent tomul(x,y)

Page 208: C presentation book

Chapter-12 File Management in C

using the functions such as scanf and printf to read and write data. These are console oriented I/O functions which always use the terminal as the target place.This works fine as long as the data is small.In many real-life problem involve large volume of data and in this situation console oriented operations pose two major problems1. it is more time consuming to handle large volumes of data.2. the entire data is lost when either the program is

terminated.so, it’s a more flexible that data can be stored on the disk and read whenever necessary, without destroying the data.this is possible using the concept file to store data.

A file is a place on the disk where a group of related data is stored.

Page 209: C presentation book

• Basic file operations are :naming a file opening a filereading data from filewriting data to a fileclosing a file

DEFINING AND OPENING A FILE :General format for defining and opening a file :syntax :

FILE *fp ;fp = fopen(“filename”,”mode”);

where fp is a pointer variable which points to the data type FILE. FILE is a structure that is defined in the I/O library.

The second statement open the file named filename. the second method also specifies the openig of the file.the mode do this job.

Page 210: C presentation book

• There are three types of mode :r open the file for reading onlyw open the file for writing onlya open the file for appending data to it.

when trying to open a file,there are three possibilities :1. In write mode : a file with specified name is created if the file does not exist.the contents are deleted if the file are already exist.2. In append mode : when the purpose is “appending” the file is opened with the current content safe.a file with the specified file name is created if file does not exist. 3. In read mode : if file is exist then open file in read mode otherwise an error occurs.

Ex: FILE *p1 , *p2 ;p1 = fopen(“data”,”r”);p2 = fopen(“results”,”w”);

Page 211: C presentation book

• Closing a file :

Using this function you can close the file.

syntax : fclose(file_pointer);

Ex: fclose(*p1);

fclose(*p2);

INPUT OUTPUT OPERATION IN FILE :

getc and putc Functions :

Using getc function you can read a character from a file that has been opened in read mode.

syntax : c = getc(fp);

where fp is a file pointer which points to a file which is opened in a read mode

Page 212: C presentation book

And store the character to the variable c. Readind should be terminated when EOF is encountered.

using putc function you can write character to a file.

syntax : putc(c,fp1)

where fp1 is a function pointer which points to a file which is opened in write mode to store the character and c is a character variable which stores the character which is write to a file.

Page 213: C presentation book

• Ex : #include<stdio.h>Void main(){

FILE *f1;char c;

f1 = fopen(“INPUT”,”w”);while((c=getchar()) != EOF)

putc(c,f1); fclose(f1);

f1 = fopen(“INPUT”,”r”);while((c=getc(f1)) != EOF) printf(“%c”,c);fclose(f1);

}Note :You terminate the entering string by pressing ctrl + Z.

Page 214: C presentation book

• Similarly getw and putw functions are used to read the integer value from file and to write the integer value to the file.

#include<stdio.h>Void main(){

FILE *f1;int no , i;

f1 = fopen(“INPUT”,”w”);for(i=0 ; i < 10 ; i++)

{ scanf(“%d”,&no);if(no == -1) break;putw(no,f1);

} fclose(f1);

f1 = fopen(“INPUT”,”r”);while((no=getw(f1)) != EOF) printf(“%d”,no);fclose(f1);

}

Page 215: C presentation book

/****PROGRAMM FOR TO READ AND WRITE FROM FILE***********/#include<stdio.h>main(){FILE *f,*f1,*f2;int c,i;clrscr();printf("ENTER THE THE DATA ==== >");

f=fopen("input","w");for(i=0;i<50;i++){scanf("%d",&c);if(c==999)break;putw(c,f);}

fclose(f);

Page 216: C presentation book

f=fopen("input","r");f1=fopen("even","w");f2=fopen("odd","w");

while(!feof(f)){c=getw(f);printf("%d",c);if(c%2==0) putw(c,f1);else putw(c,f2);}fclose(f);fclose(f1);fclose(f2);

f1=fopen("odd","r"); f2=fopen("even","r");

Page 217: C presentation book

printf("GIVE DATA IS ODD\n");while(!feof(f1)) { c=getw(f1); printf("%d",c); } printf("GIVE DATA IS EVEN\n"); while(!feof(f2)) { c=getw(f2); printf("%d",c); }

fclose(f1); fclose(f2);

}

Page 218: C presentation book

• The fprintf and fscanf function :the functions fprintf and fscanf are identical to the printf and scanf function.

fscanf and fprintf functions are generally used to perform input and output operation.

syntax for fprintf :fprintf(fp,“control string”,list)

where fp is a file pointer associated with the file that has been opened for writing. The control string contains output specifications for the items in the list. The list may include variables , constants and strings.Ex: fprintf(f1,”%s %d %f”, name,age,7.5);

fscanf functions are generally used to read the data from the file.

Page 219: C presentation book

syntax for fscanf :fscanf(fp,“control string”,list)

where fp is a file pointer associated with the file that has been opened for reading. The control string contains input specifications for the items in the list. The list may include variables , constants and strings.

Ex: fscanf(f2,”%s %d”, item , &quantity);

Page 220: C presentation book

• Error handling during I/O operation :It is possible that an error may occur during I/O operation on a file.typical error situation include :

1. Trying to read beyond the end – of – file mark.2. Trying to use a file that has not been opened.3. Trying to perform an operation on a file.,when the file

opened for another type of operation.4. Opening a file with an invalid filename.5. Attempting to write to a write – protected file.

this type of errors are handles during the I/O operations.

The feof function can be used to test for an end of file condition.

if(feof(fp)) printf(“End of data \n”);

Page 221: C presentation book

• Where fp is file pointer it pass as a arguments to the feof function.

• The ferror function is used to check that an error has occurred or not during the reading processing.

Ex: if(ferror(fp) != 0 ) printf(“An error has occurred\n”);

• When the file cannot be opened for some reason,then the function returns a null pointer.this facility can be used to test whether a file has been opened or not.

Ex: if(fp == NULL)printf(“File could not be opened”);

Page 222: C presentation book

• Ex: #include<stdio.h>void main(){

char *filename;FILE *fp1,*fp2;int i , number;fp1 = fopen(“TEST”,”w”);for(i=0;i<=100;i+=10)

putw(i , fp1);fclose(fp1);printf(“Input file name \n”);

Open_file :scanf(“%s”,filename);if((fp2 = fopen(filename,”r”)) == NULL){ printf(“can not open the file Try again\n ”); goto open_file; }

Page 223: C presentation book

elsefor(i=1;i<=20;i++){ number = getw(fp2);

if(feof(fp2)){ printf(“\n Range out of data.\n”); break;}else printf(“ %d \n”, number);

}

fclose(fp2);

}

Page 224: C presentation book

• Random access to a files :using ftell , rewind and fseek functions we can randomly access the files.

ftell function :-using ftell function we can know the current position

of the file.syntax : n = ftell(fp)

where fp = filepointer , n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written)

rewind function :- using this function we can resets the position of the pointer to the start of the file.

syntax : rewind(fp);n=ftell(fp);where fp = file pointer. When second

statements are executed it would assign 0 to n because file position has been set to the start of the file by rewind.this functions helps us in reading a file more than once,without having close and open the file

Note : whenever file is open for reading or writing , rewind is done automatically

Page 225: C presentation book

• fseek function : fseek function is used to move the file position to a desired location.

syntax : fseek(fileptr,offset,position);

where fileptr is a pointer to the file concerned , offset is a number or variable of type of long.the offset specifies the number of positions to be moved from the location specified by position.

The position take one of the following three form :value meanings0 Beginning of the file1 current position2 End of the file

Page 226: C presentation book

• The offset may be positive, meaning move forwards or negative meanings move backwards.

the following examples illustrate the operation of the fseek function :

Statement Meaningfseek(fp,0L,0) Go to the Beginningfseek(fp,0L,1) stay at current positionfseek(fp,0L,0) Go to the end of the file.

fseek(fp,m,0) Move to (m+1)th byte in the filefseek(fp,m,1) Go forward by m bytesfseek(fp,-m,1) Go backward m bytes from

current position.fseek(fp,-m,2) Go backward by m bytes from the end.When operation is successful,fseek returns a 0 otherwise returns -1.

Page 227: C presentation book

• Example:#include<stdio.h>void main(){

FILE *fp;long n;char c;fp = fopen(“RANDOM”,”w”);while((c=getchar()) != EOF) putc(c,fp);printf(“No.of character entered=%ld”,ftell(fp));fclose(fp);

fp = fopen(“RANDOM”,”r”)n = 0L;

Page 228: C presentation book

while(feof(fp)==0){

fseek(fp,n,0) /* position to (n+1)th character */printf(“Position of %c is %ld\n”,getc(fp),ftell(fp));n=n+5L;

}}Output :ABCDEFGHIJKLMNOPQRSTUVWXYZ^ZNo.of character entered = 26Position of A is 0Position of F is 5Position of K is 10Position of P is 15Position of U is 20Position of Z is 25Position of is 30

When printing current position 30 the loop is terminating.

Page 229: C presentation book

• Command line arguments :-command line arguments is a parameter supplied to a program when the program is invoked.

Execution of the c program is starting from the main function. main function also contains arguments like another normal function.

main function can take two arguments : argc and argvvariable argc counts the number of arguments on the command line.

argv is an argument vector and represents an array of character pointers that point to the command line arguments. The size of this array will be equal to the value of argc.

Page 230: C presentation book

• Ex: if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE,then we may use command line like,

c:> PROGRAM X_FILE Y_FILEWhere PROGRAM is a filename where program execution code is stored.

so, argc ----> 3 argumentsargv[0] ------> programargv[1] ------> X_FILEargv[0] ------>Y_FILE

to access the command line arguments, we must declare main function and its parameters.

main(int argc, char *arg[v]){…………….……………}

Page 231: C presentation book

Example:

#include<stdio.h>#include<conio.h>void main(int argc , char *argv[]){

FILE *fp;int i;char word[15];clrscr();fp=fopen(argv[1],"w");printf("No.of arguments =%d\n",argc);for(i=2;i<argc;i++) fprintf(fp,"%s",argv[i]); /* write contents to file */fclose(fp);

Page 232: C presentation book

/* writing contents of the file to the screen */printf("contents of the file to the screen\n");fp = fopen(argv[1],"r");for(i=2;i<argc;i++){

fscanf(fp,"%s",word);printf("%s",word);

}fclose(fp);printf("\n\n");getch();

}

Page 233: C presentation book

Chapter 13 Dynamic Memory Allocation

Need for DMA ?Most often we face situations in programming where the data is dynamic in nature. That is, the number of data items keep changing during execution of the program.

Ex :A program for processing the list of customers of corporation.the list grows when the names are added and shrinks when names are deleted.When list grows we need to allocate more memory space to the list to accommodate additional data items.such situations can be handled more easily and effectively by using what is known as dynamic data structures.

Page 234: C presentation book

• What is DMA ?The process of allocating memory at runtime is known as Dynamic Memory Allocation.

There are four memory allocation function :malloc : It allocates requested size of bytes and returns

a pointer to the first byte of the allocated space.

calloc : Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory.

free : Frees previously allocated space.

realloc : Modifies the size of previously allocated space.

Page 235: C presentation book

• Memory allocation process

Local variables

Free memory

Global variables

C program instructions

Stack

Heap

Permanent storage

Area.

The memory space that is located between two region is available for dynamic memory allocation during execution of the program.this free memory region is called heap.the size of the heap keep changing during the execution of the program.therefore it is possible to memory overflow problem during dynamic allocation process.in such situation memory allocation function returns a NULL pointer.

Page 236: C presentation book

• malloc :

Using this function we can allocate a block of memory. The malloc function reserve a block of memory of specified size and returns a pointer of type void. This means that we can assign it any type of the pointer.

syntax : ptr = (cast-type *) malloc (byte-size)

ptr : is a pointer of the type cast-type.

malloc : returns a pointer to an area of memory with size

byte-size.

Ex: x = (int *) malloc (100 * sizeof(int));

100 * sizeof(int) memory space is allocated and x points to the first byte of the memory allocated spaces.

Page 237: C presentation book

cptr = (char *) malloc (10)

it allocates 10 bytes of space for the pointer cptr of type char.

cptr

Remember ,the allocation fail if the space in the heap is not sufficient to satisfy request.If it fails,it returns a NULL.we should there for check whether the allocation is successful before using the memory pointer.

Address of first byte

10 bytes of space

Page 238: C presentation book

• Ex:#include<stdio.h>#include<stdlib.h>define NULL 0main(){

int *p, *table;int size;printf(“\n what is the size of the tbale ?”);scanf(“%d”,size);

if(table = (int *)malloc(size * sizeof(int))) == NULL){

printf(“No space is available \n”);exit(1);

}printf(“Reading Table values\n”);for(p=table;p<table+size;p++)

scanf(“%d”,p);

for(p=table;p<table+size;p++)printf(“%d”,*p);

}

Page 239: C presentation book

• malloc :

using this function we can allocate multiple block of storage and each of the same size and then sets all bytes to zero.

syntax : ptr = (cast-type *) calloc (n,elem-size)

the above statements allocates contiguous space for n blocks , each of size elem-size bytes.all bytes are initialised to zero and a pointer returns to the first bytes of the allocated region.if there is not space then it returns NULL pointer

It is generally used for storing derived data – type such as arrays and structures.

Page 240: C presentation book

• Ex:struct student{

char name[25];float age;long int id_num;

};typedef struct student record;record *st_ptr;int class_size=30;

st_ptr=(record *) calloc (class_size , sizeof(record));…………..……………if(st_ptr == NULL){

printf(“Available memory is not sufficient\n”);exit(1);

}

Page 241: C presentation book

• free :using free function we can releases the block of memory which is created by malloc and calloc function.

syntax : free(ptr)

Where ptr is a pointer to a memoryblock which is created by malloc and calloc.

• realloc :using this function we can change the already allocated memory – size.and this process is called the reallocation process.

Ex: ptr = malloc(size) /* allocates the space */

ptr = realloc(ptr,newsize) /* reallocates the space */

Page 242: C presentation book

• Ex: program for use of realloc and free function :#include<stdio.h>#include<stdlib.h>#define NULL 0void main(){

char *buffer;/* allocating memory */if(buffer = (char *)malloc(10))==NULL){

printf(“malloc failed\n”);exit(1);

}

strcpy(buffer,”HYDERABAD”);printf(“Buffer contains : %s\n”,buffer);

Page 243: C presentation book

/* Reallocation */

if(buffer = (char *) realloc(buffer,15))==NULL){

printf(“Reallocation failed \n”);exit(1);

}printf(“Buffer size is modified.\n”);strcpy(“buffer”,”SECUNDERABAD”);printf(“buffer now contains : %s\n”,buffer);

/* Freeing memory */free(buffer);

}

Page 244: C presentation book

Chapter 14: The Preprocessor

What is preprocessor?

The preprocessor is a program that processes the source codeBefore it passes through the compiler.

Preprocessor Directives:

Following are the preprocessor directives:#define Define a macro substitution#undef Undefined a macro#include Specifies the file to be included#ifdef Test for macro definition#endif Specifies the end of if#ifndef Tests whether a macro is not defined#if Tests a compile time condition#else Specifies alternative when #if test fails.

Page 245: C presentation book

Preprocessor directive follow special syntax rule. • They all begin with the symbol #.• They don’t require the semicolon at the end.• Preprocessor directives are placed before the main

line

These directives can be divided into three categories:• Macro Substitution directives• File inclusion directives• Compile control directives

Macro Substitution:

Macro substitution is a process where an identifier in aProgram is replaced by a predefined string composed of one or more tokens.

Page 246: C presentation book

There are different form of macro substitution.• Simple macro substitution.• Argument macro substitution.• Nested Macro substitution.

Simple macro substitution.

The preprocessor accomplish this task under the direction ofthe #define statement

This statement usually known as a macro definition or simply macro.

Syntax: #define identifier string

Page 247: C presentation book

Ex:#define count 100#define False 0#define PI 3.14#define AREA 5*12.46#define SIZE sizeof(int)*4#define D 45-22#define A 78+32

#define TEST if(x>y)#define AND #define PRINT printf(“Very Good.\n”);

TEST AND PRINT

The preprocessor translate above line to.If(x>y) printf(“Very Good.\n”);

Page 248: C presentation book

#define EQUALS ==#define AND &&#define BLANK LINE printf(“\n”);#define INCREMENT ++

Macro with Arguments:

When you passed arguments to the macro is called the macrowith arguments.

Syntax: #define identifier(f1,f2……fn) string

Ex:#define CUBE(x) (x*x*x)If the following statements occur in the program.Volume = CUBE(side);

Page 249: C presentation book

Then the preprocessor expand this statement to :

Volume = (side * side * side);

If consider the following statement:Volume = CUBE(a+b)This would be expand to :Volume = (a+b * a+b * a+b)

Ex:#define MAX(a,b) (((a) > (b)) ? (a) : (b) )

Page 250: C presentation book

Nesting of the macros:

We can also use one macro inside another macro is called theNesting of the macro.

Ex:

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

Page 251: C presentation book

The preprocessor expands each #define macro, until no moremacro appear in the text.

For example, the last definition is first expanded into((SQU(x) * (x)) * (SQU(x) * (x)))

Since SQU(x) is still a macro, it is further expanded into line.((((x) * (x))*(x)) * (((x) * (x)) * (x)))

Which is finally evaluated as x6

Undefining a Macro:A define macro can be undefined, using the statement.#undef identifierThis is useful when we want to restrict the definition only to aparticular part of the program.

Page 252: C presentation book

FILE INCLUSION:

An external file containing functions or macro definition canbe included as a part of a program so that we need not

rewritethose functions or macro definitions. This is achieved by thepreprocessor directives.

#include “filename”

Where filename is the name of the file containing the requireddefinition of functions. At this point, the preprocessor inserts the entire contents of filename into the source code of the program. When the filename is included with the double quotation marks, the search for the file is made first in thecurrent directory and then in standard directories.

Page 253: C presentation book

#include <filename>Without double quotation marks. In this case, the file issearched only in the standard directories.

Nesting of included file is allowed. That is an included fileinclude another file.

Ex:#include<stdio.h>#include “SYNTAX.C”#include “STAT.C”#include “TEST.C”

Page 254: C presentation book

COMPILER CONTROL DIRECTIVES:

While developing large programs, you may face one or moreof the following situation.

Situatuion1 :

You have included a file containing some macro definitions. Itis not known whether a particular macro(say, TEST) has beendefined in that header file.

This situation refers to the conditional definition of a macro.We want to ensure that the macro test is always defined,irrespective it has been defined in the header file or not.

Page 255: C presentation book

This can be achieved as follow.

#include “DEFINE.H”#ifndef TEST

#define TEST 1

#endif

In the above case searched for the definition of TEST in theheader file and if not defined, then all the lines between the

#ifndef and the corresponding #endif directives are ‘active’ in the program.

That is the processor

#define TEST is processed.

In case, the TEST has been defined in the header file, the

#ifndef condition become false , therefore the directive

#define TEST is ignored.

Page 256: C presentation book

#ifdef TEST#undef TEST#endif

In the above case, even if TEST is defined in the header file, its

definition is removed.

Situation 2:

Suppose a customer has two different types of computers andyou are required to write a program that will run on both thesystem. You want to use the same program, although certainlines of code must be different for each system.

The main concern is to make the program portable.

Page 257: C presentation book

This can be achieved as following:main(){ ………. #ifdef IBM_PC{ ………. // Code for IBM_PC}#else{ ………. // Code for HP machine} #endif ……….}If we want the program to run of IBM PC. We include the

directive#define IBM_PC

Page 258: C presentation book

Situation 3.

This is similar to the above situation#ifdef ABC group A lines#else group B lines#endif

Group A lines are included if the customer ABC is defined.Otherwise Group B lines are included.

Page 259: C presentation book

Situation 4:This is useful for debugging a particular macro.Ex: #ifdef Test

{printf(“Array Element”);

for(i=0;i<m;i++)printf(“x[%d] = %d\n”, I, x[i]);

}#endif………….#ifdef TEST

printf(…….);#endif

Directives #ifdef and #endif are included only if the macroTEST is defined. Once Every thing is OK undefine the TEST.This makes the #ifdef TEST condition become false and therefore all the debugging statements are left out.

Page 260: C presentation book

The C preprocessor also support a more general form of testcondition - #if directive. This takes the following form:

#if constant expression{

statement 1statement 2………………

}#endif

If the result of the constant expression is true then all thestatements are executed otherwise they are skipped.

As a constant expression may be any logical expression.