You are on page 1of 50

COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

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.

Features and applications of C language:


 C is a highly portable language. i.e. programs (software) written for one computer can
be run on another computer with little or no alteration.

 C is a general purpose structured programming language.

 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 has an ability to extend itself. C program is a collection of functions. We can


develop our own functions and add them to C library.

 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.

 C is a case sensitive language.

 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..

History and evolution of C

COBOL FORTRAN
Commercial purpose Engg. & scientific purpose

960’s ALGOL 60 International committee

CPL
1963 Combined Programming Language Cambridge University

1967 BCPL Cambridge University


Basic Combined Programming Language
Martin Richards.

1970 B Ken Thompson at AT&T Bell labs

ALGOL
Developed by inheriting the
1972 features of ALGOL, BCPL, and B.
BCPL C +
New data types and features.

B Dennis Ritchie

In 1960’s the international committee people developed ALGOL 60 by combining the


features of the languages COBOL and FORTRAN. ALGOL is root of all modern languages.
It is the first language to use block structure. It was widely used in Europe but not popular in
USA. It is not popular because it’s too abstractness and too general.

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

1978 K&RC Kernighan and Ritchie

‘The C programming language’

1989 American National Standard Institute


ANSI C
(Technical Committee approved the
version)
1990 ANSI / ISO C International Standard Organization
C 89

1999 Added few features of C++/Java


C 99 By Standardization committee of C.

Note: All the commonly available compilers do not support all the new features of C99.

C FUNDAMENTALS:

Steps in learning English language:


Alphabets Words Sentences Paragraph
Steps in learning C language:
Alphabets Constants
Digits Variables Instructions Program
Special symbols Keywords
The C character set:

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.

Auto double int struct


Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
Continue for signed void
Default goto sizeof volatile
do if static while
Some C compilers may recognize other keywords also for which we have to refer manual or
help of that compiler software to get a complete list of keywords for a particular compiler.

All keywords must be used in lower case letters.

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.

Rules for declaring identifiers:

 The first character must be an alphabet or underscore.


 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.

Prepared by Kalpana 4
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

 It must not contain white space or blank space.


 We should not use keywords as identifiers.
 Upper and lower case letters are different.
Ex: nag, NAG, Nag all are different.
Ex:
Valid identifiers: a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1.

Invalid identifiers: $amount, “num”, grand-total, sum of digits, 4num.


$amount : Special character is not permitted
“num” : Illegal character “.
grand-total : hyphen is not permitted.
sum of digits : blank spaces between the words are not allowed.
4num : should not start with a number (first character must be a letter or underscore).
Note: Some compilers of C recognize only the first 8 characters only; because of this they are
unable to distinguish identifiers with the words of length more than eight characters.
Ex: diameter3 and diameter42 are both syntactically correct but some compilers may not
distinguish them, because the first eight characters are the same for each identifier.

CONSTANTS:
Constants refer to values that do not change during the execution of a program.

Constants can be divided into two major categories:

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

Integer constants: An integer constant is an integer-valued number. It consists of sequence


of digits.
Integer constants can be written in three different number systems:
1. Decimal integer (base 10).
2. Octal integer (base 8).
3. Hexadecimal (base 16).

Decimal integer constant: It consists of set of digits, 0 to 9.


Valid declaration: 0, 124, -56, + 67, 4567 etc.
Invalid declaration: $245, 2.34, 34 345, 075.
23,345,00. it is also an invalid declaration.
Note:
 Embedded spaces, commas, characters, special symbols are not allowed between digits.
 They can be preceded by an optional + or – sign.

Octal integer: It consists of set of digits, 0 to 7.


Ex: 037, 0, 0765, 05557 etc. (valid representation)
It is a sequence of digits preceded by 0.
Ex: Invalid representations
0394: digit 9 is not permitted (digits 0 to 7 only)
235: does not begin with 0. (Leading number must be 0).

Hexadecimal integer: It consists of set of digits, 0 to 9 and alphabets A, B, C, D, E, and F.

Hexadecimal integer is a sequence of digits preceded by 0x or 0X. We can also use a through
f instead of A to F.

Ex: 0X2, 0x9F, 0Xbcd, 0x0, 0x1. (Valid representations)

