Sie sind auf Seite 1von 90

MATHEMATICS,BIOLOGY AND COMPUTERS FOR

CHEMISTS
UNIT-IV

1) PROGRAMMING: “SET OF INSTRACTIONS”

2) ALGORITHM : The approach or method that is used to


solve the problem is known as an Algorithm.
“Algorithm is a step by step procedure of a
program”. Algorithm is a sequence of steps that we write before
going to write any program in any programming language.

3) LANGUAGES:

Computer languages can be classified into three


types. They are
• Machine Language,
• Assembly Language
• High Level language.
Machine Language : It is a machine understandable language
which contains 0’s and 1’s. This is called as Low level Language.
Using this language they are facing number of problems, that are:
1. It is very difficult to understand.
2. Programs are too long.
3. Correction of errors (debugging) with in the program is very
difficult..
Assembly Language: To solve the difficulties associated with
machine language, the users used assembly language called
Symbolic Language. In this language there is some mnemonical
codes like ADD, MOV, JMP, MLT, DIV, SUB etc.
Merits:

1. Assembly language instructions are very clear to


understand.
2. Programs can be developed in a short time.
Demerits:

1. It is not portable language because it can be used different


forms in different areas.
2. Comparing with high level language assembly language
instructions are not easy to understand.

High Level Language: High level language resembles with the


English and Mathematics and it is a very portable language. Over
100 programming languages exist, because each was designed for
specific purpose. For example some languages solve typical
business problems, others perform large and complex calculations
and still others create graphics. Following are the some of the
high level programming languages.
BASIC, COBOL, FORTRAN, PASCAL, C++, JAVA etc.
Merits:

1. High level language instructions are very clear to


understand.
2. Programs can be developed quickly and efficiently.
3. Corrections of bugs is very easy.
Demerits:

1. Expensive hardware and software supports are required.


2. High level language instructions execute at a low-level
speed.
TRANSLATORS
(Language Processors)

Language Translators is a type of system software, which


converts source programs to object program. Language
translators include Assemblers, Interpreters and compilers.

Assembler: It is a translator, which translates assembly


language program into machine language program.

Interpreter: It is a translator which translates High-Level


language program into machine language program. It converts a
program line by line. In case of found error in any statement the
interpreter stops the conversion and displays the error message.

Compiler: It is a translator which translates High-Level language


program into machine language program. It converts complete
programs all at once. In case of found errors in program the
compiler displays all the errors without converting any statement.

FLOW CHART

FLOW CHART is the pictorial representation of the program (or)


Flowchart is a graphical representation of a program. In a
flowchart we represent how to control the flows through the
sequence of the instructions. This is represented by the arrow
marks in a flowchart.
Flowchart Symbols:

OPERATING SYSTEMS:

“Intermediate between user and system”.


Ex: One of the most popular operating systems today is the
UNIX operating system.
Microsoft Windows XP is another example of a popular
operating system.

INTEGRATED DEVELOPMENT ENVIRONMENTS(IDE)

The process of editing, compiling, running, and debugging


program is often managed by a single integrated application
known as Integrated Development Environment (IDE).
PREPROCESSOR DIRECTIVES

The Preprocessor is a program that processes the source code


before it passes through the compiler. It operates under the
control of what is known as preprocessor command lines or
directives. Preprocessor directives are placed in the source
program before the main line. Before the source code passes
through the compiler, it examined by the preprocessor for any
preprocessor directives. Preprocessor directives begin with the #
and do not require a semicolon at the end. A set of commonly
used preprocessor directives are:

***************
HISTORY OF C

• The root of all modern languages is ALGOL, introduced


in 1960s. ALGOL was the first computer language to use a
block structure.
• In 1967, Martin Richards developed a language called
BCPL (Basic Combined Programming Language) primarily for
writing system software.
• In 1970, Ken Thompson created a language using many
features of BCPL and called it simply B. B was used to create
early versions of UNIX operating system at Bell Laboratories.
• C was evolved from ALGOL, BCPL and B by Dennis
Ritchie at the Bell Laboratories in 1972. C uses many concepts
from these languages and added the concept of data types and
other powerful features. Since it was developed along with the
UNIX operating system

BASIC STRUCTURE OF C PROGRAM

Documentation Section
The Documentation section consists of a set of comment lines
giving the name of the program, the author and other details,
which the programmer would like to use later.

Link Section

The Link section provides instructions to the compiler to link


functions from the system library.

Definition Section

The definition section defines all symbolic constants.

Global Declaration Section

There are some variables that are used in more than one function.
Such variables are called Global variables and are declared in the
global declaration section that is out side of all the functions.

Main ( ) Function Section

Every C program must have one main ( ) function section. This


section contains two parts.
1) Declaration part
2) Executable part
The declarative part declares all the variables used in the
executable part. There is at least one statement in the executable
part. These two parts must appear between the opening and
closing braces. The program execution begins at the opening
brace and ends at the closing brace. The closing brace of the main
function section is the logical end of the program. All statements
in the declaration and executable parts end with a semicolon
(;).

Subprogram Section

This sub program section contains all the user defined functions
that are called in the main function. User-defined functions are
generally placed after the main function, although they may
appear in any order. All sections except the main function may be
absent when they are not required.

INPUT AND OUTPUT FUNCTIONS


scanf( ) function: Input data can be entered into the computer
from a standard input device by using the C - library function
scanf. This function can be used to enter any combination of
numerical values, single character.

Genral Syntax : scanf ("control string", arg1, arg2 - - -


argn);
A control string refers to a string containing certain required
formatting information and arg1, arg2 - - - argn are arguments
that represent the individual data items.
%c, %d, %f, %o, %x, %s
%c - single character
%d - decimal integer
%r - floating point value
%o - octal
%s - string
%x - hexa decimal
Each variable name must be preceded by an ampersand.
The arguments are actually pointers which indicate where the
data items are stored in the computer memory.
Examples: 1) int a ;
float b ;
char c;
scanf ("%d %f %c", &a, &b, &c);

2) char s [20];
scanf (“%s”,s)
This form of scanf reads a string until a new line char is
encounter.
printf( ) function: Output data can be return from the computer
and a standard output device using the library function printf ().
This function can be used to output any combination of numeric
value, single char and strings.

General form: printf ("control string", arg1, arg2, -

- - argn);
Where control string refers to a string that contains formatting
information and arg1, arg2 - - - argn are arguments that
represent individual output data items.
Eg : 1) printf ("%d %f", a,b)';
2) printf ("\n J.B.PG College");
3) printf ("sum of %d and %d is %d",a,b,c);
The arguments should match in number, order and types with the
format specification

getchar ( ) function : Reading a single character can be done by


using the function getchar ( )

Syntax: Variable-name = getchar ( )

Where variable name is a valid ‘C’ name that has been declared as
"char" type.
When this statement is encountered, the computer waits until a
key is pressed and then assigns this char as a value to getchar ( ).
Since getchar ( ) is used the right hand side of an assignment
statement and the character value of getchar ( ) is assigned to the
variable name on the left.

