You are on page 1of 29

Chapter – 1

Introduction to C Language

Computer Language

Humans use some language to communicate with other human beings; such languages are
called natural Languages such as Urdu, Pashto, Arabic or English etc. it is necessary for both the
communicating bodies to understand each other’s conversation for successful coordination.

We use computers to solve our problems. Computer does not understand what the problem is and how
it can be solved. We have to tell the computer what to do ? And How to do it ? By giving instruction to
it. These instructions must be given to computer in such a way that it can understand these. Those
languages which are used for this purpose are called computer languages.

A computer language has a specific character set, syntax, punctuation style, data types and certain rules
that can be used for writing a successful computer program. A computer program is actually a set of
instructions that tell the computer what to do and how to do. Theses instructions must be written
according the syntax of a particular computer language.

TYPES OF COMPUTER LANGUAGES

There are many different computer languages used for writing computer programs. These
languages are grouped into the following categories.

1. MACHINE LANGUAGES

Machine language is the Mother-Tongue or natural dialect of computer system. This


language is a collection of very detailed, cryptic instructions that control’s the internal
circuitry of computer system. Instructions are written in this language in the series of zeros
difficult. However, machine language program is executed very quickly.

2. ASSEMBLY LANGUAGES
Assembly languages are easier than machine languages because programs are written
using English like words called mnemonics in assembly language. For example.
LDA A
ADD B
Where
LDA means load accumulator with A and
Add number B to A
Assembly language program also requires translation into machine language, therefore,
assemblers are used. These are also difficult as compared to High – Level languages.
3. HIGH-LEVEL LANGUAGES
High-level languages are called high-level because they are easily understandable for
human beings. These languages use daily English words and mathematical notation for
writing instructions. For example, print, save, and read. As a rule, a single high-level
instruction is equivalent to several machine instructions. That’s why these languages
greatly simplify the task of writing, compiling and executing programs. Compilers and
interpreters are used for translation of these languages. Examples of high-level
languages are BASIC, FORTRAN, COBOL, C etc.
4. OBJECT-ORIENTED LANGUAGE
High-level languages are suitable for structured programming. But structured
programming begins to fail when the program size exceeds than 50 thousand
instructions.
For developing large size software object-Oriented programming methodology is used
Object-Oriented Programming consists of creating CLASSES and deriving OBJECTS from
those classes. A CLASS is designed to model real world object. Each class models the
attributes and behavior of real world objects. Then OBJECTS are derived from these
CLASSES.
Object-Oriented Programming uses Encapsulation, Inheritance and Polymorphism
techniques to develop large size software. Those computer languages are C++ , java, C#
etc.

TRANSLATION SOFTWARE

Translation software is used to translate a computer program that is written in one computer
language into Machine language. An Assembly language or High-level language program is not
understandable for a computer system that is why such a program must be translated into Machine
Language so that it can be executed successfully. There are three types of Translation software
discussed below.

1. ASSEMBLER
Assembler is a translator that converts an Assembly language program into Machine
language.
2. COMPILER
A compiler converts a program written in a High-level language into machine language.
Compiler first reads the whole program, checks for compilation errors, then compiles
the program into machine code at once. This machine code can then be executed easily.
3. INTERPRETER
The interpreter also converts a High-level language program into machine cade. But
there is a little difference between compiler and interpreter.
Interpreter fist reads the first instruction of program, converts it into machine code and
executes it there. Then selects the second instruction of program, converts it into
machine code and executes it and so on the whole program is translated as well as
executed therefore, interpreter is a little slower that compiler.
TYPES OF ERRORS

Errors can occur while writing computer programs. Errors halt the normal execution of
programs. Errors can occur at various stages of program development. There are three types of errors
which are discussed below.

SYNTAX ERRORS

Syntax errors are generated due to the violation of syntax rules of a language. These are
also called Compilation errors. These are found in the source code and they appear when we compile
the source code. The compiler alerts about the error and its location in the source code, therefore, these
errors are easier to remove. For Similarly other example, if a statement is not terminate with the
semicolon (;) then it’s a syntax error. Similarly other examples of syntax errors are below.

1. Using a variable name that is not declared.


