Introduction of C

C
C is
a general-purpose, procedural, imperative computer
programming language developed in 1972 by Dennis Ritchie at
theBell
Telephone
Laboratories for
use
with
the Unix operating system.
It is a high-level programming language that is able to
manipulate the computer at a low level like assembly language.
During the last half of the 1980s, C became the language of
choice for developing commercial software.
C has also greatly influenced many other popular languages, especially C++, which
was originally designed as an enhancement to C. It is the most commonly used
programming language for writing system software, though it is also widely used for
writing applications.C, and its object-oriented successor C++, are used to write a huge
variety of applications and almost all operating systems.
Fundamental concept of Problem solving
Introduction
Firstly we will discuss here Fundamental concept of Problem solving. Then This
chapter gives the viewer/reader an overview of C language and tells about the
structure of C program and various component of a C program. C language allows
us to create custom data types.
Problems are the undesirable situations that prevent any software from fully
achieving its objectives.
When we wish to transform the existing situation into a more desired one, problem
occurs, and a need for solving the problem arises.
Defining a problem clearly in terms of goals and objectives helps largely in
problem solving.
There are three related terms that need to be well understood to successfully solve
the problem:
1. Mission: It is the broad statement of the purpose of the organization.
2. Goals: It is the general statement of what is to be accomplished.
3. Objectives: It is the statement of measurable results to be achieved in a specified
time frame.
Problem solving strategies
The most popular method of problem solving is to divide and conquer. This means
that the problem has to be divided into smaller problems, each of which must be
solved to get the complete solution.
For instance, if it is required to find the second smallest element in an array, the
problem could be divided into two parts viz.
Arranging the elements in the array in ascending or descending order and then
getting the second smallest element form the sorted array.
This strategy is called divide and conquer.
If you want to find the sum of the digits in a number, it can be divided into 3 parts:
1. Finding modulus of 10 i.e. finding the remainder when the number is divided by
10.
2. Adding the remainder to a sum whose initial value is zero.
3. Dividing the number by 10 and then repeating the process from (1) again till the
quotient is zero.
Program design & implementation
There are two types of designing approach:
1. Top down design.
2. Bottom up design.
Both have been describe together with examples.
Any problem can be dealt with two ways, viz. top down or bottom up. A simple
example is given here to illustrate the concept.
Sorting an array of numbers involves the following two steps:
1. Comparison
2. Exchange
1. Top down design:
At the top level, an algorithm has to be formulated to carry out sorting. Once
the algorithmis confirmed, then the algorithms for comparison and exchange are
formulated, before implementation of the entire algorithm.
Therefore, in this approach, one begins from the top level without bothering about
the minute details for implementation, to start with.
2. Bottom up design:
The bottom up approach is just the reverse. The lower level tasks are first carried
out and are then integrated to provide the solution.
In this method, lower level structures of the program are developed first and then
progressively higher level structures are created.
Here the algorithms for exchange and comparison will be formulated before
formulating thealgorithm for the whole problem.
In any case, dividing the problem into small tasks and then solving each task
provides the solution.
If the program development is assumed to be a single task and the program
statements are developed in sequence, then it is quite likely that the program may
not work.
Therefore, either the top down or bottom up methodology has to be adopted for
dividing the problem into smaller modules and then solving it.
Difference between Top design and Bottom up approach:
In the top down methodology, the overall structure is defined before getting into
details, but in the bottom up approach, the details are worked out first before
defining the overall structure.
Implementation
A good program is one which contains a main function and the main function calls
procedures or sub-programs or functions to carry out specific tasks.
The subprograms are dependent on the main program. They do what the main
program asks them to do.
Each language gives different names to sub-programs. Sub programs are known as
functions in C.
The quality of program will also get enhanced when the program is made modular
as mentioned above with functions.
Each function will receive input and may return some output to the called program.
By dividing the problem into a number of functions, the problem can be divided
and conquered.
This facilities focus on small programs and dealing with one problem at a time.
Introduction to C
Introduction
C is general-purpose, structured programming language, developed by Denis
Ritchie in 1972 atBell lab USA.
Its instructions consist of terms that resemble algebraic expressions, augmented by
certain English keywords such as if, else, for, do and while.
In this respect C resembles other high-level structured programming languages
such as Pascaland FORTRAN.
C also contains certain additional features, however, that allow it to be used at a
lower level, thus bridging the gap between machine language and the more
conventional high-level languages.
This flexibility allows C to be used for system programming as well as for
applications programming.
C is characterized by the ability to write very concise source programs, due in part
to the large number of operators included within the language.
It has a relatively small instruction set, though actual implementations include
extensive library functions which enhance the basic instructions.
C compilers are easily available for computers of all sizes, and C interpreters are
becoming increasingly common.
The compilers are usually compact, and they generate object programs that are
small and highly efficient when compared with programs compiled from other
high-level languages.
The interpreters are less efficient, though they are easier to use when developing a
new program.
Many programmers begin with an interpreter, and then switch to a compiler once
the program has been debugged (i.e., once all of the programming errors have been
removed).
How to open C program code window
Before opening C on your computer. Please ensure that C compiler has been
loaded or not. If not then please load it first and then try any of the following ways
to open C which suit your computer setting.
1.Start>>Program >> Turbo c.
2. If turbo C icon is present on your computer desktop then simply click on it.
3. My computer >>c:\>> tc (folder)>> bin (folder) >> tc.exe (icon).
4. Or make sure the path where you have loaded the C on your computer and try to
run it from there.
After following the above instructions the screen which is given below will appear
on your desktop:
Description of C code window
1. =: Interface to external programs.
2. File: File related option such as opening and saving file.
3. Edit: Cut,Copy,Paste operation.
4. Search: Find,Find & Replace operation.
5. Run: Compile and run the file currently loaded in the text editor. And debugging
such as setting/clearing trace points can be performed from this menu.
6. Compile: The menu item compiles a source file to an object file or an .exe file.
7. Debug: Provides interactive debugging. Variables can be examined/set/cleared,
and we can watch variables change during execution.
8. Project: This menu item controls Borland C++'s handling of large programs that
are in multiple source file.
9. Option: Default option are set during installation . The user can change any
option at any time through this menu.
10. Windows: Windows operation include zoom, arranging windows on the screen
, and closing windows.
11. Help: Borland C++ includes a context sensitive help capability. Select Help or
press f1 for general Help, Shift f1 for indexed help or Ctrl f1 for context sensitive
help.
Editing File
To open a new file, first press Alt F then Enter key, File pull down will activated,
select newand then press Enter key, the display will be change into a blank screen
of text editor having file name NONAME00.C, on which you can start entering
your code through keyboard.
To open existing file press Alt F and then Enter, from the activated file pull down
menu selectOpen, A Open Dialoge Box will appear, select desired file name path
and press Enter.
Saving and Running a program
Press Alt F, move the cursor to save , press Enter and then type file name
with extension .Cin given Text Box and press Enter to save the program.
Running a program
Press Alt R to pull down the Run menu and Enter to begin compilation,
A compile window opens and shows progress and output can be viewed
in output window and press Alt W to pull down window menu, move the cursor
down to output and press Enter. Press Alt W and move the cursor to close to
close output window immediately.
Exiting Borland C
Press Alt X to Exit Borland C and return to Dos Prompt.
The components of C language
There are five main component of C language are:
1. The character set: Any alphabet ,digit or special symbol ,used to represent
information is denoted by character. The character in C are grouped into four
categories.
1
2
3
Letters
Digits
Special Symbol
4
White Space
A...Z and a...z
0,1,2,.....9
~,`,!,@,#,$,%,^,&,*,(),.,<,>,?,/,",:,;,{},[]
blank space, Carriage return, form feed, newline,
horizontal tab
2. The data types: The power of the programming language depends, among other
thing, on the range of different types of data it can handle.
3. Constants: A constant is a fix value that doesn't change while program
execution.
4. Variable: A variable is an entity whose value can change during program
execution.
5. Keywords: Keywords are those word which have been assigned specific
meaning in C language. Keywords should not be used as variable names to avoid
problem.
Note: Above given all the term has been discussed in details in next section.
Structure of C Program
Every C program is made of function and every function consist of instructions
called statement.
Structure of C Program.
#include //stdio.h is the header file
main() // main function is the first function which is executed by a C program.
All C statements are written within main function.
{
// All C statements.
}
Functions
Every C program consists of one or more modules called 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.
A function name is always followed by a pair of parenthesis, namely, ( ). And all
function statements are enclosed within a pair of braces { }.
The program execution always starts with main function. When the closing brace
of the main function is reached, program execution stops, and the control is handed
back to the OS (Operating System).
Statements
Single C language instruction is called a statement. Statements are written
according to the grammar of C language. Every C language statement must ends
with semicolon(;).
In order to write a C program we should follow some basic rules which are
described below:
a) Usually all statements in C are entered in small alphabets.
b) Blank spaces may be inserted between two words to improve the program
readability. However no blank spaces are allowed within a variables,
constants or key words.
c) It has no specific rules for the position at which statements is to be retained
that's why it’s often called a free form language.
d) All C statements must end with a semicolon (; )
Till now, We have very little knowledge about the type of variables,
constants and keywords. Now we would try to understand the simple C program.
A sample of C language program
Example of C program to calculate area of circle:
Explanation of above program :
# is the preprocessor directive which commands that the content of file should be
included at the time of compilation.
< stdio.h> is the header file which contains all input and output functions
like scanf(), printf() which are frequently used in c programs.
main() is the first function which is executed by a C program.
1. int a,r=5; -> This statement declares 2 variables a and r of type integer and r has
been assigned a value of 5.
2. const pi=3.14; -> This statement declares pi as constant and value 3.14 has been
assigned to it.
3. a = pi * r *r; -> This statement computes the area of circle and assign it to
variable a
4. printf("%f",a); -> This statement prints the area of circle using printf function.
5. getch(); -> It is used to get character from user.
Note: /* Any thing written within it is consider as comment statements. */
C character set and keywords
Introduction
C language consists of some basic elements which are used to construct simple C
statements.
These elements include the C character set, identifiers, and keywords, data types,
constants, variables and arrays, declaration, expressions and statements.
We will see how these basic elements can be combined to form more
comprehensive program components.
The C character set
C uses the uppercase letter A to Z, the lowercase letters a to z, the digits 0 to 9, and
certain special characters as building blocks to form basic program elements ( e.g.,
constants, variables, operators, expressions, etc.).
Some of the special characters are listed below:
+
-
*
~
%
/
&
(
)
{
}
[
]
?
"
<
>
!
;
:
Most versions of the language also allow certain other characters, such as @ and $,
to be included within strings and comments.
C uses certain combinations of these characters, such as \b,\n and \t, to represent
special conditions such as backspace, new line, and horizontal tab, respectively
These character combinations are known as escape sequences.
Identifiers
Identifiers are names that are given to various program elements, such
as variable, functionsand arrays.
Identifiers consist of letters and digits, in any order, except that the first character
must be a letter.;
Both upper- and lowercase letters are permitted, though common usage favors the
use of lowercase letters for most types of identifiers. Upper- and lowercase letters
are not interchangeable.
The underscore (_) character can also be included, and is considered to be a letter.
An underscore is often used in the middle of an identifier.
An identifier may also begin with an underscore, though this is rarely done in
practice.
The following names are valid identifiers:
X
y12
sum_1
tax_rate
area
_temperature
Key words
There are certain reserved words, called keywords, which have standard,
predefined meanings in C.
These keywords can be used only for their intended purpose; they cannot be used
as programmer-defined identifiers.
Some standard keywords are:
auto
switch
extern
sizeof
break
register return long
int
floatn
else
static
while
case
short
for
Char
Void
Some C compilers may recognize other keywords.
Note that the keywords are all lowercase. Since uppercase and lowercase
characters are not equivalent, it is possible to utilize an uppercase keyword as an
identifier.
Normally, however, this is not done, as it is considered a poor programming
practice.
Data Types
Introduction
To communicate with the computer, it is required to pass an appropriate value to
the computer from the keyword.
The value passed may be of different types, viz. Single character, integer, decimal,
string.
In each, the memory required is of different size. Such a defined type of value is
called data type.
C supports several different types of data, each of which may be represented
differently within the computers memory.
The memory requirement of each data type will determine the permissible range of
values for that data type.
C data type can be broadly divided in two categories:
(a) Primary data types.
(b) Secondary data types.
Primary data types
Primary data types are independent data types. It's not derived from other basic or
secondary data types.
There are five primary data types in C language:
1. Void
2. Character
3. Integer
4. Float
5. Double
Secondary data types
Secondary data types are also called as derived data types. Secondary data types
are derived from the basic data types.
They are also five in number:
1. Array
2. Pointer
3. Structure
4. Union
5. Enum
Primary Data Type
1. Void
Description:
Used to specify empty set containing no values.
Storage Space: 0 byte.
Format: (void).
Range of values: ______.
2. Character (Denoted as "char" in C programming language)
Description:
A character denotes any alphabet, digit or special symbol used to represent in
formation and it is used to store a single character.
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.
3. Integer (Denoted as "int" in C programming language)
Description:
Integer type is used to store positive and negative integer.
Storage space: 2 bytes.
Format: %d
Range of values: -32768 to +32767.
4. Float
Description:
It is used to store real number, with single precision floating point number
(precision of 6 digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.
5. Double
Description:
It stores real numbers with double precision. The use of double doesn't guarantee
to double the number of significant digits in our result, but it improves the
accuracy of the arithmetic and reduces the accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.
An example program of using basic data type:
Output of the program:
Explanation: Numeric data stored is stored in the memory in their binary form,
while the character data has to be codified as a unique integer and that code
number is stored in the internal storage.
The integer equivalents of alphabets are:
Lower case: a-z = 97 to 122
Upper case: A-Z = 65 to 90
In the above program when the characters are displayed in the integer format the
corresponding ASCII code are displayed, similarly when integers are displayed in
the characterformat then equivalent character is displayed.
Secondary Data Type
1. Array:
It is a collection of data of similar data type.
e.g. Int num [5];
Reserve a sequence of 5 location of two bytes each for storing integers.
2. Pointer:
Pointer is a variable that stores the address of some other variable.
e.g. int *i;
The above statement declares i as pointer to integer data type.
3. Structure:
A structure is a collection of data of different data types under one name.
e.g.
Struct employees
{
char Name[10];
int Age;
int Salary;
}
4. Union:
It is a collection of data of different types sharing common memory space.
e.g. Union item
{
int m;
float x;
char c;
};
5. Enumerated Data types:
This data types gives us an opportunity to invent your own data type and define
what values the variable of this data type can take.
Example: enum colors
{
red, green, blue, cyan
};
colors foreground, background;
Here the declaration has two parts:
a) The first part declare the data type and specifies its possible values.
b) The second part declare variable of this data type.
Now we can give the values to these variables:
foreground=red;
background=blue;
But remember we can't use values that aren't in the original declaration. Thus, the
following declaration cause error.
foreground=yellow;
Note: Secondary data type has been given in detail later.
Variables
Introduction
The defined type of memory area where the value is stored is called variable.
Variables are the data item whose values may vary during the execution of the
program.
A specific location or the address in the memory is allocated for each variable and
the value of that variable is stored in that location.
These locations may be integer, real or character etc.
Rules for constructing variables names
There are some specific rules for constructing variable names in C language:
(a) Variable name may be a combination of alphabet digits or underscores and its
lengths should not exceed 8 characters, some compilers allow 40 characters also.
(b) The first character must be an alphabet.
(c) No comma, blank spaces are allowed in variable name.
(d) No special symbols except underscore can be used as variable names.
Variable declaration
All the variables must be declared before their use. It does two things:
(a) Tell the compiler what the variable name is.
(b) Specify what type of data that a variable will hold.
Syntax of variable declaration:
data_type variable_name;
Example of variable declaration:
int i,j,k;
char ch;
Assigning values to variables
To assign values to the variables, assignment operator (=) is used.
Syntax of assigning values:
variable declaration;
Variable_name = value;
Example of assigning values:
Int i , j;
j=5;
i=0;
It is also possible to assign a value at the time of declaration.
e.g.
int i = 5;
More than one variable can be initialized in one statement using multiple
assignment operators.
e.g. j = m = 2;
There could be an exception while using multiple assignment operators.
e.g. int i , j = 2 , k;
here the assignment will be i = 0 j=2 and k = garbage value
An example program which shows the example of assignments:
Output of the Program:
Scope of variables: LOcal & Global
Scope of variable means where the variable stands in the program.
All variables may not necessary be available to all statements in a program.
Variables can have two types of scope:
a) Local:
When a variable is declared inside the function then such a variable is known
as localvariable.
A local variable can only be accessed by the function in which it is declared. It
cannot be accessed by other function.
b) Global:
A variable which is declared outside all functions is known as global variable.
A variable with a global scope is accessible to all the statements in the program.
A globalvariable can be accessed by all the functions.
Constants
Introduction
There are some values which do not change during the execution of the program.
These values are called constants.
Constants are of fixed value that remain unchanged during the execution of a
program, and are used in assignment of statements. Constants are stored in
variables.
Syntax of constant declaration:
Const datatype var_name = value;
Example of Constant declaration:
Const int a = 5;
In C language there are five types of constants which has been described separately
Character constants
A character constant consists of a single digit or a single special symbol enclosed
within a pair of single inverted commas. The maximum length of a character
constant can be 1 character.
e.g. --> 'a', 'i' , '5', '='.
There are some character sequence constants which are used in C to represented
special action, these are called C Escape Sequence.
List of these escape sequence and its tasks are given below:
\a : audible bell
\f : form feed
\r : carriage return
\v : vertical tab
\' : single quote
\? : question mark
\HHH: 1 to 3 digit hex value.
\b : backspace
\n : newline
\t : horizontal tab
\\ : backslash
\" : double quote.
\000 : 1 to 3 digit octal value
Integer constants
An integer constant refers to a sequence of digits. It could be either positive or
negative. and must have at least one digit.
It mustn't have a decimal point. No commas or blank are allowed within
an integer constant. The allowable range for integer constants is -32767 to 32767.
There are three types of integer constants:
1. decimal :
In decimal notation ,simply we write decimal number. e.g. 24,678
2. octal :
In octal notation, write(0)immediately before the octal represention,e.g.-076,-076
3. hexadecimal :
In hexadecimal notation ,the constant is preceded by 0x,e.g.,0x3e,-0x3e.
Some example of integer constants:
: 426
: +762
: -8000
: -7605
Real constants
Real constants are often called Floating Point constants.
It has three parts:
1. A sign (+ or -) preceding the number portion (optional).
2. A number portion (representing the base).
3. An exponent portion following the number portion (optional). This starts with E
or E followed by an integer. The integer may be preceded by a sign.
A real constant must have at least one digit. It must have a decimal point. It could
be either positive (default) or negative. No commas and blank are allowed within a
real constant.
Some example of real constants:
: +.72
: +72
: +7.6E+2
: 24.4e-5
Logical & String constants
A logical constant can have either of two values either true or false. In C a nonzero value is always treated as true whereas zero is treated as false.
The logical constants are very useful in evaluating logical expressions and complex
condition.
A group of character enclosed within a pair of double inverted commas (" ") is
treated as astring constant.
some example of string constant:
: "Hello"
"Welcome to eBiz"
"a"
C instruction set
Introduction
In previous section we discuss about various types of C constants,
variables and keyword.
Now in this section we will discuss about how they are grouped to
from instructions.
There are basically four types of instruction in C. which has been described
separately.
1. Type Declaration Instruction
2. Input Output instruction
3. Arithmetic Instructions
4. Control Instructions
Type Declaration & Input/Output Instructions
This type of instruction is used to declare the type of variable being used in the
program.
Any variable used in the program must be declared before using it in any
statement.
This instruction is usually written at the beginning of the C program.
Example:
int a;
float re,ad;
char name ,des.
Input Output instructions
These instructions are used to supply input data to a program and obtain
the output results from it.
Example:
printf(), scanf().
Arithmetic Instructions
These types of instructions are used to perform arithmetic operations
between constants andvariables.
Some of the arithmetic operators are: +, -, * and /.
Example:
int a;
float b, deta, alpha, gamma, beta;
a=500;
b=0.0056;
deta=alpha*beta/gamma+0.5*2/5;
There are three types of arithmetic statements:
1. Integer mode arithmetic statement:
In this type of arithmetic statement all operands are either integer
variable or integer constant.
2. Real mode arithmetic statement:
In this type of arithmetic statement all operands are either real constant or real
variables.
3. Mixed mode arithmetic statement:
In this type of arithmetic statement some of the operands are integer and some of
them arereal.
Control Instructions
These types of instructions are used for controlling the sequence of execution of
various statements in C program. It determines the 'flow of control' in a program.
There are four types of control instructions in C:
1. Sequence Control Instructions
The sequence control instruction ensures that the instructions are executed in the
same order in which they appear in the program.
2. Selection or Decision Control Instructions
These types of instruction allow the computer to take a decision.
3. Case Control Instruction
These types of instruction determine which instruction is to be executed next.
4. Repetition or Loop Control Instruction
The loop control instruction helps computer to execute a group of statements
repeatedly.
Operators
Introduction
An operator specifies an operation to be performed. C is rich
in operator. Operators join the various variables and constants to from an
expression.
Some operator requires one operand and some require more than one operands.
An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulation in data stored in variables.
C is extremely rich in operators It has as many as 45 different operators.
Arithmetic operators
Arithmetic Operators are used to Arithmetical calculation.
There are five Arithmetic operators in C:
Operator
+
*
/
%
Purpose
Addition
Subtraction
Multiplication
Division
Remainder after integer division
Relational operators
Relational operators are used to compare two operands and to check whether they
are equal, unequal, greater than and lesser than other.
There are 6 relational operators:
Operator
<
>
<=
>=
==
!=
Meaning
Less than
Greater than
Less than equal to
Greater than equal to
Equal to
Not equal to
The value of the relational operator is either one or zero. If the relation is true,
result is 1 otherwise it is 0.
Logical operators
Logical operators are used to combine two or more relational expressions.
There are three logical operators:
Operator
&&
||
!
Meaning
Logical And
Logical or
Logical not
The expression which combines two or more relational expressions is termed as
logical expression or compound relational expression.
The result of a logical expression is either one or zero.
Example:
a) if (age > 50 && weight < 80)
b) if (a < 0 || ch = = 'a')
c) if ( ! (a < 0))
Increment & Decrement operators
These types of operators operate on only one operand, therefore these operators are
also called Unary operators.
These two powerful operators in C are + + (Increment), _ _ (Decrement). Operands
must be declared as variables not a constant.
These operators may be used either after or before the operand.
When they are used before the operand, it is termed as Prefix while when they are
used after the operand they are termed as Postfix.
In prefix operations the value of operator is incremented or decremented first and
then the expression is evaluated. Prefix operators has the effect of Change then use.
In postfix operation the expression is evaluated first and then the value of operator
is either incremented or decremented. Postfix operators has the effect of Use Then
Change.
e.g.: b=a++; this is postfix increment expression. In the expression firstly b=1;
then a=a+1; will be executed ,
while in prefix increment expression
b=--a;
firstly a =a-1;then b=a; will be executed.
An example program clarifies the Postfix and Prefix operators:
Output of the program:
Bitwise operators
The smallest element in memory on which we are able to operate as yield is a byte;
and we operate on it by use of the data type char Bitwise operator is used for
manipulation of data at bit level.
These operators are used for testing the bits, shifting them right to left. Bitwise
operator may not be applied to float or double data type.
This is a powerful feature of C to manipulate a bit. The programmer can access and
manipulate individual bits within a piece of data.
Some of the bitwise operators in C are:
Operator
&
|
^
<<
>>
~
Meaning
Bitwise Logical AND
Bitwise Logical OR
Bitwise Logical XOR
Left Shift
Right Shift
Once Compliment
Conditional & ternary operators
The conditional operator? and: are sometimes called ternary operators.
A ternary operator is one which contains three operands.
The general form of ternary operator is:
exp 1 ? exp 2 : exp 3
The operator works as, if exp 1 is evaluated first. If the result is true then exp 2 is
executed, otherwise exp 3 is executed.
A program of ternary operator:
Output of the program:
The comma operators
This operator is used to link the related expression together the expression is
separated by the, operator.
An example program showing uses of comma operator:
Output of the program:
Here firstly value 1 is assigned to a, followed by this 2 is assigned to b, and then
the result of a+b is assigned to c.
The comma operator is often used in conjunction with a control statement called
For.
Size of operator
The size of operator returns a number of bytes the operand occupies in memory.
The operand may be a variable, a constant or a data type qualifier. It is a compile
time operator.
An example of size of operator:
Output of size of operator:
The output of the above program is 2 because int occupies two byte in memory.
The size of operator is generally used to determine the length of entities called
arrays and structures when their size is not known to the programmer.
Assignment operator
Assignment operators are used to assign the result of an expression to a variable.
The most commonly used assignment operator is (=).
eg:
i=i+10;
i=i+10 is an assignment expression which assigns the value of i+10 to i.
Expression like i=i+10, i=i-5, i=i*2 etc. can be rewritten using shorthand
assignment operators.
e.g.: i=i+5 is equivalent to i+=5
i=i*(y+1) is equivalent to i*=(y+1)
Operator Precedence:
While executing an arithmetic statement which has two or more operators, we may
have some problems about how exactly does it get executed.
To answer these questions satisfactorily we have to understand the precedence of
operators.
Precedence defines the sequence in which operators are to be applied on the
operands. Operators of same precedence are evaluated from left to right or right to
left, depending upon the level.
This is known as associativity property of an operator.
Summary of precedence of associativity is given below:
Description
Operator
Associativity
()
[]
->
.
Left to Right
Left to Right
Left to Right
Left to Right
Function Expression
Array Expression
Structure Operator
Structure Operator
Description
Operator
Unary minus
Increment/Decrement
One's Compliment
Negation
Address of
Value at address
Type cast
Size in bytes
Description
Multiplication
Division
Modulus
Addition
Subtraction
++/-~
!
&
*
(type)
sizeof
Operator
*
/
%
+
-
Associativity
Right to Left
Right to Left
Right to Left
Right to Left
Right to Left
Right to Left
Right to Left
Right to Left
Associativity
Left
Left
Left
Left
Left to Right
to Right
to Right
to Right
to Right
Description
Operator
Associativity
<<
>>
Left to Right
Left to Right
Left Shift
Right Shift
Description
Operator
Associativity
<
<=
>
Left to Right
Left to Right
Left to Right
>=
Left to Right
Less Than
Less Than Equal to
Greater than
Greater than Equal
to
Description
Equal to
Not equal to
Description
Operator
==
!=
Description
Bitwise OR
Description
Logical AND
Logical OR
Description
Left to Right
Left to Right
Operator
Bitwise AND
Bitwise XOR
&
^
Operator
^
Operator
&&
||
Operator
?:
Operator
Assignment
Assignment
Assignment
Assignment
Assignment
Description
Comma
Associavity
Left to Right
Left to Right
Associavity
Left to Right
Conditional
Description
Associavity
=
*= /= %=
+= -= &=
^= |=
<<= >>=
Operator
,
Associavity
Left to Right
Left to Right
Associavity
Right to Left
Associavity
Right
Right
Right
Right
Right
to
to
to
to
to
Left
Left
Left
Left
Left
Associavity
Right to Left
Type modifier
The basic data types may have modifier preceding them to indicate special
properties of the object being declared.
These modifiers change the meaning of the basic data types to suit the specific
needs.
These modifiers are unsigned, signed, long and short. It is also possible to give
these modifiers in combination, e.g., unsigned long int.
eg:Modifier for char Data Type
main()
{
char ch=291;
printf("%d\t%c\n",ch,ch);
}
output:- 35
Here ch has been defined as a char ,and char cannot take a value bigger
than +128.That is why assigned value of ch is 291 and is considered to be 35 (291128-128).
Data type
Range
signed char
unsigned char
short signed int
short unsigned int
long signed int
long unsigned int
float
double
long double
Bytes occupied
-128 to +127
0 to 255
-32768 to 32767
0 to 65535
-2147483648 to +2147483647
0 to 4294967295
-3.4e38 to 3.4e38
-1.7e4932 to +1.7e308
-1.7e4932 to 1.7e4932
1
1
2
2
4
4
4
8
10
Format
%c
%c
%d
%u
%ld
%lu
%f
%lf
%lf
Expressions
Evaluation of expression
An expression is a combination of variables, constants and operators arranged
according to the syntax of the language.
C can handle any complex expression with ease.
It is little bit different from algebraic expression.
Algebraic Expressions
axb-cxd
(m+n)(a+b)
C Expressions
a*b-c*d
(m+n)*(a+b)
Evaluation of expression:
We can evaluate an expression by using assignment statement. As
Variable = Expression.
e.g. :
Temp = ((f * cos(x)/sin (y))+(g * sin(x)/cos(y)))
All relevant variables must be assigned values before the evaluation of the
expression.
Type conversion in expression:
To effectively develop C programs, it would be necessary for you to understand the
rules that are used for the implicit conversion of operands.
If an expression contains an operation between an int and a float, the int would be
automatically promoted to a float before carrying out of operation.
Automatic type conversion
If the operands are of different types the lower type is automatically converted to
the higher type before the operation proceeds
The result is of the higher type
Given below is the sequence of rules that are applied by evaluating expressions.
Operator 1
Long Double
Double
Float
Unsigned Long Int
Long Int
Unsigned Int
Operator 2
any
any
any
any
any
any
Result
Long Double
Double
Float
Unsigned Long In
Long Int
Unsigned Int
Final result of an expression to the type of the variable on the left of the assignment
signed before assigning the value to it.
However, the following changes are introduced during the final assignment:
1. Float to Int causes truncation of the fractional part.
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of the excess higher order bits
Type Casting:
Casting a value is a forcing a type conversion in a way that is different from the
automatic conversion and this process is called type cast.
This should be clear from the following examples:
An example of automatic conversion:
Output of automatic conversion:
The answer turns out to be 1.000000 and not 1.5 this is because, 6 and 4 are both
integers, and hence 6/4 yields an integer, 1.
This 1 when stored in a is converted to 1.000000. But what if you don't want the
question to be truncated. One solution is to make either x or y as a float.
The general form of casting is:
(type_desired) expression;
where type_desired : standard C data types and
expression: constant, variables or an expression.
An example of type casting:
Output of type casting example:
Type Definition using typedef
C allows us to create data types via the typedef statement.
The format of typedef statement is:
typedef data type new_type_name;
Example:
typedef int units;
units bat1,bat2; /*this statement is equivalent to int bat1,bat2*/
Basic Input/Output
Introduction
Input refers to accepting data while output refers to presenting data. Every program
performs three main functions accepting data from user, processing it and
producing the output.
In C language there are several input and output functions.
These functions are collectively found in IO.h and such IO function together form
a library name stdio.h .
User will require all such library function.
These library functions are classified into three broad categories:
1. Console I/O functions
2. Disc I/O functions
3. Port I/O functions
Console I/O function
Console I/O refers to the operation that occur at the keyboard and the screen of
your computer.
Console I/O function can also be classified in two parts:
1. Formatted console I/O:
Formatted I/O function accepts or present in a particular format. The example of
formatted console I/O function is printf( ) and scanf( ).
printf
It is highly desirable that the output are presented in such a way that they are
understandable and are in a form easy to use.
The printf() statement provides certain features through which the screen output is
effectively controlled.
The general form of printf() function is:
printf("Control String ",arg1,arg2....);
Control string may contain:
1. character that are simply printed as they are.
2. Conversion specification that begin with a sign.
3. Escape sequence that begin with \ sign.
Given below is a list of conversion charcter that can be used with printf() function:
scanf
scanf allows formatted reading of data from the keyboard. Like printf it has a
control string, followed by the list of items to be read.
However scanf wants to know the address of the items to be read, since it is a
function which will change that value. Therefore the names of variables are
preceeded by the & sign.
Character strings are an exception to this. Since a string is already a character
pointer, we give the names of string variables unmodified by a leading &.
Control string entries which match values to be read are preceeded by the
percentage sign in a similar way to their printf equivalents.
2. Unformatted console I/O:
This function cannot control the format of reading and writing the data. some of
the example of this function are getch( ),getche( ),getchar( ),gets( ),putchar(
),putch( )and puts( ).
getchar
getchar returns the next character of keyboard input as an int.
If there is an error then EOF (end of file) is returned instead. It is therefore useful
to compare this value against EOF before using it.
If the return value is stored in a char, it will never be equal to EOF, so error
conditions will not be handled correctly.
As an example, here is a program to count the number of characters read until
an EOF is encountered. EOF can be generated by typing Control - d.
Output of the program:
putchar
putchar puts its character argument on the standard output (usually the screen).
The following example program converts any typed input into capital letters.
To do this it applies the function toupper from the character conversion library
ctype.h to each character in turn.
An example program using putchar.
Output of the program:
gets
gets reads a whole line of input into a string until a newline or EOF is encountered.
It is critical to ensure that the string is large enough to hold any expected input
lines. When all input is finished, NULL as defined in stdio.h is returned
puts
puts writes a string to the output, and follows it with a newline character.
An example program which uses gets and puts to double space typed input
Out put of the program
Note: putchar, printf and puts can be freely used together. So can getchar,
scanf and gets.
Disc & Port I/O function
Function which performs secondary storage devices like floppy disk or hard disk is called disk I/O
functions.
Port I/O functions
This type of functions performs I/O operation among various codes like printer port, mouse port.
Control Structures
Sequence control statements
This type of statements insured that the instruction in a program is executed in the same order. In
which they appear in the program.
An example of sequential Control Statements:
Out put of the program
Explanation of the program:
There are three variable a, b, c is declared as int datatype the value of a=2, b=3 and the result of
the sum is stored in the c variable which is 5.
Decision control & conditional statements
Decision control statements and Conditional Statements allow the computer to take
decision. And force to work under given condition:
Decision control statements:
It gives the control to the computer for taking the decisions.
Two decisions control instruction which are implemented in C are following:
a) The if statements.
b) The if-else statements.
General form of if statements is:
if (condition is true) execute this statement;
A structure image of if condition >
Here we can add else statement also as follow:
else
printf("you have enter number greater than 50");
}
An example of if-else statement:
Out put of the program:
Explanation of the program:
In the above given program you will be asked to enter any no which is less than 50.
Suppose you enter 47 then you will get output, you have entered no. less than 50
value.
Otherwise you have entered number greater than 50.
A structure image of if else condition >
Case control statements
The Case control statements allow the computer to take decision as to be which
statements are to be executed next. It is a multi way decision construct facilitate
number of alternatives.
C has multi way decision statement known as switch statements. It tests the value of
a given variable or expression against a list of case value and when a match found a
block of statement associated with the case is executed.
Syntax of switch statement:
switch(expression)
{
case constant_1:
statements;
case constant_2:
statements;
case constant_n:
statements;
default:
statements;
}
Explanation:
First in expression parentheses we give the condition.
This condition checks to match, one by one with case constant.
If value match then its statement will be executed. Otherwise the default statement
will appear.
A structure image of switch statements>
An example program to check whether a given number is even or odd, using switch
statements:
Out put of the program
Explanation of the program:
First you will be asked to enter any number
Suppose you enter 7
Now the given condition check, so the modulus is 0 or not. (% operator is use to
find out the remainder)
if the modulus is 0 then ch=1 otherwise 2, statement will be execute.
Repitition & loop control statements
This type of statements helps the computer to execute a group of statements
repeatedly.
This allows a set of instruction to be performed until a certain condition is reached.
There are three types of loops in C:
1. for loop
2. while loop
3. do-while loop
The for loop
There are three parts of for loop:
a)counter initialization.
b)check condition
c)modification of counter.
Syntax:
for (variable initialize; check condition; modify counter)
{
statements 1;
-----------;
-----------;
statements n;
}
Explanation:
1. The initialization is usually an assignment that is used to set the loop control
variable.
2. The condition is a relational expression that determines when the loop will exit.
3. The modify counter defines how loop control variables will change each time
the loop is repeated.
These three sections are separated by semicolon (;).
The for loop is executed as long as the condition is true. When, the condition
becomes false the programe execution will resume on the statement following the
block.
Advantage of for loop over other loops:
All three parts of for loop (i.e. counter initialization, check condition, modification
of counter) are implemented on a single line.
A structure image of for loop >
An example program to print a message 5 times using for loop:
Out put of the program
Explanation of the program:
The o/p will be in the loop 1 time, 2times till 5 times.
Something more about for loop:
1. for (p=1,n=2;n<17;n++):- we can assign multiple variable together in for loop.
2. for (n=1,m=50;n<=m;n=n+1,m=m-1):-The increment section may also have
more than one part as given.
3. for (i=1,sum=0;i<20&&sum<100;++i):-The test condition may have any
compound relation as given.
4. for (x=(m+n)/2;x>0;x=x/2):-It is also permissible to use expressions in the
assignment statements of initialization and increment section as given.
5. for (;m!=100;):-we can omitted the initialization and increment section to set up
time delay.
while loop
It is a primitive type looping control because it repeats the loop a fixed no. of time.
It is also called entry controlled loop statements.
Syntax:
while (test_condition)
{
body of loop
}
Explanation:
The test condition is evaluated if the condition is true, the body of loop will be
executed.
A structure image of while >
An example of program to print the number 1 to 10 using while loop:
Out put of the program
The do-while loop
The minor Difference between the working of while and do-while loop is the place
where the condition is tested.
The while tests the condition before executing any of the statements within
the while loop
As against this, the do-while loop tests the condition after having executed the
statement within the loop.
syntax:
do
{
body of loop;
}
while (test condition);
A structure image of do-while loop >
Explanation:
It first executes the body of the loop, and then evaluates the test condition. If the
condition is true, the body of loop will executed again and again until the condition
becomes false.
Example of program using do-while loop:
Out put of the program
Explanation of the program:
First it will print "hello there" then it will go for condition statements.
Some more statements
The break Statement
We have already met break in the discussion of the switch statement. It is used to
exit from aloop or a switch, passing control to the first statement beyond the loop or
a switch.
With loops, break can be used to force an early exit from the loop, or to implement
a loop with a test to exit in the middle of the loop body.
A break within a loop should always be protected within an if statement which
provides the test to control the exit condition.
An Example program to determine whether a number is prime or not:
Out put of the program
The continue Statement
This is similar to break but is encountered less frequently. It only works within
loops where its effect is to force an immediate jump to the loop control statement.
In a while loop, jump to the test statement.
In a do while loop, jump to the test statement.
In a for loop, jump to the test, and perform the iteration (looping).
Like a break, continue should be protected by an if statement. You are unlikely to
use it very often.
An example of program using continue statement:
Out put of the program
The goto Statement
C has a goto statement which permits unstructured jumps to be made. It requires a
label in order to identify the place where the branch is to be made.
A label is any valid variable name,and must be followed by a colon(:).
Syntax:
goto label;
..................
label:
statement;
The label can be any where in the program either before or after the goto
label; statement.
An example program using goto statement:
Out put of the program
Explanation of the program
Here the program will ask untill you give negative value at the time when you give
positive value then instantly it will show you the square root value of the given
number.
Another use of the goto statement is to transfer the control out of a loop (or nested
loops) when certain particular conditions are encountered.
Note: We should try to avoid using goto as far as possible because, it is not good for
readability of the program or to improve the program execution speed.
The exit() function
This function is used for terminating the execution of C program.
Syntax:
exit(int status);
Array and String
Introduction of Array
Whenever there is need to store a group of data of the same type in the
memory, arrays are used. Two terms has been described here Array and String.
Strings in C are represented by the array only therefore it would be convenient to
describestrings separately in the same block but in the different section.
Arrays are the contiguous memory location used to store similar data type or in
other terms we can say Arrays are a data structure which holds multiple variables of
the same data type.
Consider the case where a programmer needs to keep track of a number of people
within an organization. So far, our initial attempt will be to create a
specific variable for each user.
This might look like:
int name1 = 101;
int name2 = 232;
int name3 = 231;
It becomes increasingly more difficult to keep track of this as the number
of variablesincreases. Arrays offer a solution to this problem.
An array is a multi-element box, a bit like a filing cabinet, and uses an indexing
system to find each variable stored within it.
In C, indexing starts at zero. Arrays, like other variables in C, must be declared
before they can be used.
The replacement of the above example using arrays looks like:
int names[4];
names[0] = 101;
names[1] = 232;
names[2] = 231;
names[3] = 0;
We created an array called names, which has space for four integer variables. You
may also see that we stored 0 in the last space of the array.
This is a common technique used by C programmers to signify the end of an array.
An image showing internal stucture and location distribution method of array >
Array Declaration
Arrays are defined in the same manner as ordinary variables, except that
each array name must be accompanied by the size specification.
The general form of array declaration is:
data_type array_name[size];
data-type specifies the type of array, size is a positive integer number or symbolic
constant that indicates the maximum number of elements that can be stored in
the array.
Example:
float height[50];
This declaration declares an array named height containing 50 elements of type
float.
Array Initialization
The Element of array are initialized in the same way as the ordinary variables.
Example:
int num[6]={2,4,5,35,12,12,67};
An example showing the index and its corresponding data (prices) >
An example program of entering data into Array:
Out put of the program
In this example, using the for loop, the process of asking and receiving the marks is
accomplished.
When the count has the value 0, the scanf() statement will cause the cvalue to be
stored atnum[0].
The process continues until count has the value greater than 5.
Reading data from Array
In the above program we enter the data into an Array. Now to read value from
this array , we will again use for Loop.
The below program segment explains the retrieval of the values from the array:
Two Dimensional Array
Two dimensional array (2-D array) is also called Matrix
General form of 2-D array is:
data_type array_name[row_size][column_size];
Example:
int marks [4][2]
Different ways of Initialization of a 2-Dimensional Array:
int table [2][3]={0,0,0,1,1,1};
initialization done by row.
int table[2][3]={{0,0,0},{1,1,1}};
surrounding the elements of each row by braces.
int table[2][3]={{0,0,0,},
initialization as matrix.
An example program that stores roll number and marks obtained by a student side
by side in Matrix:
Explanation
There are two parts of the program. In the first part a for loop will read the values
of rollno. and marks, whereas in the second part another loop will print these
values.
Two Dimensional Array
Two dimensional array (2-D array) is also called Matrix
General form of 2-D array is:
data_type array_name[row_size][column_size];
Example:
int marks [4][2]
Different ways of Initialization of a 2-Dimensional Array:
int table [2][3]={0,0,0,1,1,1};
initialization done by row.
int table[2][3]={{0,0,0},{1,1,1}};
surrounding the elements of each row by braces.
int table[2][3]={{0,0,0,},
initialization as matrix.
An example program that stores roll number and marks obtained by a student side by side in
Matrix:
Explanation
There are two parts of the program. In the first part a for loop will read the values of rollno. and
marks, whereas in the second part another loop will print these values.
Multi Dimensional Array
Arrays of three or more dimension is called Multi-Dimensional Array.
General form Multi-Dimensional Array:
data_type array_name[s1][s2][s3]......[sn];
Example:
int survey[3][5][12]
Here survey is a 3-dimensionalarray declared to contain 180 integer_type elements.
(3x5x12=180)
Initialization of 4-Dimensional Array:
static int arr [3] [4] [2]={{{2,4}, {7,3}, (3,4}, {5,1}, }, {{3,4}, {3,4}, {3,2},
{4,5}}, {{2,3}, {2,7}, {2,3}, {4,3}}}
In this example, the outer array has three element , each of which is a two
dimensional array of four rows, each other of which is a one dimensional array of
two elements.
An example program to sort an integer array:
Out put of the program
String
Strings in C are represented by arrays of characters. The end of the string is marked
with a special character, the null character, which is simply the character with the
value 0.
Because C has no built-in facilities for manipulating entire arrays (copying them,
comparing them, etc.), it also has very few built-in facilities for manipulating
strings.
In fact, C's only truly built-in string-handling is that it allows us to use string
constants (also called string literals) in our code.
Whenever we write a string, enclosed in double quotes, C automatically creates
an array of characters for us, containing that string, terminated by the \0 character.
For example, we can declare and define an array of characters, and initialize it with
a string constant:
char string[] = "Hello, world!";
Two ways to initilize string >
In this case, we can leave out the dimension of the array, since the compiler can
compute it for us based on the size of the initializer.
This is the only case where the compiler sizes a string array for us, however; in
other cases, it will be necessary that we decide how big the arrays we use to hold
strings.
An example program showing the character data type array:
Out put of the program
In the above example, a character based array named word is declared, and each
element ofarray is assigned a character.
The last element is filled with a zero value, to signify the end of the character
string (in C, there is no string type, so character based arrays are used to hold
strings).
A printf statement is then used to print out all elements of the array.
Function and Recursion
Function Definition
Functions are self contained program segments that carry out some specific well
defined task.
In "C" , we include the header files like stdio, conio, string, etc.
These files contain number of library functions which are as follows:
printf( ), scanf( ), getchar( ), putchar( ), getche( ), gets( ), puts( ), strlen( ), getch( ),
etc.
In C it is possible for the function to call themselves. we will see how it can be
possible through Recursions.
A Function is a self-contained block of statement that perform a coherent task of
some kind. Every C program must have a function. One of the function must
be main().
Why should we use Function?
a) Using function it becomes easier to write programs and keep track of what they
are doing
b) Length of the program can be reduced by using function.
c) Debugging is easier.
d) It facilitates top-down modular programming.
Classification of Function
C function can be classified into two categories:
1. Library function:
They are predefined in the standard library of C. We need to include the Library.
2. User-defined function:
User defined functions are need to be developed by the user at the time of program
writing.
Function and Recursion
Function Declaration
Before defining the function, it is desired to declare the function with its prototype.
In function prototype, the return value of function, type, and number of argument
are specified.
Function declaration is written in following ways:
return data_type function_name (data_type argument 1, data_type argument 2
................data_type argument n)
{
local variable declaration;
executable statement 1;
executable statement 2
..................................
................................
executable statement n;
return(expession);
}
Note: An empty pair of parenthesis must follow the function name if the function
definition does not include any arguments.
Example:
If it returns a float than command is:
float f1(float arg 1, int arg 2);
if it returns no value or return a character, then replace float by void or char
respectively. If no arguments passed into a function than command is:
char fun1 ( );
An example program using a small add function:
Out put of the program
Function Call
Function can be called either by value or by reference .A function can be called by
specifying its name followed by a list of arguments enclosed in parentheses and
separated by commas.
From the above example the following line is used as a function call:
sum=add(a,b); /* function call */
Call by value: Call by value means directly pass value within the function.
An example program of call by value:
Out put of the program
Call by reference: Call by reference means sending the addresses of the argument to
the called function.
In this method the addresses of actual arguments in the calling function are copied
into formal arguments of the called function. (later discussed in pointer section)
The Return Statement
Information is returned from the function to the calling portion of the program via
return statement.
General form of return statement:
return;
or
return(expression);
Storage Classes
There are two different ways to characterize variables:
1. By data type
2. By storage Class
Data type refers to the type of information while storage class refers to the life time
of a variable and its scope within the program.
A variable in c can have any one of the four storage classes:
1. Automatic Variable:
It is created when the function is called and destroy when the function is exited.
Hence the name is Automatic. By default a variable is declared Automatic.
2. External Variable:
It is also known as Global Variable. This variables can be accessed from any
function that falls within their scope.
3. Static Variable:
A static variable may be either internal or external type , depending on the place of
declaration.
Internal static variable extends up to the function in which they are defined and
external static variable is declared outside of all function and is available to all the
functions in the program.
4. Register Variable:
We can tell the compiler that a variable should be kept in one of the machine's
registers, instead of keeping in the memory (where normal variables are stored ).
Since, a register access is much faster than a memory access and keeping the
frequently accessed variables in the register will lead to faster execution of
programs.
Recursion
Repetitive calling of the same function is called recursion. Recursions are those
functions which call itself again and again. Recursive functions can easily
become infinite loops.
An example program to find out the factorial of any number is the one of the best
example of recursion:
Out put of the program
Pointers
Introduction
Pointers are a fundamental part of C. If you cannot use pointers properly then you
have basically lost all the power and flexibility that C allows. The secret of C is in
its use of pointers.
C uses pointers a lot. Why?
It is the only way to express some computations.
It produces compact and efficient code.
It provides a very powerful tool.
C uses pointers explicitly with following:
1. Functions.
2. Arrays.
3. Structures. (discussed later)
Note: Pointers are perhaps the most difficult part of C to understand. C's
implementation is slightly different from other languages.
What is a Pointer?
A pointer is a variable which can hold the address of a memory location rather than
the value at the location.
Pointer Notation
The actual address of a variable is not known immediately. We can determine the
address of the variable using address of operator(&).
We have already seen the use of address of operator in the scanf() function.
Another pointer operator available in C is "*" called "value of address" operator. It
gives the value stored at a particular address. This operator is also known as
indirection operator.
Pointer Declaration
To declare a pointer to a variable:
int *pointer;
Note: We must associate a pointer to a particular type: You can't assign the address
of ashort int to a long int,
Pointer expression
Like other variables pointer variable can also be used in
expressions. Arithmetic andcomparison operation can be performed on the pointers.
Pointer Arithmetic
Example:
Addition of a number to a pointer int i=4,*j,*
j=&i;
j=j+1;
j=j+9;
k=j+3;
Example:
Subtraction of number from a pointer int i=4,*j,*k;
j=&i;
j=j-2;
j=j-5;
k=j-6;
But the following operation are not allowed on pointers:
a) multiplication of pointer with a constant
b) addition of two pointer
c) division of pointer with a constant
Pointer Comparison
Pointer can be compared using relational operator. Expression such as- p1>p2
p1=p2p1!=p2 are allowed.
Pointer & functions
Let us now examine the close relationship between pointers and C's other major
parts. We will start with functions.
When C passes arguments to functions it passes them by value.
There are many cases when we may want to alter a passed argument in the function
and receive the new value back once the function has finished.
C uses pointers explicitly to do this.
The best way to study this is to look at an example where we must be able to
receive changed parameters. Let us try and write a function to swap variables
around?
The usual function call:
swap (a, b) won't work.
Pointers provide the solution: Pass the address of the variables to the functions and
access address of function.
Thus our function call in our program would look like this:
swap (&a, &b)
The Code to swap is fairly straightforward:
void swap(int *px, int *py)
{ int temp;
temp = *px;
/* contents of pointer */
*px = *py;
*py = temp;
}
Pointer & Array
Pointers and arrays are very closely linked in C.
Hint: Think of array elements arranged in consecutive memory locations.
Consider the following:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this case) */
Warning: There is no bound checking of arrays and pointers so you can easily go
beyond array memory and overwrite other things.
C however is much more subtle in its link between arrays and pointers.
For example we can just type:
pa = a;
instead of
pa = &a[0]
and
a[i] can be written as *(a + i).
i.e. &a[i] =a + i.
We also express pointer addressing like this:
pa[i] =*(pa + i).
However pointers and arrays are different:
A pointer is a variable. We can do pa = a and pa++.
An Array is not a variable. a = pa and a++ ARE ILLEGAL
This stuff is very important. Make sure you understand it. We will see a lot more of
this. We can now understand how arrays are passed to functions.
When an array is passed to a function what is actually passed is its initial element
location in memory
So: strlen(s) strlen(&s[0])
This is why we declare the function:
int strlen(char s[]);
An equivalent declaration is:
int strlen(char *s);
since char s[] is equivalent to char *s.
strlen () is a standard library function that returns the length of a string.
Let's look at how we may write a function:
int strlength(char *s)
{
char *p = s;
while (*p != '\0');
p++;
return p-s;
}
Now let’s write a function to copy a string to another string. strcpy () is a standard
library function that does this:
void strcopy (char *s, char *t)
{ while ( (*s++ = *t++) != `\0' );}
This uses pointers and assignment by value.
Note: Uses of Null statements with while.
Malloc Library Function
Function: Allocates main memory
Syntax: void*malloc(size_t size);
Prototype in: stdlib.h, alloc.h
Remarks: malloc allocates a block of size bytes from the C heap memory. It allows
a program to allocate memory explicitly, as it is needed and in the exact amounts
needed.
Calloc Library Function
Function: Allocates main memory
Syntax: void*calloc(size_t n size);
Prototype in: stdlib.h, alloc.h
Remarks: Calloc provides access to the C heap memory . Calloc allocates a block of
size n items of x size. The block is cleared to 0.
Multi Dimensional Arrays & Pointer
We should think of multidimensional arrays in a different way in C:
A 2D array is really a 1D array, each of whose elements is itself an array
Hence
a[n][m] notation.
Array elements are stored row by row.
When we pass a 2D array to a function we must specify the number of columns and
the number of rows is irrelevant.
The reason for this is pointers again. C needs to know how many columns in order
that it can jump from row to row in memory.
Considerint a[5][35] to be passed in a function:
We can do:
f(int a[][35]) {.....}
or even:
f(int (*a)[35]) {.....}
We need parenthesis (*a) since [] have a higher precedence than *
So:
int (*a)[35]; /*declares a pointer to an array of 35 int */
int *a[35]; /*declares an array of 35 pointers to int */
Now lets look at the (subtle) difference between pointers and arrays. Strings are a
common application of this.
Consider:
char *name[10];
char Aname[10][20];
We can legally do name[3][4] and Aname[3][4] in C.
Arrays of Pointer
We can have arrays of pointers since pointers are variables.
Example use: Sort lines of text of different length.
Note: Text can't be moved or compared in a single operation.
Arrays of Pointers are a data representation that will cope efficiently and
conveniently with variable length text lines.
How can we do this: Store lines end-to-end in one big char array n will delimit
lines.
Store pointers in a different array where each pointer points to 1st char of each new
line.
Compare two lines using strcmp () standard library function.
If 2 lines are out of order swap pointer in pointer array (not text).
Pointer & functions
When an array is passed to a function as an argument , only the address of the first
element of the array is passed , but not the actual values of the array elements.
If x is an array, when we call sort(x), the address of x[0] is passed to the
function sort().
The function uses this address for manipulating the array elements.
The address of a variable can be passed as an argument to a function in the normal
fashion.
When address is passed to a function , the parameters receiving the address 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.
Example:
main()
{
int x;
x=20;
change(&x);
printf("%d\n",x);
}
change( int *p)
{
*p=*p+10;
}
Explanation: When the function change() is called, the address of the variable x, not
its value, is passed into the function change().
Inside change(), the value at which p points is incremented by 10 , and the changed
value is then displayed in the main function.
Structures
Introduction
The C language allows us to create custom data types.
The structure is a custom data type which c combines different data types .
The structure is a custom data type which combine different data types to form a
new user define data type.
Definition
A structure is a collection of variable reference under one name providing a
convincible means of related information together.
Format: struct tag_name
{
data _type member1;
data_type member2;
--------------------------------------};
here a keyboard struct declares a structes to hold the details of field of different data
types.
Example:
struct addr
{
char name [30];
char city [15];
int pincode ;
};
Creating Structure variable
structure can be created in two ways:
1. declaration using tagname anywhere in the program.
Example:
struct book
{
char name [30];
char author [25];
float price;
};
struct book book1 book2
2. it is also allowed to combine structure declaration and variable declaration in one
statement.
Example:
struct person
{
char *name;
int age;
char*address;
};
p1,p2,p3
while declaring structure variable along with their definition, the use of tag-name is
optional.
Struct
{
char *name;
int age;
char * address;
}
p1,p2,p3
Image showing how the given value allocate in structure with the help of an
example >
Giving values to member
The link between a member and a variable is established using member operator `.'
to dot operator.
An example program to define a structure and assign value to members:
Out put of the program
Structure Initialization
a structure variable can be initialization as any other data type.
Main()
{
static struct
{
int weight;
float height;
}
}
student{560,080,75};
This assign the value 60 to student weight and 180.75 student height. there is a one
to one correspondents between the members and their initializing values.
The following statements initialize two structures variables:
Main()
Struct st_decord
{
int weight;
float height;
}
static struct st_record student2={53, 170,60}
}
another method is to initlialize a structure variable outside the function.
Struct st_record/* No static word*/
{
int weight;
int height
}
student={60,50,75}
}
main()
{
static struct st_record student2={53,170,60}
}
Comparison of structure variables
Two variables of the same structure type can be compared the same way as ordinary
variables.
operation meaning
person1=person2*assign perosn2 to person1
person1== person2*compare all name of person1 and person2 and return1
Arrays of structures
The most common use of structures is in arrays of structures. To declare an array of
structures, first the structure is defined then an array variable of that structure is
declared.
E.g.: struct class student [100];
It defines an array called student which consists of 100 elements of structure named
class.
Ans is stored inside the memory in the same way as a multidimensional array
example program.
To implements on array of structures.
Arrays with in structures
Single as multidimensional arrays of type int as float can be defined as structure
members.
Example:
struct marks
{
int number;
float subject[3];
}
student [2];
Here the member subject contains three elements, subject[0],
subject[1] and subject[2]there elements can be accessed using appropriate subscript.
For instance, the name student [1] student [2]; would refer to the marks obtained in
the third subject by the secured student.
Structures with in structures
Structures within a structure means nesting of structures.
Example:
struct salary
{
char name [20];
char department [10];
int basic-pay;
int dearness-allowance;
int huse_rent_allowance;
int city_allowance;
}
employee;
This structure defines name, department, basic pay and three kinds of allowances.
All the items related to allowance can be grouped together and declared under a
sub-stricture. As shown below, strut salary
{
char name []2;
char department [10];
struct;
}
int dearness;
int house_rent;
int city;
[allowance;
}
employee's;
The salary structure contains a member named allowance which use is a structures
with.
Three members. Now ; the member compared in the inner structure;, namely,
;dearness,house_rent and city can ;be left to as;
employee. ;allowance. Dearness
employee. Allowance. House_rent
employee allowance. city
The inner most member in a nested structure can be accessed by chaining all the
concerned structure variables (from outermost to inner most) with the member
using dot operator.
Passing structure to function
There are three methods by which the values of structure can be transferred from
one function to another:
1. The first method is to pass each member of the structure as an actual argument of
the function call.
The actual argument is then treated independently like ordinary variables.
2. The second methods involve passing of a copy of the entire structure to the called
function
Since the function is working on a copy of the entire structure to the called function,
changes are not reflected in the original structure (in the calling function).
It is necessary for the entire function to return the entire structure back to the calling
function.
3. The third approach employs a concept called pointers to pass the structure as an
argument .
In this case, the address location of the structure is passed to the called function.
The function can access indirectly the entire structure and work on it.
The general format of sending a copy of structure to the called function is:
function_name (structure_variable_name)
Union
Introduction
Union are derived data types, the way structure are. Though, unions and structures
look alike, and there is a fundamental difference.
While structure enables you to create a number of different variables stored in
difference places in memory, unions enable you to treat the same space as a number
of different variables
Union-Definition and Declaration
Unions, like structures, contain members whose individual data types may differ
from one another.
However, the members within a union all share the some storage space within the
computer's memory, whereas each member within a structure is assigned its own
unique storage area.
Thus, unions are used to conserve memory.
They are useful for applications involving multiple members, where values need not
be assigned to all of the members at any one time.
Within a union, the bookkeeping required to store members whose data types are
different (having different memory requirements) is handled automatically to the
compiler.
However, the user must keep track of what type of information is stored at any
given time.
An attempt to access the wrong type of information will produce meaningless
results. In general terms, the composition of a union may be defined as:
Union tag
{
Member 1;
Member 2;
…..
member n;
};
Where union is required keyword and the other terms have the same meaning as in
a structure definition.
Individual union variables can then be declared as:
storage-class union tag variable 1, variable 2, . . . , variable n;
Where storage-class is an optional storage class specified, union is a required
keyword, tag is the name that appears in the union definition, and variable 1,
variable 2, . . . , variable n are union.
The two declarations may be combined, just as we did with structures. Thus, we can
writeStorage-class union tag
{
Member 1;
Member 2;
.....
member n;
}
The tag is optional in this type of declaration.
Notice that the union and structure declarations are external to the program
functions, but the structure variable is defined locally within each function.
Accessing a union member
To access a union member, you can use the same syntax that you use for structure
members.
Example:
code.m, code.x etc.
During execution, we should make sure that the value of accessing member is
currently stored.
Initialization of Union variable
A union variable can be initialized , provided its storage class is either external or
static.
Only one member of a union can be assigned a value at any one time.
The initialization value is assigned to the first member within the union.
An example program to demonstrate initialization of union variables:
Uses of Union
Union, like structure, contain members whose individual data type may differ to
each other.
But the members that compose a union share the same storage area within the
computer's memory, whereas each member within a structure is assigned its own
unique storage area.
Thus, union are used to conserve memory.
1. Unions are useful for application involving multiple members, where value need
not to be assigned to all of the members at any one time.
2. Unions are useful whenever there is a requirement to access the same memory
location in more than one way. etc.
Dynamic Data Structure
Linked list
Before talking about the different mechanism of data structure we will take a short
view of DMA (Dynamic Memory Allocation).
DMA: C language requires the number of elements in an array to be specified at
compile time.
But it is not practically possible with Array.
In array we allocate the memory first and then start using it.
This may result in failure of a program or wastage of memory space.
The concept of dynamic memory allocation can be used to eradicate this problem.
In this technique , the allocation of memory is done at run time.
C language provides four library function known as memory management function
that can be used for allocating and freeing memory during program execution.
These are:
malloc: allocate memory and return a pointer to the first byte of allocated space.
Example:
ptr=(cast.type*)malloc(byte_size);
calloc: allocates the memory spaces, initialize them to zero and returns pointer to
first byte.
Example:
ptr=(cast_type*)calloc(n.elem_size);
free: frees previously allocated space.
Example:
free(ptr);
realloc: modifies the size of previously assigned space
Example:
ptr=realloc(ptr,newsize);
We studied about Array there we can observe one major disadvantage of Array is ,if
an array is not filled by value, then memory will be locked up.
To overcome this problem we use Linked lists and other data structure mechanism.
Linked List are a way to store data with structures so that the programmer can
automatically create a new place to store data whenever necessary.
Specifically, the programmer writes a struct definition that contains variables
holding information about something, and then has a pointer to a struct of its type.
Each of these individual struct in the list is known as a node.
Think of it like a train. The programmer always stores the first node of the list. This
would be the engine of the train.
The pointer is the connector between cars of the train.
Every time the train add a car, it uses the connectors to add a new car.
This is like a programmer using the keyword new to create a pointer to a new struct
In memory it is often described as looking like this:
---------- ---------- Data - >- Data ->
---------- - ---------- Pointer- - - - Pointer---------- ----------
Stack
A stack is a data structure that resembles a stack of trays in a spring loaded bin.
A tray will be added to the bin on top of the stack. When you add a tray, the
previous one on top will go down by one position.
You can add trays till the first trays reach the bottom of the stack. Similarly, a tray
can be removed only from the top of the stack.
In the computer science item is nothing but a data element or an object.
Therefore a stack is a list in which items are added, deleted or examined at one only
one end.
The size of the stack is defined by the user before compilation and hence this is a
static data structure.
It adopts LIFO (last in first out ) methodology for storage and retrieval.
Opening Existing Project
Suppose you have to open a existing project, then follow the steps below:
1. Go to the File Menu.
2. Click on to the open project project.
3. Click on the Open button on the title Bar OR You can use Ctrl+O for opening a
existing project.
The window looks like below:
Queue
Queue is also a list. Here, the data items are added at one end and removed from the
other hand work as first in first out for storage and retrieval.
Queues are used extensively in operating systems to keep track of user waiting for
resources such as CPU, printing etc.
It adopts FIFO(first in first out )methodology for storage and retrieval.
Data File Handling through C
Introduction
Many applications require that information be written to or read from an auxiliary
memory.
Such information is stored on the memory device in the form of a data file.
Thus files allow us to store information permanently, and to access and alter that
information whenever necessary.
In C, an extensive set of library; functions is available for creating and processing
data files. Unlike other files.
However, there are two different types of data files
1. Stream-oriented (or standard) data files:
Stream oriented data files are generally easier to work with and are therefore more
commonly used.
Stream-oriented data files can be subdivided into two categories.
The first category are text files, consisting of consecutive characters. There
characters can be interpreted as individual data items, or as components of strings
or numbers.
2. System-oriented (or low level) data files:
System-oriented data files, often referred to as unformatted data files, organizes
structures, such as arrays and structures.
A separate set of library functions is available for processing stream-oriented data
files of this type.
These library functions provide single instructions that can transfer entire arrays or
structures to or from data files.
Note: Library function has been discussed in detail in next section.
File operation
There are two distinct ways to perform the file operation in C:
1. Low level I/O operation (it uses UNIX system call therefore we won't discuss
here)
2. High level I/O operation (it uses function in C's Standard I/O library)
List of I/O function with their operation:
fopen()
fclose()
getc()
putc()
fprintf()
fscanf()
getw()
putw()
feof()
creates a new file for use or opens an existing file for use.
close a file which has been opened for use.
reads a character to a file.
writes a character to a line.
writes a set of data values to a file.
reads a set of data values from a file.
reads an integer from a file.
writes an integer to a file.
test for an end of file condition.
Opening & closing a data file
When working with a stream-oriented data file, the first step is to establish
a buffer area (a holt station for data processing) where information is temporarily
stored while being transferred between the computer's memory and the data file.
This buffer area allows information to be read from or written to the data file more
readily than would otherwise be possible. The buffer area is established by writing
FILE * ptvar;
Where FILE (uppercase letter required) is a special structure type that establishes
thebuffer area, and ptvar is a pointer variable that indicates the beginning of
the buffer area.
The structure type FILE is defined within a system include file,
typically stdio.h. The pointerptvar is often referred to as a stream pointer, or simply
a stream.
A data file must be opened before it can be created or processed. This associates the
file name with the buffer area (i.e., with the stream).
It also specifies how the data file will be utilized, i.e., as a read-only file, a write only file, or a read/write file, in which both operations are permitted.
The library function open is used to open a file. This function is typically written
as Ptvar =open (file-name, file-type)
Where file-name and file-type are strings that represent the name of the data
file and the manner in which the data file will be utilized.
The name chosen for the file-name must be consistent with the rules for naming
files, as determined by the computer's operating system.
The file-type must be one of the strings shown:
"r"
"w"
"a"
"r+"
"w+"
"a+"
Open an existing file for reading only.
Open a new file for writing only. If a file with the specified filename currently exists, it will
be destroyed and a new file will be created in its place.
Open an existing file for appending. A new file will be created if the file with the specified
file-name don't exists.
open an existing file for both reading and writing
Open an existing file for both reading and writing. If a file with the specified file
name currently exists, it will be destroyed and a new file created in its place
Open an existing file for both reading and appending. A new file will be created if the file
with the specified file-name does not exists.
Creating a data file
A data file must be created before it can be processed.
A stream-oriented data file can be created in two ways. One is to create the file
directly, using a text editor or a word processor.
The other is to write a program that enters information into the computer and than
writes it out to the data file.
Unformatted data files can only be created with such specially written programs.
Example:
Reading a data fileThe following program will read a line of text from a data file on a character by
character basis, and display the text on the screen.
The program makes use of the library functions get and putchar to read and display
the data.
An example program to read a line of text from a data file and display it on the
screen:
Data file consisting entirely of strings can often be created and read more casually
with programs that utilize special string-oriented library functions.
Some commonly used functions of this type are gets, puts, fgets and fputs.
The functions gets and puts read or write strings to or from the standard output
devices, whereas fgets and fputs exchange strings with data files.
Processing a data file
Most data file applications require that a data file be altered as it is being processed.
For example, in an application involving the processing of customer records, it may
be desirable to add new records to the file there requirements in turn suggest several
different computational strategies.
Another approach is to work with two different data files- an old file and a new file.
Each record is read from the old file, updated as necessary, and then written to the
new file.
When all of the records have been updated, the old file is deleted or placed into
archival storage and the new file renamed. Hence, the new file become the struck
for the next round of updates.
Historically, the origin of this method goes back to the early days of computing,
when data files were maintained on magnetic tapes. The method is still used,
however, because it provides a series of old source.
File that can be used to generate a customer history. The most recent source file can
also be used to recreate the current file if the current file is damaged or destroyed.
Unformatted data file
Some applications involve the use of data files to store block of data, where each
block consists of a fixed number of contiguous bytes.
Each block will generally represent a complex data structure, such as a structure or
an array.
For example, a data file may consist of multiple structures having the same
composition, or it may contain multiple arrays of the same type and size.
For such applicators it may be desirable to read the entire block from the data, or
write the entire block to the data file, rather than reading or writing the individual
components (i.e., structure members of array elements) within each block
separately.
The library functions fread and fwrite are intended to be used in situations of this
type.
There functions are often referred to as unformatted read and write functions.
Similarly, data files of this type are often referred to as unformatted data file.
Each of these functions requires four arguments: a pointer to the data block, the size
of the data block, the number of data blocks being transferred, and the stream
pointer.
Thus, a typical fwrite function might be written as: fwrite(&customer,
sizeof(record), 1, fpt);
Where customer is a structure variable of type record, and fpt is the stream pointer
associated with a data file that has been opened for output.
An example program to create an unformatted data file containing customer
records:
Reading file:
Displaying the contents:
C Preprocessor & Macro
Introduction
The C preprocessor is a tool which filters your source code before it is compiled.
The preprocessor allows constants to be named using the # notation.
The preprocessor provides several other facilities which will be described here.
It is particularly useful for selecting machine dependent pieces of code for different
computer types, allowing a single program to be compiled and run on several
different computers.
The C preprocessor isn't restricted to use with C programs only. Programmers who
use other languages may also find it useful, however it is tuned to recognize
features of the C language like comments and strings, so its use may be restricted in
other circumstances.
Set of commonly used Preprocessor Directives and their Functions:
#define
#undef
#include
#ifdef
#ifndef
#if
#endif
#else
defines a macro substitution.
undefined a macro.
specifies the files to be include.
tests for a macro definition
tests whether a macro is not defined.
tests a compile-time condition.
specifies the end of #if.
specifies alternatives when #if test fails.
These Preprocessor or directives can be divided into three categories:
1. Macro Substitution Directives
2. File Inclusion Directives
3. Compiler Control Directives
Macro substitution directives
We have already met this facility, in its simplest form it allows us to define textual
substitutions using #define statement.
The #define statement can be used for more, however, than simply defining
symbolic constants.
In particular, it can be used to define macros; its, single identifiers that are
equivalent to expressions, complete statement or groups of statements. Macros
resemble function in this sense.
They are defined in an altogether different manner than functions, however, and
they are treated differently during the compilation process.
Format: #define identifier string
e.g.: #define MAXSIZE 256
This will lead to the value 256 being substituted for each occurrence of the
word MAXSIZE in the file.
Example:
Out put of the program
This program contains the macro area, which represents the expression length*
width.
When the program is compiled, the expression length * width will replace the
identifier area within the printf statement, so that printf statement will become
Printf("\narea =%d", length *width);
Note that the format string " \n area =%d" is unaffected by the #define statement.
When the program is executed, the values for length and width are entered
interactively from the keyboard, and the corresponding value for area is displayed.
A typical interactive session is shown below. The user's responses are underlined,
as usual.
Length =_3
Width =_4
Area=12
Macro definitions are customarily placed at the beginning of a file, ahead of the first
function definition.
The scope of a macro definition extends from its point of definition to the end of the
file. However, a macro defined in one file is not recognized within another file.
Multilane macros can be defined by placing a backward slash (\) the end of each
line except the last.
This feature permits a single macro (i.e. a single identifier) to represent a compound
statement.
Here is another simple c program that contains multilane macro:
Out put of the program
Macros are sometimes used in place of functions within a program.
The use of a macro in place of a function eliminates the time delays associated with
function calls.
If a program contains many reported function calls, the time savings resulting from
the use of macros can become significant.
On the other hand, macro substitution will take place whenever a reference to a
macro appears within a program.
Thus, a program that contains several references to the same macro may become
unreasonably long. We therefore face a tradeoff between execution speed and size
of the compiled object program.
The use of a macro is most advantageous in applications where there are relatively
few functions calls but the function is called repeatedly.
Using #define to Create Functional Macros
#define can also be given arguments which are used in its replacement. The
definitions are then called macros.
Macros work rather like functions, but with the following minor differences.
Since macros are implemented as a textual substitution, there is no effect on
program performance (as with functions).
Recursive macros are generally not a good idea.
Macros don't care about the type of their arguments. Hence macros are a good
choice where we might want to operate on reals, integers or a mixture of the two.
Macros are full of traps for the unwary programmer. In particular the textual
substitution means that arithmetic expressions are liable to be corrupted by the
order of evaluation rules.
Here is an example of a macro which won't work:
#define DOUBLE(x) x+x
Now if we have a statement
a = DOUBLE(b) * c;
This will be expanded to
a = b+b * c;
And since * has a higher priority than +, the compiler will treat it as.
a = b + (b * c);
The problem can be solved using a more robust definition of DOUBLE
#define DOUBLE(x) (x+x)
Here the brackets around the definition force the expression to be evaluated before
any surrounding operators are applied. This should make the macro more reliable.
In general it is better to write a C function than risk using a macro.
File inclusion
The preprocessor directive #include is an instruction to read in the entire contents of
another file at that point.
This is generally used to read in header files for library functions. Header files
contain details of functions and types used within the library.
It must be included before the program can make use of the library functions.
Library header file names are enclosed in angle brackets, < >. These tell
the preprocessorto look for the header file in the standard location for library
definitions.
Example: #include
another use for #include for the programmer is where multi-file programs are being
written.
Certain information is required at the beginning of each program file. This can be
put into a file called globals.h and included in each program file.
Local header file names are usually enclosed by double quotes, " ". It is
conventional to give header files a name which ends in .h to distinguish them from
other types of file.
Our globals.h file would be included by the following line. #include "globals.h"
Compiler control directive
The C Preprocessor offer a feature known as conditional compilation, which can be
used to switch on or off a particular line or group of lines in a program.
This is achieved by the inserting #ifdef or #endif.
Conditional selection of code using #ifdef,#endif.
The preprocessor has a conditional statement similar to' C's if else.
It can be used to selectively include statements in a program. This is often used
where two different computer types implement a feature in different ways. It allows
the programmer to produce a program which will run on either type.
The keywords for conditional selection are; #ifdef, #else and #endif. #ifdef
takes a name as an argument, and returns true if the name has a current definition.
The name may be defined using a #define, the -d option of the compiler.
#else
is optional and ends the block beginning with #ifdef. It is used to create a 2 way
optional selection.
#endif
ends the block started by #ifdef or #else.
Where the #ifdef is true, statements between it and a following #else or #endif are
included in the program.
Where it is false, and there is a following #else, statements between the #else and
the following #endif are included.
This is best illustrated by an example.
Using #ifdef for Different Computer Types
Conditional selection is rarely performed using #defined values. A simple
application using machine dependent values is illustrated below:
Out put of the program
Note: sun is defined automatically on SUN computers. vax is defined automatically
on VAX computers. ibm is defined automatically on IBM pc's else type not defined
message will be displayed (different types of computer)
Using #ifdef to Temporarily Remove Program Statements
#ifdef also provides a useful means of temporarily "blanking out" lines of a
program.
The lines in question are preceded by #ifdef NEVER and followed by #endif. Of
course you should ensure that the name NEVER isn't defined anywhere.
Command line parameter of C
Command line parameter
You may have been wondering about the empty parentheses in the first line of the
main function, i.e. main().
The parentheses may contain special arguments that allow parameters to be passed
to main from the operating system.
Most versions of C permit two such arguments, which are traditionally
called argc and argv, respectively.
The first of these, argc, must be an integer variable, while the second, argv, is an
array of pointers of characters; i.e., an array of strings.
Each string in this array will represent a parameter that is passed to main. The value
ofargc will indicate the number of parameters passed.
Example: The following outline indicates how the arguments argc and argv are
defined within main.
Vod main(int argc, char *argv[])
{
.....
}
The first line can be written without the keyword void, i.e.,
main(int argc, char *argv[])
A program is normally executed by specifying the name of the program within a
menu-driven environment.
Some compilers also allow a program to be executed by specifying the name of the
program (actually, the name of the file containing the compiled object program) at
the operating system level.
The program name is then interpreted as an operating system command. Hence, the
line in which its appears is generally referred to as a command line.
In order to pass one or more parameters to the program when it is executed from the
operating system, the parameters must follow the program name on the command
line.
E.g.: Program-name parameter 1 parameter 2 . . . parameter n
The individual items must be separated from one another either by blank spaces or
by tabs.
Some operating systems permits blank spaces to be included within a parameter
provided the entire parameter is enclosed in quotation marks.
The program name will be stored as the first item in argv, followed by each of the
parameters. Hence, if the program name is followed by n parameters.
There will be (n+1) entries in argv, ranging from argv [0] to argv [n].
Moreover, argc will automatically be assigned the value (n+1).
Note that the value for argc is not supplied explicitly from the command line.
An example program which will be executed from a command line:
Out put of the program
This program allows an unspecified number of parameters to be entered from the
command line.
When the program is executed, the Count value for argc and the elements
of argv will be displayed as separate lines of output.
Sample red white blue
then the program will be executed, resulting in the following output.
argc =4
argv [0]=sample.exe
argv [1]=red
argv [2]=white
argv [3]=blue
The output tells us that four separate items have been entered form the command
line.
The first is the program name, sample. exe, followed by the three parameters., red.
White and blue.
Each item is an element in the array argv. (Name that sample.exe is the name of the
object file resulting from the compilation of the source code sample. C.)
Similarly, if the command line is
Sample red "white blue"
The resulting output will be
argc=3
argv [0]=sample.exe
argv [1]=red
argv [2]=white blue
In, this case the string "white blue" will be interpreted as a single parameter,
because of the quotation marks.
Once the parameters have been entered, they can be utilized within the program in
any desired manner.
One particularly common application is to specify the names of data files as
command line parameter.
Header file
Introduction
The C provides a large number of C functions as libraries. Some of these implement
frequently used operations, while others are very specialized in their application.
Wise programmers will check whether a library function is available to perform a
task before writing their own version.
This will reduce program development time. The library functions have been tested,
so they are more likely to be correct than any function which the programmer might
write.
This will save time when debugging the program. For using these files ,certain files
are needed to be included in the program which make call to these functions.
These files are known as Header files and they contain macro definition ,type
definition, and function declarations.
These header files usually have an extension .h as stdio.h, ctype.h, string.h,
math.h,stdlib.h, stdarg.h, time.h etc.
Use of library functions
To use a function, ensure that you have made the required #includes in your C file.
Then the function can be called as though you had defined it yourself.
It is important to ensure that your arguments have the expected types; otherwise the
function will probably produce strange results.
Some libraries require extra options before the compiler can support their use.
For example, to compile a program including functions from the math.h library the
command might be cc mathprog.c -o mathprog –lm
The final -lm is an instruction to link the maths library with the program. The
manual page for each function will usually inform you if any special compiler flags
are required.
Some Useful library functions
There is a vast collections of function .Some of them are grouped together and
listed below.
String Function:
strcpy
strcat
strcmp
strcmpi
strlen
strrev
copies one string into another.
appends one string to another.
compare one string to another.
compare one string to another without case sensitive.
calculates the length of a string.
reserve a string.
Mathematical Function:
abs
returns absolute value of an integer.
sin
calculate the sine.
cos
tan
acos
asin
atan
ceil
floor
log
pow
sqrt
calculate the arc cos.
calculate the arc tangent.
calculate the arc cosine.
calculate the arc sine.
calculate the arc tangent.
rounds up.
rounds down.
calculate the natural logarithm of x.
calculate x to the power of y.
calculate the positive square root of input value.
Date & Time Function:
asctime
clock
getdate
gettime
setdate
settime
time
converts date and time to ASCII.
determine process time.
gets system date
gets system time.
sets DOS date
sets system time.
gets time of day.
Utility Function:
abort()
bsearch()
tolower()
toupper()
qsort()
exit()
free()
abnormally terminates a process.
binary search of an array.
translate character to lower case.
translate character to upper case.
sorting using the quick sort algorithm.
terminate execution of a program.
frees allocated block.
Character Class Test Functions:
isupper()
islower()
isspace(()
isascii()
isalpha()
iscntrl()
toascii()
tolower()
check and returns non-zero if c is an upper case letter (A-Z).
check and returns non-zero if c is a lower case letter (a-z).
check and returns non-zero if c is a space tab, carriage return, newline, vertical tab,
form feed etc.
tests whether a character is an ASCII (0 to 127) character.
check and returns non-zero if c is a letter (A-Z or a-z).
tests whether a character is a control character.
translate character to ASCII format.
translate character to upper case.