Example: char name ;


name = getchar ( );

putchar function
The function putchar ( ) is used for writing characters one at a
time to the terminal.
Syntax: putchar (variable-name);

Where variable name is a type ‘char’ containing a character. This


statement displays the character contained in the variable name
at the terminal.
Example: ch=’a’;
putchar (ch);

CHARACTER SET
The characters that can be used to form words numbers and
expressions depend upon on the computer on which the program
is run. The characters in C are grouped as follows.
1) Letters: - A to Z (Upper case) and a to z (Lower case)
2) Digits:-All decimal digits 0 to 9
3) Special characters: - , comma, . Period, ; semicolon, :
colon, ? Question mark, ‘apostrophe, “ quotation mark, ),!
Exclamation mark, | vertical bar, / slash, \ back slash, ~ tilde, _
under score, $ dollar sign, % percent sign, & ampersand, ^ caret,
* asterisk, - minus sign, + plus sign, < opening angle bracket (or
less than sign > closing angle bracket (or greater than sign), (left
parenthesis,) right parenthesis, [ left bracket, ] right bracket,
{ left brace, } right brace, # number sign.
4) Blank spaces (white spaces): - Blank spaces, Horizontal tab,
Carriage return, new line, form feed.

C TOKENS
In a C program the “smallest individual units” are known as C
tokens. C has six types of tokens.
KEYWORDS:

Every C word is classified as either a keyword or an identifier. All


keywords have fixed meanings and these meanings cannot be
changed. All keywords must be written in lowercase. The
following are the keywords used in C programming.

IDENTIFIERS:

Identifiers are programmer-designed tokens. Identifiers


refer to the names of variables, functions and arrays. These are
user-defined names and consist of a sequence of letters and
digits, with a letter as a first character.
Both uppercase and lowercase letters are permitted,
although lowercase letters are commonly used. The underscore
character is also permitted in identifiers. It is usually used as a
link between two words in long identifiers.

Rules for Identifiers:

1. First character must be an alphabet (or underscore)


2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant
4. Cannot use a keyword
5. Must not contain white space.

CONSTANTS:

Constants in C refer to fixed values that do not change during the


execution of a program. C supports several types of constants as
follows:

Integer Constants: An Integer constant refers to a sequence of


digits. There are three types of integer constants. They are:
Decimal Integer, Octal Integer and Hexadecimal integer.
a) Decimal Integers: Decimal integers consists of a set of digits, 0

to 9, preceded by an optional – or + sign.


Ex: 123 -321 0 43564 +765
b) Octal Integers: An Octal integer constant consists of any

combination of digits form 0 to 7, with a leading 0.


Ex: 035 0 0435 0776
c) Hexadecimal Integers: A sequence of digits preceded by 0x or 0X

is considered as hexadecimal integer. They may also include


alphabets A to F or a to f. The letters A to F represent the
numbers 10 to 15.
Ex: 0x2 0x9f oXbcd 0x

Real Constants: Integer numbers are inadequate to represent

quantities that vary continuously, such as distance, heights,


temperatures, prices, and so on. These quantities are represented
by numbers containing fractional parts like 17.548. Such numbers
are called real (or floating point) constants.
Ex: 0.0083 -0.75 456.76 +32.3

Single Character Constants: A single character constant (or


character constant) contains a single character enclosed within a
pair of single quote marks.
Ex: ‘5’ ‘X’ ‘;’ ‘ ‘

String Constants: A String constant is a sequence of characters


enclosed in double quotes. The character may be letters,
numbers, special characters and blank spaces.
Ex: “Hello!” “STUDENTS”, “Well Done” “J.B.PG College” “Kavali”

Backslash Character Constants: C supports some special


backslash character constants that are used in output functions.
Each one of them represents one character, although they consist
two characters. These characters combinations are known as
escape sequences.

VARIABLES
A variable is a data name that may be used to store data value. A
variable may take different values at different times during
execution. Variable names may consist of letters, digits, and the
underscore ( _ ) character.
Rules:
1. They must begin with a letter. Some systems permit
underscore as the first character.
2. ANSI standard recognizes a length of 31 Characters.
3. Uppercase and lowercase are significant. That is, the
variable Total is not the same as total or TOTAL.
4. It should not be a keyword.
5. White space is not allowed.
Ex: marks sum distance value

DECLARATION OF VARIABLES

After designing suitable variable names, we must declare them to


the compiler. Declaration does two things:
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold.
Declaration of variables must be done before they are used in the
program.

Primary Type Declaration:

A variable can be used to store a value of any data type.

v1, v2, ……, vn are the names of variables. Variables are


separated by commas. A declaration statement must end with a
semicolon.

int and double are the keywords to represent integer type and
real type data values respectively.

ASSIGNING VALUES TO VARIABLES:

Assignment Statement:

Values can be assigned to variables using the assignment


operator = as follows:
It is also possible to assign a value to a variable at the time the
variable is declared.

The process of giving initial values to variables is called

initialization. C permits the initialization of more than one


variable in one statement using multiple assignment operators.

DATA TYPES
C language is rich in its data types. Every variable in ‘C’ has a data
type. Data types specify the size and type of values that can be
stored.

C supports three classes of data types:


1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
1. FUNDAMENTAL (OR) PRIMARY DATA TYPES:

C compilers support five fundamental data types. They are integer


(int), character (char), floating point (float), double-precision
floating point (double) and void.

Integer types:

Integer types are for numbers with out fractional part. Negative
values are also allowed. C has three classes of integer storage.
They are short int, int and long int, in both signed and unsigned
forms. The size and range of these types are shown in the
following table:

Floating Point Types:

Integer types are for numbers with fractional part. Floating point
numbers are stored in 32 bits, with 6 digits precision. Floating
point numbers are defined by C by the keyword float. When the
accuracy provided by a float number is not sufficient, the type
double can be used to define the number. A double data type
number uses 64 bits giving a precision of 14 digits. These are
known as double precision numbers. To extend the precision
further, we may use long double which uses 80 bits.

Character Type:

A single character can be defined as a character (char) type data.


Characters are usually stored in 8 bits (One byte) of internal
storage. The qualifier signed or unsigned may be explicitly applied
to char.

Void Types:

The void type has no values. This is usually used to specify the
type of functions. The type of a function is said to be void when it
does not return any value to the calling function.

2. DERIVED DATA TYPES

Arrays:

An Array is a group of memory locations of the same data type


addressed by a common name, all the items are stored in
physically adjacent (contiguous) memory locations. For instance,
the statement
int marks [10];
defines an array by the name marks that can hold a maximum of
ten numbers. The individual elements of an array are accessed
and manipulated using the array name followed by their index.
The index starts from 0.

Functions:

A function is a self-contained block of code that performs a