2. Using only the opening bracket ({) and forgetting the closing one (})
3. Using the same name for two variables.
4. Using the variable name on the Right-hand side of assignment operator (=)
5. Applying unary operators on the constants instead of variables.

LOGICAL ERRORS

Logical errors are difficult to remove as compared to compilation errors because these errors
are not detected by the compiler. A program that contains logical error will compile successfully but will
not produce accurate result. These errors can only be removed by thoroughly analyzing each statement
of program. Examples of these errors are given below.

1. Using wrong operator in arithmetic or relational expression.


2. Using wrong format specifier in scanf()or printf() functions.
3. Using an integer type variable where a long integer is required.

RUNTIME ERRORS

Runtime errors occur at the time of executing a program that’s why these also called execution
errors. These are the most dangerous errors because such errors result in the abnormal termination of
program or hanging the computer system. These can be eliminated by analyzing the program statement
by statement. Examples of these errors are division by zero and unavailability of memory.

C.LANGUAGE

C is a general –purpose computer language developed between 1969 and 1973. Computer
programs can be written very concisely in this language. It is easier to program because its instructions
consists of terms that resemble algebraic expressions and uses certain English keywords like if , else, do,
continue, break, for, while etc. The instruction set is relatively small but actual implementations include
a large number of library functions which enhance the basic instructions. The features and capabilities of
this language can be extended by the users because C encourages the users to write their own library
functions. It is a high –level language but it can be used for system programming (e.g. for writing
operating systems) as well as applications programming.

ADVANTAGES AND WEAKNESSES OF C LANGUAGE

C is a very popular programming language which has the following advantages.

1. C has features that allow the programmer to organize programs in a clear, easy, and logical way.
2. C is succinct. It permits the creation of tidy, compact programs.
3. It can be used for system level programming such as writing operating systems, system drivers,
text editors, language compilers etc.
4. The vocabulary of C language is not very large and a new programmer can easily learn and use
it.

0 C is a portable language and program written for one computer can be executed on others.

5. C contains a lot rich library of built-in functions. Thus a programmer just needs to know and use
a required function.
6. It is a compiled language and is therefor, faster than interpreted languages.
7. C is a building block for many other known languages such as C++, Java, and Python etc. So if we
understand C and can program in this language the other languages can be easily learnt.

Inspire of several advantages there are some weaknesses or disadvantages of C language, which
are explained below.

1. There is no string data type in C language which makes it difficult to handle string data.
2. In C, memory is manually managed because there is no garbage collection concept in C.
3. No formal exception handling technique is available in C. There is no runtime checking in C.
4. C does not have object-Oriented programming features.
5. There is no strict type checking.

HISTORY OF C

C was originally developed between 1969 and 1973 by Dennis Ritchie at Bell Telephone
Laboratories. It was named C because most of its features were derived from an earlier language called
B. The B programming language was also developed at Bell Laboratories by Ken Thompson. B was a
stripped-down version of another language called BCPL (Basic Combined Programming Language). The
BCPL was a procedural and structured programming language designed by Martin Richards of the
University of Cambridge in 1966. BCPL was designed for writing compilers.
C was largely confined to use within Bell Laboratories until 1978, when Brian Kernighan and Ritchie
published a definitive description of the language. This description is commonly known as K&R C.

After the K&R description the C language become very popular among professional programmers and
they started to promote it. Several C compilers and interpreters have been written for computers of all
sizes and many commercial application programs have been written. There were some differences
between the K&R’s definition and early commercial implementations of C which resulted in minor
incompatibilities between different implementations of C language. Consequently, the American
National Standard Institute (ANSI) has developed a standardized definition of the C language. Now it is
commonly known as ANSI C.

Difference Between C and C++


The differences between C and C++ are given below

1. C is not Object – Oriented but C++ is an object – Oriented language.

2. The input/output functions are totally different in C and C++.

3. Structures in C cannot have functions, whereas C++ objects have both variables and functions.

4. C does not have reference variables at all whereas in C++ the reference variables can be passed
to functions instead of concrete objects.

5. Inline functions are not available in C.

6. In case of C, the data is not secured whereas in C++