Ex: Invalid representations: 0af, 0xb3g, 0Xgh.

0af: does not begin with 0x or 0X.


0xb3g, 0Xgh: illegal characters like g, h. (only a to f are allowed)

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)

Decimal integer constant: 32767 (215 – 1)


Octal integer constant: 077777
Hexadecimal integer constant: 0X7FFF

Note: The largest value that can be stored is machine dependent.

Prepared by Kalpana 6
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Floating point constants or Real constants

The numbers with fractional parts are called real constants.

These are the numbers with base-10 which contains either a decimal part or exponent (or
both).

Representation: These numbers can be represented in either decimal notation or exponent


notation (scientific notation).

Decimal notation: 1234.56, 75.098, 0.0002, -0.00674 (valid notations)

Exponent or scientific notation:

General form: Mantissa e exponent

 Mantissa: It is a real number expressed in decimal notation or an integer notation.


 Exponent: It is an integer number with an optional plus (+) or minus (-) sign.
 E or e: The letter separating the mantissa and decimal part.
Ex: (Valid notations)

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:

25 Either a decimal point or an exponent must be present.


2,345.89 Comma is not permitted
5E+2.5 Exponent must be an integer.
8E -4 Illegal character (blank space) after E not allowed.

Character constants

Single character constants: It is character enclosed within single quotes.


Ex: ‘5’, ‘a’, ‘A’, ‘;’, ‘ ‘,‘+’
Character constants have integer values known as ASCII values. (American Standard Code
for Information Interchange).

Prepared by Kalpana 7
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Ex: character ASCII value


‘a’ 97
‘A’ 65
‘5’ 53
‘+’ 43
‘‘ 96 (blank space)
 The character constants may be used in numeric operation just as integers.
Ex: ‘A’+25 = 90. (65+25)
 The character constant ‘5’ is not same as the number 5.
 The statement printf (“%d”, ‘a’); would print the ASCII value 97.
String constants or string literal:

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.

Ex: “Nagendra”, “2010”, “good morning”, “5+7”, “a”, “ “, “S S N R”

Note: The character constant ‘a’ is different from “a”.

Escape Sequences or Backslash Character Constants

C language supports some nonprintable characters, as well as backslash ( \ ) which can be


expressed as escape sequences. An escape sequence always starts with backslash followed by
one or more special characters. For example, a new line character is represented by ‘\n’.

These are used in formatting output screen, i.e. escape sequence are used in output
functions.

Some escape sequences are given below:

Escape sequence Character


‘\a’ audible alert
‘\b’ back space
‘\f’ form feed
‘\n’ new line
‘\t’ horizontal tab
‘\v’ vertical tab
‘\’’ single quote
‘\”’ double quote
‘\?’ question mark
‘\\’ backslash
‘\o’ null

Prepared by Kalpana 8
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Enumeration constants:

An enumeration is a list of constant integer values. Identifiers declared as enumerators are


constants of type int.

Ex: enum colors {GREEN, RED, BLUE, WHITE, YELLOW};

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.

printf (“%d”, WHITE);

The above output statement will print 3 on the output screen.

Syntax: enum identifier {v1, v2, v3,…….,vn};


Note: The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants.

Explicit assignment: enum branch {CSE=1, ECE=2, IT=3, CIV=4};

Symbolic constants:

A constant is more expressive if it is a symbol. It is declared by using preprocessor directives.


In programming, we can observe certain constants may appear in a number of statements in
the program.

#define is used to define symbolic constant.

Ex: #define PI 3.14


#define MAX 100

Using this symbolic constant declaration we can overcome the following problems:

 Modifiability: Problem in modification of the program if we used that constant more


number of times.
 Understandability: we can understand the problem easily.

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

Rules for Constructing Variables:

 The first character of variable names must be a letter or an underscore.


 The first character of variables cannot be a digit.
 The variable name consists of letters, digits, and underscore.
 The variable name can be up to 31 characters long (ANSI). Only first eight characters
are distinguishable in many compilers. (In C99 – 63characters).
 All variable names are case sensitive.
 The C keywords are not used as variable names.
 Blank spaces, commas and special symbols are not allowed within variable name.

Ex: sum, marks, a, b, grand_total, class_strength, total1, x1 (valid variable names)