particular task. Once a function has been designed and packed, it
can be treated as a ‘black box’ that takes some data from the
main program and returns a value. The inner details of operation
are invisible to the rest of the program. All that the program
knows about a function is: What goes in and what comes out.
Every ‘C’ program can be designed using a collection of these
black boxes known as functions.

Pointers:

Pointers contain memory addresses as their values. Since these


memory addresses are the locations in the computer memory
where program instructions and data are stored. Pointers can be
used to access and manipulate data stored in the memory.

Syntax: data_type *pt_name;

This tells the compiler three things about the variable pt_name.
1. The asterisk ( * ) tells that the variable pt_name
2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type.
Example: int *p;
Declares the variable ‘p’ as a pointer variable that points to an
integer data type.

3. USER-DEFINED DATA TYPES

Structures:

Structure is a collection of data items of different types using a


single name. It is a convenient tool for handling a group of
logically related data items.

The keyword struct declares a structure to hold the details of four


data fields title, author, pages and price. These fields are called
structure elements or members. Each member may belong to a
different type of data. ‘Books’ is the name of the structure and is
called the structure tag.

Unions:

Unions are a concept borrowed from structures and therefore


follow the same syntax as structures. However, there is major
distinction between them in terms of storage. In structures, each
member has its own storage location, whereas all the members of
a union use the same location. A union may contain many
members of different types, it can handle only one member at a
time.
The union contains three members, each with a different data
type. However, we can use only one of them at a time. This is due
to fact that only one location is allocated for a union variable.

Enumerated :

Another user-defined data type is enumerated data type. It is


defined as follows:

The ‘identifier’ is a user-defined enumerated data type which can


be used to declare variables that can have one of the values
enclosed within the braces (known as enumeration constants).

The compiler automatically assigns integer digits beginning with 0


to all the enumeration constants. That is, the enumeration
constant vaue1 is assigned 0, value2 is assigned 1, and so on.

Typedef :
C supports a feature known as “type definition” that allows users
to define an identifier that would represent an existing data type.
The user-defined data type identifier can later be used to declare
variables.

Where type refers to an existing data type and “identifier” refers


to the “new” name given to the data type. The existing data type
may belong to any class of type, including the user-defined ones.
The new type is ‘new’ only in name, but not the data type. typedef
cannot create a new type.

Here, units symbolizes int and marks symbolizes float. They can
be later used to declare variable as follows:

Batch1 and batch2 are declared as int variable and m1, m2, m3
are declared as floating point variables.

OPERATORS AND EXPRESSIONS


‘C’ supports a rich set of operators. An operator is a symbol that
tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate
data and variables. ‘C’ operators can be classified into a number
of related categories as below:
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators
7) Bit-wise operators
8) Special operators
1. Arithmetic Operators: Arithmetic Operators are used to
construct Mathematical expressions as in algebra. ‘C’ provides all
the basic arithmetic operators. They are:

Arithmetic operators are used as shown below:

Here a and b may be variables or constants and are known as


operands.
a) Integer Arithmetic: When both the operands in a single
arithmetic expression such as a+b are integers, the expression is
called an integer expression, and the operation is called integer
arithmetic. Integer arithmetic always yields an integer value.
If a=14 and b=4 we have the following results:

b) Real Arithmetic : An Arithmetic operation involving only real

operands is called real arithmetic. A real operand may assume


values either in decimal or exponential notation.
If a = 20.5, b = 6.4 we have the following results.

c) Mixed-mode Arithmetic : when one of the operands is real and


the other is integer, the expression is called mixed-mode
arithmetic expression. If either operand is of the real type, then
the other operand is converted to real and the real arithmetic is
performed. The result will be a real.

2. Relational Operators: A Relational Operator compares two


values and determines the relationship between them. ‘C’
supports six relational operators. They are:

A simple relational expression contains only one relational


operator and is of the following form.

ae -1 and ae -2 are arithmetic expressions, which may be simple


constants, variables or combination of them.

3. Logical Operators: In addition to the relational operators, ‘C’


has three logical operators, they are:
The logical operators && and || are used when we want to form
compound conditions by combining two or more relations.

Example: A > b && x == 10

An expression of this kind which combines two or more


relational expressions is termed as a logical expression or a
compound relational expressions. Like the simple relational
expressions, a logical expression also yields a value of true or
false.

Examples:
If (age >55 && salary < 10000)
If (number<0 || number > 100)

4. Assignment Operators: Assignment Operators are used to


assign the value of an expression to a variable. The usual
assignment operator =. In addition, ‘C’ has a set of ‘short hand’
assignment operators which are used in the form

Where ‘v’ is a variable, ‘exp’ is an expression and ‘op’ is a ‘C’


binary operator. The operator ‘op’ = is known as the short hand
assignment operator.
Some of the commonly used short hand assignment operators are
shown below:
5. Increment and Decrement Operators: ‘C’ has two very
useful operators not generally found in many other languages.
These are the increment and decrement operators: ++ and - -.
The operator ++ adds 1 to the operand while – subtracts 1. Both
are unary operators and are used in the following form.

6. Conditional Operators: The character pair ? : is a ternary


operator available in ‘C’. This operator is used to construct
conditional expressions of the form

where exp1, exp2 and exp3 are expressions.


Exp1 is evaluated first. If it is nonzero (true), then the expression
exp2 is evaluated and becomes the value of the conditional
expression. If exp1 is false, exp3 is evaluated and its value
becomes the value of the conditional expression. Only one of the
expressions (either exp2 or exp3) is evaluated.

In this example, x will be assigned the value of b.


7. Bitwise Operators: ‘C’ has a distinction of supporting special
operators known as bitwise operators for manipulation of data at
values of bit level. These operators are used for testing the bits,
or shifting them to the right or left. Bitwise operators may not be
applied to float or double.

