C Language Theory

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

C LANGUAGE

SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

C LANGUAGE

HISTORY OF C

1. C is a programming language which born at “AT & T‟s Bell Laboratory” of


USA in 1972.
2. C was written by Dennis Ritchie, thats why he is also called as father of c
programming language.
3. C language was created for a specific purpose i.e designing the UNIX
operating system (which is currently base of many UNIX based OS).
4. From the beginning, C was intended to be useful to allow busy programmers
to get things done because C is such a powerful, dominant and supple
language
5. Its use quickly spread beyond Bell Labs in the late 70‟s because of its long
list of strong features

Importance of „c‟ language


C lang is a famous programming lang due to its qualities. Some qualities r:

(1) it is robust lang whose rich setup of built in functions and operator can be used
to write any complex prog.
(2)prog written in c are efficient due to several variety of data types and powerful
operators.
(3)the c complier combines the capabilities of an assembly lang with the feature of
hige level language. Therefore it is well suited for writing both system software
and business package.
(4)there r only 32 keywords, several standard functions r available which can be
used for developing prog.
(5)c is portable lang , this means that c programes written for one computer system
can be run on another system, with little or no modification.
(6)c lang is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 1
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

make a program debugging and testing easier.


(7)c language has its ability to extend itself. A c program is basically a collection
of functions that are supported by the c library. We can contuniously add our own
functions to the library with the avaibility of the large number of functions.

Middle Level Language ?


C Programming bridges gap between traditional Machine Understandable Machine
Level language and more conventional High level languages. User can Use C
Language to do system programming for writing operating system as well as
application programming. Middle Level Programming languages are closely
related to Machine as well as Human Being.

Why C is Middle Level Language ?


1. C Programming Supports Inline Assembly Language Programs .
2. Using inline assembly language feature in C we can directly access system
registers.
3. C Programming is used to access memory directly using pointer.
4. C Programming also Supports high Level Language Features.
5. It is more User friendly as compare to Previous languages so C
programming is Middle Level Language.

Character set of C

character:- It denotes any alphabet, digit or special symbol used to represent


information

Use:- These characters can be combined to form variables. C uses constants,


variables, operators, keywords and expressions as building blocks to form a basic
C program.
Character set:- The character set is the fundamental raw material of any language
and they are used to represent information. Like natural languages, computer
language will also have well defined character set, which is useful to build the
programs.The characters in C are grouped into the following two categories:

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 2
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

1) Source character set


a. Alphabets
b. Digits
c. Special Characters
d. White Spaces

2) Execution character set


a. Escape Sequence

Source character set

ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z

DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

SPECIAL CHARACTERS

~ tilde % percent sign | vertical bar


@ at symbol + plus sign < less than

_ underscore - minus sign > greater than


^ caret # number sign = equal to

& ampersand $ dollar sign / slash


( left parenthesis * asterisk \ back slash

) right parenthesis ′ apostrophe : colon


[ left bracket " quotation mark ; semicolon

] right bracket ! exclamation mark , comma


{ left flower brace ? Question mark . dot operator

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 3
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

} right flower brace

WHITESPACE CHARACTERS