123, $total, 25th, a+b (invalid arguments)

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;

Ex: int a,b;


float average;
char c;
Data item is assigned to the variable in one of the following ways:
1. Assign the data item to the variable, by using assignment statement.
Ex: a = 100;
2. Read the data from the keyboard (or from a data file) into a variable or variables.
Ex: scanf (“%d”, &a); (Runtime assignment).
The data item can be accessed later in the program simply by referring to the variable name.
*Declaration of variable provides two things:
 Compiler obtains the variable name.
 It tells to the compiler, data type of the variable declared and helps in allocating the
memory.

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

Integral type void Floating Point type

Integer data type character data type float double long double

Signed Unsigned char


signed char
Int unsigned int unsigned char
short int unsigned short int
long int unsigned long int

Prepared by Kalpana 11
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

PRIMARY DATA TYPES


1. Integral data types
a. Integer data type
b. Character data type
2. Floating point data types
3. Void short int (8 bits)
Integral data types: Int (16 bits)
Integer data type: Long int (32 bits)

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

Signed bit Magnitude


Ex: signed int x= -100;
1 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0

Signed bit Magnitude


Signed bit: 0 represents positive integer, 1 represents negative numbers
Unsigned integers: Unsigned integers use all 16 bits to store the magnitude.
Size and range of integer data type on a 16- bit machine are shown in the table:
Data type Size (memory) Range format specifier
(key word)
short int or 8 bits (1 byte) -128 to +127 %d
signed short int
unsigned short int 8 bits (1 byte) 0 to 255 %u
int or signed int 16 bits (2 bytes) -32,768 to +32,767 %d
unsigned int 16 bits (2 bytes) 0 to 65535 %u
long int or 32 bits (4 bytes) -2,147,483,648 to %ld
signed long int +2,147,483,647
unsigned long int 32 bits (4 bytes) 0 to 4,294,967,295

Prepared by Kalpana 12
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Character data type: (char)


A single character can be defined as a character data type. Character data type occupies one
byte of memory for storage of character. The qualifiers signed or unsigned can be applied on
‘char’ data type.
Size and range of character data type on a 16- bit machine are shown in the table:
Data type Size (memory) Range format specifier
(key word)
char or 8 bits (1 byte) -128 to +127 %c
signed char
unsigned char 8 bits (1 byte) 0 to 255 %c

Floating point data types (Real numbers)


Floating point data type is used to store real numbers. In C the keyword ‘float’ is used to
declare a variable. The floating point numbers with 6 digits of precision occupies 4 bytes for
storage. A ‘double’ data type number uses 8 bytes giving a precision of 14 digits. These are
also known as double precision numbers.
Size and range of floating point data type is shown in the table:
Data type Size (memory) Range format specifier
(key word)
Float 32 bits (4 bytes) 3.4E-38 to 3.4E+38 %f
Double 64 bits (8 bytes) 1.7E-308 to 1.7E +308 %lf
long double 80 bits (10 bytes) 3.4E-4932 to 1.1E+4932 %lf

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

Array: (Subscripted variable)


An array is a collection of elements of similar data type. An array can be accessed with the
variable name and its elements can be accessed using an index (subscript[ ]). In C, the array
index starts from 0. Suppose A is an array of 10 integer elements, we can declare the array
as: int A[10];
Each element starting from first can be accessed as A[0], A[1]………A[9].

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.

User-defined data types:

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

Syntax: typedef type identifier;


Type: refers to an existing data type
Identifier: refers to new name given to the data type.
Typedef cannot create a new type but it creates a new name to the existing type.
The main advantage of typedef is that we can create meaningful data type names for
increasing the readability of the program.

Ex: 1. typedef int marks;


Here marks are later used to declare variables as:
marks sub1[60], marks sub2[60];
sub1[60], sub2[60] are declared as 60 element integer variables.

Enumeration:
The enumeration data type is defined as follows:

Syntax: enum identifier {value1, value2, …….,valuen} ;

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:

enum identifier v1, v2, v3,…….,vn ;

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

CONSTANT AND VOLATILE VARIABLE:

Declaring a variable as constant


The value of a variable remains constant during the execution of a program if we declare the
variable with the qualifier const at the time of initialization.
Ex: const int a = 10;