8. Special Operators: `C' supports some special operators. Such


as comma, ‘sizeof’ operator, pointer operator (& and *) and
member selection operator (. ) The comma operator is used to
link the related Expression together.
The ‘sizeof’ operator is a compile time operator and when used
with an operand it returns the no.of bytes the operand occupies.
Eg : int sum, m;
m = sizeof (sum);

PRECEDENCE OF ARITHMETIC OPERATORS

An arithmetic expression with out parentheses will be evaluated


from left to right using the rules of precedence operators. There
are two priority levels in C.
1) High priority - /, %, *
2) Low priority - +, -

SYMBOLIC CONSTANTS

A symbolic constant is a name that substitutes for a sequence of


characters. The characters may represent a numeric constant,
char const (or) string const.

Syntax: # define name text


where name represents a symbolic name written in upper case
letters and text represent the sequence of characters associated
with the symbolic name. The text does not end with a semi colon.
Example: # define PI 3.14

CONTROL STATEMENTS

DECISION MAKING DECISION MAKING


& BRANCHING & LOOPING

DECISION MAKING AND BRANCHING

When a program breaks the sequential flow and jumps to


another part of the code, it is called branching. When the
branching is based on a particular condition, it is known as
conditional branching. If branching takes place without any
decision, it is known as unconditional branching.

Decision making or Control Statements:


1. if statement
2. switch statement
3. Conditional Operator Statement.
4. goto statement.

1. Decision making with if Statement: The if statement is a


powerful decision making statement and is used to control the
flow of execution of statements. It is basically a two-way decision
statement and is used in conjunction with an expression.
It allows the computer to evaluate the expression first and then,
depending on whether the value of the expression is ‘true’ or
‘false’, it transfers the control to a particular statement.

The if statement may be implemented in different forms


depending on the complexity of conditions to be tested.
A. Simple if statement
B. if . . else statement
C. Nested if . . statement
D. else if ladder

A. Simple if Statement: The general form of a simple if


statement is

The ‘statement-block’ may be a single statement or a group of


statements. If the test expression is true, the statement-block
will be executed; otherwise the statement-block will be skipped
and the execution will jump to the statement-x.
B. The if …else Statement: The if …else statement is an
extension of the simple if statement. The general form is

If the test expression is true, then the true-block statement(s)


immediately following the if statement, are executed;
otherwise, the false block-statement(s) are executed. In either
case, either true-block or false-block will be executed, not oth.

C. Nesting of if….else Statements: when a series of


decisions are involved, we may have to use more than one
if…else statement in nested form as follows:
The logic of execution is illustrated in the above diagram. If the
conditon1 is false, the statement-3 will be executed otherwise
it continues to perform the second test. If the condition-2 true,
the statement-1 will be evaluated otherwise statement-2 will
be evaluated and then the control is transferred to the
statement-x.

D. The else if Ladder: There is another way of putting ifs


together when multi path decisions are involved. A multi
path decision is a chain of ifs in which the statement
associated with each else is an if. It takes the following
general form.
This construct is known as the else if ladder. The conditions are
evaluated from the top (of the ladder), downwards. As soon as
the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x.
When all the n conditions become false, then the final else
containing the default-statement will be executed.
2. Switch Statement : ‘C’ has a built in multi way decision
statement known as switch. The switch statement tests the value
of a given variable against a list of case values and when a match
is found, a block of statements associated with that case is
executed.

The expression is an integer expression or characters. Value-1,


value-2, … are constants or constant expressions and are known
as case labels. Each of these values should be unique within a
switch statement. Block-1, block2, … are statement lists and may
contain zero or more statements. Case labels must end with a
colon (:). The break statement at the end of each block signals
the end of a particular case and causes an exit from the switch
statement, transferring the control to the statement-x following
the switch. The default is an optional case. When present, it will
be executed if the value of the expression does not match with
any of the case values. If not present, no action takes place when
all matches fail and the control goes to the statement-x.

3. The ? : operator: The ‘C’ language has an unusual operator,


useful for making two-way decisions. This operator is a
combination of ? and : and takes three operands. This operator is
popularly known as the conditional operator.
The conditional expression is evaluated first. If the result is true,
expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise, expression2 is evaluated and
its value is returned.

4. The goto Statement: ‘C’ supports the goto statement to


branch unconditionally from one point to another in the program.
The goto 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. The label is placed immediately before the
statement where the control is transferred.
Syntax:

The label: can be anywhere


in the program either
before or after the goto
label. The goto breaks the
normal sequential execution of the program. If the label is before
the statement goto label the loop will be form and some
statements is executed repeatedly. Such jump is known as
backward jump. If the label is placed after the goto label some
statements will be skipped and the jump is known as forward
jump.
DECISION MAKING AND LOOPING (OR) ITERATIVE

CONTROL

The process of repeatedly executing a block of statements is


known as looping. If a loop continues forever, it is called an
infinite loop. The ‘C’ language provides for three constructs for
performing loop operations. They are:
1. While construct
2. Do construct
3. For construct

1. The While Statement: The simplest of all the looping


structures in C is the while statement.

The while is an entry-controlled loop statement. The test


condition is evaluated and if the condition is true, then the body
of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true, the body is
executed once again. This process of repeated execution of the
body continues until the test condition finally becomes false and
the control is transferred out of the loop. On exit, the program
continues with the statement immediately after the body of the
loop.
The body of the loop may have one or more statements. The
braces are needed only if the body contains two or more
statements.
2. The Do Statement: The while loop checks the test condition
before the loop is executed. Therefore the body of the loop may
not be executed at all if the condition is not satisfied at the very
first attempt. On some occasions it might be necessary to
execute the body of the loop before the test is performed. Such
situations can be handled with the help of the do statement.

On reaching the do statement, the program proceeds to evaluate


the body of the loop first. At the end of the loop, the test condition
in the while statement is evaluated. If the condition is true, the
program continues to evaluate the body of the loop once again.
This process is continues as long as the condition is true. When
the condition becomes false, the loop will be terminated and the
control goes to the statement that appears immediately after the
while statement. The do…while construct provides an exit-
controlled loop and therefore the body of the loop is always
executed at least once.
3. The For statement: The for loop is another entry-controlled
loop structure.

Initialization of control variable is executed first. The value of the


control variable is tested using the test condition. The test
condition is a relational expression that determines when the loop
will exit. If the condition is true, the body of the loop is executed.
Otherwise the loop is terminated and the execution continues
with statement that immediately follows the loop. When the body
of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now,
the control variable is incremented/decremented using an
assignment statement such as i = i + 1 and the new value of the
control variable is again tested to see whether it satisfies the loop
condition. If the condition is satisfied, the body of the loop again
executed. This process continues till the value of the control
variable fails to satisfy the test condition.
JUMPS IN LOOPS

Loops perform a set of operations repeatedly until the control


variable fails to satisfy the test condition. Sometimes, when
executing a loop it becomes desirable to skip a part of the loop or
to leave the loop as soon as a certain condition occurs. Java
permits a jump form one statement to the end or beginning of a
loop s well as a jump out of a loop.

Jumping out of a loop:

An early exit from a loop can be accomplished by using the break


statement or the goto statement. When the break statement is
encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the
loop. When the loops are nested, the break would only exit from
the loop containing it. That is, break will exit only a single loop. A
goto statement can transfer the control to any place in a program,
it is useful to provide branching within a loop.
Skipping a part of a loop:

During the loop operations, it may be necessary to skip a part of


the body of the loop under certain conditions. Like the break
statement, ‘C’ supports another similar statement called the
continue statement. Unlike the break which causes the loop to be
terminated, the continue, as the name implies causes the loop to
be continued with the next iteration after skipping any statements
in between. The continue statement tell the compiler “Skip the
following statements and continue with the next iteration”.
In while and do loops, continue causes the control to go directly
to the test condition and then to continue the iteration process. In
the case of for loop, the increment section of the loop is executed
before the test condition is evaluated.

*********

ARRAYS
An Array is a group of related data items of the same data
type addressed by a common name, all the items are stored in
physically adjacent (contiguous) memory locations. The
individual elements of an array are accessed and manipulated
using the array name followed by their index. The index starts
from 0.
Example:
int marks [10];

defines an array by the name marks that can hold a maximum of


ten numbers. The individual values in an array are called
elements. Arrays can be of any variable type.

ONE DIMENSIONAL ARRAY: A list of items can be given one


variable name using only one subscript and such a variable is
called a single subscripted variable (or) one dimensional array.
Single subscripted can be expressed as a [0] a [1] - - - - - - a[n].
The subscript can begin with a number 0 i.e., a [0] is allowed. The
subscript of an array can be integer constant.
Declaration of arrays: Like any other variable arrays must be
declared before they are used.

The type specifies the type of element that will be contained in


the array, such as int, float or char. The size indicates the
maximum number of elements that can be stored inside the array.

It indicates that the height to be an array containing 10 real


elements. Any subscripts from 0 to 9 are allowed.
We can initialize the elements of arrays when they are declared.

The values in the list are separated by commas


The size may be omitted in such cases the compiler allocates
enough space called initialized elements.

TWO DIMENSIONAL ARRAYS: An array of arrays is called as two-


dimensional array. The array variables that can store a list of
values. ‘C’ allows us to define tables of items by using two
dimensional arrays. In two dimensional arrays, the first index
selects the row and the second index selects the column within
that row.

Initializing two dimensional arrays:

A two dimensional array can be initialized during its definition as


follows:

defines two-dimensional array of order 2 x3 and initializes all its


elements.
The above statement can be equivalently written as

by surrounding the elements of each row by braces.


We can also initialize a two-dimensional array in the form of a
matrix as shown below:
MULTI-DIMENSIONAL ARRAYS: ‘C’ allows arrays of three or more
dimensions. The exact limit is determined by the compiler.

Where si is the size of the ith dimension.

Survey is a three-dimensional array declared to contain 180


integer type elements. Similarly table is a four-dimensional array
containing 300 elements of floating-point type.

FUNCTIONS
FUNCTION: A Function is a self contained block of code that
performs a particular task. Once a function has been designed and
packed, it can be treated a block box that takes some data from
the main program and returns a value. The inner details of
operation are invisible to the rest of the program. All that the
programs knows about a function is: what goes in and what
comes out. Every ‘C’ program can be designed using a collection
of these boxes.
Advantages of Functions:
1. It facilitates top down modular programming. The high level
logic of the overall program is solved first while the details
of each lower level functions are addressed later.
2. The length of a source program can be reduced by using
functions at appropriate places.
3. It is easy to locate and isolate a faulty function for further
investigation.
4. A function may be used by many other programs.
5.
PARTS OF FUNCTION:
A function has the following parts:
1. Function prototype declaration.
2. Definition of a function (function declarator)
3. Function call
4. Actual and Formal Arguments
5. The return statement.

1. Function Prototypes: A function prototype declaration consists


of the function return type, name, and arguments list. It tells the
compiler the name of the function, the type of value returned and
the type and number of arguments. When the programmer
defines the function, the definition of function must be like its
prototype declaration. If the programmer makes a mistake, the
compiler generates an error message. The function prototype
declaration statement is always terminated with semi-colon.
Ex: void show void);
float sum (float, int);
float sum (float x, int y);

2. Function Definition: The first line is called function declarator


and is followed by function body. The block of statements
followed by function declarator is called as function definition.
The declarator and function prototype declaration should match
each other. The function body is enclosed with curly braces. The
function can be defined anywhere.

3. Function Call: A function call is a latent body. It gets activated


only when a call to function is invoked. A function must be called
by its name, followed by argument list enclosed in parenthesis
and terminated by semi-colon.

4. Actual and Formal Arguments: The arguments declared in caller


function and given in the function call are called as actual
arguments. The arguments in the function declarator are known
as formal arguments.

5. The return statement: The return statement is used to return


value to other caller function. The return statement returns only
one value at a time. When a return statement is encountered,
compiler transfers the control of the program to caller function.
Syntax: return (variable-name); or return variable-name;

TYPES OF FUNCTIONS:
In ‘C’ functions can be divided into two types:
1. Library Functions
2. User-defined Functions

Library Functions: Prototypes and Function definitions for library


functions are available in some header files like math.h, stdio.h,
conio.h etc.(scanf and printf are also predefined functions whose
prototypes and definitions are available in stdio.h header file).
Every compiler provides list of header files and their pototypes.
Examples: printf( ) scanf ( ) clrscr ( ) getch ( ) sqrt ( )
pow ( )

User-Defined Functions: User can develop in reference to the


requirements of design of the project.
Syntax 1:
Syntax 2:
CATEGORIES OF FUNCTIONS:

1) Functions with no arguments and no return values.


2) Functions with arguments and no return values.
3) Functions with arguments and with return values.
4) Functions with no arguments and with return value

1. Functions with No arguments and no return values:


When a function has no arguments, it does not receive any data
from the calling function, when it does not return a value then the
calling function does not receive data from the called function i.e.,
their is no data transfer between the calling function and the
called function.

2. Functions with Arguments but no return values :


In this type read the data from the keyboard or assign values to
the variables in the calling function and pass it to the called
function. The calling function arguments are called actual
arguments where as the called function arguments are called
formal arguments. The actual and formal arguments should match
in number, type and order. The values of actual arguments are
assigning to the formal arguments on a one to one basis starting
with first argument.
3. Functions with arguments and with return values:
In this we have the use of two way data communication between
the calling and the called function.
The function call transfers the control to the called function along
with copies of the values of the actual arguments. The called
function is executed until the return statement is encounter. This
return statement returns the value to the calling function. The
calling statement is executed normally and the return value is
assigned to the left side variable.

4. Functions with no arguments and with return value:


In this case first call the function with out arguments and process
the statement and executed statements under the called function
until the return statement is encounter. The called function
returns the value to the calling function.

LOCAL VARIABLES:
Local variables are the variables defined with in a function whose
scope, visibility is limited to that particular function. Local
variables belongs to one function cannot be accessed in to
another function. The local variables belongs to different
functions may have the same name.

GLOBAL VARIABLES:
Global variables are the variables whose scope and visibility is
along the program. These variables can be accessed into any sub
function. Whenever both the global, local variables have the same
name then the scope of the global variable is overridden by the
local variable.

PASSING ARRAYS TO FUNCTIONS:


Sending One-Dimensional Array as an Argument:
Like the values of simple variables, it is also possible to pass the
values of an array to a function. To pass a one-dimensional array
to a called function, it is sufficient to list the name of the array
without any subscripts, and the size of the array as arguments.
Syntax:
Sending a Two-Dimensional Array as an Argument:
Like simple arrays, we can also pass multi-dimensional arrays to
functions. The approach is similar to the one we did with one-
dimensional arrays.
Rules:
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array
has two-dimensions by including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function
header.

SCOPE AND VISIBILITY OF VARIABLES:


Scope: Scope is the duration of memory allocation belongs to any
variable.
Visibility: Visibility is the boundaries in which a variable can be
accessed.

THE SCOPE AND LIFETIME OF VARIABLES :


The four storage classes are
1) Automatic variables
2) External variables
3) Static variables
4) Register variables
1) Automatic variables: Automatic variables are declared inside a
function in which they are to be utilized. They are created when
the function is called and destroyed automatically when the
function is exited. Automatic variables are private to the function
in which they are declared. These are also refer to as local (or)
internal variables. By default, a variable declare inside a function
without storage class specification is an automatic variable.
Automatic variables value cannot be changed accidentally by
changing a value in some other function in the program.

2) External variables: Variables that are both alive and active


throughout the entire program are known as external variables.
They are also known as global variables. Global variables can be
accessed by any function in the program. External variables are
declared outside a function. Once a variable has been declared as
global any function can using and change its value.
The external declaration of a variable inside the functions informs
the compiler that the variable is a specific type defines some
where else in the program. The extern declaration does not
allocate storage place for the variables.

3) Static variables: The value of static variables persists until the


end of the program. A variable can be declared by using a
keyword static.
Eg : static int x;
static float y;
A static variable may be either an internal type or an external
type depending on the place of declaration. Internal static
variables are those which are declared inside a function. The
scopes of internal static varibles extend up to the end of the
function in which they are defined. Therefore internal static
variables are similar to auto variables, except that they remain in
existence throughout the program. The internal static variables
can be used to retain values between function calls. A static
variable is initialized only once, when the program is compiled. It
is never initialized again

An external static variables is declared outside of all functions


i.e., available all the functions in that program. The difference
between a static external and a simple external variable is that
the static external variable available only within the file where it
is defined, while a simple external variable can be accessed by
other files.
4) Register variables: Since a register access is much faster than
memory access keeping the frequently accessed variables in the
register will lead to faster execution of programs.
Eg : register int num;
Since only a few variables can be placed in the register, it is
important to carefully select the variables for this purpose. `C'
will automatically convert register variables into non register
variables once the limit is reached.