7. C is function-driven while C++ is Object – driven. It means that functions are the building block
of a C program while objects are the building blocks of a C++ program.

8. C does not have Boolean type data whereas C++ has Boolean data type.

Basic structure of C program


Every C program consists of one or more components called functions. One of the functions.
One of the functions must be called main. The program will always begin by executing the main
function, which may access other functions. Any other function definitions must be defined
separately. Either ahead of or after main.

Each function must contain.


1. A function heading, which consists of the function name, followed by an optional list of
arguments, enclosed in parentheses.
2. A compound statement, which comprises all the statements of the function.
The general syntax or basic structure of a C program is discussed below.

#include<headerfileName>

Void main (void)

Statement-1;

Statement-2;

Statement-n;

The first is in instruction to the compiler which says “Take the header file and place it hear”.

The header file are identified by their file extension ( .h ). A header file actually contain the
declaration of certain function . We cannot use a library function in our main function until we

Include its proper header file. For example ,the printf () and scanf() functions have their

declaration in the stdio.h header file. Therefor, the stdio.h header file must be included in the

program. Similarly the declaration of clrscr() function is contained in the conio.h header file.

The second line contains the function heading. The first viod shows that this main function

Will not receive any data.

In the third line shows the opening brace {state the body of the function main and the closing
brace } on the last line shows the end of function body. The function body consists of all C
language statements that program the desired processing.

HEADER FILES : Header file are actually text file but they have .h file extension. Header file
contain instruction which are not program code but are instead massages to the compiler.

These massages are called compiler Directives. Header file are merged with the source

Program during the compilation process.


These header file contain prototype of library function. A prototype is the function heading
which shows the function-name ,data type that it return and data types that it receives. Header
files also contain definition of symbolic constants.

PREPROCESSOR DIRECTIVES

Normal program statements are instructions to the microprocessor whereas directives,


are instructions to the compiler .

To understand preprocessor directives, let us first see what a compiler does. When we write a
line of program code such as;

Int Num = 50;

We are asking the compiler to translate this code into machine – language instructions that can
be executed by the microprocessor chip in the computer. Thus most of our code is instructions
to the microprocessor. Preprocessor directives, on the other hand, are instructions to the
compiler itself. Rather than being translated into machine language, they are operated on
directly by the compiler even before the compilation process begins.