/* 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

volatile const d=10;

Prepared by Kalpana 16
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

INPUT AND OUTPUT FUNCTIONS IN C

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.

Input devices Input functions C program Output functions Screen


Ex: scanf ( ) printf ( )
gets ( ) puts ( )
getch ( ) putch ( )

Classification:
Input and output functions

Formatted functions Unformatted functions


(All types of data values) (Only for character data)

Input Output Input Output


scanf( ) printf( ) gets( ) puts( )
getch( ) putch( )
getchar( ) putchar( )
getche( )
Note: Each program that uses a standard input/output function must contain the statement
#include<stdio.h>
FORMATTED I/O 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.

scanf ( ) (scan formatted)


Scans (read) all types of data values from keyboard. The general form of the scanf( ) function
is Scanf (“control string “, arg1, arg2, arg3 ...…argn);
Control string (format string): It specifies the field format in which the data is to be entered.
The control string includes:

1. The filed specifications consisting of:


 Conversion character %
 A data type character (type specifier) – ex: d/f/c/s based on the type of data.
 An optional number specifying the field width.

Prepared by Kalpana 17
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

2. Blanks, tabs, or newlines and these are ignored.

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.

Reading integer numbers:


The field specifications for reading integer numbers are: %wd

Here, %: indicates that conversion specification follows.


w: integer number which specifies the field width of the number to be read.
d: indicates data type character.

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.

2. scanf (“%2d %5d”,&a,&b); // with field width specification


Input data: 25 31245
It will read the data correctly and assign 25 to a and 31245 to b.
If the input data is: 31245 25
The variable a will be assigned 31(because of %2d) and b will be assigned 245 which is
unread part of 31245. The value 25 that is unread will be assigned to the first variable in the
next scanf call.

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

Syntax: printf (“Control String”, arg1, arg2, arg3, …….. argn);

 The control string consists of


 Characters that will be printed on the screen as they appear.
 Format specifiers that define the output format for display each data item.
 Escape sequence characters such as \t, \n, \b etc.
 arg1, arg2, arg3 … argn are names of variables whose values must be printed on
console (monitor) in the format specified in the control string.

Note: The arguments should match in number, order and type with the format specifications.

Output of Integer Numbers: %wd


The format specification for printing an integer number is:

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.

Ex: Output of the number 1234.


void main ( )
{ Output:
printf("\n%d",1234); //Without field width 1 2 3 4
printf("\n%6d",1234); // Right alignment
1 2 3 4
printf("\n%-6d ",1234); //Left alignment
printf("\n%012d",1234); //Padding with Zero 1 2 3 4
printf("\n%2d",1234); //Overriding the
field width value. 0 0 0 0 0 0 0 0 1 2 3 4
}
1 2 3 4

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.

Output of Real Number:

The output of a real number may be displayed in two ways:

1. Decimal Notation ex: 2.345, 0.000005, -2.8976, 3456.987 etc.


2. Exponential Notation

Output of Real Number in decimal notation: % w.p f

Here both w and p are integers.


 The integer w indicates the minimum number of positions that are to be used for
display of the value.
 The integer p indicates the number of digits to be displayed after decimal point
(precision).
 The value when displayed is rounded to p decimal places and printed right-justified in
the field of w columns.

Ex: Output of the number 98.7654.

printf("\n %f", y); 9 8 . 7 6 5 4

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

Output of Real Number in decimal notation:


%w.p e
The display takes the form [-] m.nnnnn e [+ or -] xx

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

Ex: Output of the number 98.7654.


printf("%10.3e",-y); 9 . 8 7 7 e + 0 1
printf("\n%e", y);
printf("\n%10.2e",y); 9 . 8 7 6 5 4 0 E + 0 1

9 . 8 8 e + 0 1

Prepared by Kalpana 20
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Printing of a single character:


The format specification for printing a character is:

printf("%c",’S’); S

printf("\n%3c",’S’); S
printf("\n%6c",’N’);
N
printf(“\n%10c”,’R’);
R

Commonly used format codes:

%c Printing a single character


%d Print decimal integer
%f Print a floating point value without exponent
%g Printing a floating point number with trailing zeros truncated
%o Printing an octal number
%x Printing a hexadecimal integer with Lower case hex-digits (a-f)
%X Same as %x, but with upper case hex-digits (A-F)
%u Print an unsigned decimal integer
%d Printing a short integer
%ld Printing a Long integer
%s Printing a string
%lf Printing a double
%e Printing a floating point number in exponent form

/* program to show the effect of mismatch of data types */