BITWISE OPERATORS
There are three logical bitwise operators.
1. Bitwise Logical Operators
2. Bitwise Shift Operators
3. One’s Complement Operators.
1. BITWISE LOGICAL OPERATORS: There are three logical Bitwise
operators. They are
Bitwise AND (&)
Bitwise OR (|)
Bitwise Exclusive OR (^)
These are binary operators and require two integer type
operands. These operators work on their operands bit by bit
starting from the least significant (i.e the right most) bit, setting
each bit in the result.

Bitwise AND: The Bitwise AND operator is represented by a single


ampersand (&) and it is surrounded on both sides by integer
expressions. The result of ANDing operation is 1 if both the bits
have a value of 1, otherwise it is 0.
If x = 13, y= 15 the binary representations of these two variables
are:

The resulting bit pattern represents the decimal number 9.


Bitwise AND is often used to test whether a particular bit is 1 or 0.

Bitwise OR: The Bitwise OR is represented by the symbol |


(vertical bar) and is surrounded by two integer operands. The
result of OR operation is 1 if at least one of the bits has a value of
1, otherwise it is 0.
If x = 13, y = 25

Bitwise Exclusive OR (^): The Bitwise Exclusive OR is represented


by the ^ .The result of Exclusive OR is 1 if only one of the bits is
1, otherwise it is 0.

