100% found this document useful (1 vote)
176 views30 pages

Bca C Language 1

This document is for beginners of C language this document has first chapter of see you can start to learn C language by reading this document

Uploaded by

Rahul Gajare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
176 views30 pages

Bca C Language 1

This document is for beginners of C language this document has first chapter of see you can start to learn C language by reading this document

Uploaded by

Rahul Gajare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT 1

L.1.L. Histoff ,.r. ,


designid and developed by Dennis Ritchie at Bell Laboratories in 1972.

developed in the year 1960 at Cambridge university. This language is


associated closely with UNIX operating system. The source code for the
UNIX operating system is coded in C.

spread beyond Bell Labs. In the late 70's C began to replace widespread well-
known languages of that time like PL/I, ALGOL, etc'

however, different organizations began applying their own versions of C with


a subtle difference. This posed a serious problem for system developers. To
solve this problem, the American National Standards Institute (ANSI) fonned
a committee in 1983 to establish a standard definition of C. This committee
approved a version of C in 1989 which is known as ANSI C. With few
ei"eptions, every modern C compiler has the ability to adhere to this
standard. ANSI C was then approved by the International Standards
Organization (ISO) in 1990.

because its predecessor was called B. The B language was developed by Ken
Thompson of Bell Labs.

are efficient, fast and highly portable, i.e., C programs written on one
computer can be riin op another with little or no modification. C functions are
the building blocks in which all programming activities are incorporated.

why it is known as middle-level language. It is well-suited for writing both


application software and system software.

languages such as Pascal, FORTRAN, etc. A structured language allows


variety of programs in small modules. It is easy for debugging, testing' and
maintlnance if a language is a sffuctured one. Structured languages are easier and
most of the developers prefer these languages than the non-structured ones like
BASIC and COBOL. Programming is a bit tough as compared to structured
languages. It provides loop constructs like while, do-while and for. The user is
required to think of a problem in terms of function blocks. With appropriate
collection of different rnodules, the programmer can make a complete program.

1.1.2. Properties of C
fo. structured
programming.
Weak Typing like for instance, characters can be used as integers.
l-ow-level access to computer memory via machine addresses and typed pointers.
Function pointers allow for a basic form of run-time polymorphism.
A standardized C prep(rcessor for macro definition, source code files
inclusion, conditional compilation, etc.

functions and file handling delegated to library routines.

e.g., {...}.

meaningless operations.

reference is achieved in C by explicitly passing pointer values.

elements to be combined and manipulated as a unit.

1..L.3. Advantages of C
l) Flexibility: To give access to any level of the computer down to raw machine
language, however, C was designed and because of this, it is perhaps the most
fl exible high-level language.

2) Logica[y Organized Code: To organize programs in a clear, easy, logical way,


C has features that allow the programmer For example, C allows meaningful
names for variables without any loss of efficiency, yet it gives a complete
freedom of p,rognmming style, a set of flexible comrnands for performing tasks
repetitively (for, while, do) and including flexible ways of making 9ecislpns.
turd'"o*pu.,
3) Readability and Simpticity: It permits the creation of tidJ
pro$ams. C is alsO.c.gncise. This feature can be a mixed blessing, however,
and the C programm#ifiust balance readability and simplicity.
4) Efficient Resource Hantlling: Wittl C, prograrmer can use every resource of the
computer it offers. C ties to link closely with the local environmeng providing
facilities for gaining access to common peripherals like printers and disk drives.
5) High-Level Constructs: The offered constructs are concise and efficient
with less syntactical constructs.
6) Efficient Programs: The programs are efficient and concise enough for even
system coding.
7) Portability: Compiled on a variety of computers.
!.1.4. Disadvantages of C
1) Poor error detection which can make it putting off to the beginner.
2) The knowledge of syntax is a must for a programmer for correct codes.
3) The C codes are written with the compiler package only; they do not have a
facility of being written on any editor.

L.L.5. Basic Structure of C Programming


C program is a collection of one or more function. Every function is a collection
of staLments, performs some specific task. The structure of C program is as
follows:
1) Include Header File Smtion: C program depends upon some header files for
function definition that are used in progftrm. Each header file by default is
extended with .h, the file should be included using #include directive as given
below:
#includecstdio.h> or #include "stdio.h"
Header File
lobal Declaration Section
/* comments */ 1

main0 Function Name


{
/* comments */
Declaration Part
Executable Part
l
User-defined Functions
{

Figqre 1.1: Stnrcturc of a 'C'Program

In this example <stdio.h> file is included, i.e., all the definitions and
prototypes of function defined in this file are available in the current
program. This file is also compiled with original program.

2) Global Declaration: This section declares some variables that are used in
more than one function. These variables are known as global variables. These
variables must be declared outside of all tho functions.

3) main0 Function: Every progrdm written in C language must contain


maino function.; Empty parentleqes after main are necessary. The
function main0 is the starting poifrf bf every 'C' program. The execution
of the program always begins with the function maino. Except the maino
function, other sections may not be necessary. The program execution
starts with the opening brace'{'and ends with the closing brace'}'.
Between these two bras.eq fire programmer should declare the declaration
and the executable part)\t Jttl