void main ( )
{
int a;
clrscr( );
printf (“Enter value of a:”);
scanf(“%c”,&a);
printf(“a = %c”,a);
getch ( );
}

Prepared by Kalpana 21
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

OPERATORS AND EXPRESSIONS

 An operator is a symbol which represents a particular operation that can be performed on


data.
 An operand is the object on which an operation is performed.
 By combining the operators and operands we form an expression. An expression is a
sequence of operands and operators that reduces to a single value.

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).

C operators are classified into the following categories:


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
9. Unary operators

ARITHMETIC OPERATORS:

The arithmetic operators used in C are:

Arithmetic operator Meaning


+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division (Remainder)

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.

Ex: int x = 10, y = 20, z; // operands

z = x + y; //Addition operation on the operands x and y, the value of z = 30


z = x - y; // subtraction operation on the operands x and y, the value of z = -10
z = x * y; // multiplication operation on the operands x and y, the value of z =200
z = x / y; // Division operation on the operands x and y, gives the quotient value when x is
divided by y and value of z = 0.
z = x % y; // Modulo division operation with the operands x and y produces remainder of
integer division.

Prepared by Kalpana 22
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Here the operands x and y must be of integer type.


Arithmetic operations are classified in to three ways:
i) Integer arithmetic
ii) Real arithmetic
iii) Mixed mode arithmetic
Integer arithmetic
Both the operands are of integer type in integer arithmetic. It always yields an integer value.

Ex: 20+10 = 30, 20-10 = 10, 20*10 =200, 20/3 = 6 (Decimal part is truncated),
20%10 = 0 (Remainder of a division).

/*C program on Integer Arithmetic Expressions*/

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
}

Note: a % b=20.0 % 3.0- invalid expression

Mixed mode arithmetic

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.

Note: The left operand in an assignment expression must be a single variable.


There are two forms of assignment:
 Simple assignment
 Compound assignment

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);

Advantages of using shorthand assignment operator:


1. What appears on the left-hand side need not be repeated and therefore it becomes easier to
write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

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.

Ex: 4<7 is true.


Note: 1. There should not be any space between two characters in operators <= / >=.
2. The assignment operator (=) is different from equal to operator (==).

/* C program on relational operators*/