2. BITWISE SHIFT OPERATORS:


The shift operators are used to move bit patterns either to the left
or to the right. The shift operators are represented by the symbols
‘<<’ and ‘>>’.
Left Shift: op << n;
Right Shift: op >> n;
‘op’ is the integer expression i.e. to be shifted and ‘n’ is the
number of bit positions to be shifted.
Left Shift Operator (<<): The left shift operation causes all the
bits in the operand ‘op’ to be shifted to the left by ‘n’ positions.
The left most ‘n’ bits in the original bit pattern will be lost and the
rightmost ‘n’ bit positions that are vacated will be filled with 0s.
Right Shift Operators (>>): The right shift operation causes all
the bits in the operand ‘op’ to be shifted to the right by ‘n’
positions. The rightmost ‘n’ bits will be lost. The leftmost ‘n’ bit
positions that are vacated will be filled with zero.

3. BITWISE COMPLEMENT OPERATORS:


The complement operator ‘~’ (also called the one’s complement
operator) is an unary operator and inverts all the bits represented
by its operand. That is, 0s becomes 1s and 1s become zero.
Example:

PREPROCESSOR DIRECTIVES
The Preprocessor is a program that processes the source code
before it passes through the compiler. It operates under the
control of what is known as preprocessor command lines or
directives. Preprocessor directives are placed in the source
program before the main line. Before the source code passes
through the compiler, it examined by the preprocessor for any
preprocessor directives. Preprocessor directives begin with the #
and do not require a semicolon at the end. A set of commonly
used preprocessor directives are:
Preprocessor directives can be divided into three categories:
1. Macro Substitution Directives
2. File Inclusion Directives
3. Compiler Control Directives
1. MACRO SUBSTITUTION DIRECTIVES: Macro substitution is a
process where an identifier in a program is replaced by a
predefined string composed of one or more tokens. The
preprocessor accomplishes this task under the direction of
#define statement. This statement is known as a macro definition.
Syntax:

The string may be any text, while the identifier must be a valid ‘c’
name. there are different forms of macro substitution. The most
common forms are:
A. Simple Macro Substitution
B. Argumented Macro substitution
C. Nested Macro Substitution
A. Simple Macro Substitution: Simply string replacement is
commonly used to define constants.
Example: #define M 10
Will replace all occurrences of ‘M’ with ‘10’ starting from the line
of definition to the end of the program. However, a macro inside a
string does not get replaced.
A macro definition can include more than a simple constant value.
It can include expressions as well.
Example: #define AREA 5 * 12.46
#define SIZE sizeof(int) * 4
#define TWO-PI 2.0 * 3.1415926
B. Macro with Arguments: The preprocessor prermits us to define
more complex and more useful form of replacements.
Syntax: #define identifier (f1, f2, ………………fn) string
There is no space between the macro identifier and the left
parentheses. The identifiers f1, f2, …….fn are the formal macro
arguments that are analogous to the formal arguments in a
function definition. Subsequent occurrence of a macro with
arguments is known as a macro call. When a macro is called the
preprocessor substitutes the string, replacing the forma
parameters with the actual parameters.
Example: #define CUBE(x) x*x*x

C. Nesting of Macros: We can also use one macro in the definition