Blank Space, Horizontal Tab, Vertical Tab, Carriage Return, New Line, Form
Feed(„ „, „\t‟,‟\v‟,‟\r‟, „\n‟, „\f‟

Execution Character Set

Certain ASCII characters are unprintable, which means they are not displayed on
the screen or printer. Those characters perform other functions aside from
displaying text. Examples are backspacing, moving to a newline, or ringing a bell.
They are used in output statements. Escape sequence usually consists of a
backslash and a letter or a combination of digits. An escape sequence is considered
as a single character but a valid character constant.
These are employed at the time of execution of the program. Execution characters
set are always represented by a backslash (\) followed by a character. Note that
each one of character constants represents one character, although they consist of
two characters. These characters combinations are called as escape sequence.

Backslash character constants

\0- Null Character


\t Horizontal Tab
\v Vertical Tab
\b- Backspace
\n- New Line
\r- Carriage Return
\f – Form Feed
\a- Alert
\‟- Single Quote
\”- Double Quote
\?- Question
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 4
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

\\ - Back Slash

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 5
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

C tokens
the smallest individual unit in a c program is known as a token or a lexical unit. C
tokens can be classified as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

C Keywords

C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed.

The list of C keywords is given below:

auto break case char const


continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while

C Identifiers

Identifiers are used as the general terminology for the names of variables, functions
and arrays. These are user defined names consisting of arbitrarily long sequence of
letters and digits with either a letter or the underscore(_) as a first character.

There are certain rules that should be followed while naming c identifiers:

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 6
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

They must begin with a letter or underscore(_).


They must consist of only letters, digits, or underscore. No other special
character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are
significant.

Some examples of c identifiers:

Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C Constants
C constants refers to the data items that do not change their value during the
program execution. Several types of C constants that are allowed in C are:
1. Integer Constants
Integer constants are whole numbers without any fractional part. It must have at
least one digit and may contain either + or – sign. A number with no sign is
assumed to be positive.
There are three types of integer constants:
1.1. Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional
– or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
1.2. Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting
with 0 is said to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540
1.3. Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits
preceded by 0x or 0X. They may also include alphabets from A to F representing
numbers 10 to 15.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 7
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Example of valid hexadecimal integer constants


0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in
programming.
2. Real Constants
The numbers having fractional parts are called real or floating point constants.
These may be represented in one of the two forms called fractional form or the
exponent form and may also have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or
scientific form is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal
notation.
The letter e separating the mantissa and the exponent can also be written in
uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:252E85, 0.15E-10, -3e+8
3. Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
„a‟ , „Z‟, „5‟
It should be noted that character constants have numerical values known as ASCII
values, for example, the value of „A‟ is 65 which is its ASCII value.

Escape Characters/ Escape Sequences

C allows us to have certain non graphic characters in character constants. Non


graphic characters are those characters that cannot be typed directly from
keyboard, for example, tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a
single character.
Escape Sequence Description
a Audible alert(bell)
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 8
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
“ Double quotation mark
„ Single quotation mark
? Question mark
Null

String Constants

String constants are sequence of characters enclosed within double quotes. For
example,
“hello”
“abc”
“hello911”

Every sting constant is automatically terminated with a special character ‘’ called


the null character which represents the end of the string.

Special Symbols

The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose.

[] () {} , ; : * … = #

Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.

Parentheses(): These special symbols are used to indicate function calls and
function parameters.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 9
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.

C Operators

C operators are symbols that triggers an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.

Depending on the number of operands that an operator can act upon, operators can
be classified as follows:

1. Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.
2. Binary Operators: Those operators that require two operands to act upon
are called binary operators.
3. Ternary Operators: These operators requires three operands to act upon.

C data types
C data types are defined as the data storage format that a variable can store
a data to perform a specific operation.
Data types are used to define a variable before to use in a program.

C – data types:

There are 3 data types in C language. They are,

S.no Types Data Types


1 Basic data types int, char, float, double, void
2 User defined data type Enum, typedef
3 Derived data type pointer, array, structure, union

Basic data type

integer
Integer data type allows a variable to store numeric values.
“int” keyword is used to refer integer data type.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 10
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

The storage size of int data type is 2 or 4 or 8 byte.


It varies depend upon the processor in the CPU that we use. If we are using 16
bit processor, 2 byte (16 bit) of memory will be allocated for int data type.
Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int data type.
int (2 byte) can store values from -32,768 to +32,767
int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
%d is used for print integer data. %ld is used for long integer.

Floating Point
Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc.
Keywords either float or double is used for declaring floating type variable.
“float” & “double” keyword is used to refer float & double data type.

%f- Display the floating point number using decimal representation


%e- Display the floating point number using scientific notation with e
%g- Use shorter of the two representations: f or e
%lf – Use for long float & double
%Lf – Use for long double
Difference between float and double
Generally the size of float(Single precision float data type) is 4 bytes and that of
double(Double precision float data type) is 8 bytes. Floating point variables has a
precision of 6 digits whereas the the precision of double is 14 digits.
Note: Precision describes the number of significant decimal places that a floating
values carries.

Character data type:


Character data type allows a variable to store only one character.
Storage size of character data type is 1. We can store only one character using
character data type.
“char” keyword is used to refer character data type.
%c- Display the character

Void Type

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 11
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

The void type has no value. 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
calling function.

Modifiers in C:

In c language Data Type Modifiers are keywords used to change the properties of
current properties of data type. Data type modifiers are classified into following
types.
long
short
unsigned
signed
Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
long:
This can be used to increased size of the current data type to 2 more bytes, which
can be applied on int or double data types. For example int occupy 2 byte of
memory if we use long with integer variable then it occupy 4 byte of memory.
short
In general int data type occupies different memory spaces for a different operating
system; to allocate fixed memory space short keyword can be used .
unsigned
This keyword can be used to make the accepting values of a data type is positive
data type.
signed
This keyword accepts both negative or positive value and this is default properties
or data type modifiers for every data type.

Size & Range of Data Type in C

Type Size(Bytes) Range

int ,signed int, short int 2 -32768 to 32767

long int ,signed long 4 -2,147,483,648 to


int 2,147,483,647

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 12
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

unsigned int 2 0 to 65535

float 4 3.4e -38 to 3.4e+38

double 8 1.7e-308 to 1.7e+308

long double 10 3.4e-4932 to 1.1e+4932

char, signed char 1 -128 to 127

unsigned char 1 0 to 255

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 13
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

C OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical


or logical functions. C language is rich in built-in operators and provides the
following types of operators –

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

S.no Types of Operators Description


These are used to perform mathematical
1 Arithmetic_operators calculations like addition, subtraction,
multiplication, division and modulus
These are used to assign the values for the
2 Assignment_operators
variables in C programs.
These operators are used to compare the
3 Relational operators
value of two variables.
These operators are used to perform logical
4 Logical operators
operations on the given two variables.
These operators are used to perform bit
5 Bit wise operators
operations on given two variables.
Conditional operators return one value if
Conditional (ternary)
6 condition is true and returns another value
operators
is condition is false.
These operators are used to either increase
Increment/decrement
7 or decrease the value of the variable by
operators
one.
8 Special operators &, *, sizeof( ) and ternary operators.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 14
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Arithmetic operators

C supports all the basic arithmetic operators. The following table shows all the
basic arithmetic operators.

Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division

Relation operators

The following table shows all relation operators supported by C.

Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Logical operators

C language supports following 3 logical operators. Suppose a=1 and b=0,

Operator Description Example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 15
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Assignment Operators

Assignment operators supported by C language are as follows.

Operator Description Example


assigns values from right side operands to left side
= a=b
operand
adds right operand to the left operand and assign the a+=b is same as
+=
result to left a=a+b
subtracts right operand from the left operand and a-=b is same as
-=
assign the result to left operand a=a-b
mutiply left operand with the right operand and assign a*=b is same as
*=
the result to left operand a=a*b
divides left operand with the right operand and assign a/=b is same as
/=
the result to left operand a=a/b
calculate modulus using two operands and assign the a%=b is same as
%=
result to left operand a=a%

The above operator ( +=, -=, *=, /= , %= ) are shorthand assignment operators.

Increment & Decrement Operators( Unary Operators)

Operator Description
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one

Conditional operator(ternary operator)

It is also known as ternary operator and used to evaluate conditional expression.


epr1 ? expr2 : expr3
If epr1 Condition is true ? Then value expr2 : Otherwise value expr3

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 16
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Bitwise operators

Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to
float or double.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift

Special operator

Operator Description Example


sizeof(x) return size of the variable
sizeof Returns the size of an variable
x
&x ; return address of the variable
& Returns the address of an variable
x
* Pointer to a variable *x ; will be pointer to a variable x
Link the related expression
, Comma int a,b,c
together

C Operator Precedence Table

Operator Description Associativity


() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 17
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

!~ Logical negation/bitwise complement


(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

Typecasting

Typecasting concept in C language is used to modify a variable from one date type
to another data type. New data type should be mentioned before the variable
name or value in brackets which to be typecast.
Conversion between data types can be done in two ways by casting:
Implicit casting
Explicit casting

Implicit casting
Implicit casting doesn't require a casting operator. This casting is normally used
when converting data from smaller integral types to larger or derived types to the
base type.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 18
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Hide Copy Code


int x = 123;
double y = x;
In the above statement, the conversion of data from int to double is done implicitly,
in other words programmer don't need to specify any type operators.

he sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long
double and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is
converted to long int.
2. otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable
on left side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of
double to float causes rounding of digits and the conversion of long int to int
causes dropping of excess higher order bits.

Explicit casting
Explicit casting requires a casting operator. This casting is normally used when
converting a double to int or a base type to a derived type.

double y = 123;
int x = (int)y;

In the above statement, we have to specify the type operator (int) when
converting from double to int .

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 19
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

The following rules have to be followed while converting the expression from one
type to another to avoid the loss of information:

1. All integer types to be converted to float.


2. All float types to be converted to double.
3. All character types to be converted to integer.

Decision making in C
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met. C language handles decision-making by supporting the following
statements,
if statement
switch statement
conditional operator statement
goto statement

Decision making with if statement


The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are,
1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement

Simple if statement

The general form of a simple if statement is,


if( expression )
{
statement-inside;
}
statement-outside;

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 20
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

If the expression is true, then 'statement-inside' it will be executed, otherwise


'statement-inside' is skipped and only 'statement-outside' is executed.

if...else statement
The general form of a simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1'
is skipped and 'statement-block2' is executed.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 21
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Nested if....else statement

The general form of a nested if...else statement is,

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}

if 'expression' is false the 'statement-block3' will be executed, otherwise it


continues to perform the test for 'expression 1' . If the 'expression 1' is true the
'statement-block1' is executed otherwise 'statement-block2' is executed.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 22
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as the
true condition is found, the statement associated with it is executed.

Switch statement
Switch statement is used to solve multiple option type problems for menu like
program, where one value is associated with each option. The expression in switch
case evaluates to return an integral value, which is then compared to the values in
different cases, where it matches that block of code is executed, if there is no
match, then default block is executed. The general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 23
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

break;
case value-4:
block-4;
break;
default:
default-block;
break;
}

