Beruflich Dokumente
Kultur Dokumente
INTRODUCTION TO C LANGUAGE
The communication medium between the computer and human being is a language. Now a
day’s computers are playing vital role each and every field. To write programs the number of
high level languages is developed in past three decades.
Ex: FORTRAN, BASIC, PASCAL, C++, JAVA, C etc.
The evolution of C as a programming language has made application development very easy.
It is the general purpose and most powerful language.
It was developed by Dennis Ritchie in 1970’s (1972) at AT & T Bell Laboratories USA.
C was extensively used in development of UNIX operating system. C is often called a middle
level language because it has the features of both high level languages and low level
languages. With this we can write efficient programs like high level languages and these
programs give better machine efficiency like Low level languages.
C is modular, the code written can be written in routines called functions. These
functions can be used in other applications or programs. By passing piece of
information to the functions, we can create useful, reusable code.
C is well suited for writing system software like UNIX, as well as application
programming because the C compiler combines the capabilities of an assembly
language with the features of the high-level language.
C language allows the dynamic allocation of memory. i.e., a program can request the
operating system to allocate or release memory in run time.
Programs written in C are efficient and fast, due to its variety of data types and
powerful operations.
C is a robust language whose rich set of built in functions and operations can be used
to write any complex program.
Prepared by Kalpana 1
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Where is C useful?
C’s ability to communicate directly with hardware makes it a powerful choice for system
programmers. In fact, popular operating systems such as Unix and Linux are written entirely
in C. Additionally, even compilers and interpreters for other languages such as FORTRAN,
Pascal, and BASIC are written in C. However, C’s scope is not just limited to developing
system programs. It is also used to develop any kind of application, including complex
business ones. The following is a partial list of areas where C language is used:
Embedded Systems, Systems Programming, Artificial Intelligence, Space Research, etc..
COBOL FORTRAN
Commercial purpose Engg. & scientific purpose
CPL
1963 Combined Programming Language Cambridge University
ALGOL
Developed by inheriting the
1972 features of ALGOL, BCPL, and B.
BCPL C +
New data types and features.
B Dennis Ritchie
In 1963, CPL is developed by the people of Cambridge University. It is so big with so many
features. It is very hard to learn and difficult to implement.
Prepared by Kalpana 2
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
In 1967, Martin Richards of Cambridge University developed BCPL. The aim of this
language is solving the problem by bringing CPL down to its basic good features. But this
language is too specific and less powerful.
In 1970, Ken Thompson of AT&T Bell Laboratories developed a new language with the
name B for simplification of CPL, but it is same as BCPL. It is also too specific.
In 1972, Dennis Ritchie of AT&T Bell Laboratories developed a new language by inheriting
the features of ALGOL, BCPL and B. The C language consists of new data types and
powerful features and operators. It is reliable, simple and easy to use.
Improvements and changes in C
1972 Dennis Ritchie
Traditional C
Note: All the commonly available compilers do not support all the new features of C99.
C FUNDAMENTALS:
Alphabets: A, B, C, D, E… Y, Z.
a, b, c, d, e… y, z.
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Special symbols: ~, !, @, #, $, %, ^, &, *, (, ), +, -,;, :, ., ,, blank space, |, \, / etc.
C also uses certain combinations of these characters such as \t, \b,\n etc. these are called as
escape sequences.
Prepared by Kalpana 3
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
C TOKENS:
In a passage of text, individual words and punctuation marks are called tokens. In the same
way in C language the smallest individual units are called as tokens. C has six types of
tokens.
KEY WORDS
IDENTIFIERS
CONSTANTS
C TOKENS
STRINGS
OPERATORS
SPECIAL SYMBOLS
KEYWORDS:
These are the words whose meaning is already been explained to the C compiler (or
computer). These words are reserved words, which have standard, predefined meaning in C.
These keywords can be used only for their intended purpose; Keywords cannot be used as
variable or identifier names.
IDENTIFIERS:
Identifiers are the names given to various program elements such as variables, functions and
arrays. These are user defined names consisting of sequence of letters and digits.
Prepared by Kalpana 4
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
CONSTANTS:
Constants refer to values that do not change during the execution of a program.
1. Primary constants:
a) Numeric constants
Integer constants.
Floating-point (real) constants.
b) Character constants
Single character constants
String constants
2. Secondary constants:
Enumeration constants.
Symbolic constants.
Arrays, unions, etc.
Rules for declaring constants:
1. Commas and blank spaces are not permitted within the constant.
2. The constant can be preceded by minus (-) signed if required.
3. The value of a constant must be within its minimum bounds of its specified data type.
Prepared by Kalpana 5
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Hexadecimal integer is a sequence of digits preceded by 0x or 0X. We can also use a through
f instead of A to F.
The magnitude (maximum value) of an integer constant can range from zero to some
maximum value that varies from one computer to another.
Typical maximum values for most personal computers are: (16-bit machines)
Prepared by Kalpana 6
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
These are the numbers with base-10 which contains either a decimal part or exponent (or
both).
1.23456E+3 (1.23456×103)
7.5098e+1 (7.5098×101)
-4
2E–4 (2×10 )
These exponential notations are useful for representing numbers that are either very large or
very small.
Ex: 0.00000000987 is equivalent to -9.87e-9
Invalid representations:
Character constants
Prepared by Kalpana 7
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
String constant is a sequence of zero or more characters enclosed by double quotes. The
characters may be alphabets, digits, special characters and blank space.
These are used in formatting output screen, i.e. escape sequence are used in output
functions.
Prepared by Kalpana 8
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Enumeration constants:
The first name (GREEN) in the enum has value 0, RED has value 1, the next 2, and so on,
unless explicit values or specified.
Symbolic constants:
Using this symbolic constant declaration we can overcome the following problems:
VARIABLES:
A variable is a data name that may be used to store a data value (Variable names are names
given to locations in the memory of computer). Unlike constants that remain unchanged
during the execution of a program, a variable may take different values at different times
during execution (quantity which may vary during the execution of a program.).
Types of variables:
Integer variables.
Floating point variables.
Character variables.
Prepared by Kalpana 9
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
The contents of the variable may change during the execution of the program. However, the
data type associated with the variable cannot change.
Variable declaration:
All variables must be declared before they can appear in executable statement. The
declaration of a variable should be done in the declaration part of the program.
Syntax: data_type variable_name;
Prepared by Kalpana 10
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
STRUCTURE OF C PROGRAMS:
The document section contains of a set of comment Documentation Section
lines giving the name of the program and other details.
Link Section
The link section provides instructions to the compiler to
Definition Section
link functions from system library. By using #include
(it is a preprocessor compiler directive). Global Declaration Section
Ex: #include<stdio.h> main() Function Section
{
The definition section defines all symbolic constants. Declaration part;
Ex: #define PI 3.14 (#define preprocessor directive) Executable part;
}
There are some variables that are used in more than one Subprogram section
function. Such variables are called global variables and Function1
are declared in the global declaration section. This .
section also declares all the user-defined functions. .
User-defined functions
Every C program must have one main() function .
section. This section contains two parts; declaration part .
and Executable part. The declaration part declares all Function n
the variables (local variables) used in the executable part. There is at least one statement in
the executable part. These 2 parts must appear between the opening and closing braces {}.
All statements in the declaration and executable parts end with a semicolon (;).
The subprogram section contains all the user-defined functions that are called in the main
function.
DATA TYPES:
A data type is used to indicate the type of data value stored in a variable. All C compilers
support a variety of data types. This variety of data types allows the programmer to select the
type appropriate to the needs of the application as well as the machine.
ANSI C supports the following classes of data types:
1. Primary (fundamental) data types.
2. Derived data types.
3. User-defined data types.
Primary data types
Integer data type character data type float double long double
Prepared by Kalpana 11
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
This data type is used to store whole numbers. These numbers do not contain the decimal
part. The size of the integer depends upon the world length of a machine (16-bit or 32-bit).
On a 16-bit machine, the range of integer values is -32,768 to +32,767.
C provides control over range of integer values and storage space occupied by these values
through the data types: short int, int, long int in both signed and unsigned forms.
Signed integers: (16-bit machine)
A signed integer uses 1 bit for sign and 15 bits for the magnitude of the number.
(-215 to +215 -1).
Ex: signed int x=100;
0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0
Prepared by Kalpana 12
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Void type
The void type has no values. This is usually used to specify the type of functions. The type of
the function said to be void when it does not return any value to the calling function.
Derived data types:
C supports some other data types, which can be derived from the basic data types, such as
Array
Structure
Union
Pointer
Prepared by Kalpana 13
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Like an integer array, a group of character can be stored in a character array. These character
array are often called strings. Ex: char name[30];
Structure:
A structure is a collection of variables of different data types that are logically grouped
together and referred under one name.
Ex: struct employee
{
int empcode;
char name[20];
char doj[15];
float salary;
};
Using the structure definition, we can declare variable, of type structure employee as
Struct employee emp1,emp2;
Union:
A union is also a collection of variables of different data types. Unlike structures, the
variables share the same memory area. The amount of storage space occupied for a union
variable is the amount of storage required for the largest member of the union. In general, the
unions are used to save the memory area occupied by the program. The union declaration has
the same form as the structure declaration except the keyword Union.
Ex: union number
{
int inum;
float fnum;
char cvalue;
} num1,num2;
Union allows only one of the members available at a time. Hence, any reference to the
wrong type of data will produce meaningless results.
Pointer:
Pointer is a variable which holds the address of another variable. i.e. A pointer variable holds
an address of a physical memory location.
The data types defined by the user are known as the user-defined data types. C provides two
identifiers typedef and enum to create new data type names.
Typedef:
It allows the 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.
Prepared by Kalpana 14
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Enumeration:
The enumeration data type is defined as follows:
Identifier: it 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 (enumeration constants).
Declaration of variables of this new type:
The enumerated variables v1, v2, v3,…….,vn can only have one of the values value1,
value2, …….,valuen .
Assignments: ex: v1 = value3;
v4 = value2;
Ex: enum day {Monday, Tuesday, Wednesday, …. Sunday}; (definition of identifier ‘day’)
enum day week_st, week_end; (declaring variable of new type day)
week_st = Monday;
week_end= Friday;
Note:
1. The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants .i.e. 0 is assigned to value1, 1 is assigned to value2, 2 is assigned
to value3, and soon. User can also assign values explicitly to the enumeration constants.
Ex: enum day {Monday=1, Tuesday, Wednesday, …. Sunday};
2. The definition and declaration of enumeration variables can be combined in one
statement.
Ex: enum day {Monday, Tuesday, Wednesday, …. Sunday} week_st, week_end;
Prepared by Kalpana 15
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
/* Example program*/
int b; //global variable
void main( )
{
const int a=10; //local variable initialization
clrscr( );
printf ("a=%d", a);
a=20; // new assignment
getch ( );
}
If we compile this code then the compiler will show an error: cannot modify constant
object.
Note: The compiler protects the value of a from modification. The user cannot assign new
value to a, but using scanf ( ) statement the value can be replaced.
Volatile variable The volatile variables are those variables that are changed at any time by
other external program or the same program. The syntax is as follows
volatile int d;
If the variable in the current program is to be maintained constant and desired not to be
changed by any other external operation, then the declaration of variable will be as follows
Prepared by Kalpana 16
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Reading the data from the input devices or data files and displaying the results or information
on the output screen are the two main functions of any program. To perform these I/O
operations C has a number of input/ output functions based on data types.
Classification:
Input and output functions
Formatted functions read and write all types of data values. They require conversion
symbol (format specifier) to identify the data type.
These functions return the values after execution.
Return value: It represents the number of variables successfully read/ written. Using this
return value the user can find out the errors occurring during reading/writing the data.
Formatted Input
Formatted input refers to an input data that has been arranged in a particular format.
Prepared by Kalpana 17
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
The arguments arg1, arg2, arg3 ...…argn specify the address of locations where the data is
stored (address of the variable).
The scanf ( ) function requires & operator called address operator. In scanf ( ) statement the
role of & operator is to indicate the memory location of the variable, so that the value read
would be placed at that location.
Ex: 1. scanf (“%d %d”, &a, &b); //without field width specifications.
This statement will read the data for two variables a, b.
Input data: 25 31245
It will read the data correctly and assign 25 to a and 31245 to b.
Note: Input data items must be separated by spaces, tabs or newlines. Punctuation marks are
not allowed between two input values.
Note:
1. The scanf ( ) statement will read a particular value until the number of characters specified
by field width is reached.
2. The input field may be skipped by specifying * in the place of field width.
Ex: scanf (“%d %*d %d”, &a, &b);
Input data: 25 35 45
The scanf statement will assign the data as follows:
25 to a 35 skipped (because of *) 45 to b
Note: It is not always advisable to use field width specifiers in scanf statement. Some times
it may assign wrong values to variables as shown in above examples.
Prepared by Kalpana 18
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
printf ( ): This function prints all type of data values to the console. It requires conversion
symbol and variable name to print the data. The number of conversion symbols and variable
names must be same in number.
/* Example program */
void main( )
{
int x=2;
float y=2.75;
char z=’c’;
printf(“x = %d \t y = %f \t z = %c “, x, y, z);
getch( );
}
OUTPUT: x=2 y=2.75 z=c
Note: The arguments should match in number, order and type with the format specifications.
Where, w specifies the minimum field width for the output and d specifies that the value to be
printed is an integer.
If a number (no. of digits) is greater than the specified field width, it will be printed in full,
overriding the minimum specification.
Prepared by Kalpana 19
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
It is possible to force the printing to be left-justified by placing a minus sign (-) after the
%character.
By default with positive sign printing will be done with right-justification with leading
blank spaces when field width is greater than the number of digits in the given number.
It is possible to pad with 0’s the leading blanks by placing a 0 before field width
specifier.
The minus (-), plus (+) and zero (0) are known as flags.
printf("\n%7.4f",y); 9 8 . 7 6 5 4
printf("\n%7.2f",y); 9 8 . 7 7
printf("\n%-7.2f",y); 9 8 . 7 7
Here the string of n’s is specified by the precision p. The default precision is 6 digits. The w
should satisfy the condition W ≥ P+7
9 . 8 8 e + 0 1
Prepared by Kalpana 20
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
printf("%c",’S’); S
printf("\n%3c",’S’); S
printf("\n%6c",’N’);
N
printf(“\n%10c”,’R’);
R
Prepared by Kalpana 21
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
A simple expression contains only one operator. Ex: 10+20 is a simple expression whose
value is 30.
A complex expression contains more than one operator. Ex: 2+5*7 (value is 37).
ARITHMETIC OPERATORS:
Here, all the operators are called binary operators; because these are operate on two operands at a
time. Each operand can be int, float, or char.
Prepared by Kalpana 22
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Ex: 20+10 = 30, 20-10 = 10, 20*10 =200, 20/3 = 6 (Decimal part is truncated),
20%10 = 0 (Remainder of a division).
void main()
{
int a, b;
clrscr();
printf("a+b=%d", a+b); OUTPUT:
printf("\na-b=%d", a-b); a+b=23
printf("\na*b=%d", a*b); a-b=17
printf("\na/b=%d", a/b); a*b=60
printf("\n a mod b=%d", a%b); a/b=6
getch(); a mod b=2
}
Real arithmetic
Both the operands are of real/float type in real arithmetic. It always yields a real value.
void main( )
{
float a, b;
clrscr();
printf(“Enter values for a and b:”);
scanf(“%f %f”, &a, &b);
printf("\n a+b=%f", a+b);
printf("\n a-b=%f", a-b); OUTPUT:
printf("\n a*b=%f", a*b); Enter values for a and b: 20.0 3.0
printf("\n a/b=%f", a/b); a+b =23.000000
//printf("\n a mod b=%f", a%b); Error a-b =17.000000
statement Illegal use of floating point. a*b=60.000000
getch(); a/b=6.666667
}
When one operand is integer and other is real it is known as mixed mode arithmetic. Here,
the result will always be real.
Prepared by Kalpana 23
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
void main()
{
float a;
int b;
clrscr();
printf("Enter values for a and b:");
scanf("%f %d", &a, &b);
printf("\n a+b=%f", a+b);
printf("\n a-b=%f", a-b); OUTPUT:
printf("\n a*b=%f", a*b); Enter values for a and b: 20.0 3
printf("\n a/b=%f", a/b); a+b=23.000000
//printf("\n a mod b=%f", a%b); Error a-b=17.000000
Illegal use of floating point a*b=60.000000
getch(); a/b=6.666667
}
ASSIGNMENT OPERATOR:
The assignment expression evaluates the operand on the right side of the operator (=) and
places its value in the variable on the left.
Simple assignment
In algebraic expressions we found these expressions.
Ex: a=5; a=a+1; a=b+1;
Here, the left side operand must be a variable but not a constant. The left side variable must
be able to receive a value of the expression. If the left operand cannot receive a value and we
assign one to it, we get a compile error.
Compound Assignment
A compound assignment is a shorthand notation for a simple assignment. It requires that the
left operand be repeated as a part of the right expression.
Variable operator=
Syntax: ex: a+=
expression;
Here the operator, operator= is known as shorthand assignment operator.
Ex: a+=1 is equivalent to a=a+1;
a-=b+1; is equivalent to a=a-(b+1);
Prepared by Kalpana 24
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Some of the commonly used shorthand assignment operators are shown in the following
table:
Statement with simple assignment operator Statement with shorthand operator
a=a+1 a+=1
a=a-1 a-=1
a=a*1 a*=1
a=a/1 a/=1
a=a%1 a%=1
a=a*(n+1) a*=n+1
Ex: using shorthand assignment operator
#define A 2 //creates a variable A with constant value 2
main() //start of the program
{
int a; //variable a declaration
a = A; //assigns value 2 to a
printf(“%d \n”,a); //print the current value of a
a *= a; //shorthand form of a = a * a
printf(“%d \n”,a);
} //end of the program
OUTPUT: 2
4
RELATIONAL OPERATORS:
Relational operators are used to test the relationship between two variables or between a
variable and a constant. C has six relational operators.
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
An expression containing relational operator is termed as a relational expression.
The value of the relational expression is either 0 or 1.
In C, true is any value other than 0 and false is zero.
Prepared by Kalpana 25
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
clrscr();
printf("Enter a, b values:");
scanf("%d %d", &a, &b);
printf("a>b:%3d",a>b); OUTPUT:
printf("\na<b:%3d",a<b); Enter a, b values: 5 9
printf("\na>=a:%3d",a>=a); a>b: 0 //false
printf("\na<=b:%3d",a<=b); a<b: 1 //true
printf("\na==b:%3d",a==b); a>=a: 1 //true
printf("\na!=b:%3d",a!=b); a<=b: 1 //true
getch(); a==b: 0 //false
} a!=b: 1 //true
BITWISE OPERATORS:
A bitwise operation operates on one or more bit patterns or binary numerals at the level of
their individual bits. i.e. these operators manipulate data at bit level.
Operator Description
Shift Operators
The shift operators move bits to the right or the left. These are of two types:
Bitwise shift right operator
Bitwise shift left operator
Prepared by Kalpana 26
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
When bits are shifting right, the bits at the right most end are deleted.
/* C program on right shift operator to shift inputted data by two bits right*/
void main() y=x;
{ printf("y=%d", y);
int x,y; getch();
clrscr(); }
printf("Enter value for x:"); OUTPUT:
scanf("%d",&x); Enter value for x: 8
x>>=2; Y=2
Explanation: The number entered through the keyboard as input is 8 and its corresponding
binary number is 1000.
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
After execution of the program the input data x is to be shifted by 2 bits right side. The
answer in binary form would be as follows:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
The right shift operator divides the given number by a power of 2. If we shift a binary
number two places to the right, we are dividing the given number by 4 (22).
s
i.e. y=x/2 , where s is the number of shifts towards right.
When bits are shifting left, the bits at the left most end are deleted.
Ex: int a=2;
a<<=3;
Shift left is the opposite of shift right operator. The left shift operator multiplies the given
number by a power of 2. If we shift a binary number three places to the left, we are
multiplying the given number by 8 (23).
s
i.e., y=x × 2 , where s is the number of shifts towards left.
Prepared by Kalpana 27
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Bitwise OR operator ( | )
The bitwise OR operator is a binary operator it requires two integral operands (character or
integer). It does a bitwise comparison as shown below:
LOGICAL OPERATORS:
Logical Data: A piece of data is called logical if it conveys the idea of true or false. In C we
use int data type to represent logical data. If the data value is zero, it is considered as false. If
it is non -zero (1 or any integer other than 0) it is considered as true.
C has three logical operators for combining logical values and creating new logical values:
1. Logical AND operator (&&).
2. Logical OR operator (||).
3. Logical NOT operator (!).
We use these logical operators when we want to test more than one condition and makes
decisions.
Ex: a>b && x==10.
a>b || a>c.
An expression of this kind which combines two or more relational expressions is called as
logical expression or a compound relational expression.
A logical expression also yields a value of one or zero.
Truth tables for AND (&&) and OR (||) operators: X Y X&&Y X||Y
0 0 0 0
Truth table for NOT (!) operator: 0 1 0 1
X !X
0 1 1 0 0 1
1 0 1 1 1 1
Prepared by Kalpana 28
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
UNARY OPERATORS:
A unary operation is an operation with only one operand. i.e. an operation with single input.
Operator Description
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Address
~ Ones complement
Sizeof Size of operator
Type Type casting
SPECIAL OPERATORS:
The SIZEOF operator:
It returns the number of bytes occupied by the operand. The operand may be a variable, a
constant (data value) or a data type qualifier.
Ex: int a, c, f, d;
c=sizeof(a);//here c=2,the sizeof operator returns the size of the variable a which is of int type
f=sizeof(long double); //f value is 10 which is the size of the long double qualifier type
d=sizeof(23.345); //d value is 4 which is the size of the float constant value
The sizeof operator is normally used to determine the length of arrays and structures. It is
also used to allocate space dynamically to the variable s during execution of a program.
Operator Description
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement
Prepared by Kalpana 29
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Both the increment and decrement operators may either precede or follow the operand.
Postfix Increment/Decrement :( a++/a--)
In postfix increment (Decrement) the value is incremented (decremented) by one.
Thus the a++ has the same effect as a=a+1; a-- has the same effect as a=a-1.
The difference between a++ and a+1 is, if ++ is after the operand, the increment takes place
after the expression is evaluated.
The operand in a postfix expression must be a variable.
Ex1: int a=5; Ex2: int x=4;
B=a++; y=x--;
Here the value of B is 5. Here the value of y is 4, x value is 3
the value of a is 6.
Prefix Increment/Decrement (++a/ --a)
In prefix increment (decrement) the effect takes place before the expression that contains the
operator is evaluated. It is the reverse of the postfix operation.
The effects of both postfix and prefix increment is the same: the variable is incremented by 1.
But they behave differently when they used in expressions as shown above.
The execution of these operators is fast when compared to the equivalent assignment
statement.
CONDITIONAL OPERATOR:
C provides a ternary operator pair “?:” which is used in reducing the code. It requires three
operands.
The general format is,
True
False
As shown above expression1 is evaluated first. If the value of exp1 is true then exp2 is
evaluated and it becomes the value of expression. If the value of exp1 is false, then exp3 is
evaluated and it becomes the value of expression. Note that only one of the expression is
evaluated.
Ex: 3<5 ? 8 : 7;
Here exp1 is true, so 8 becomes the value of expression.
Prepared by Kalpana 30
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Promotion
There is normally no problem with promotion. The rank of the right expression is evaluated
to the rank of the left variable. The value of the expression is the value of the right expression
to make it the same rank as the left variable.
/* Example C program*/
void main()
{ f=i;
int i; d=c;
char c; printf("c=%c \t i=%d \t f=%f \t d=%lf", c,
float f; i, f, d);
double d; getch();
clrscr(); }
c='A'; Output:
i=c; c=A i=65 f=65.000000 d=65.000000
Prepared by Kalpana 31
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
double
float
long int
unsigned int
int
char | short
Demotion
Demotion may or may not create problems. If the size of the variable at the left side can
accommodate the value of the expression, there is no problem.
When an integer or a real is assigned to a variable of type character, the least significant
byte of the number is converted in to character and stored.
When a real is stored in an integer, the fraction part is dropped. If the integer part is larger
than the maximum value that can be stored the results are invalid and unpredictable.
When we try to store a long double in a variable of type float, the results are valid if the
value fits or invalid if it is too large.
/* Example program*/
void main() printf("\n c=%c ",c);
{ getch();
int i=65; }
char c;
float f=2.675; Output:
clrscr(); c=A
printf("c=%c ",c); c=☻
c=f;
Ex:
char c=’A’;
int i=345; i+c; // c is promoted; result is an int
float f=567.45; i*f; // I is promoted; result is in float
long double d=654.00965; i+d; //I is promoted; result in long double
Prepared by Kalpana 32
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Ex:
double da = 5.5;
double db = 5.5;
int result = (int)da + (int)db;
//Result would be equal to 10 instead of 11.
ARITHMETIC EXPRESSIONS:
An arithmetic expression is a combination of variables, constants and operators as per the
rules (syntax) of the language. In C every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable. Some
examples of C expressions are shown in the table given below.
a×b-c a*b-c
(m+n) (x+y) (m+n)*(x+y)
a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y+c
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and then replaces the previous value of the variable on the left hand side. All
variables used in the expression must be assigned values before evaluation is attempted.
Examples for valid C expressions are
x=a*b–c
y=b/c*a
z = a – b / c + d;
void main ()
{
float a, b, c x, y, z;
a = 9;
Prepared by Kalpana 33
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %fn”, x); Output
printf (“y = %fn”, y); x = 10.00
printf (“z = %fn”, z); y = 7.00
} z=4.00
Precedence in Arithmetic Operators
An arithmetic expression without parenthesis will be evaluated from left to right using the
rules of precedence of operators. There are two distinct priority levels of arithmetic operators
in C.
Precedence (priority)
It is used to determine the order in which different operators in a complex expression are
evaluated. i.e. the precedence is used to determine how an expression involving more than
one operator is evaluated. There are distinct levels of precedence and an operator may belong
to one of these levels. The operators of higher precedence are evaluated first.
Associativity
It is used to determine the order in which operators with the same precedence are evaluated in
a complex expression. The operators of same precedence are evaluated from right to left or
from left to right depending on the level. This is known as associativity property of an
operator.
In evaluation of a complex expression precedence is applied before associativity to determine
the order. Associativity then applied if necessary.
Prepared by Kalpana 34
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Example2:
When the expression contains the parenthesis then the innermost expression must be
evaluated first.
y = ( 2 * ( 2 * 4 *( 2 / 2 ) ) ) because 2 / 2 = 1
1
y=(2*(2*4)) 2 * 4 =8
2
y=(2*8)
3
y = 16
Prepared by Kalpana 35
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Prepared by Kalpana 36
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Ex1: a+=b*=c-=9;
In this expression all the operators have right to left associativity. i.e. the right most
expression is evaluated first; then its value will be assigned to the operand on the left of the
assignment operator and the next expression will be evaluated.
The given expression is evaluated as
(a+= (b*= (c-=9) ) );
This is expanded to
(a=a+ (b= b* (c=c-9) ) );
If the initial values of a, b, c are 3, 4, and 5.
(a=3+ (b= 4* (c=5-9) ) );
Result:
c= -4
b= -16
a= -13
MATHEMATICAL FUNCTIONS
The following are some of the mathematical functions supported by most of the C compilers:
Function Description
Note: To use these functions in any C program we should include math.h header file.
# include <math.h>
Prepared by Kalpana 37
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
DECISION MAKING
A piece of data is called logical if it conveys the idea of true or false. In real life, logical
data (true or false) are created in answer to a question that needs a yes–no answer. In
computer science, we do not use yes or no, we use true or false.
C program is a set of instructions which are normally executed sequentially in the order in
which they appear. However, in practice there are a number of situations where the order of
execution of the statements has to be changed, based on certain conditions or repeat a group
of statements if certain conditions are met. This process involves a certain kind of decision
making to see whether a particular condition has occurred or not. C language possesses such
decision making capabilities and supports the following statements known as control
structure or decision making statements.
C language has 4 different types of decision-making capabilities by supporting the following
statements:
1. If statement
2. Switch statement
3. Conditional operator statement
4. Goto statement
Here the ENRTY meaning the condition is being taken into the IF statement (Test expression
command). And if it is stated FALSE it is given to FALSE command directly and the
program ends over there. And if it is stated TRUE the program continues for next step.
Some more different types of IF statements are simple if, if…..else, nested if else, else if
ladder
Some examples of decision making, Using IF statements are:-
1. If (room is dark) put the lights on
2. If ( age is more than 55) person is retired
Simple IF statement:
The general form of simple IF statement is
If (test expression)
{
statement –block;
}
Statement – x;
Prepared by Kalpana 38
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
If the expression (if…else) is true, then true-block statement-1 immediately following the
if condition and it is executed, Otherwise the false statement -2 will be executed and the
program continues for next condition.
An if statement may also optionally contain a second statement, the ``else clause,'' which is to
be executed if the condition is not met.
Prepared by Kalpana 39
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
#include<stdio.h>
int main()
{
int number;
printf(“Enter a number : “);
scanf(“%d”, &number);
if((number %2) == 0)
printf(“%d is even number.”,number);
else
printf(“%d is odd number.”,number);
}
___________________________________________________________________________
Nesting of IF-Else statements
It's also possible to nest one if statement inside another. When a series of decisions are
involved, we may have to use more than one if…..else statement in nested form as shown:-
For example:-
There is a post available in a organization the required qualification to apply for the post is
B.tech(c.s.e) of age 28 yrs. And for reservation candidates even 30 yrs is taken into
consideration.
The program will be in the following
manner:
………
Prepared by Kalpana 40
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
EX-2:
If ( B.tech with C.s.e)
{
If( age is 28 yrs and no reservation)
printf(“The candidate can apply”);
else
with reservation
If (age is 30 yrs with reservation)
{
printf(“The candidate can apply”);
} ………
Else if ladder
There is another way of putting IF’s together when multi path decisions are involved. A
multi path decision is a chain of if’s in which the statement is associated with each if and
else…. In else-if the same variable is being tested in the expressions.
let us consider an example of grading the students in an academic institution. The grade is
done accordingly:
Average marks Grade
80—100 Honors
60—79 First division
50—59 second division
40—49 Third division
0—39 fail
Prepared by Kalpana 41
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Multiway Selection
Only one variable is tested, all branches must depend on the value of that variable. The
variable must be an integral type. (int, long, short or char).
Prepared by Kalpana 42
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Example Program2:
/* Estimate a number as none, one, two,
several, many */ printf("Two\n");
void main() break;
{ case 3 :
int number; case 4 :
{ switch(number) { case 5 :
case 0 : printf("Several\n");
printf("None\n"); break;
break; default :
case 1 : printf("Many\n");
printf("One\n"); break;
break; }
case 2 : }
Each interesting case is listed with a corresponding action. The break statement prevents any
further statements from being executed by leaving the switch. Since case 3 and case 4 have
no following break, they continue on allowing the same action for several values of number.
Both if and switch constructs allow the programmer to make a selection from a number of
possible actions.
Prepared by Kalpana 43
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
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 colon (;). The label is placed immediately
before the statement where the control is to be transferred. The general form of goto is shown
below:
goto label; label:
…………. statement;
…………. ………….
………… ………….
label: …………
statement; goto label;
statement;
Forward Jump Backward Jump
The label: can be anywhere in the program either before or after the goto label; statement.
If the label: is placed after the goto label;, some statements will be skipped and jump is
known as a Forward Jump.
If the label: is placed before the goto label; a loop will be formed some statements will be
executed repeatedly. Such a jump is known as a Backward Jump.
Example:
void main( )
{
float x,y;
read:
scanf(“%f”,&x);
if(x<0) goto read;
y=sqrt(x);
printf(“%f%f”,x,y);
goto read;
}
The program uses two goto statements, one at the end, after printing the results to transfer the
control back to the input statement, and the other to skip any further computation when the
number is negative.
Due to the unconditional goto statement at the end, the control is always transferred back to
the input statement. In fact, this program puts the computer in a permanent loop known as an
infinite loop. We take some special steps to terminate the infinite loop.
To avoid infinite loop situations, it is always advisable not to use backward goto with form an
infinite loop.
Prepared by Kalpana 44
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Each loop must have an expression that determines if the loop is done. If it is not done, the
loop repeats one more time; if it is done, the loop terminates.
We need to test for the end of a loop, but where should we check it—before or after each
iteration? We can have either a entry control loop or a exit control loop terminating condition.
In a entry control loop , the condition is checked at the beginning of each iteration.
In a exit control loop, the condition is checked at the end of each iteration.
In each iteration, the control expression is tested first. If it is true, the loop continues;
otherwise, the loop is terminated.
In each iteration, the loop action(s) are executed. Then the control expression is tested. If it is
true, a new iteration is started; otherwise, the loop terminates.
The test may be either to determine whether the loop has been repeated the specified number
of times or to determine whether a particular condition has been met. In case, due to some
reasons the control sets up an infinite loop and the body is executed over and over again.
Looping includes the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
Prepared by Kalpana 45
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
The while and for are Entry control loops,and the do…while is a Exit control loop.
While Loop:
While is an entry control loop statement. A while loop has one control expression, and
executes as long as that expression is true. 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.
Syntax:
while(test-condition)
{
body of the loop
}
Prepared by Kalpana 46
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
scanf(“%f”,&x);
sum += x; Output:
++ count;
} while(count <= 5); x=1.0 x=2.0 x=3.0 x=4.0 x=5.0
printf(“\nAverage = %f “, (sum/5)) Average = 3.0
}
For loop:
The for loop is another entry-controlled loop that provides a more concise loop control
structure.
Syntax:
for(initialization; test-condition; increment / decrement)
{
body of the loop
}
Ex:
for(int a=1; a<5; a++)
{
printf(“ a=%d”,a);
}
Additional feature of for loop is more than one variable can be initialized at a time.
Prepared by Kalpana 47
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
JUMPS IN LOOP:
Loops perform a set of operations repeatedly until the condition fails. Sometimes, when
executing a loop it becomes skip a part of the loop in that time c permits a jump from one
statement to another within a loop.
In earlier we are using the break statement in the switch case and goto statement in the if else
construct. These statements can also be used with in the while, do and for loops.
Break statement:
It comes with decision making statement like if and switch statements. It is used to quite from
the loop, switch block break, when come out of the loop or switch it will not go back again.
Exit() is a function which is used to terminate from the program. It takes an integer value as
its arguments.
Syntax: exit();
Ex: exit(1);
Zero is used to normal termination and non-zero value to indicate termination due to some
errors or abnormal termination.
Prepared by Kalpana 48
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
It also comes with if statement. The statement is also used with an any loop. The continue
statement continues the loop while continuing below of the continue statement are not
executed.
By using continue; the loop to be continued with the next iteration after skipping any
statements in between. The continue statement tells the compiler, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
Syntax: continue;
Structured Programming
Structured programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being written to
make it more efficient and easier to understand and modify. Certain languages such as C,
Ada, Pascal, and dBASE are designed with features that encourage or enforce a logical
program structure.
Structured programming frequently employs a top-down design model. A defined function or
set of similar functions is coded in a separate module or sub module, which means that code
can be loaded into memory more efficiently and that modules can be reused in other
programs. After a module has been tested individually, it is then integrated with other
modules into the overall program structure.
Prepared by Kalpana 49
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II
Sequence
Any valid expression terminated by a semicolon is a statement.
Statements may be grouped together by surrounding them with a pair of curly braces.
Selection
The selection constructs allow us to follow different paths in different situations. We
may also think of them as enabling us to express decisions.
Iteration
Looping is a way by which we can execute any some set of statements more than one times
continuously .In C there are mainly three types of loops are used :
while Loop
do while Loop
For Loop
The control structures are easy to use because of the following reasons:
1) They are easy to recognize
2) They are simple to deal with as they have just one entry and one exit point
3) They are free of the complications of any particular programming language
Prepared by Kalpana 50