void main()
{
int a,b;

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

& Bitwise AND


| Bitwise OR
<< Shift Left
>> Shift Right
^ Bitwise Exclusive OR
~ One’s Complement
These operators are used for testing the bits, or shifting them right or left.
Note: These operators may not be applied to float or double.

One’s complement or Bitwise NOT


The bitwise NOT, or complement, is a unary operation that performs logical negation on each
bit, forming the ones' complement of the given binary value. Digits which were 0 become 1,
and vice versa.
Ex: NOT 0111 (decimal 7) = 1000 (decimal 8)
In C, t he bitwise NOT operator is "~" (tilde).
Truth table: Expression value ~ Expression
0 1
1 (non-zero) 0
Note: One’s complement (Bitwise NOT) operator is different form Logical NOT operator.
We use this operator in encoding and decoding process.

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

Bitwise shift right operator


It is a binary operator it requires two integral operands. The first operand is the value to be
shifted and the second operand specifies the number of bits to be shifted.

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.

Bitwise shift left operator


It is a binary operator it requires two integral operands. The first operand is the value to be
shifted and the second operand specifies the number of bits to be shifted left.

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.

Bitwise AND operator (&)


The bitwise AND operator is a binary operator it requires two integral operands (character or
integer). It does a bitwise comparison as shown below:

First Operand Bit Second Operand Bit Ope1 & Ope2


0 0 0
0 1 0
1 0 0
1 1 1

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:

First Operand Bit Second Operand Bit Ope1 | Ope2


0 0 0
0 1 1
1 0 1
1 1 1

Bitwise EXCLUSIVE OR operator ( ^ )


The bitwise EXCLUSIVE OR operator is a binary operator it requires two integral operands
(character or integer). It does a bitwise comparison as shown below:

First Operand Bit Second Operand Bit Ope1 ^ Ope2


0 0 0
0 1 1
1 0 1
1 1 0

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.

The Comma Operator (,)


The comma operator can be used to link the related expressions together. A comma linked list
of expressions is evaluated left to right and the value of the right most expression is the value
of the combined expression.
Ex: a=(x=10, y=20, x+y);
First assigns the value 10 to x, then assigns 20 to y and finally assigns 30 to variable a.
It has the lowest precedence among all the operators.
We use comma operator in loop statements and declaration statements to separate variables
of same type.

INCREMENT (++) AND DECREMENT (--) OPERATORS:


The operator ++ adds one to its operand where as the operator – – subtracts one from its
operand. These operators are unary operators and take the following form:

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.

++a has the same effect as a=a+1.


--a has the same effect as a=a-1.

Ex: int b=4;


A= ++b;

In this case the value of b would be 5 and A would be 5.

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

expression 1? expression2: expression3

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

Example program uses different kinds of operators.


void main() //start of program
{
int a, b, c, d; //declaration of variables
a = 15; b = 10; c = ++a-b; //assign values to variable, new value of a=16 is used thus giving value 6 to C
printf (“a = %d, b = %d, c = %d\n”, a,b,c); //print the values
d=b++ + a; // d=26 and b=11
printf (“a = %d, b = %d, d = %d\n, a,b,d); // a=26, b=11 and d=26
printf (“a / b = %d\n”, a / b); //value is 2
printf (“a %% b = %d\n”, a % b); //value is 4
printf (“a *= b = %d\n”, a *= b); //value is 8
printf (“%d\n”, (c > d) ? 1 : 0 ); //6>26 false, so print 0
printf (“%d\n”, (c < d) ? 1 : 0 ); //6<26 true,so print 1
}

TYPE CONVERSION IN EXPRESSIONS:


It is the process of converting one type into another. In other words converting an expression
of a given type into another is called type casting. When we write an expression that involves
two different data types, to perform the evaluations one of the types must be converted. In C
we have two types of conversions:

 Implicit Type Conversion


 Explicit Type Conversion

Implicit Type Conversion (Automatic Conversion):


When the data types of two operands in a binary expression are different, C automatically
converts one data type to another so that the expression can be evaluated without losing any
significance. This conversion is known as implicit type conversion.
Conversion in assignment expression: A simple assignment involves an assignment
operator and two operands. Depending on the difference in the rank, C tries to either promote
or demote the right expression to make it the same rank as the left variable.

 Promotion occurs if the right expression has lower rank.


 Demotion occurs if the right expression has a higher rank.

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

Fig: conversion rank


long double

double

float

unsigned long int

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;

Conversion in other binary expressions


The steps to follow in evaluation of binary expressions in most of the cases:
1. The operand with the higher rank is determined using the ranking shown in the above figure.
2. The lower-ranked operand is promoted to the rank defined in step 1. After the promotion, both
expressions have the same rank.
3. The operation is performed with the expression value having the type of the promoted rank.

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

Type casting otherwise called as Explicit Conversion:


Explicit type conversion is a type conversion which is explicitly defined within a program
(instead of being done by a compiler for implicit type conversion).
Explicit conversion can be done using type cast operator and the general syntax for doing this is
(type) expression;
Here in the above type is the data type which the programmer wants the expression to gets
changed as.

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.

Arithmetic expression C expression

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;

The following program illustrates the effect of presence of parenthesis in expressions.

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.

High priority */%


Low priority +-

Rules for evaluation of expression


 First parenthesized sub expression left to right are evaluated.
 If parentheses are nested, the evaluation begins with the innermost sub expression.
 The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
 The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
 Arithmetic expressions are evaluated from left to right using the rules of precedence.
 When Parenthesis is used, the expressions within parenthesis assume highest priority.

OPERATOR PRECEDENCE AND ASSOCIATIVITY:


Each operator in C has a precedence associated with it.

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

Examples for Left to right associativity:


Example: x= 2 * 3 - 4 / 2 + 3;
Step 1: Here * and / has the same priority but while evaluating from left to Right * must be
evaluated first.
x= 2 * 3 - 4 / 2 + 3;
1
Step 2: After evaluating * the next operator to be evaluated is /.
x = 6 - 4/ 2 + 3;
2
Step 3: After / is evaluates – and + has the same priority but from left – is to be evaluated
first.
x = 6 - 2 + 3;
3
x = 4 + 3;
4
Step 4: Finally x contains the value 7.
x= 7.

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

PRIORITY AND ASSOCIATIVITY OPERATORS:

Operators Description Associativity Priority/precedence


() Function call/ Parenthesis
[] Array expression 1
Left to right
-> Structure operator
. Structure operator
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! NOT operator 2
Right to left
~ Ones complement
* Pointer operator
& Address operator
Sizeof Size of operator
Type Type casting operator
* Multiplication
/ Division Left to right 3
% Mod
+ Addition 4
Left to right
- Subtraction
<< Left shift 5
Left to right
>> Right shift
< Less than
<= Less than or equal to 6
Left to right
> Greater than
>= Greater than or equal to
== Equality 7
Left to right
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Right to left 13
=,+=,*=,/=,%=,&=,|=, 14
Assignment operator Right to left
<<=,>>=,^=,-=
, Comma operator Left to right 15

Prepared by Kalpana 36
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Examples for right to left associativity:

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

sqrt(x) Square root of x, x>0


pow(x,y) X to the power Y (xy)
exp(x) ex
fmod(x,y) Remainder of x/y.
log(x) Natural log of x, x>0.
log10(x) Base 10log of x, x>0.
fabs(x) Absolute value of x.
cos(x) Cosine of x, x is in radians
sin(x) Sine of x.
tan(x) Tangent of x
acos(x) Arc cosine of x.
asin(x) Arc sine of x
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x

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

CONTROL FLOW STATEMENT

Decision making with IF statements


The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression.
Two-Way Selection: The decision is described to the computer as a conditional statement
that can be answered either true or false. If the answer is true, one or more action statements
are executed. If the answer is false, then a different action or set of actions is executed.
It takes the following form:-

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

The “statement-block” may be a single statement or a group of statements.


If it is true it will execute the statement –block and will go to the next step for execution.
If it is false then the command will directly go to statement-x and after that the next step or
the process continues.

/* check a citizen is eligible for voting */


#include<stdio.h>
int main()
{
int age;
printf(“Enter the age : ”);
scanf(“%d”,&age);
if(age >= 18)
printf(“Eligible for voting…”);
getch();
}
___________________________________________________________________________
The if…else statement is an extension of the IF statement.
The general form is:-
If ( test expression)
{
True-block statement (1);
}
Else
{
False-block statement (2);
}
Statement-x;

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.

Syntactical Rules for if…else Statements

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

EX: /* print a number is even or odd */

#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:
………

/* check whether a year is leap year


or not */
#include<stdio.h>
int main() {
int year;
printf("Enter the year ?");
scanf("%d",&year);
if((year %100) == 0)
{
if((year % 400) == 0)
printf("%d is leap year.",year);
else
printf("%d is not leap year.",year);
} else {
if((year % 4) == 0)
printf("%d is leap year.",year);
else
printf("%d is not leap year.",year);
}
getch();
}

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

/* program to print the grade of student */


#include<stdio.h>
int main() {
int marks;
printf("Enter marks ? ");
scanf("%d", &marks);
if(marks >= 80)
printf("Honors");
else if(marks >= 60)
printf("First division");
else if(marks >= 50)
printf("Second division");
else if(marks >= 40)
printf("Third division");
else
printf("Failed");
getch();
}

Prepared by Kalpana 41
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Multiway Selection

In addition to two-way selection, most programming languages provide another selection


concept known as multiway selection. Multiway selection chooses among several
alternatives. C has two different ways to implement multiway selection: the switch statement
and else-if construct.

The switch Statement


Switch Decision Logic syntax

Switch statement rules

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 Program1: Switch Flow:

/* program to simulate a simple calculator */


#include<stdio.h>
int main() {
float a,b;
char opr;
printf("Enter number1 operator number2 : ");
scanf("%f %c %f",&a,&opr,&b);
switch(opr)
{
case '+':
printf("Sum : %f",(a + b));
break;
case '-':
printf("Difference : %f",(a - b));
break;
case '*':
printf("Product : %f",(a * b));
break;
case '/':
printf("Quotient : %f",(a / b));
break;
default:
printf("Invalid Operation!");
}
}

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:

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

DECISION MAKING AND LOOPING (OR) REPETITION


Concept of a loop:
The real power of computers is in their ability to repeat an operation or a series of operations
many times. This repetition, called looping, is one of the basic structured programming
concepts.

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.

Entry Loops and Exit Loops:

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.

Entry Control Loop

In each iteration, the control expression is tested first. If it is true, the loop continues;
otherwise, the loop is terminated.

Exit Control Loop

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.

Entry Control Loop Exit Control Loop

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

In C there are mainly three types of loops are use:


 while loop
 for loop
 do…while loop

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
}