We don't use those expressions to evaluate switch case, which may return
floating point values or strings.
It isn't necessary to use break after each block, but if you do not use it, all the
consecutive block of codes will get executed after the matching block.

Goto statement

goto statement in C programming provides an unconditional jump from the 'goto'


to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming
language because it makes difficult to trace the control flow of a program, making
the program hard to understand and hard to modify. Any program that uses a goto
can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in
the C program above or below to goto statement.

Flow Diagram

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 24
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Looping

A while loop in C programming repeatedly executes a target statement as long as a


given condition is true.
Syntax
The syntax of a while loop in C programming language is −

while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The


condition may be any expression, and true is any nonzero value. The loop iterates
while the condition is true.
When the condition becomes false, the program control passes to the line
immediately following the loop. This is an entry-controlled loop statement. Here,
the key point to note is that a while loop might not execute at all. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 25
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Flow Diagram

For loop

This is one of the most frequently used loop in C programming. It is also entry
controlled loop. The syntax of for loop is –

for (initialization; condition test; increment or decrement)


{
//Code – C statements needs to be repeated
}

Here is the flow of control in a 'for' loop −


The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the 'for' loop.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 26
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again condition).
After the condition becomes false, the 'for' loop terminates.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 27
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Do while loop

Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time. So it is known as exit controlled loop.
Syntax
The syntax of a do...while loop in C programming language is −
do
{
statement(s);
} while( condition );

The conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop executes again. This process repeats until the given
condition becomes false.

Flow Diagram

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 28
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Nested loop in c programming

A loop inside another loop is known as nested loop. We can write any loop inside
any loop in c i.e. we can write for loop inside the loop or while loop or do while
loop etc.

The syntax for a nested for loop statement in C is as follows −


for ( init; condition; increment )
{

for ( init; condition; increment ) {


statement(s);
}

statement(s);
}
The syntax for a nested while loop statement in C programming language is as
follows −
while(condition) {

while(condition) {
statement(s);
}

statement(s);
}
The syntax for a nested do...while loop statement in C programming language is
as follows −
do {

statement(s);

do {
statement(s);
}while( condition );

}while( condition );
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 29
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Arrays

In C language, arrays are referred to as structured data types. An array is defined as


finite ordered collection of homogenous data, stored in contiguous memory
locations.
Here the words,
finite means data range must be defined.
ordered means data must be stored in continuous memory addresses.
homogenous means data must be of similar data type.
Example where arrays are used,
to store list of Employee or Student names,
to store marks of a students,
or to store list of numbers or characters etc.

Types of C arrays:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array
1. Two dimensional array
2. Three dimensional array, four dimensional array etc…
1. One dimensional array in C:
A list of item can be given one variable name using only on subscript is called one
dimensional array.