of another macro i.e. macro definitions may be nested.
Example:
Undefining a Macro: A defined macro can be undefined using the
statement #undef identifier.
Example: #undef CUBE(x)
2. FILE INCLUSION: An external file containing functions are
macro definitions can be included as a part of a program so that
we need not rewrite those functions or macro definitions. This is
achieved by the preprocessor directive
#include “filename”
Where filename is the name of the file containing the required
definitions or functions. At this point the preprocessor inserts the
entire contents of filename into the source code of the program.
Alternatively this directive can take the form
#include <filename>
3. COMPILER CONTROL DIRECTIVES: There is some preprocessor
conditional compilation statements used to select a path of
program before its compilation. It is mostly used while developing
an application for different platform. The preprocessor the
following conditional compilation statements i.e. #ifdef, #ifndef,
#if, #else, #elseif, #endif.
The main concern here is to make the program portable. This can
be achieved as follows:

If we want the program to run on IBM PC, we include the directive


#define IBM_PC
In the program, otherwise we don’t. The compiler compiles the
code for IBM PC if IBM_PC is defined, or the code for the HP
machine if it is not.
CHARACTER FUNCTIONS
Character Array:

The above example defines an array and results 10 bytes of


memory for storing a set of characters. The length of this string
cannot exceed 9. Since one storage location must be reserved for
storing the null character (‘\0’).
Initializing at the point of definition:

Write a program to initialize set of characters to one dimensional


character array and to display the contents of array.
Accepting a String from the Keyboard:
A string is combination of characters embedded with in double
quotations (“ “). A string can be directly accessed from the
keyboard by the scanf function. ‘%s’ is the formatting character
used to access a string.
Syntax: scanf(“%s”, address of base elements);

gets( ) function:
The gets function is used to read a set of alpha numeric
characters from the keyboard until carriage return is pressed and
places a null character in the memory.

puts( ) function:
The put function continuous to send characters to the standard
output stream until a null character is found.
STRING HANDLING FUNCTIONS:
C library support a large number of string handling functions that
can be used to carry of many of the string manipulations.
strlen( ): The strlen function is used to find the number of
characters in a given string. A string constant (or) an array of
characters can be passed as an argument. The length of the string
excludes the end of string character (NULL).
Syntax: variable = strlen(array_name);
Example:

strcpy( ): The string function is used to copy the contents of one


string to another string. It takes two arguments. The first
argument is the destination string array and the second argument
is the source string array. The source string is copied to the
destination string.
Syntax: strcpy(destination_string-array, source_string_array);

Strcat( ): The string function strcat concatenates two strings


resulting in a single string. It takes two arguments which are the
destination and source string. The destination and source strings
are concatenated and the resultant string is stored in the
destination string is stored in the destination string.
Syntax: strcat(Destination_string_array, Source_string_array);
Strcmp( ): The strcmp function compares two strings character
by character. It accepts two strings as parameters and returns an
integer, whose value is
• < 0 if the first string is lessthan the second.
• 0 if the first string is greater than the second.
• = 0 both are same
Syntax: strcmp(destination_string_array, source_string_array);

Strlwr( ): This function is used to convert a string to lower case.


It takes one argument.
Syntax: strlwr(string);

Strupr( ): This function is used to convert a string to upper case.


This function takes one argument.
Syntax: strupr(array_name);

Strrev( ): This function is used to reverse the contents of a string.


This function takes one argument.
Syntax: strrev(str);
Strncat( ): This function is used to append up to ‘n’ characters
from the contents of source string to end of the destination string.
Syntax: strncat(destination_string, source_string, no.of
characters to append);

Strncpy( ): This function is used to copy exact ‘n’ characters to


the destination string.
Syntax: strncpy(destination_string, source_string, no.of
characters to copy);

Strncmp( ): This function is used to compare up to ‘n’ characters


of destination string with up to ‘n’ characters of the source string.
If Destination string < Source string it returns -1
If Destination string > Source string it returns 1
If Destination string = Source string it returns 0
Syntax: strcmp(destination_string, source_string, No.of
Characters to compare);
TABLE OF STRINGS:
A list of names can be treated as a table of strings and two
dimensional character array can be used to store the entire list.
Example: char name[30][15];
It stores a list of 30 names, each of length not more than 15
characters.
We can initialize the list of character arrays at the time of
declaration.
Example:

STRUCTURES
Array can be used to represent a group of data items that belong
to the same type, such as int or float. If we want to represent a
collection of data items of different data types using a single
name is called structure. The structure is a method for packing
data of different data types. A structure is convenient tool for
handling a group of logically related data items.
Defining a Structure:
Syntax:
Graphical Representation:

The keyword struct declares a structure to hold the details of the


fields. These fields are called elements (or) members. Each
member may belong to a different type of data. The declaration of
structure is terminated with a semicolon.

Structure definition may appear before the main function along


with macro definition. In such cases the definition is global and
can be used by other functions.
Declaring Structure Variables:
After defining a structure format we can declare variables of that
type. A structure variable declaration is similar to the declaration
of any other data types. It includes
• The Keyword struct
• The Structure tag name
• List of variable names separated by commas.
• A terminating semicolon

Declares s, s1 and s2 as variables of type struct student.


The structure members themselves are not variables. They do not
occupy any memory until they are associated with the structure
variables. They should be linked to the structure variables.

Accessing Structure Elements:


We can access and assign values to the members of a structure in
a number of ways. The link between a member and a variable is
established using the member operator, which is also known as
dot (.) operator (or) Period operator.

Before the dot operator there must always be a structure variable


and after the dot operator there must be a structure element.
Assigning values to the members of Structures:
Structure Initialization:
The structure variables can be initialized like any other data type.
However, a structure must be declared as static if it is to be
initialized inside a function.
Example:

There is a one to one correspondence between the members and


their initializing values.
Another method to initialized the structure variable is
Example:

We can initialize a structure variable outside the function.


Example:
ARRAYS OF STRUCTURES:
Similar types of structures placed in a common heading or a
common variable name is called an array of structures.

In the above example s[3] is a structure variable. It may


accommodate a structure of student up to three elements. Each
record may be accessed and processed separately like an
individual elements of an array.

Initialization of Array of Structures:


ARRAYS WITHIN STRUCTURES:
‘C’ permits the use of arrays as structure members. We can use
single-dimensional or multi-dimensional arrays of type int or float
inside the structure as structure members.

The data member ‘m’ contains 10 elements like m[0], m[1], . . . . .


. , m[9]. These elements can be accessed using subscripts.

It would refer to the marks obtain in the 4th subject by the 6th
student.
FUNCTIONS AND STRUCTURES
‘C’ supports the passing of structure values as arguments to
functions. The general format of sending a copy of a structure to
the called function is:

The called function takes the following form:

The following points are important to note:


1. The called function must be declared for its type, appropriate
to the data type it is expected to return. For example, if it is
returning a copy of the entire structure, then it must be
declared as struct with an appropriate tag name.
2. The structure variable used as the actual argument and the
corresponding formal argument in the called function must
be of the same struct type.
3. The return statement is necessary only when the function is
returning some data back to the calling function. The
expression may be any simple variable or structure variable
or an expression using simple variables.
4. When a function returns a structure, it must be assigned to a
structure of identical type in the calling function.
5. The called functions must be declared in the calling function
appropriately.
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES)
A structure is declared as the member of another structure. It is
called as a nested structure or structure within a structure.