/* c program to find sum of 1 to 10 numbers */


#include<stdio.h>
int main() {
int i = 1,sum = 0;
while(i<=10){
sum = sum + i;
i = i + 1;
}
printf(“Total : %d “,sum);
} Output: Total : 55

The do…while statement:


The do while is an exit control loop statement, the program proceeds to evaluate the body of
the loop first. At the end of the loop, the test-condition in the while statement is evaluated. If
the condition is true, the program continues to evaluate the body of the loop once again. This
process continues as long as the condition is true. When the test-condition becomes false and
the control is transferred out of the loop.

/*To find average of 5 numbers and read numbers from keyboard */


#include<stdio.h>
int main() {
int count = 1;
float x, sum = 0;
do {
printf(“x = “);

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.

Ex: for(int a=1, n=5; a<n; ++a)


{
printf(“ a=%d”,a);
}

It is also permissible to use expressions in the assignment statement of initialization and


increment section.

Ex: for(a=(b+c)/2; a>0; a=a/2)


{
printf(“%d”,a);
}

/* check whether a number is prime or not */


#include<stdio.h> }
int main() { if (factors == 2)
int n,i,factors = 0; printf("%d is prime number.",n);
printf("Enter a number : "); else
scanf("%d",&n); printf("%d is not prime number.",n);
for(i = 1; i <= n; i++) }
{
if((n % i)==0) Enter a number: 11
++factors; 11 is prime number

Prepared by Kalpana 47
COMPUTER PROGRAMMING & DATA STRUCTURES UNIT - II

Nesting of for loops: One for statement in another for statement


Example: ……………….
……………….
for(i=1; i<10; i++)
{
………………..
………………..
for( j=1; j<i; j++)
{ Inner Outer
………….. loop loop
…………..
}
………………..
}
………………..
………………..

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.

Ex: while(..) for(….) while(..) for(..)


{ { { { abc:
…… …… …….. ....for(..) {
if(condition) if(…) if(…) if(..)
break; break; goto stop: goto abc;
…….. ……… ………. ………
} } } } …. }
stop:
Exit():

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

Continue statement or skipping a part of loop:

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;

Ex: while(condition) int count=0;


{ while(count<=10)
……. {
if(..) if(count<0)
continue; continue;
……….. printf(“…”);
} }

/* use of continue statement*/


void main( )
{
int a,b;
for(a=1; a<=3; a++)
{ Output:
for(b=1; b<=3; b++) 1 2
{ 1 3
if(x==y) 2 1
continue; 2 3
printf(“%d \t %d \n”,a,b); 3 1
} 3 2
}
getch();
}

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

Advantages of Structured Programming


1. Easy to write: Several Programmers can work on a single, large program, each
working on a different module. Studies show structured programs take less time to
write than standard programs. Procedures written for one program can be reused in
other programs requiring the same task. A procedure that can be used in many
programs is said to be reusable.
2. Easy to debug: Since each procedure is specialized to perform just one task, a
procedure can be checked individually.
3. Easy to Understand: The relationship between the procedures shows the modular
design of the program. Meaningful procedure names and clear documentation identify
the task performed by each module. Meaningful variable names help the programmer
identify the purpose of each variable.
4. Easy to Change: Since a correctly written structured program is self-documenting, it
can be easily understood by another programmer.

Structured Programming Constructs


It uses only three constructs -
 Sequence (statements, blocks)
 Selection (if, switch)
 Iteration (loops like while and for)

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

You might also like