Like any other variable, arrays must be declared before they are used. General
form of array declaration is,
data-type variable-name[size];

for example :
int arr[10];

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 30
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type. Index of an array starts
from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and
last element will occupy arr[9].

Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbage
value(any random value). An array can be initialized at either compile time or at
runtime.

Compile time Array initialization


Compile time initializtion of array elements is same as ordinary variable
initialization. The general form of initialization of array is,
type array-name[size] = { list of values };

int marks[4]={ 67, 87, 56, 77 }; //integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization


int marks[4]={ 67, 87, 56, 77, 59 }; //Compile time error
One important things to remember is that when you will give more initializer than
declared array size than the compiler will give an error.

Runtime Array initialization


An array can also be initialized at runtime using scanf() function. This approach is
usually used for initializing large array, or to initialize array with user specified
values.

Multidimensional array
1. Array having more than one subscript variable is called multidimensional array.
2. Multidimensional array is also called as matrix.
Consider the Two dimensional array –
1. Two Dimensional Array requires Two Subscript Variables
2. Two Dimensional Array stores the values in the form of matrix.
3. One Subscript Variable denotes the “Row” of a matrix.
4. Another Subscript Variable denotes the “Column” of a matrix.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 31
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Example

int a[2][2]

Strings in C

In C programming, array of character are called strings. A string is terminated by


null character \0. „C‟ does not support strings as a data type. However, it allow us
to represent string as character array. In C, therefore, a string variable is any valid
C variable name and is always declared as an array of characters. For example:

char a[10]=”rajiv”;

r a j i v \0
0 1 2 3 4 5

Here, "rajiv" is a string. When, compiler encounters strings, it appends null


character at the end of string.

Reading Strings from user.

char c[20];
scanf("%s",c);
String variable c can only take a word. It is because when white space is
encountered, the scanf() function terminates.

C String functions:

String.h header file supports all the string functions in C language. All the
string functions are given below.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 32
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

ction Work of Function


strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string

strcat()

The strcat function joins two strings together. It takes the following form:
strcat(string1,string2);
string1 and string2 are character array. When function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the of string1 and
placing string2 from there. The string2 remain unchanged.

strcpy()
The strcpy function work almost like a string assignment operator. It take the
form:
strcpy(string1,string2);
string1 and string2 are character array. When function strcpy is executed, the
content of string is copied to string1.

strcmp()

The strcmp function compares two strings identified by the arguments and has a
value 0 if they are equal. If they are not, it has the positive value if first string is
bigger & negative if first is smaller. It has the numeric difference between the first
non matching characters in the string.
strcmp(string1,string2)

strlen()

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 33
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

this function counts and returns the number of characters in a string. It takes
the form
n=strlen(string)
where n is a integer variable, which receives the value of length of string. The
argument may be string constant. The counting ends at the first null
character.

Functions

A function is a group of statements that together perform a task. Every C program


has at least one function, which is main().
There are times when we need to write a particular block of code for more than
once in our program. This may lead to bugs and irritation for the programmer. C
language provides an approach in which you need to declare and define a group of
statements once and that can be called and used whenever required. This saves
both time and space.
C functions can be classified into two categories,
Library functions
User-defined functions

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 34
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Library functions are those functions which are defined by C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to
use these functions. These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the
time of writing program. Functions are made for code reusability and for saving
time and space.

Defining a Function
The general form of a function definition in C programming language is as follows

return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a
function body. Here are all the parts of a function –