Preprocessor directives always start with a number sign (#). The directives can be placed
anywhere in a program but most often they are used at the beginning of a file. Examples of
preprocessor directives are given below.

#include used to include a header file in the current source program.

#define used to define symbolic constant.

WRITING, SAVING,COMPILING AND RUNNING C PROGRAM

C language programs can be written by using any text editor such as word pad, note pad or MS
word etc. But C compiler contains a special IDE (Integrated Development Environment) which is
used for writing C programs.

Creating a C language program involves writing instructions according to the syntax and
semantics of C language, saving this file with the extension. C or CPP, compiling the source code,
linking the object files and finally executing the program. The IDE is equipped with all the
necessary weapons to write a successful C program. IDE can be invoked by manually executing
the tc.exe file saved on the following path.

C:\tc\bin\tc.exe
The IDE main screen will display. It consists of a menu bar containing menu items like FILE, EDIT,
SEARCH, RUN, COMPILE etc. From here we can make a new file, open an existing file, compile
and run our programs etc.

WRITING A NEW PROGRAM

In order to write a new C language program Click on the file menu and the Click New
command . A blue screen will be displayed which is called language editor. All the instructions
will be written here.

SAVING

Once the program instructions have been written completely the must be saved. To
save dialogue box will appear. Here write down the name of the file with file extension. C or .
cpp .

This file is called the source file or source code. This source code cannot be executed by the
computer because it is not in machine language. Therefore, it must be translated into machine
language by compiling it.

COMPILING

In order to compiler our new created source file, Click on the compile menu and then
click the compile command. If the source code does not contain any syntax error then it will be
compiled successfully. If and syntax error exists in the program, the compiler will highlight the
error and its location in the program. Such errors are called compilation or syntax errors.

The short cut key Alt +9 is also used to compile the source file.

When a source code successfully compiles anew file is generated by the compiler called object
code. The object file is identified by its. Obj file extension.

RUNNIGN

Once the object file is created successfully the it can be executed by selecting the Run
command form run menu. Or by using the short cut key Ctrl+F9.\

C/C++ COMMENTS

Comments are helping details that can be included in the source code. These comments
are written in daily English language. These can be read by the humans but are invisible to
compiler. These are only part of the source file and are not visible in the output. There are two
ways to write comments in C.

1. SINGLE LINE COMMENTS


This type of comment begins with double slash (//) symbol and continues until the end of
line. For example, the following comment will be ignored by the compiler.
// This is single line comment.
2. MULTILINE COMMENTS
This type of comment is used when it is larger then a single line. It start with (/*)and ends
with (*/).
For example,
/* This is an example of a multiline comment.
The compiler does not consider these lines as syntax error because
These lines are simply ignored by the compiler.
Comments are important in a program because they help the programmer to identify
various program elements quickly.

C/C++ LIBRARIES

Libraries are the asset of a language .The C language has a large library of built-in
function whereas C++ has a large library of built-in classes. These library items can be used by a
programmer by including them into source programs. Library files are groups of precompiled functions
for performing specific tasks. For example programmer uses a function such as print f()to display text on
the screen, the code to create the display is contained in a library file. Such library files have extension.
Lib Similarly there are math library files which contain code for mathematical processing. Another group
of library files are runtime library object files. These files contain the code to perform various functions
after your program is running.

LIBRARY FUNCTIONS

The C language is accompanied by a number of library function that carry out various commonly
used operations or calculations. Some functions return a data item to their access point; other indicate
whether a condition is TRUE or FALSE by returning a 1 or a 0, respectively. Still there are some functions
that carry out specific operations on data items but do not return anything.

For example, there are library functions that carry out standard input/output operations(e.g. read and
write characters, read and write numbers, open and close files etc), functions that perform operations
on characters (e.g. convert from lower to uppercase, lest to see if a character is uppercase etc),
functions that perform operations on strings (e.g. copy a string , compare strings, concatenate strings
etc ), and functions that carry out various mathematical calculations (e.g. solving trigonometric,
logarithmic and exponential functions, compute square root and absolute values etc). Other kinds of
functions are also available.

Library functions that are functionally similar are usually grouped together as compiled object program
in separate library files. These library files. These library files are supplied as a part of each C compiler. A
library function is accessed simply by writing the functions name, followed by a list of arguments that
hold the information being passed to the function. The arguments must be enclosed in parentheses and
separated by commas. The arguments can be constants, variables names, or more complex expressions.
The parentheses must be present, even if there are no arguments.
Printf() Function

The printf() function is an output function which is used to display output on the screen.
The parentheses contain the arguments separated by commas. General syntax is given below.

printf( control string, argument_1, argument_2,…..,argument_n);

where control string refers to a string that contains formatting information and argument_1,
argument_2 are arguments that represent the individual output data items. The arguments can be
written as , single variable or array variable names, or more complex expressions. Function names can
also be used as arguments.

The control string consists of messages and format specifies. Format specifiers will be used according to
the output data items. For example,

#include<stido.h>

#include<conio.h>

Void main(void)

Int number;

Float pi;

char ch;

number = 10;

pi = 3.14;

ch=’a’;

printf(“number=%d, Pi =%f, ch=%c”, number, pich);

In the above program the integer value will be printed in place of %d, float value will be printed in place
of % and the character value will be printed in place of % c. The name of these variables will appear as
messages in the output. Here is the output of above program.

Number = 10, Pi 3.140000, ch = a

Scanf() Function
This function is used to enter data in the program from the keyboard. Any type of data such as
numbers, characters, and strings can be entered by this function. The general syntax of this function is
given below.

Scanf(control string, arg1,arg2,…….argn);

Here control string refers to a string containing formatting information and arg1, arg2 are the arguments
that represent the individual input data items. The control string consists of format specifiers according
to the type of data items to be input.

The arguments are written as variables or arrays, whose data types matche the corresponding format
specifier in the control string. Each variable name (and individual array element) must be preceded by
an ampersand(&). However, array names should not begin with an ampersand. For example consider
the following program.

#include<stdio.h>

#include<conio.h>

Void main(void)

Int X;

Int arry[3];

Float pi;

Char name[10];

Printf(“ Enter a number “);

Scanf( “ % “m &X );

Printf( “ \n\n Enter three numbers “);

Scanf( “ % d % d % d “ , &arr*0+ , &arr*1+ , &arr*2+ );

Printf(“ \n\n Enter your name “);

Scanf(“%s” , name );

Printf (“\n\n Your given data is displayed below “);

Printf (“\n\n X = %d , arr*0+ = %d , arr*1+ = %d , arr*2+ =%d “,X, arr*0+, arr*1+, arr*2+;
Printf(“\n\n name =%s “ , name );

Getch();

The above program will first declare four variables, An integer type variable X, integer type array of size
3 arr , a float type variable pi, and a character type array of size 10 name.

Then a message will ask to enter a number. When the number is typed and enter key is pressed, then
another message appears asking the user to enter three numbers. Here the user can enter three
numbers by pressing the enter key after typing each number or by typing three numbers directly
separated by a space character and then pressing enter key. It should be noted here that each array
element in the scanf() function begins with ampersand(&). Finally a message appears asking the user to
enter name. This name is captured by the scanf() function and is stored in the character array name.
Again it should be noted that when the whole array is to be captured from the keyboard then the
ampersand (&) is not used with the array name.
CHAPTER-2

BUILDING BLOCK OF C LANGUAGE

THE C CHARACTER SET


The character set of C language consists of total 92 characters. These
include 26 Upper case alphabets, 26 Lower case alphabets, 0-9 digits and the following 30 special
character.

+ - * / = % & ! ? / I
< > ( ) [ ] { } : ; . , _
“ ‘ ~ (blank Space)
Each C language program is the combination of character from this character set.

RESERVED WORDS/KEYWORDS

Reserved word or keyword are certain words that have standard predefined
meanings in C language and these word cannot be redefined by users as variable names, function names
or array names. Reserved word are white color in the language editor.

The standard Keywords are:

Auto Break Case Char Const Continue Default

Do Double Else Enum Extern Float For

Goto If Int Long Register Return Short

Signed Sizeof Static Struct Switch Typedef Union

Usingned Void Volatile While


An important point to be noted is that all these reserved words are written in lover case. It will no longer
be a reserved word if it is written in upper case, for example AUTO is not a reserved word.

IDENTIFIERS

Identifiers are user defined names that are given to various program elements such as variables,
functions and arrays. Identifiers consist of letters and digits and special character Underscore (_). An
uppercase letter and a lowercase letter (for example A and a) are not the same in C language. Because
both have different ASCII codes (A = 65 and a = 97).

RULES FOR CREATING IDENTIFIERS

The following rules must be followed while creating identifiers ( names ) for a variable, a
function or an array.

1. The first character of an identifier must be an alphabet or underscore. It cannot be a digit.

2. Reserved word cannot be used as an identifier.

3. Blank space cannot be used in an identifier.

4. No special character can be used in an identifier except the underscore(_).

5. Length of identifier can be any number of characters but only the first 31 characters are
significant.

DATA TYPES

C supports several different types of data which are represented differently in the computer’s
memory. The basic data types and there size in memory are given below.

Data Type Description Memory Requirements

Int Integer Quantity 2 Bytes

Long int Integer Quantity 4 Bytes

Char Single Character 1 Bytes

Float Floating – Point number 4 Bytes

Double Floating – Point number 8 Bytes

Long Double Floating – Point Number 10 Bytes


Int

Integer data type is used to represent whole numbers such as 1, 2 , 1000 etc that does not
include decimal point. 2 Bytes of memory is reserved for an integer variable. These two bytes
can store values ranging from -32768 to +32767.

Values greater than 32767 and values less than -32768 cannot be stored in an integer variable.

Long int

Long integer data type is also used to represent whole number but of larger range. 4 bytes of
memory are reserved for a long integer variable. These four bytes can store values ranging from
-2147483648 to +2147483647.

Char

Character type is used to represent single characters. A single character is enclosed by single
quotation marks (apostrophes). One byte of memory is reserved for a character type variable.
One byte can store values ranging from -128 to +172. Since characters are unsigned therefore, a
character on the keyboard has a specific ASCII code. These ASCII codes range from 0 to 255.
Some of the characters along with their ASCII codes are listed below.

A = 66, B = 67 , C = 68 , and so on Z = 90

a = 97 , b = 98, and so on z = 122

0 = 48, 1 = 49 , 2 = 50, 3 = 51, and so on 9 = 57

@ = 64, < = 60, >=62, $ = 36, ! = 33, [ = 91 , ] = 93, ( = 40 , ) = 41 , + = 43, * = 42

Float

Float data type represents real numbers, that is, numbers which contains decimal point. Four
byes of memory are reserved for a float variable. It can store values ranging from 3.4 X 10-38 to
3.4 x 10+38.

Double

The data type ‘double’ represents real numbers, but double can represent large real numbers
which cannot be represented by float data type. Eight bytes of memory are reserved for 1.7 to
10-308 to 1.7 x 10+308.

Long double

The data type ‘long double’ also represents real numbers. But it can represent such large values
which cannot be represented by double data type. The range of values include this data type
occupies 10 bytes of memory space.
VARIABLES

A variable is a name (identifier) that is given to a memory location. It is used to represent a


single data item such as an integer value or a real value or a character value. The contents of a
variable can change during the execution of a program. Variable are use in a program to hold
various data items. Each variable has a specific data type which specifies the values that the
variable can hold. For example if the type of a variable is int, then such a variable can hold only
whole number and it cannot store real number.

Each variable in a program must be associated with a specific data type. Associating a variable
with a data type is very simple. Just write a data type and then write the variable name.

Array Variable

An array is a variable that refers to a collection of data item that all have the same data type and
same name. The values that are stored in an array are called array elements. Each array has a
specific size which shows how many values it can store. The array variable is distinguished by a
pair of square brackets ([ ]). These brackets contain the subscript or index.

Suppose X is a 10 element array . The first element is referred to as X[ 0 ], second as X [1], third
as X[2] and so on the tenth element is referred to as X[9].

X [2]
Name of array Subscript or Index

CONSTANTS

A constant is a value that does not change during the execution of a program. A constant is
assigned to a variable. There are basically Four types of constant.

1. Integer constant.
An integer constant is an integer-valued number. Thus it consists of a sequence of digits.
Commas and blank spaces are not allowed in an integer constant. If an integer constant of more
than one digits then the first digit cannot be a zero. For example the following are valid integer
constants,
0 234 567890 1232
But the following are not valid integer constants,
0.001 12,234 233456 0987

2. Floating –point constant :

A floating –point constant is a numeric value that contains a decimal point. Thus it is a real
number . a floating-point constant can also be written in the form of base and exponent.
For example the following are valid floating-point constants.

2.3 0.0003 23e3 0.0123E-5

3. Character constant:

A character constant is single character enclose in apostrophes(i.e. single quotation marks).for


example the following are valid character constant .

‘A’ ‘1’ ‘0’

ASCII character set is mostly used in all personal computer. In ASCII character set each individual
charcter.is encoded with a numeric value. Thus a character constant can be represented by both its s
symbol as well as by its numeric code. The following are some characters with their codes.

‘A’ = 65 a =’a’ ‘)’ = 41 ‘Z’=

4 string constant.

A string constant is any sequence of characters enclosed in double quotation marks. For
example the following are valid string constants.

“hello” “12345” “123-12345-12” “I love my country”

DECLARATION OF VARIABLES

Each variable has a specific name and a specific date type. The data type must be associated
with the variable name before it is used in the program. The assigning ( associating) of a data type to a
variable name in the start of a program is called declaration of variable. The name of a variable is a user-
defined word. For example the following line declares an integer type variable called count.

int count;

more than one variables of the same data type can be declared in the same row, such as,

int sum , product , x ;

an initial value can be assigned to a variable at the time of declaration such as,

int count=0;

long int sum = 0 , c =1 , i = 10;

char choice =’y’;

float pi = 3.14;

if the keyword const is applied to a data item (variable) then its value cannot change during the
execution of the program. Such a data item must be assigned an initial value. For example, the following
float type data item average is given an initial value of 3.5 which cannot be changed during the program
execution.

Const float average = 3.5;

DEFINING ARRAY VARIABLES

An array variable can be defined in the same way as an ordinary variable, except that each array
name must be accompanied by a size specification (i.e. the number of elements in the array).

Suppose we want to define an array which can store 50 integers (elements) and we give it the name list.

Then it can be defined as follow.

int list[50];

similarly the following statement defines a 30-element character array called name.

char name[30];

STRING VARIABLE

A string constant is a series of characters enclosed in double quotation marks. String constants
can b constants
Library Function
The C language is accompanied by a number of standard library functions which carry out various useful
tasks. In particular, all input and output operations(e.g., writing to the terminal) and all math
operation(e.g., writing to the terminal) and all math operations(e.g., evaluation of sines and cosnes) are
implemented by library functions.

In order to use a library function, it is necessary to call the appropriate header file at the beginning of
the program. The header file informs the program of the name, type, and number and type of
arguments, of all of the functions contained in the library in question. A header file is called via the
preprocessor statement. Library are the following.

 Trigonometric Functions.
Trigonometric functions are available in <math.h> header file.
i) Sin()

The sin() function is used to fine the trigonometric sine of specified angle. The angle is given in
radians as floating point value.

Synatx: sin(x); x indicates the angle in radians.

ii) Cos()

The cos() function is used to find the trigonometric cos of specified angle. The angle is given in
radians as floating point value.

Syntax: cos(x); x indicates the angle in radians.

iii) Tan()

The tan() function is used to find the trigonometric tangent of specified angle. The angle is given
in radians as floating point value.

Syntax: tan(x); x indicates the angle in radians.

Programming Example.

#include<iostream.h>

#include<math.h>

Clrscr();

Float n;

Cout<<”enter a floating point value”;


Cin>>n;

Cout<<”Trigonometric sin of “<<sin(n)<<endl;

Cout<<”Trigonometric cos of “<<cos(n)<<endl;

Cout<<”Trigonometric tan of “<<tan(n)<<endl;

Getch();

Arithmetic functions.

Arithmetic functions are available in <math.h> header file.

i.abs()

The abs() function is to find the absolute value of an integer e.g abs(-5)=5.

Syntax: abs(X); x indicate the integer whose absolute value to be found.

ii. fabs() function is used to fined the absolute value of a floating point number. E.g fabs(-
3.6)=3.6.

syntax : fabs(X); X indicate the following point number whose absolute value is to be found.

Programing Example:

#include<iostream>

#include<conio.h>

#include<math.h>

Void main(){

Clrscr();

Int n;

Float f;

Cout<<”Enter an integer”;

Cin>>n;

Cout<<”Enter a float”;

Cin>>f;
Cout<<”The absolute value of “<<n<<”is=”<<abs(n)<<endl;

Cout<<”The absolute value of “<<f<<”is=”<<fabs(f)<<endl;

Getch();

iii. log()

The log(x) calculates the natural logarithm of x

Syntax : log(x); x indicate the value whose log to be found e.g log(5.5)=1.704748.

iv. ceil()

the ceil() function rounds a float or double value to an integer and return it. E.g
ceil(13.2)=14

v. floor ()

the floor() function rounds a float or double value to an integer and returns it . The
rounded value is not greater than the original value e.g floor(13.3)=13

syntax: floor(x) X it indicates the float or double value that is to be rounded.

Programing Example:

#include<iostream>

#include<math.h>

Void main()

Clarscr();

double d ;

Cout<<”Enter an integer”;

Cin >>d;

Cout<<”The round value with ciel()=”<<ciel(d)<<endl;

Cout<<”The round value with floor()=”<<floor(d)<<endl;

Getch();}
Pow:

Pow()function is C is used to fined the power of the given number.

The power function is used to find the result of none integer raised to the power of second
integer “math.h”header file support pow() function.

Syntax: for pow() function in C is given below.

Pow (base , component ).

Pow (3,2) = 9

Example Program

#include<iostream>

#include<math.h>

Void main()

Clrscr()

Int a , b ;

Cout<<”Enter first integer”;

Cin>>a;

Cout<<”Enter second integer”;

Cin>>b;

Cout<<”The result of pow(a , b)=”<<<pow(a,b);

Getch();

Pow10()function

Pow 10() function in C is used to find the power of 10.The power of function is used to find the
result of 10 raised to the an integer.

#include<iostream>

#include<math.h>
Int main()

{
int x = 5;

Double result ;

result =pow 10();

printf(“Then raised to % d is %lf/n”, x , result);

return0;

vii).sqrt(x).

The sqrt()function is used to calculate the square root of a floating point number.

Syntax: sqrt(x);

Programing Example:

#include<iostream>

#include<math.h>

Void main()

Clrscr();

Float n;

Cout<<”Enter a floating point number”;

Cin>>n;

Cout<<”The square root of “<<n<<”is=<<sqrt(n);

Getch();

viii) pow10()

The pow10() function is the power ).It has the following general format:
Double pow10(int p);

For example:

Pow10(5)->10000

Pow(-2)->0.01

ix). Exp()

The exp function is referred to as exponent function (e**x) .The exp is the exponent of a
natural log and performs the opposite of the function .

Form example exp(0)=1.

X).rnd()(random)

Returns integral number in the range between 0 and RAND_MAX.

Example

The following example shows the usage of rand()function .

#include<sdio.h>

#include<sdiolib.h>

Int main()

Int i,n;

Time t;

N=5;

//Intializes random number generator

Srand((unsigned )time(&t));

//Print 5 random from 0 to 49

For(i=0 ; i<n;i++)

Printf(“%d\n”,rand()%50);

}
Return (0);

String function

String function are available in <string.h>header file.

i.) Strlen()The word ‘strlen’ stand for word string length. The function is used to find the
length of a string.The length include all character e.g

Strlen(gcms)=4

Syntax: strlen(str);

Programming Example

#include<iostream.h>

#include<conio.h>

#include<string.h>

Void main()

Clrscr();

Char str[10];

Int len;

Cout<<”enter a string:”;

Cin>>str;

Cout<<”the string contains”<<len<<”characters”;

Getch();

(ii) Strcpy()

The word ‘strcpy’ stand string copy. The function is used to copy one string to another including the
terminating null character.
Syntax:strcpy(str1, str2);

Programming Example;

#include<iostream.h>

#include<conio.h>

#include<string.h>

Void main()

Clrscr();

Char str1 [10]; char str2 [10];

Cout<<”str1”; cin>>str1;

Cout<<”str2”; cin>>str2;

Strcpy (str1 , str2);

Cout<<”string copy”<<strcpy (str1 , str2);

Getch();

(iii) Strncpy_()

The strncpy() function is used to copy one string to another including the terminating null character. It
copies only specified number of char-acters in one string to another.

Syntax: strncpy (str1 , str2, n);

(iv) strrev() The strrev() function reverses all characters in a string ex-cept the null character.

Syntax: strrev(str): e.g strrev (GCMS)=(SMCG)

Programming Example.

#include<iostream.h>

#include<conio.h>

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

Clrscr();

Char str[10];

Cou<<”str:”;

Cin>>str;

Strrev(str);

Cout<<”string reverse:”<<str;

Getch();

Strlwr()

The strlwr() function converts all characters of a string to lower case.

Syntax: strlwr(str) ;e.g strlwr (GCMS)=gcms.

Programing Example:

#include<iostream>

#include<string.h>

using namespace std;

int main ()

char str[10];

cout<<"str:";

cin>>str;

strlwr(str);

cout<<"string in Capital letters:"<<str;

return 0;

}
Strupr()
The strupr () function converts all characters of a string to upper case.

Syntax;strupr();e.g strupr(gcms)=GCMS.

#include<iostream>

#include<string.h>

using namespace std;

int main ()

char str[10];

cout<<"str:";

cin>>str;

strupr(str);

cout<<"string in Capital letters:"<<str;

return 0;

You might also like