4) Declaration Part: The declaration part declares the entire variables that are
used in executable part. The initializations of variables are also done in this
section. The initialization means providing initial value to the variables.
s) Executable Part: This part contains the moments following the declaration
of the variables. This part contains a set of statements or a single statement.
These statements are enclosed between the braces.*.*1,::
6) user-Defined Function: The functions defined by the user are called user-defined
functions. These functions are generally defined after the main0 function. They
can also be defined before main0 function. This portion is not compulsory.
7) Comments: Comments are not necessary in the program. However, to understand
the flow of programs, the programmer can include comments in the program.
comments are to be inserted by the progarrmer. It is useful for documentation.
The clarity of the program can be followed if it is properly documented.
Comments are nothing but some kind of statements which are placed between
the delimiters /* and */. The compiler does not execute comments..Thus, we
can say that comments are not the part of executable programs.
The user can frequently use any number of comments that can be placed
anywhere in the program.
Note: comments and statements can be nested. The user should select the oprloN
MENU of the editor and selecr the (COMPILER-SOURCE - NESTED
COMMENTS ON/OFF). The comments can be inserted with a single starement or in
nested statements.

1.1.6. First Program in C


Program 1: /*Program to add two numbers*/
#includecstdio.h>
#include<conio.h>
void main0
{
int numl, num2, sum;
clrscr0;
printf("Enter the two integer values to be added");
scanf(" Vod Va d", &nttm1, &num2) ;
sum=num1+num2;
printf("Addition of Vod and Vod is Vod\n", num1, num2, sum);
getch0;
)

Explanation: The followiitg is the step by step program description:


1) The lines between the /*...........'*1are comments which are written for the
prograrnmer they are not compiled.
2) C Program starts with #include<stdio.h>: This line includes the "standard VO
Library" into the program. The standard uo library rets to read input from the
keyboard called "standard in", write output to the screen called "standard
out", process text files stored on the disk, and so on. It is an extremely useful
library. C has a large number of standard libraries like conio, including string,
time and math libraries. A library is simply a package of code that someone
else has written to make coding easier.
3) The line void main0 declares the main function. Every C program must have
a function named rnain somewhere in the code. At run time, program
execution starts at the first line of the main function.
4) In C, the
.{, and,}' symbols mark the beginning and end of a block of code.
5) The variable initialization is done in the format data type var-name.
6) 'scanf' takes the input from the end user.
7) The print of statement in C allows to send output to standard out 'generally',
the screen. The portion in quotes is called the format string and describes how
the data is to be formatted when printed.
8) The return 0; line callses the function to return an elror code of 0 'no error' to
the shell that started execution.

1.1.6.1. Compiling and Executing the Program


Once the program has been entered into the computer, edited and saved, it can be
compiled and executed by selecting Run from the Debug menu. A new window
will then be opened, and an attempt will be made to compile the current program.
If the program does not compile successfully, a list of error messages will appear
in a separate window. Each error message indicates the line number where the
error was detected as well as the type of error. If the program does compile
successfully, however, it will immediately begin to execute, prompting for input,
displaying output, etc., within the new window.

Program Code

-*T-l
Source Program

Syntax Errors?

Logic Error
Logic and Data
Errors?
No Errors

Figure 1.2: Process of Compiling and Running a C Program


/*programtoaddtwonumbers*/ ..,
#include<stdio.h>
finclude<conio.h>
void mainQ
{ F2.C is the C program. Save the file
int numl, num2, suml with the .C extension. It is in human-
clrscr0; readable fom.
printf("Enter the two integer values to be
added");
scanf("7od 7od", &numl, &num2);
sum=numl+num2;
printf("Addition of %od anil Vod is 7od\n",
numl, num2, sum);
getch0;
l

C
Compiler To compile F2.C, click Debug and then
Run

F2.exe

101 1010100101 r010


10100100100100010
The C compiler takes F2.C as input and l0l0l0010l0l0l I 10
tums it into a machine-readable
executable fom. The computer
"executes" this executable.

Figure 1.3

1.1.6.2. Running First Program


step 1) First, start by loading the addition program, F2.c into the computer's
memory, by selecting Open from the File menu. Then select Save As
from the menu, as shown in figure 1.4:

Figure 1.4
Step 2) Select Run from the menu, as shown in figure 1'5'
Theprogramiscompiledandimmediatelybeginstoexecute'Anew
program
windowlshowing the lnput/output dialog, appears containing_the
listing. This is ,ho*, in ngure 1.5 for the values numl as 50 and
num2
as 2i. These values have been entered by the user, in response
to the
input promPts.

i,"!,-.r 1.-r. r,,:i.:)it 1l,l:f .,.li:i:


Go to cursor F4
Irace into F?
Step ouer F8
firgunents. . .

Figure 1.5

Step 3) once the input has been entered the program resumes execution as shown
in the figure 1.6:

Figure 1.6

'
Step 4) As the last input has been entered the' program resumes execution,
see that a value
resulting in the finpl output shown iir'figure 1'7' Thus' we
of sum is 75 is bbtained for the given input quantities:

Figure 1.7
declared as, say, integer or floating point. c is not, howevei, strongry typed,
in that the values in variables can change type atthe will of the prograflrmer.

control structures, functions, and modules. Modular programming helps


break larger problems into a collection of smaller, more^manageable pieces.
The use of functions is encouraged in c and often in fact iequired. For
example, input and output, must be done via function calls.

parampdtfrs- to functions and when dealings with arrays, strings, and dynamii
memfr allocation.

The keywords are also identifiers but cannot be user defined since they are
reserved words.

Basic feature of C may include:


l) Character Set
2) Keywords
3) Identifiers
4) Variables
5) Constants and Literals
6) Strings (Alphabets)
7) Special Symbols (Delimiters)
8) Data Types
9) Operators
10) Expressions

1.2.1. Character Set


The c character set includes alphabets of both upper (A-Z) and lower case (a_z)
letters. As C is case sensitive, upper and lower case letters are treated differently
by the compiler. It also includes the numerals (0-9). Apart from these, there arl
30 special characters allowed in the-c chaiacter set. Each of them has some
specific meaning ald. is used in creatiiig c syntax appropriately. The c character
set is given in tablb 1.1:
Table 1.1: Character Set in C
Nature Symbols
Alphabets A-Z,a-z
Numerals 0-9
Arithmetic +-*lVo=?
Logical !><l &
?9. Parentheses o
Punctuation
l-i"#
Soecial =,,,#\^_(blank)
1.2.2. Tokens
In general text, a word and puiictuation marks are called tokens' In C program,
the smallest individual units are known as token'

Basically c has six types of tokens as shown below. All the c programs are
written using these tokens and syntax of the language'

Types of C Token

1.2.3. Kdywords words


There are certain words, which are reserved for doing specific tasks' These
are known as keywords. These keywords have standard, predefined meaning in
C. The keywords are also identrfrgr 99J,g3ll-o--t,be user.lttrt$'qince they are
reserved words. User must not choose them as variable or identifiers'

There are following keywords available in C:


Table .2: Reserved inC
auto break case char
const continue default do
double else enum extern
float for soto if
int Iong reeister refurn
short sisned sizeof static
struct switch tvpedef union r
unsigned void volatile while

1.2.4. Identifiers
An identifier is a sequence of characiers that represents an entity such as a

function or a data object. ..'

Syntax
identifier nondigit
identifier digit
identifier dollar-sign
Where,
1) nondigit: any character from the set:
-abcdefghijklmnoP
qrstuvwxYzABCDEFG
HIJKLMNOPQRSTUVWX
YZ
2) digit: any character from the set:
0123456789
3) dollar-sign: $ character
For example, Thakur-publisher.

l-.2.5. Variables
variable is a named location in memory, i.e., used to hold a value that can be
modified by the progftlm. These variables can take different values but one at a
time. The values of variables can be changed during execution. All the variables
should be declared before they can be used.

Variable names may be consists of uppercase character, lowercase character and


underscore.

Rules for Naming Variables


Rules for giving the name to the variable are as follows:
1) First character should be a letter or underscore in some special cases.
2) The variable names cannot be a keyword.
3) White space(s) is (are) not allowed.
4) Uppercase and lowercase letters are significant, e.g., code, code, coDES are
three different variables. But usually variables are in lowercase. A variable
can be arbitrarily long.

For Example: Some of Valid Variable Names are


i) dailypay
ii) _data

For Example: Some of Invalid Variable Names


Variable Remark
5bc First character should start with letters or underscore (_)
int int is a keyword
rec# # is a special character
avs no blank space is not permitted .

Declaration of Variqble
It is must to declare the variable before it is used in the program. We declare the
variable with data type;.means the variable name can store ihe value of this data
type. c compiler distinguiihes all these variable names, which are declared.

Declaration of variable can be done as:


, <data type> <variable name>;

Here data type may be int, float, char, double etc.


Examples of declaration of variable are
int basic;
int a, b, c:
as data type int.
Here basic, a, b, c are the variable names which are declared
Initialization of variables can also be done with the declaration of variable'
int a=5, b, t=10;
float b=3.5, c=4.9;
char ch;
charch='y';(Herechisacharactervariable,whichhasthevalue'y')'