A. Return Type − A function may return a value. The return type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return type is the
keyword void.
B. Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
C. Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
D. Function Body − The function body contains a collection of statements that
define what the function does.

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 35
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

int max(int num1, int num2);


Parameter names are not important in function declaration only their type is
required, so the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the
program control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function −
S.N. Call Type & Description
Call by value

1 This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on
the argument.
Call by reference

2 This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 36
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

function-body
The function body contains the declarations and the statement(algorithm)
necessary for performing the required task. The body is enclosed within curly
braces { } and consists of three parts.
local variable declaration.
function statement that performs the tasks of the function.
a return statement that return the value evaluated by the function.

Difference between Call by Value and Call by Reference


Difference between call by value and call by reference
call by value call by reference
In call by value, a copy of actual In call by reference, the location
arguments is passed to formal arguments (address) of actual arguments is passed
of the called function and any change to formal arguments of the called
made to the formal arguments in the function. This means by accessing the
called function have no effect on the addresses of actual arguments we can
values of actual arguments in the calling alter them within from the called
function. function.
In call by reference, alteration to actual
In call by value, actual arguments will arguments is possible within from called
remain safe, they cannot be modified function; therefore the code must handle
accidentally. arguments carefully else you get
unexpected results.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 37
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have
four different storage classes in a C program −
auto
register
static
extern
Automatic variables
A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.

External storage class


A variable that is declared outside any function is a Global variable. Global
variables remain available throughout the entire program. One important thing to
remember about global variable is that their values can be changed by any function
in the program.
In case of large program, containing more than one file, if the global variable is
declared in file 1 and that variable is used in file 2 then, compiler will show error.
To solve this problem, keyword extern is used in file 2 to indicate that, the variable
specified is global variable and declared in another file.

Register variable

Register variables are similar to automatic variable and exists inside that particular
function only.
If the compiler encounters register variable, it tries to store variable in
microprocessor's register rather than memory. Value stored in register are much
faster than that of memory. Since, there are limited number of register in processor
and if it couldn't store the variable in register, it will automatically store it in
memory.
NOTE : We can never get the address of such variables.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 38
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Static variables
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and
goes out of scope, static is initialized only once and remains into existence till the
end of program. A static variable can either be internal or external depending upon
the place of declaration. Scope of internal static variable remains inside the
function in which it is defined. External static variables remain restricted to scope
of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.

Recursion

Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then
it is called a recursive call of the function.
The C programming language supports recursion, i.e., a function to call itself. But
while using recursion, programmers need to be careful to define an exit condition
from the function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 39
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Structure

Structure is a user-defined data type in C which allows you to combine different


data types to store a particular type of record. Structure helps to construct a
complex data type in more meaningful way. It is somewhat similar to an Array.
The only difference is that array is used to store collection of similar data types
while structure can store collection of any type of data.
Structure is used to represent a record. Suppose you want to store record of
Student which consists of student name, address, roll number and age. You can
define a structure to hold this information.

Defining a structure

struct keyword is used to define a structure. struct define a new data type which is
a collection of different type of data.
Syntax :
struct structure_name
{
Data type member 1;
Data type member 2;

};

Declaring Structure Variables


It is possible to declare variables of a structure, after the structure is defined.
Structure variable declaration is similar to the declaration of variables of any
other data types. Structure variables can be declared in following two ways.

1) Declaring Structure variables separately


struct Student
{
char[20] name;
int age;
int rollno;
};

struct Student S1 , S2; //declaring variables of Student

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 40
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

2) Declaring Structure Variables with Structure definition


struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is not
much recommended.

Accessing Structure Members


Structure members can be accessed and assigned values in number of ways.
Structure member has no meaning independently. In order to assign a value to a
structure member, the member name must be linked with the structure variable
using dot . operator also called period or member access operator.

Structure Initialization

Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization


or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 41
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Array of structure

As you know, C Structure is collection of different datatypes ( variables ) which


are grouped together. Whereas, array of structures is nothing but collection of
structures. This is also called as structure array in C.

Structure within Structure : Nested Structure


Structure written inside another structure is called as nesting of two structures.
Nested Structures are allowed in C Programming Language.
We can write one Structure inside another structure as member of another
structure.