UNIONS
In structures each member has its own storage location where as
all the members of a union use the same location. A union may
contain many members of different types. It can handle one
member at a time. Like Structures, a union can be declared using
the keyword union.

The compiler allocates a piece of storage i.e. large enough to hold


the largest variable type in the union. In the above example the
member height requires 4 bytes which is the largest among the
members and all the three variables share the same address.
To access a union member we can use the same syntax that
we use for structure members.
What is the difference between structures and unions?
Memory Allocation: The amount of memory required to store a
structure variable is the sum of sizes of all members. In case of a
union, the amount of memory required is the same as but
required by its largest member.

Operations on Members: All the structure members can be


accessed at any point of time. Only one member of a union may be
accessed at any give type. The member which is last written can
be read only. Other members will contain garbage values.
What is difference between structures and Arrays?
1. An array is a collection of related data elements of same
type. Structures can have elements of different types.
2. An array is derived data type where as a structure is a user-
defined data type.
3. An array behaves like a built-in data type. All we have to do
is to declare an array variable and use it. But in the case of a
structure, first we have to design and declare a data
structure before the variables of that type are declared and
used.

ENUMERATED DATA TYPE:


The enumerated data types gives you an opportunity to invent
your own data type and define what values the variable of this
data type can take.

1. The first part declares the data types and specifies its
possible values. These values are called “enumerators”.
2. The second part declares variable of this data types.
Now we can give values to these variables.
person1=married;
person2=divorced;
Internally, the compiler treats the enumerators as integers, each
value on the list of values corresponds to an integer, starting with
0. Thus the above example, single is stored as 0, married is stored
1, divorced as 2 and widowed as 3.

USER-DEFINED TYPE DECLARATION (typedef)


‘C’ supports a feature known as type definition. That allows user
to define an identifier that would represent an existing data type.
The user defined data type identifier can later be used to declare
variables.
Where type refers to an existing data type and identifier refers to
the new name given to the data type.

Typedef provides a short and meaning full way to call a data type.

TYPE CASTING
Sometimes we are required to force the compiler to explicitly
convert the values of an expression to a particular data type. The
process of converting one data type into another is called casting.
Automatic conversion:
For some types, it is possible to assign a value of one type to
a variable of a different type without a cast. ‘C’ does the
conversion of the assigned value automatically. This is known as
automatic type conversion. Automatic conversion is possible only
if the destination type has enough precession to store the source
value. For example, int is large enough to hold a short int value.
Therefore,

are valid statements.


The process of assigning a smaller type to a large one is
known as widening or promotion and that of assigning a larger
type to a smaller one is known as narrowing. Narrowing may
result in loss of information.
POINTERS
Every variable declared in a ‘C’ program has three important
characteristics i.e. the name, value and address. Address is the
location of the variable in the primary memory.

Address of (&): Ampersand is a special symbol called referencing


operator is used to access the address of a specified variable
belongs to any type. Address is the sequence of a first cell of a
variable with in the primary memory. ‘%u’ is used as a formatting
character to print the address of a variable.
Value at ( * ): It is an operator called dereferencing operator (or)
indirection operator is used to extract the value at the specified
positions i.e. the address of a variable.

POINTER: Pointer is a variable which stores the address of


another variable belongs to any data type. The name of the
pointer variable should be prefixed with a pointer operator ( * ).
Declaration of a Pointer Variable:

This tells the compiler three things about the variable pt_name.
1. The ‘*’ operator tells that the variable pt_name is a pointer
variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.

Declares the variable ‘p’ is a pointer variable that point to an


integer data type.
Initializing Pointers:
Once a pointer variable has been declared, it can be made to point
to a variable using an assignment statement.

A pointer variable can be initialized in its declaration itself.

Accessing a variable through its pointer:


Once a pointer has been assigned the address of a variable, how
to access the value of the variable using the pointer? This done
by using another unary operator * (asterisk), usually known as
indirection operator or dereferencing operator.

The first line declares qty and n as integer variables and p as


pointer variable pointing to an integer. The second line assigns
the value 143 to qty and the third line assigns the address of qty
to the pointer variable p. the fourth line contains the indirection
operator *. When this operator is placed before pointer variable,
it returns the value of variable qty.
The two statements
p=&qty;
n = *p;
Will be equivalent to n=*&qty, which in turns is equivalent to n =
qty.

POINTERS AND ARRAYS


When an array is declared, the compiler allocates a base address
and sufficient amount of storage to contain al the elements of the
array in ‘contiguous’ memory locations. The base address is the
location of the first element (index 0) of the array.
Suppose the base address of ‘x’ is 1000 and assuming that each
integer requires two bytes. The 5 elements will be stored as
follows:

If we declare ‘p’ as an integer pointer, then we can make the


pointer ‘p’ to point to the array ‘x’ by the following statement.

We can access every value of ‘x’ using pointer variable ‘p’ as


follows:

Address of x[3] = base address + (3 * scale factor)


= 1000 + (3 * 2)
= 1006
We can use pointer to access array elements.

Scale factor: When we increment a pointer, its value is increased


by the length of the data type that it points to. The length is called
the scale factor.
POINTERS AND FUNCTIONS
PASSING ARGUMENTS TO FUNCTIONS
PASS BY VALUE: In this type value of actual arguments is passed
to the formal arguments and operation is done on the formal
arguments. Any change in the formal argument does not effect
the actual arguments because formal arguments are photocopy of
actual arguments. Hence when function is called by pass by value
method, it does not effect the actual contents of actual
arguments. Changes made in the formal arguments are local to
the block of called function. Once control returns back to the
calling function the changes made vanish.

PASS BY ADDRESS: In this type instead of passing values,


addresses are passed. Function operates on address rather than
values. Here the formal arguments are pointers to the actual
arguments. Hence changes made in the arguments are
permanent.
ALIAS NAME TO A VARIABLE: The same memory location may be
referred with multiple names.

SECOND INDIRECTION VARIABLE:


It is a pointer of pointer. Pointer to pointer variable is a variable
which stores the address of another pointer variable. It can refer
the value of original variable by using an operator “* * “.

POINTERS AND CHARACTER STRINGS


A character pointer is a pointer to the character. It can be
declared as
char *pt_char;
a character pointer can also be used to access character arrays
and string constants in the same way as accessing numeric arrays
using their respective pointer variable. Here string can
conveniently be represented by either using a one-dimensional
char array or a character pointer.
ARRAY OF POINTERS (OR) POINTER ARRAY
The way there can be an array of ints or an array of floats,
similarly, there can be an array of pointers. Since a pointer
variable always contains an address, an array of pointers would
be nothing but a collection of addresses. The addresses present in
the array of pointers can be addresses of array elements or any
other addresses.

POINTERS AND STRUCTURES


The symbol is called the arrow operator (also known as member
selection operator) and made up of a minus sign and a greater
than sign.

Das könnte Ihnen auch gefallen