Types of Variable
variables they are
it ,yp"r of variables are defined by the location of the its
"
declared. The place of declaration of the var-iable affects storage and its
of and which has to be
memory storage. Hence declaration is prime concerns
started Lven before the actual coding is started:
are called
1) Local variables: variables that are declared lside a lrnctioq thit are inside
local variables. Local variables can be uied oniy by statements
local variables
the block in which the variables are declared. In other words,
is upon
are not known outside their own code block. A local variable
created
within one
entry into its block and destroyed upon exit. A variable declared
code block has no bearing on or relationship to another variable
with the
same name declared within a different code block'
program and
z) Global variables: variables that are .known throughout the
Also, they will hold their value throughout
may be used by any piece of code.
the program," Global variables are created uv g*gle}l.g_!u:!1-
"*""irtior.
ou1.':$g.'"qf gay*fuap.tronl'Any expression may access
them, regardless of what
tioCii # it is in. Storage for global variables is in a fixed
. "oa" " "*pr"ssion
region of memory sei aside for this purpose by the compiler. Global variables
same data. Use of
aII t"tpfut when many functions in the program use the,
u,n""",,ury global variables, however, because they take-up memory thea
are needed. If
entire time the progruln is executing, not just when they
to that
global variable uoa i to"ut variable have the same name, all references
is declared
variable name inside the code bl0ck in which the l0cal variable
will refer to that local variable and have no effect on the global variable.

1.2.6. Constants and Literals


cannot be changed
Constant is a value that can be stored in thg memory and
during execution of the.program. There are $ree types of constants:
' Constants
Types of Constants

- --
Numeric Character
Constants Constants

Integer Real Single String


Constants Constants Character Constants
Constants

Figure 1.8: Basip Types of C Constants


{) Numerid Constant: Numeric constants are numeric digits which may or may
not have decimal point (.). These are the rules for defining numeric constant:
i) Numeric constant must have atleast one digit.
ii) No comma and space are allowed within the numeric constant.
iii) Numeric constants can either be positive or negative but default sign is
alwavs positive.

Types,i.' Numeric Constant


, Integer constant: Integer constants are whole numbers, which has no
decimal point (.). There are three types of integer constants, which are in
different number systems:
Decimal number 0,1,2,3,4,5,6.7.8.9 6ase 10)
Octal number 0,1,2,3,4.5.6.7 (base 8)
Hex decimal number 0,1,2,3,4,5,6,7,8.9. A. B. C. D. E. F (base l6)
Some valid integer constants are:
0
123
370s
837590
Some invalid decimal integer constants are:
Invalid Remark
2.5 Illegal Character (
3#5 IllegalCharacter(#)
985 No blank space allowed
0925 First digit cannot be zero
8.354 Comma is not allowed

ii) Real (Floating Point) constant Floating point constanrs are rhe
numbers, which hold the decimal point. Some valid floating point
constants are:
0.5
5.3
4000.0
0.0073

2) character Constant: A character constart is a singte character that is


enclosed within single quotes (' ').'For exarytple:
,a,
,9,
,$,

Every character constant has a unique integer value associated with it. These
are-r{S-Cl (American standard code for Information I,lte-rchange) value for
each character of the character set. For exCmpte:
A-Z ASCII value (65-90)
a-z ASCII value (97-t2Z)
0-9 ASCII value (48-57)
ASCII value (59)
Types of Character Constant
i) String Constant: A string constant has a zero, one or more than one
character. A string constant is enclosed within double quotes (""). Atthe
end of string \0 is automatically placed. For example:

"Panil" and "593"

ii) Symbolic Constant: If we want to use certain unique constants several


times then we can use symbolic constant. A symbolic constant is a name
that substitutes for a sequence of characters. The character may represent
a numeric constant, a character constant or a string constant'

This is generally written at the beginning of the program. This is written as -


#define name value. Here name is the symbolic name, this can be written in
Jppercase letters. Value can be numeric, character or string constant.

Some examples of symbolic constant are as:


#define MAX 100
#define Pl 3.14
#define CH 'y'
#define NAME 'T{EMANT"

iii) Backstash Character Constants [Escape Sequences]: Backslash


character constants are special characters used in output functions.
Although they contain two characters they represent only one character.
Given below is the table of es( uence and their meanings:
escape sequence
Constant Meanine
\a Audible Bell
\b Backspace
u Form feed
\n New Line
\r Carriase Return
\t Horizontal Tab
Vertical Tab
\0 Null

1.2.7. Data Types


A data fype is an interpretation applied to a string of'bits'

Forrnally, data type is definbd as a finite set Qi values alongwith well-defined set
of rules for operations that cah be performed bn these values'
C supports different types oi data. Storage representations of these data types are
also different in memory.

Types of Data TYPes


rhere are four fundamental data types in c, which are as follows:
1) int: It is used to store the integer value.
2) char: It is used to store any single character.
3) flo*t: It is used for storing decimal numbers.
4) double: It is used for storing long range of decimal numbers'
Size and range of some data types are given below:
Data Tvoes Size (bytes) Range
char or signed char I -128 to 127
unsigned char 1 0 to 255
int or siqned int 2 -32,768 to 32,767
unsigned int 2 0 to 65535
short int or sisned short int I -I28 to 127
unsigned short int I 0 to 255
long int or signed lons int 4 -2,147,483,648 to 2,147,483,U7
unsisned lons int 4 0 to 4,294,967,295
float 4 3.48-38 to 3.4E+38
double 8 l.7E-308 to 1.7E+308
lone double 10 3.484932to l.lB+4932
1) Type: int
Size: System dependent. Usually eirher 2or 4 bytes. t
Description: A (positive or negative) integer. Integers are whole numbers
with a range of values, which are machine dependent. Generally an integer
occupies 2 bytes memory space and its value range limited to -3276g to
+32768 (i.e., -215 to +215-1). A signed integer use one bit for storing sign
and rest 15 bits for number.

To control the range of numbers and storage space, c has three classes of
integer storage namely short int, int and long int. All three data types have
signed and unsigned forms. A short int requires half the amount of storage
than normal integer. unlike signed integer, unsigned integers are always
positive and use all the bits for the magnitude of the number. Therefore the
range of an unsigned integer will be from 0 to 65535. The long integers are
used to declare a longer range of values and it occupies 4 bytes of storage
space.

For Example: 5, 6, 100, 2500.

Syntax: int <variable name>;."


Examples of int V.griable Declaratioiis

short int num2;


Iong int num3;

2) Type: char
Size: I byte.
Description: A (positive or negative) integer. Usually represents a character
according to a character code (e.g., ASCII). Character type variable can hold
a single character. As there are signed and unsigned int (either short or long),
in the same way there are signed and unsigned chars; both occupy I byte
each, but having different ranges. Unsigned characters have values between
0
and255, signed characters have values from -128 to 127 '
Syntax: char <variable name>;

ForExamPle: a, b, g, S, j.
Examples of char Variable Declaration
char cFirst;
char csecond, cThird;
char ch = 'a';

3) Type: float
Size: System dependent; Often 4 bytes.

Description: A (positive or negative).s1ngfe;precision floating point number'


The float data type is used to siore rr;aionit numbers (redl numbers) with 6
digits of precisi&. Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is insufficient, we can use
the double to define the number.

Syntax: float <variable name>;


For ExamPlez 9.125, 3.t254.
Examples of float Variabte Declarations
float numl;
4) Type: double
Size: System dependent; Often 8 bytes'

Description: A (positive negative) double-precision floating point


or
numbei. double is used to define big floating point numbers. It reserves twice
the storage for the number. on PCs this is likely to be 8 bytes. The double is
(8 bytes) than
same as float but with longer precision and takes double space
float. To extend the precision further we can use long double which occupies
10 bytes of memory space.

Examples of double Variable Declarations


double dFirst ,. i
double dSecond. dThird;

l*Program b illustrate various data type in C


*/
Program 2z

#includecstdio.h>
/* main function */
int mainQ
{
/* declare and initialized variables */
int p = 2000; /* positive integer datatype
*l
short int q'-120; /* variation */
unsigned short int r= l2l; /* variation */
float s = 21.566578; /* float data type */
char t= 'r'; /* chat datatype *l
long u = 5678; /* long positive integer data type */
unsigned long v = 5678; /x variation */
long w = -5678; l* -.ve long integer datatype */
int x = -l7I; l* -ve integer data type x/
short Y = 17; le Short -ve integer data type */
unsigned short z = 99', /* variation x/
double a = 88.12345; /* double float data type*/
float b = -3.245823; /* float dataYpe *l
char Title[50] = "The Making of the Casino Royale";
pnntf( "\t--Data type again--\n" ) ;
printf("\t-------------------\n" ) ;
printf("\nl. \"int\" sample: \t\t 7od, the data size: Vodbytes", p, sizeof(p));
printf("\n2. \"short\" int sample: \t Vod, the data size: Vod bytes',, q,
sizeof(q));
printf("\n3. \"unsigned short int\" sample: Vod, the data size: Vod bytes,,, t,
sizeof(r)):
printf("\n4. \"float\" sample: \t\t7o.7f, the data size: Vodbytes", s, sizeof(s));
printf("\nS. \"char\" sample: \t\t%oc, the data size: Vodbyte", t, sizeof(t));
printf("\n6. \"long\" sample: \t\t 7od, the data size: Vodbytes", u, sizeof(u));
printf("\n7. \"unsigned long\" sample: \t vod, the data size: Tod bytes", v,
sizeof(v)):
printf("\nS. negative \"long\" sample: \t Vod, the data size: Tod bytes", w,
sizeof(w));
printf("\n9. negative \"int\" sample: \t vod, the data size: vod bytes", x,
sizeof(x));
printf("\r110. negative \"short\" sample: \t vod, the data size: vorl-bytes", y,
sizeof(y)):
printf("\nl1. unsigned \"short\" sample: \t vad, the data size: vod bytes", z,
sizeof(z));
printf("\n12. \"rlodbJe\" sample: \t\t To.4f, the data size: Vod bytes,,, a,

printf("\n13. negative \"float\" sample: \t Vo.Sf, the data size: ?od bytes", b,
sizeof(bl):
printf("\n14. The NULL terminated string data size: vod bytes\n",
sizeof(Title));
return 0;
Output

1.2.8. Comments \: '

Comments are also statements which are used for understanding the program'
The comments are used for documentation. Comments are given by starting with
/* and ending with */. It can be of one or many number of lines'

For Example
1) Single Line Comment: /* THIS IS C PROGRAM *l
2) Multiple Line Comment
l*
F3;
b=a*cl
c=alb:'
*l

An operator is a symbol that tells the processor to perform certain mathematical


or lolical manipulations Operators are uied in programs to manipulate data and
variables. The data itselfis called 'operand'.

Operators thus operate on operands. C is extremely rich in operators. It


has about
4i different operators. They usually form a part of mathematical or logical series
called expressions.

1.3.1. Types of OPerators


Depending on lt functions performed, the C operators can be classified into
a
"
number of categories. They include:
1.3.2. ArithmeticOperators
These operators generally include arithmetic operands.

These include:
+ addition
subtraction
* multiplication
division
Vo modulus (remainder)

Each of these operators can work with ints, floats or chars values.

For example, the expression


n%o 4

gives the remainder when n is divided by 4. The usual precedence of operators


applies. Thus + and - have the same precedence. x, I and vo have the same
precedence. The precedence of *, I and 7o is higher than that of+ and -.
when two or more (of the above) operators of the same precedence appear in an
expression, they are evaluated from left to right. We say they associate from left
to right. Thus a/ b * c is evaluated as (a/ b) i c. As usual, thi order of evaluation
can be changed by using parentheses. For example, in expression a / (b * c), first
b*c is calculated and then a is divided by the result of b*c.

Program 3: /*Use of arithmetic operato;s*/


#rnclude<stdio.h>
#include<conio.h> i.

int main0
t,
l.
inta=3,b=4;
clrscr0;
printf("Initially: a = 3, b = 4\n");
printf("\na 4= S a = a + b = 7od\n", a+=b);
-; =
printf("a last value %od\n",a);
printf("\na *- b a = a * b = 7od\n", a*=b);
->= Vod\n",a);
printf("a last value
printf("\na -= | a = a -b = 7od\n", a-=b);
printf("a last value = 7od\n",a);
pt'intf("\na./=b a= a lb = 7od\n" , a/=b);
-> = %od\n", a);
printf("a last value
l) = %od\n", a:(b+l));
printf("a last value = Vod\n", a);
getch0;
return (0);

L.3.3. RelationalOPerators
The operands for relational operators are variables, constants or expressrons.
Characters are also represented internally as integers (by their ASCII codes),
elements to be compared can be characters as well. Relational operators
in C
include:
eoual to
t- not equal to
sreater than
less than
less than or equal to
sreater than or equal to
For Example
num==a
"';
ch!='C' -,
sum<=(x+y) I

These operators are used for cbmparing quantities. = = and != have the same
precedence which is lower than the (identical) precedence of the others'
bperators of equal precedence associate from left to right'

program 4: /* Program to demonstrate the use of relational operators*/


finclude<stdio.h>
#include<conio.h>
main0
int p, q, r;
clrscr0;
printf("Enter all the 3 number\n");
scanf("VodVodVod", &p, &q, &r);
if(p>q)
{
if(p>r)
t
printf("Largest number is 7od\n", p);
i
else
{
printf("Largest number is 7ad \n", r);
)
)
else
t
if(>q)
{
printf("Largest number is 7od\n", r);
)
else
{
printf("Largest number is Zod\n", q);
)
)
gerchO:
return (0); )

Output

1.3.4. Logical Op6raters


Byusing a logical operator an expression evaluates to either true (non-zero value)
or false (0).
These include:
&& Ioeical and
I logical or
logical not
The && operator is used when there is a need to evaluate two expressions. The
&& operator returns truth if both the expressions turn to truth.
(expression 1) && (exPression 2)

Now when there is a need to trigger a code with the truth of any of the two
expressions in question then we have ll operator.
(expression 1) ll (exPression2)

The compound expression formed by using relational and logical operators


evaluates to either true or false.

The following table shows the result of combined expression of both logical
operators viz. && andll:
Combined of && and
Operands Results
Expression I Exnression 2 && il
0 0 0 0
0 Non-zero 0 Non-zero
Non-zero 0 0 Non-zero
Non-zero Non-zero Non-zero Non-zero

For Example: (ch r='a') && (ch .='z')


! (n < 1 ll n > 12) equivalent to (n >= 1 && n <= 12)

These operators follow a precedence like '!' has higher precedence than &&
which has higher precedence than ll. The operators && and ll associate from left
to right, and the evaluation of the expression stops as soon as its truth-value is
determined. Parentheses can be used to force a particular order of evaluation.

Program 5: /tProgram to demonstrate the use of logical operators*/


#include<stdio.h>
#include<conio.h>
void main()
{
char ch='d';
if((ch >='a') && (ctr.<='g'1;r
' .

for(ch='a'; ch<='di ch++)


pintf("Voc ", ch);
)

Output
L.3.5. AssignmentOperators
Assignment operator takes the form as,
variable = expression

The basic assignment operator is =. This is used to assign the value of an


expression to a variable, as in
c=a+b
Multiple assignments are also possible, for example, consider the following
expression:
a=b=C= 13

The operator '=' associates from right to left, so the above is equivalent to
a=(b=(c=13))

1,.3.6. Unary Operator


A unary operator is an operator that requires only one operand. For example, ++,
the increment operator, - -, the decrement operator and . !,, logical negator.

The use of these operators results in incrementing or decrementing the value of


the variable by 1. So, the expression a++ increments value in 'a' by l, and tse
expression a- - decrements it by 1.

These operators can be used either before or after their operand, i.e., in either
'prefix' or 'postfix' position, so we can have a++ (postfix) as well as ++d
(prefix).
Prefix and postfix operators have same effect if they are used in an isolated C
statement. For example, the effect of the following two statements would be
same:
a++;
++a;

However, prefix and postfix operators."have different effects when used in


association with some other operator in. a c statement. For example, if we
assume the value of the variable 'a' to be 5, ttren execution of the statement

b= **al
will first increase the value of 'a' to 6 and then assign that new value to 'b'. The
effect is exactly same as if the following two statements have been executed:
a=a+ l;
b=ai
On the other hand, execution of the statement
b = a**l
set the value of 'b' to 5 and then increase the value of 'a' to 6. The effect
will first
now is same as if the following two statements had been executed:
b=ai
a=a+ 1;

Program 6: /*Program to show the effect of increment operator as a


postfix*/
#include<stdio.h>
#include<conio.h>
void mainQ
{
int'a,z,x=10,Y=20;
clrscr0;
z = x*y++;
a=x*yi
printf("\nThe value of z and a are Vod Vod" , z, a);
getch0;
return (0);
)

Output

Explanation: In the above Program the equation z = xt.y++ gives the result 200
because 'y' does not gets,increased' After multiplication 'y' increases to 11. The
second equation gives result 210.

1.3.7. Conditional OPerator


A ternary operator pait "?:" is available in C to construct conditional expressions
of the form:
expl ? exp2 : exP3 ;:
.i

Where, exp1, exp2, and exp3 are conditional expressions'

The operator ? : works as follows:


expl isevaluated first. If it is non-zero (true), then the expression exp2 IS
evaluated and becomes the value of the expression. If expl is false, exp3 is
evaluated and its value becomes the value of the expression'

Note: Only one ofthe expressions (eitherexp2 orexp3) is evaluated'


Program 7: /*illustrating conditional operator*/

#include<stdio.h>
#include<conio.h>
void main0
{
int a, b;
clrscr0;
a=10;
b=15;
printf("Greater no is VodV, (a > b) ? a:b);
getch0;
return (0);
)

Output

Note: This program is to check greater no between two numbers without


statement.
using if

1.3.8. Bitwise Operators


c of supporting special operators known as bitwise operators
has a distinction
for manipulation of data at bit level. These operators are used for testing
the bits,
or slufting them right gr left. Bitwise operators may not be applied,to float
or
double. Table lists the bitwise operators and their meanings.

TabIe: Bitwise
Operator Meaning
& bitwise AND
bitwise OR
bitwise exclusive OR
shift left
shift rieht

l) Bitwise AND: This operator gives the net result one if bits of both the
operand have the valu'e one, otherwise zero.
Boolean Table: Bitwise AND
Bit I Bit2 Result
0 0 0
0 I 0
I 0 0
I I
For Example
x=5 00000101
Y=9 00001001
x&y 00000001
-1
2) Bitwise OR: This operator gives the net result 0 if both the operands have the
value 0 otherwise 1.
Boolean Table: Bitwise OR
Bit 1 Bir2 Result
0 0 0
0 I 1

I 0 I
1 I

For ExamPle
x=5 00000101
Y=9 00001001
x Iy 00001101
=13

3) Bitwise XOR: This operator gives the net result 1 if both the operands have
different values
"tT:;:rabre:
Bitwise XoR
Bit 1 Bit2 Result
0 0 0
0 I I
1 0 I
I I 0

For Example
x=5 00000101 d
Y=9 00001001 ft
x ^ y 00001101
=13 '

4) Bitwise Left Shifti This operator'is used for shifting the bits left' This
operator has two operands. Left shift indicates which bits are to be shifted.

For ExamPle
x=13 00001101
x<<6 01000000
-128
Y=9 00001001
y<<3 01001000
=136
5) Bitwise Right Shift: This operator is used for shifting the bits right. This
operator has two operands. Left shift indicates which bits are to be shifted.
Right operand indicates the number of bits to be shifted.

For Example
x=213 11010101
x>>4 00001101
-6
y=148 10010100
y>>6 00000010
_,,

Program 8: To illustrate the bitwise operator.


#include<stdio.h>
#include<conio.h>
int main0
{
printf("7ox\n", -I <<3) ;
getch0;
return (0);
)

Program 9: To illustrate the bitwise operator.


#include<stdio.h>
#include<conio.h>
int mainQ
{-
printf(" 7ox\n", - 1 >> 1 );
getch()l

Outnut
{--
s c:,,usemhn,",",*'n',.g."=ii*ftf.l-; l*-** t{ ---
1.3.9. Special OPerators
Comma bperator: The comma operator can be used to link the
related
1)
cxpressit-rns together. A comma-linked List of expressions
are evaluated left
to right and the value of right-most expression is the value of the
combined
expression. For example, the statement
value = (x = 10, y = 5, x+Y);
15 (i'e"
first assigns the value 10 to x, then assigns 5 to y, and finally assigns
precedence of all
10 + 5)L value. Since comma operator has the lowest
operators, the parentheses are necessary'
when used with
2)
' sizeof operator: The sizeof is a compile time operator and,
occupies. The operand
u, op".uird, it returns the number of bytes the operand
may be a variable' a constant or a data type qualifier'
For ExamPle
m = sizeof(sum);
n = sizeof(longint);
k = sizeof(235l);
The sizeof operator is normally used to determine the lengths of
arrays and
structures when their sizes are not known to the programmer. It is also used
to allocate memory space dynamically to variables during execution of a
program
Programl0:/*Programtoillustratetheusesizeofoperator*/
#include<stdio.h>
#include<conio.h>
main0
t
int x;
unsigned int i;
i=sizeof(x);
printf("The value of i is 7ou\n", i);
getchQ;
return (0);
)

optp;{- ,,,:.
ii i.:. ,.
, a: .,r".,.i,'.ire:.-
iUser:1.3rr'.'e:_' Desktnplt&he{.. ' t

Explanation: Here value of i is compiler dependent'

L.3"10. Precedence and Associativity

same precedence are evaluated in an expression'


used in an expression.

evaluates the expression by starting on the left and ,roui"rrg to the rijlit
whereas the right-to-left associativity evaluates the expressionly starting
on
the right and moving ro the left.

expressions are evaluated. Associativity is applied later, if necessary.


The tables 1.3 show the order in which operators are evaluated:
Table L.3: Precedence and Associa Table
Description Operator Associativitv
Function expression Left to Rishr
Array Expression Left to Risht
Structure operator Left to Ripht
Structure operator Left to Risht
Unary minus Right to Left
Increment/Decrement ++- zusht ro Left
One's compliment Rieht to Left
Negation I
Risht to Left
Address of & Risht to Left
Value of address * Risht to Left
Iype cast .tvpe) Risht to Left
Size in bytes sizeof Risht to Lefr
Multiplication Left to Rishr
Division Left to Rishr
Modulus Vo Lefr to Risht
Addition + Left ro Risht
Subtraction Left to Risht
Left shift Left to Risht
Risht shift Left to Rishr
Less than
Left to fusht
Less than or equal to <= Left to Risht
ureater than t-eft to Risht
Greater than or equal to >= Left to Risht
Equal to Left to Rishl
Not equal to != Left to Rieht
ultwrse ANI) & Left to Rishr
Bitwise exclusive OR Left to Rieht
Bitwise inclusive OR I Left to Rishr
Logical AND && Left to Risht
Logical OR il Left to Risht
Conditional ?: Rishr ro Lefr
Assignment Risht to Left
*- Right to trft
l=
Vo=
Right to Left
-=
ft=
Right to Left
l=
<<= Right to Left
>>=
Comma
Risht to Left
An expression is a combination o{ constants, variabies and operators arranged as
per syntax (grammar) of the language.

Types of Expressions
nu.n typ" of^expression takes certain types of operands and uses a specific set of
op"rutoi.. Evaluation of every expression produces a value of specific type.
Eipressions are not statements, but may be components of statements'

1) Arithmetic Expressions: An arithmetic expression is made-up of operands


and arithmetic operators. It produces a value that is of type int, float or
double. When an expression involve only integral operands, it is known as
pure integer expression, when it involves only real operands it is known as a
por" r"ul-"*pression, and when it involves both integral and real operands it is
known as a mixed mode exPression.

Parentheses can be used to control associativity and the order in


which
operators are evaluated. If parentheses are present in an expression, then
the
parentheses
expression within the parentheses is evaluated first and rvithin the
the implicit precedence is observed. If there is nesting of parentheses
linside parentheses), then the innermost parentheses are
lparentireses
evaluated first.

Evaluation of Arithmetic Expressions: As you know expressions are


evaluated by performing one operation at a time, and same is the case
when
expressions are evaluited by a computer. The order of evaluation
of
individual operations is governed by the precedence and associativity of
operators.

2) Relational Expressions:, Relational expressions compare the values of


two operands. ilelational expression is used to test a condition in order
to decide whether an action should be taken or not. In relational
e*pr"ssiorr, an d,rithmetic value should not be compared with a string
.ruiu". The result of a relational expression is either zero or non-zero.
zero to a
Here, non-zero value is equivalent to a Boolean value true and
Boolean value false.

For
x%o2=O Used to test whether the operand r is an even
number or not. The relational expression results in
value 1 ifx is even otherwise results in value 0'
3) Logical Expressions: A logical expression also produces a zero or non-zero
value. A logical expression is used to form a complex test condition in order
to take a decision.

For example,
(x>2)&&(xVo2=O) Used to form a test condition to check
whether the operand x is greater than 2 and x
is even (divisible by 2).T}.te resulr of this test
condition will be I only if both the
conditions hold true simultaneous

4) Conditional Bxpressions: Note that the conditional expression is indeed an


expression. A conditional expression looks like

expl ? exp2: exp3


where expl is a simple or compound condition; exp2 and exp3 are any other
kind ofexpressions. The final value ofthis conditional expresiion depends on
the outcome of condition represented by expl. If condition expl evaluates
zero (true), then value of the condition expressional will be as represented by
exp2 otherwise as represented by exp3.

l) Write the basic properties of C language.


2) Discuss the advantages and disadvantages of C language.
3) Explain the basic structure of C Programming.
4) Write a note on following:
i) Character set
ii) Variable
iii) Constant and literals
iv)Comment
5) What is data type? Explain its various types.
6) Explain arithmetic operators with a suitable program.
7) Defi ne conditional operator.
8) Explain the special operarors with suitable example.
e) What is precedence and associativity?
10) What is expression? Explain its various types.

You might also like