union

A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many members,
but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose.

Defining a Union
To define a union, you must use the union statement in the same way as you did
while defining a structure. The union statement defines a new data type with more
than one member for your program. The format of the union statement is as
follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end
of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 42
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Difference between Union & Structure

Unions in C Language
Unions are conceptually similar to structures. The syntax of union is also similar
to that of structure. The only differences is in terms of storage. In structure each
member has its own storage location, whereas all members of union uses a single
shared memory location which is equal to the size of its largest data member.

This implies that although a union may contain many members of different types,
it cannot handle all the members at same time. A union is declared using union
keyword.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 43
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Pointer

C Pointer is a variable that stores/points the address of another variable. C Pointer


is used to allocate memory dynamically i.e. at run time. The pointer variable might
be belonging to any of the data type such as int, float, char, double, short etc.
Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key points to remember about pointers in C:

Normal variable stores the value whereas pointer variable stores the address of the
variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between
these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).

Benefit of using pointers


Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as
arguments to other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.

Concept of Pointer

Whenever a variable is declared, system will allocate a location to that variable in


the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.

int a = 10 ;

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 44
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

We can access the value 10 by either using the variable name a or the address 80F.
Since the memory addresses are simply numbers they can be assigned to some
other variable. The variable that holds memory address are called pointer
variables. A pointer variable is therefore nothing but a variable that contains an
address, which is a location of another variable. Value of pointer variable will be
stored in another memory location.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 45
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Declaring a pointer variable


General syntax of pointer declaration is,
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing.
void type pointer works with all data types, but isn't used oftenly.

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer


variable. Pointer variable contains address of variable of same data type. In C
language address operator & is used to determine the address of a variable. The
& (immediately preceding a variable name) returns the address of the variable
associated with it.

Relation between Arrays and Pointers


Consider and array:
int arr[4];

In arrays of C programming, name of the array always points to the first element of
an array. Here, address of first element of an array is &arr[0]. Also, arr represents
the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address
&arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to
*arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
In C, you can declare an array and can use pointer to alter the data of an array.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 46
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Pointer to Structure

Like we have array of integers, array of pointer etc, we can also have array of
structure variables. And to make the use of array of structure variables efficient, we
use pointers of structure type. We can also have pointer to a single structure
variable, but it is mostly used with array of structure variables.
Accessing Structure Members with Pointer
To access members of structure with structure variable, we used the dot . operator.
But when we have a pointer of structure type, we use arrow -> to access structure
members. The symbol -> is known as arrow operator(member selection operator)

Although, C language inherently does not has any technique to allocated memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.

Function Use of Function


Allocates requested size of bytes and returns a pointer first byte of
malloc()
allocated space
Allocates space for an array elements, initializes to zero and then returns
calloc()
a pointer to memory
free() dellocate the previously allocated space
realloc() Change the size of previously allocated space

malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a
block of memory of specified size and return a pointer of type void which can be
casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area
of memory with size of byte size. If the space is insufficient, allocation fails and
returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 47
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.

calloc()
The name calloc stands for "contiguous allocation". The only difference between
malloc() and calloc() is that, malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of same size and sets all bytes to
zero.
Syntax of calloc()

ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of n


elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements
each of size of float, i.e, 4 bytes.

free()

Dynamically allocated memory with either calloc() or malloc() does not get return
on its own. The programmer must use free() explicitly to release space.
syntax of free()

free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated

realloc()
If the previously allocated memory is insufficient or more than sufficient. Then,
you can change memory size previously allocated using realloc().
Syntax of realloc()

ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 48
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

FILE HANDLING IN C

A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations.
Following are the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point

Opening a File or Creating a File

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

mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 49
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

r+ opens a text file in both reading and writing mode


w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.

General Syntax :

int fclose( FILE *fp );


Here fclose() function closes the file and returns zero on success, or EOF if there
is an error in closing the file. This EOF is a constant defined in the header file
stdio.h.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 50
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

Preprocessor

C Preprocessor directives:
Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
Below is the list of preprocessor directives that C language offers.
S.no Preprocessor Syntax Description
This macro defines constant value and
1 Macro #define
can be any of the basic data types.
The source code of the file “file_name”
Header file #include
2 is included in the main program at the
inclusion <file_name>
specified place
Set of commands are included or
Conditional #ifdef, #endif, #if, excluded in source program before
3
compilation #else, #ifndef compilation with respect to the
condition
#undef is used to undefine a defined
macro variable. #Pragma is used to call
4 Other directives #undef, #pragma
a function before and after main
function in a C program

Macro Substitution

Macro substitution is process where an identifier in a program is replaced by a


predefined string composed of one or more tokens. The preprocessor accomplish
this task under the direction of #define statement. This statement is known as
macro definition. The general form is
#define identifier string
If this statement is included in the program at the beginning, then the preprocessor
replace every occurrence of the identifier in the source code by the string. Note that
definition is not terminated by semicolon ‟;‟. The string may be any text and, while
the identifier must be a valid name.
There are three different form of macro substitution.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 51
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

1) Simple macro substitution


2) Argument macro substitution
3) Nested macro substitution

Simple Macro Substitution


Simple string replacement is commonly used to define constants. Example of
definition constants are
#define C 10
#define FALSE 0
#define PI 3.14
#define CAPITAL “DELHI”

We have written all macro identifier in capital. It is a convention to write all macro
in capital to identify them as symbolic constants.
A macro definition can include more than a simple constant value, it can include
expressions also.
#define AREA 5*12.45

Argument macro substitution

The preprocessor permits us to define more complex and more useful form of
replacement. It takes the form:
#define identifier(f1,f2,....fn) string
Notice that there is no space between the macro identifier and left parenthesis. The
identifier f1,f2,...,fn are the formal macro arguments that are analogous to formal
arguments in a function definition.
There is basic difference between the simple replacement & replacement of macros
with arguments. Subsequent occurrence of macro with arguments is known as
macro call. When a macro is called, the preprocessor substitutes the string,
replacing the formal parameters with actual parameter. Hence, the string behaves
like a template.
#define CUBE( x) (x*x*x)

Nesting of macro
We can also use one macro in definition of another macro. That is, macro
definition may be nested.

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 52
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

#define M 5
#define N M+1
The preprocessor expands each #define macro, until no more macro appear in the
text.

FILE INCLUSION
An external file containing functions or macro definition can be included as a part
of program so that we need not rewrite those functions or macro definitions. This is
achieved by preprocessor directive

#include “filename”

Where filename is the name of the file containing required definitions or functions.
At this point, the preprocessor insert the entire content of filename into the source
code of the program. When filename is included with the double quotation marks,
the search for file is made first in the current directory and then in standard
directories.
Alternatively this directive can taken form
#include <filename>
Without double quotation marks. In this case, the file is searched only in the
standard directories.

compiler control directives in c

These preprocessing directives create conditional compiling parameters that


control the compiling of the source code. They must begin on a separate line.
Syntax:
#if constant_expression
#else
#endif

or

#if constant_expression
#elif constant_expression
#endif
The compiler only compiles the code after the #if expression if the
constant_expression evaluates to a non-zero value (true). If the value is 0 (false),
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 53
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)

then the compiler skips the lines until the next #else, #elif, or #endif. If there is a
matching #else, and the constant_expression evaluated to 0 (false), then the lines
between the #else and the #endif are compiled. If there is a matching #elif, and the
preceding #if evaluated to false, then the constant_expression after that is
evaluated and the code between the #elif and the #endif is compiled only if this
expression evaluates to a non-zero value (true).
Examples:
int main(void)
{
#if 1
printf("Yabba Dabba Do!\n");
#else
printf("Zip-Bang!\n");
#endif
return 0;
}

#define, #undef, #ifdef, #ifndef


The preprocessing directives #define and #undef allow the definition of identifiers
which hold a certain value. These identifiers can simply be constants or a macro
function. The directives #ifdef and #ifndef allow conditional compiling of certain
lines of code based on whether or not an identifier has been defined.
Syntax:
#define identifier replacement-code

#undef identifier

#ifdef identifier
#else or #elif
#endif

#ifndef identifier
#else or #elif
#endif

M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 54

You might also like