0% found this document useful (0 votes)
264 views

Chapter-1-Basic of C Language

C Programming for Diploma Degree and BSCIT Students

Uploaded by

Manoj Kavedia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
264 views

Chapter-1-Basic of C Language

C Programming for Diploma Degree and BSCIT Students

Uploaded by

Manoj Kavedia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

BASIC OF C

History of C
- Where C stands
- C Character set ,Tokens ,Constant ,Variables and Keywords
- C operators(Arithmetic , Logical , Relational, Assignment, Increment
and Decrement ,Conditional , Bitwise ,Special Operator ,Precedence ,
C expression , Data Types ,
- Formatted Input and Output

Introduction
C is a programming language is most popular computer language
today because it is a structured high level machine independent
language. Programmers need not worry about the hardware platform
where they will be implemented

C is general purpose, structured programming language. C is


flexible, high level programming language. It includes certain low-level
features that are available in machine language. C is also referred to as a
middle level language. It is a bridge between low level language and
high level language. It is very compact language with few keywords.
Commercial C compilers are available for PC, Mini & Mainframe.

It is robust language whose rich set of built – in functions and


operators can be used to write any complex programs. The C compiler
combines the capability of and assembly language with the feature of the
High level language. And therefore suited for writing both system
software and business package. In fact many of the C compiler available
in the market are written in C.

There are 32 key words and its strength lies in its built in
functions. Several standard functions are available which can be used for
development of the programs.

C is highly portable, i.e. programs written in C are easily portable


from one computer to another with little or no modifications. It has
relatively small instructions set actual implementation can include
extensive library function.

C language is well suited for structured programming, thus


requiring the user to think of a problem in terms of function, modules or
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 1
blocks. A proper collection of these modules would make complete
program. This modular structure makes programs debugging, testing
and maintenance easier .C programs are basically collections of
functions that are supported by the C library .We also can continuously
add our own functions to the C library.

High-level language program written in C will not be understood by


comp‘s. Since comp understands only machine language i.e. programs
written in 0‘s & 1‘s.

Definitions
Compiler is software program, which converts high-level language
program into m/c language programs. Compilers are compact & they
generate object program that are very small & highly efficient After
compiling the program is linked and the final product is Executable
Object code i.e. Exe file. Hence when C program is written, compiled and
linked the different files generated are .C, .Bak, .Obj and .Exe.

About C language
C is a programming language was originally developed in 1972 by
Dennis. Ritchie at AT&T Bell Labs USA. C is developed from the
successor BCPL (Basic Combined Programming Language) also called as
B language. Developed in the 1960‘s at Cambridge University B was
modified by Dennis Ritchie and was implemented at Bell Laboratories in
1972.

C was largely confined to used within lab until 1978. When


Kernignam and Ritchie published a description of language this is
referred to as K&R C.

Computers professionals were impressed with C‘s features by


1980‘s popularity of C had become wide spread American National
Standard Institute (ANSI) has Standardized definition of C language.

History of C language
By 1960 a board of computer languages had come into existence,
almost each for a specific purpose. For example, COBOL was being used
for Commercial Applications, FORTRAN for Engineering and Scientific
Applications and so on. At this stage people started thinking that instead
of learning and using so many languages, each for a different purpose,
why not use only one language which can program all possible
applications.
Therefore, an international committee was set up to develop such a
language. This committee came out with a language called ALGOL 60.
However, ALGOL 60 never really became popular because it seemed too
abstract, too general. To reduce this abstractness and generality, a new
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 2
language called Combined Programming Language (CPL) was developed
at Cambridge University. CPL was an attempt to bring ALGOL 60 down
to earth. However, CPL turned out to be so big, having so many features,
that it was hard to learn and difficult to implement.

Basic Combined Programming Language (BCPL), developed by


Martin Richards at Cambridge University aimed to solve this problem by
bringing CPL down to its basic good features. But unfortunately it
turned out to be too less powerful and too specific. Around same time a
language called B was written by Ken Thompson at AT & T's Bell Labs,
as a further simplification of CPL.

But like BCPL, B too turned out to be very specific. Ritchie


inherited the features of B and BCPL, added some of his own and
developed C. Ritchie's main achievement is the restoration of the lost
generality in BCPL and B, and still keeping it powerful.

C 's compactness and coherence is mainly due to the fact that it's
a one-man language. Other examples of one-man languages are LISP,
PASCAL and APL. Counter examples include many headed monsters
like PL/l, ALGOL 60 and ADA. Figure shows the various stages in
evolution of C language.

As a programming language, C is rather like Pascal or Fortran..


Values are stored in variables. Programs are structured by defining and
calling functions. Program flow is controlled using loops, if statements
and function calls. Input and output can be directed to the terminal or
to files. Related data can be stored together in arrays or structures.

Of the three languages, C allows the most precise control of input


and output. C is also rather more terse than Fortran or Pascal. This can
result in short efficient programs, where the programmer has made wise
use of C's range of powerful operators. It also allows the programmer to
produce programs which are impossible to understand.

Programmers who are familiar with the use of pointers (or indirect
addressing, to use the correct term) will welcome the ease of use
compared with some other languages. Undisciplined use of pointers can
lead to errors which are very hard to trace. This course only deals with
the simplest applications of pointers.

It is hoped that newcomers will find C a useful and friendly


language. Care must be taken in using C. Many of the extra facilities
which it offers can lead to extra types of programming error. You will
have to learn to deal with these to successfully make the transition to
being a C programmer.
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 3
Where C Stands
Let us now see how does C compare with other programming
languages. All the programming languages can be divided into two
categories:

Problem oriented languages or High level languages


These languages have been designed to give a better programming
efficiency, i.e. faster program development.
Examples of languages falling in this category are FORTRAN, BASIC,
PASCAL etc.

Machine oriented languages or Low level languages


These languages have been designed to give a better machine
efficiency, i.e. faster program execution. Examples of languages falling in
this category are Assembly language and Machine language. C stands
in between these two categories. That's why it is often called a Middle
level language, since it was designed to have both a relative good
programming efficiency (as compared to machine oriented language) and
a relative good machine efficiency (as compared to machine oriented
languages)

Common C
Until recently there was one dominant form of the C language. This
was the native UNIX form, which for historical reasons is known as
either Bell Labs C, after the most popular compiler, or K. &R. C, after the
authors of the most popular textbook on the language. It is now often
called "Classic C"

ANSI C
The American National Standards Institute defined a standard for
C, eliminating much uncertainty about the exact syntax of the language.
This newcomer, called ANSI C, proclaims itself the standard version of
the language. As such it will inevitably overtake, and eventually replace
common C.

ANSI C does incorporate a few improvements over the old common


C. The main difference is in the grammar of the language. The form of
function declarations has been changed making them rather more like
Pascal procedures.

This course introduces ANSI C since it is supported by the SUN


workstation compilers. Most C programming texts are now available in
ANSI editions.

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 4


Fact About
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around 1970
 The language was formalized in 1988 by the American National
Standard Institute (ANSI).
 By 1973 UNIX OS almost totally written in C.
 Today C is the most widely used System Programming Language.
 Most of the state of the art software have been implemented using
C
 Some example of the use of C might be
o Operating Systems
o Language Compilers
o Assemblers
o Text Editors
o Print Spoolers
o Network Drivers
o Modern Programs
o Data Bases
o Language Interpreters
o Utilities

Different Programming Language

Language Year Inventor Application


FORTRAN 1954-57 John Backus, IBM Numerical processing
ALGOL 60 1958-60 Committee Numerical processing
COBOL 1959-60 Committee Business Data Processing
APL 1956-60 K. Iverson Array Processing
LISP 1956-62 John McCarthy Symbolic Computation
SNOBOL 1962-66 R. Griswold String processing
PL/I 1963-64 IBM General purpose
SIMULA 67 1967 O.J. Dahl General purpose
ALGOL 68 1963-68 Committee General purpose
BLISS 1971 Wulf et. al. System Programming
PASCAL 1971 Niklaus Wirth General and Education
C 1974 Dennis Ritchie System Programming
MESA 1974 Xerox PARC System Programming
CONCURRENT 1975 P. Brinch Concurrent Programming
CLU 1974-77 B. Liskov Abstraction Methodology
EUCLID 1977 Committee Verifiable System Programs
GYPSY 1977 Good et. al. Verifiable System Programs

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 5


PLZ 1977 Zilog inc. System Programming
MODULA 1977 Niklaus Wirth System Programming
ADA 1979 J. Ichbiah General and Embedded
C++ 1983 Bjarne Stroustrup Object Oriented Prog.
JAVA 1991 James Gosling OOP + Embedded + N/W

About ‘C’ program


Every c program consist of one or more function, one of which
must be called main The program always begin by executing main
function additional function definition may proceed or followed.

Each function must contain


1. Function Heading
Which consists of function name, followed by optional list of argument
enclosed in parenthesis.

2. A list of arguments declaration.


If argument are included in heading.

3. Compound statement
which comprises remainder of function. Arguments are symbols that
represents information being passed between function & other part of
program (argue are also referred to as parameters)

Each compound statement is enclosed within a pair of braces i.e. {


& } .The braces may contain combination of expression statement &
other compound statement. Each expression state must end with
semicolon (;).

Comments may appear anywhere within the program as long as


they are placed within the delimiters that is /* & */ Comments are
helpful in identifying programs principle feature or in explaining the logic
of various programming features.

Each instruction in a function is written as separate instruction.


These statements must appear in the same order in which we wish them
to be executed. Unless the login of the program demands a deliberate
‗jump‘ or transfers of the control to a statement, which is out of
sequence.

Structure of C program
Documentation Section
Link Section
Definition Section
Global declaration Section
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 6
main() function section
{
Local Declaration Section
Executable Section
}

sub-program Section
function1
{
Statements
}
function2
{
Statements
}
function3
{
Statements
}

Documentation Section
The documentation section consists of a set of comment lines
giving the name of the program, the author and other details such as a
short description of the purpose of the program.

Link Section
The link section provides instructions to the compiler to link
functions from the system library.

Definition Section
The definition section defines all the symbolic constants. The
variables can be declared inside the main function or before the main
function.

Global Section
Declaring the variables before the main function makes the
variables accessible to all the functions in a C language program, such
variables are called Global Variables.

Local Section
Declaring the variables within main function makes the usage of
the variables confined to the main function only and it is not accessible
outside the main function.

Main Function

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 7


Every C program must have one main function. Enclosed in the
main function is the declaration and executable parts.

Declaration Part
In the declaration part we have all the variables.

Executable Part
There is at least one statement in the executable part.

The two parts must appear between the opening and closing braces

Sub Program Section


The sub-program section contains all the user-defined functions that
are called in the main function.

User Defined Function


User-defined functions are generally placed immediately after the main
function although they may appear in any order.

Some Rules to be followed while writing C program


 Comment lines can be included in the program by including them
between /* */ .It can be one line or multiple lines. For single line //
can also be included in front of statement.
 All C statements are terminated by semicolon (;)
 Blank spaces can be inserted between two words to improve the
readability of the statement. However No blank spaces are allowed
within the words.
 C has no specific rules about the position at which different parts of a
statement are to be written .Not only can a C statement be written
anywhere in a line, it can also be split over multiple lines. That is why
it is many a time called a free form language.

Executing a C Program
The following basic steps is carried out in executing a C Program.
 Type the C language program.
 Store the program by giving a suitable name and following it with
an extension .c
 Compile the program
 Debug the errors if any, that is displayed during compile.
 Run the program.

Simple C Program that Reads in Perimeter and Areas of Rectangle


Calculate it’s Area & Then Writes Calculated Results

/* Calculation Of Area And Perimeter Of The Rectangle */

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 8


# include <stdio.h> /*library file access*/
void main( )
{
float length, width , area , perimeter ; /*variable declaration*/
printf(― Length = ‖); /*output statement or message*/
scanf(―%f ‖ ,&length ); /*input statement */
printf(― Width = ‖); /*output statement or message*/
scanf(―%f ‖ ,&width ); /*input statement */
area = length * width ; /*assignment statement*/
perimeter = 2 * ( length + width)
printf( ― Area = %f and Perimeter = %f ― ,area, perimeter ); /*output
statement*/
} /*end of main*/

Comments are added to increase program readability.

First line specifies purpose of program.

Second line refers to file <stdio.h>, which contains information that


must be included in program when it is compiled.

Third Line contains heading for function main empty parenthesis


following name of function indicates that this function does not include
any argue remaining lines are intended & enclosed within a pair of
braces This line comprises compound statement within the main.

With in main()

First line in brace is a variable declaration. It indicates that length,


width, area and perimeter are floating point variables

Second line generates request for information &this information is


entered into computer.

Third statement i.e. scanf is input statement, which helps in reading


the input variable.

Fourth line generates request for information &this information is


entered into computer.

Fifth statement i.e. scanf is input statement which, helps in reading


the input variable.

Sixth and seventh statement is assignment statement, which evaluates


area and perimeter of rectangle.

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 9


Last statement displays (printf) calculated value area each expression
statement within the compound statement ends with semicolon (;).

Execution of program generates following output.


Length = 3
Width = 3
Area = 9.0000000 and perimeter = 18.000000.

What Comments Are Used For


1. documentation of variables and their usage
2. explaining difficult sections of code
3. describes the program, author, date, modification changes,
revisions etc
4. copyrighting

Some Important Program Characteristics


Some important characteristics for well-written computer program
are as given below.

1. Integrity: This refers to the accuracy of calculation thus integrity of


calculation is very necessary in any computer program.

2. Clarity: This refers to the readability of program if the program is


clearly written it should be possible for another programmer to follow
program logic easily.

3. Simplicity: Clarity & accuracy of program are enhanced by keeping


things as simple as possible.

4.Efficiency: This is concerned with the execution speed & efficient


memory utilization.

5.Modularity: Many programs can be broken down into a series of


subtask .It is a good programming practice to implement subtask as
separate program module. Such modules are written as function in C.
The use of modules programs design as enhance or increases accuracy &
clarity of program & it facilitates future program alterations.

6. Generality: Programs should be as general as program to accept


values of certain variables or parameter rather than placing fixed values
into the program.

Token in C language
The smallest individual units in a program are known as ―Tokens‖.
There are different types of tokens: -
1. Keywords
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 10
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Literals

C Character Set
A character denotes any alphabet, digit or special symbols used to
represent information .The character that can be used to form words
numbers and expressions depending upon the computer which the
program is executed. The character set of C are grouped into following
categories:
1. Letter (Alphabets )
2. Digits
3. Special Symbols
4. White Space

Character Set Symbols ASCII Value


Alphabets A,B,C,D,E…Y,Z 65,66,67-------90,91
a, b, c,……x, y, z 97,98,99-----120,121
Digits 0,1,2,3,4,5,6,7,8,9 48,49,50,51,52,53,54,
55,56,57
Special ~ ! @ # $%^&*()_
Symbols +=|.\<>?/‖ , ‘ :;
, `
White Space Blank space,
Horizontal tab,
carriage return,
New line,
Form feed

Identifiers
Identifiers are names given to the various program elements such
as variable function arrays, identifiers consist of letters & digits.
First character must be a letter both upper case & lower case letters are
allowed. Underscore character can be included & it is considered as to be
a letter.
Both uppercase and lowercase letters are permitted. The
underscore character is also permitted in identifiers.

Examples: Valid identifiers


x , y , z NAME, stud_no,Num1, Name_1, Day_of_Month ,x1etc.

Examples: Invalid identifiers


44th  1st is not letter.

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 11


―A B C ―  illegal char ( ― ) not allowed.
stud name  Blank space is not allowed .
Num+1  Operators are not allowed
First,Name Special Character not Allowed

An identifiers can be of any length some implementation of C


recognize first 8 characters some recognizes 31 characters. ANSI
standard recognizes 31 characters.

An identifier should contain enough characters so that its meaning


is readily apparent.

The identifiers must conform to the following rules.


1. First character must be an alphabet (or underscore)
2. Identifier names must consists of only letters, digits and
underscore.
3. A identifier name should have less than 31 characters.
4. Any standard C language keyword cannot be used as a variable
name.
5. A identifier should not contain a space.

C Keywords
Keywords are the words whose meaning is already known to the C
compiler .All the key words has fixed meaning and these meaning cannot
be changed. The keywords cannot be used as variable names. The
keywords are also called as Reserved Words. All the keywords must be
written in lower case. Only 32 keywords are available in C. Following
table shows the list of keywords. Programmer cannot use these keywords
as variable. Every word in C language is a keyword or an identifier

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

Data Types in C language


C language is very rich in DATA Types. Storage representation and
machine instruction to handle constants differ from machine to machine.
The variety of data types allows the programmer to select the type
appropriate to the needs of the application as well as the machine.
C supports four fundamental data types, namely

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 12


1. Character ( char )
2. Integer ( int )
3. Floating point ( float )
4. Double – precision – floating point ( double )

Integer(int)( %d)
These are whole numbers, both positive and negative. Unsigned
integers (positive values only) are supported. In addition, there are short
and long integers.
The keyword used to define integers is,

int
An example of an integer value is 32. An example of declaring an integer
variable called sum is,

int sum;
sum = 20;
Floating point(float)(%f)
The data type float stores a single precision floating point (real)
number.These are numbers which contain fractional parts, both positive
and negative. The keyword used to define float variables is,
float

An example of a float value is 34.12. An example of declaring a float


variable called money is,

float money;
money = 0.12;

Double(double)(%Lf)
The data type double can store floating-point value with a greater
exactness than a float. Hence it requires twice as much a storage space
as float does.These are exponential numbers, both positive and negative.
The keyword used to define double variables is,
double

An example of a double value is 3.0E2. An example of declaring a double


variable called big is,

double big;
big = 312E+7;

Character(char)(%c)
The data type char is used to store any character belonging to

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 13


the character set supported by C language.These are single characters.
The keyword used to define character variables is,
char

An example of a character value is the letter A. An example of declaring a


character variable called letter is,

char letter;
letter = 'A';

Note the assignment of the character A to the variable letter is done by


enclosing the value in single quotes. Remember the golden rule: Single
character - Use single quotes.

Type Size ( Bytes ) Range


CHARACTER DATA TYPE
Char or signed 1 -128 to 127
Char
Unsigned Char 1 0 - 255
INTEGER DATA TYPE
Int or short int 2 -32768 to 32767
or
Short signed int
Unsigned int or 2 0 – 65535
Unsigned short int
Signed long int 4 -2,147,483,648 to
2,147,483,647
Unsigned long int 4 0 to 4,294,967,295
FLOAT DATA TYPE
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 TO 1.7E308
Long double 10 3.4E-4932 to 1.1E +4932

Modifiers
The modifiers define the amount of storage allocated to the
variable. The amount of storage allocated is not cast in stone. To
override the default nature of a data type, C has provided us with data
type modifiers.
Some basic data types can be argumented by using data types,
modifiers, those modifiers are
1. Short
2. Long
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 14
These are further classified as
1. signed
2. unsigned, etc.

The signed Modifier


For integers, the leftmost bit can be used as the sign bit. For
instance, if the int data type is 16 bits long and the rightmost bit is
counted as bit 0, you can use bit 15 as a sign bit. When the sign bit is
set to 1, the C compiler knows that the value represented by the data
variable is negative.
There are several ways to represent a negative value of the float or
double data types. The C Programming Language for more details on the
implementations of negative values of the float or double type.
The C language provides a data modifier, signed, that can be used
to indicate to the compiler that the int or char data type uses the sign
bit. By default, the int data type is a signed quantity. But the ANSI
standard does not require the char data type be signed; it's up to the
compiler vendors. Therefore, if you want to use a signed character
variable, and make sure the compiler knows it, you can declare the
character variable like this:
signed char ch;
so that the compiler knows that the character variable ch is
signed, which means the variable can take a value in the range of -128
(that is, -27) to 127 (that is, 27-1).(Remember that for an unsigned
character variable, the range is 0 to 255; that is, 28-1.)

The unsigned Modifier


The C language also gives you the unsigned modifier, which can be
used to tell the C compiler that no sign bit is needed in the specified data
type.
Like the signed modifier, the unsigned modifier is meaningful only
to the int and char data types.

For instance, the declaration


unsigned int x;

tells the C compiler that the integer variable x can only assume positive
values from 0 to 65535 (that is, 216_1), if the int data type is 16 bits long.
In fact, unsigned int is equivalent to unsigned according to the
ANSI standard. In other words,

unsigned int x; is the same as unsigned x;.

Also, the ANSI standard allows you to indicate that a constant is of type
unsigned by suffixing u or U to the constant. For instance,
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 15
unsigned int x, y;
x = 12345U;
y = 0xABCDu;

Here, the unsigned integer constants 12345U and 0xABCDu are


assigned to variables x and y, respectively.

Modifiers for Changing Data Sizes


Sometimes, you want to reduce the memory taken by variables, or
you need to increase the storage space of certain data types. Fortunately,
the C language gives you the flexibility to modify sizes of data types.
There are two data modifiers,
short and long

The short Modifier


A data type can be modified to take less memory by using the short
modifier. For instance, you can apply the short modifier to an integer
variable that is 32 bits long, which might reduce the memory taken by
the variable to as little as 16 bits.You can use the short modifier like this:

Declaration
short x;
unsigned short y;
By default, a short int data type is a signed number. Therefore, in the
short x; statement, x is a signed variable of short integer.

The long Modifier


If you need more memory to keep values from a wider range, you
can use the long modifier to define a data type with increased storage
space. For instance, given an integer variable x that is 16 bits long, the
declaration
long int x;

increases the size of x to 32 bits. In other words, after the modification, x


is capable of holding a range of values from -2147483648 (that is, -231) to
2147483647 (that is, 231_1).
The ANSI standard allows you to indicate that a constant has type long
by suffixing l or L to the constant. For instance

long int x, y;
x = 123456789l;
y = 0xABCD1234L;

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 16


Here, the constants of the long int data type, 123456789l and
0xABCD1234L, are assigned to variables x and y, respectively.Also, you
can declare a long integer variable simply like this:

long x;
long int x;

Summary
Example: - integer modifier can be defined as
Short int,
Long int,
Unsigned short int
Unsigned long
1. Short int require less memory (2 bytes) than an ordinary int or
may take same as an int, if short int and int both have same
memory requirement.
2. Then long int will have double the requirement (4 byte) or if int and
long int have same memory requirement (2 bytes) such
specification will vary from one c compiler to another.
3. Unsigned int requires 2 bytes in ordinary int, leftmost bit indicate
sign of number but in unsigned int all bits are used to represent
numeric values. Int varies from -32768 to +32767 i.e (2-byte int) &
unsigned int varies from 0 to 65535. Unsigned modifier can be
applied to other qualified int. We declare long and unsigned integer
to increase the range of value.

Example: unsigned short int or unsigned long int.

Character type is used to represent individual characters each


character type has an equivalent int interpretation. So char is a special
kind of short int char data type will permit a range of values from 0 to
255 (char can be a signed char or unsigned char = -128 to 127). Some
compilers permit qualifier long to be applied to float or double.
Example: long float or long double. long float is equivalent to double.
Long double may be equivalent to double or it may refer to a separate
extra large.

Qualifier
A type qualifier is used to refine the declaration of a variable, a
function, and parameters, by specifying whether:
 The value of an object can be changed
 The value of an object must always be read from memory rather
than from a register
 More than one pointer can access a modifiable memory address
You can put more than one qualifier on a declaration: the compiler
ignores duplicate type qualifiers
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 17
Type qualifiers give one of two properties to an identifier. The
const type qualifier declares an object to be nonmodifiable. The volatile
type qualifier declares an item whose value can legitimately be changed
by something beyond the control of the program in which it appears,
such as a concurrently executing thread.
The two type qualifiers, const and volatile, can appear only once
in a declaration. Type qualifiers can appear with any type specifier;
however, they cannot appear after the first comma in a multiple item
declaration. For example, the following declarations are legal:
typedef volatile int VI;
const int ci;

These declarations are not legal:

Syntax
type-qualifier:

constvolatile

The following are legal const and volatile declarations:

int const *p_ci; /* Pointer to constant int */


int const (*p_ci); /* Pointer to constant int */
int *const cp_i; /* Constant pointer to int */
int (*const cp_i); /* Constant pointer to int */
int volatile vint; /* Volatile integer */

If the specification of an array type includes type qualifiers, the


element is qualified, not the array type. If the specification of the function
type includes qualifiers, the behavior is undefined. Neither volatile nor
const affects the range of values or arithmetic properties of the object.
This list describes how to use const and volatile.
 The const keyword can be used to modify any fundamental or
aggregate type, or a pointer to an object of any type, or a typedef.
If an item is declared with only the const type qualifier, its type is
taken to be const int. A const variable can be initialized or can be
placed in a read-only region of storage. The const keyword is
useful for declaring pointers to const since this requires the
function not to change the pointer in any way.
 The compiler assumes that, at any point in the program, a volatile
variable can be accessed by an unknown process that uses or

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 18


modifies its value. Therefore, regardless of the optimizations
specified on the command line, the code for each assignment to or
reference of a volatile variable must be generated even if it
appears to have no effect.
If volatile is used alone, int is assumed. The volatile type specifier
can be used to provide reliable access to special memory locations.
Use volatile with data objects that may be accessed or altered by
signal handlers, by concurrently executing programs, or by special
hardware such as memory-mapped I/O control registers. You can
declare a variable as volatile for its lifetime, or you can cast a
single reference to be volatile.
 An item can be both const and volatile, in which case the item
could not be legitimately modified by its own program, but could
be modified by some asynchronous process.
Variables and Arrays

Variable is an identifier that is used to represent some specific


type of information within a designated portion of program.
A variable represents a single data item i.e a numeric quantity or a
char constant. A data item must be assigned to the variable at some
point in the program. The data item can be accessed later in the program
by referring to the variable name. A variable can be assigned different
data items at various places within the program that is information
represented by variable can change during the execution of program
Example: - a, b, c.
This statement states that a, b, c are integer variables thus they will each
represent and integer valid quantity.

Array is another kind of variable that is used an array is an


identifier that refers to a collection of data items which all have the same
name and data items must be of same type.
Array is another kind of variable that is used an array is an
identifier that refers to a collection of data items which all have the same
name and data items must be of same type.

Declaration
Declaration associates a group of variables with a specific data
type all variables must be declared before they can appear in executable
statement.
Declaration consist of a data type followed by one or more variable
names ending with a semi-colon each array variable, must be followed by
a pair of square bracket containing a +ve which specifies the size of the
array.
Example: int a, b, c, z[10];

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 19


Thus a, b, c are declared to be int variables and z is an 10 element
int type array.
Example: int q=12;

Declares q is an int variable whose initial value is 12.

Rules For Constructing Variable Names


i} The variable name is any combination of 1 to 8 alphabets, digits or
underscores. Some compilers allow variable names upto 40
characters.
ii} The first character in the variable name must be an alphabet.
iii} No commas or blanks are allowed within a variable name.
iv} No special symbols other than an underscore can be used in variable
name.
v} A variable name cannot be a keyword of C language.

Expression
An expression represents a single data item. The expression may
consist of single entity such as constant, a variable, an array element or
reference to a function. It may consist of combination of such entities
inter connected by one or more operators
Example: - c = a + b here value of the expression a + b is assigned to the
variable c.

Statements
Statement causes the computer to carry out some action. There
are 3 different classes of statements in C. They are
a} Expression statement
b} Compound statement
c} Control statement.

Constants
C has basic four types of constants. They are
1} Integer constant,
2} Floating point Constant ,
3} Character constant and
4} String constant.
Integer and Floating point constant represents numbers. They are
referred to as numeric type constant.

Following rules apply to all numeric type constant.


01} Commas and blank spaces can not be included within constant.
02} Constant can be preceded by -(minus) sign.
03} Value of constant can not exceed specified minimum bounds or
limits.
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 20
Integer constant
Integer constant is an integer valid number. It consists of sequence
of digits. Integer constant can be written in three different number
systems: - Decimal, Octal, Hexa Decimal.

A decimal integer constant can consist of digits from 0 to


9,preceded by + or - sign. First digit should not be zero for constant
having two or more digits. Embedded spaces, commas, and non-digit
character are not permitted between digits.

Examples
 Valid decimal constants are - 0, 1, 99, -124, +454 etc.
 Invalid decimal constants are (12,12), 36.0, $45.45, 20,000 and
09,etc.

An octal constant can consist of digits from 0 to 7. First digit must


be zero in order to identify the constant as an octal number.

Example
 Valid octal integer are: -0, 01, 0777, etc.
 Invalid octal integer constants are: - 743,058,077.77.

A hexadecimal integer constant must begin with either 0x or 0x


then followed by digit from 0 to 9. And characters from a to f. A
represents decimal number 10

Example
 Valid hexadecimal integer constants are: - 0xabcd, etc.
 Invalid hexadecimal integer constants are: - 0x12.34, 0bcd, etc.

Unsigned and long integer constant

Unsigned integer constant may exceed magnitude of ordinary


integer constant. Unsigned integer constant can be identified by
appending letter u to end of the constant.
Long integer constant may exceed magnitude of ordinary integer
constant but require more memory in computer. Long integer constant
can be identified by appending letter l at the end of constant. Unsigned
long integer may be specified by appending ul to the end of the constant.

Example
0xffffful - hexadecimal unsigned long.
0x50000u - hexadecimal unsigned
0123456l - octal long
50000u - decimal unsigned.
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 21
Rules for constructing integer constant

i. An integer constant must have at least one digit


ii. It must not have a decimal point
iii. It could be either positive or negative
iv. If no sign precedes an integer constant it is assumed to be positive
v. No commas or blanks are allowed within integer constants
vi. The allowable range for integer constant is –32768 to 32767 and so
on for other integers.

Floating point constant (REAL)


It is base 10 number that contains either decimal point or exponent
or both.
Example
 Valid floating point constants are 0, 1, 0.2, 2e-8, 0-00e-3, 12.3,etc.
 Invalid floating point constants are 1,1,000.0,2e+5.5,3e 10,

If exponent is present and if positive its effect is to shift location of


decimal point to right and to left if it is -ve 1.2*10^-3 could be written as
1.2e-3 or 1.2e-3 or .12e-2 or 12e-4. Magnitude of floating point constant
might range from 3.4e-38 to 3.4e+38.
The exponential form of representation of real constants is usually
used if the value of the constant is either to small or too large .In real
form of representation, the real constant is represented in two parts. The
part appearing before ‗e‘ or ‗E‘ is called as Mantissa, whereas the part
following ‗e‘ or ‗E‘ is called as exponent.

Rules for constructing real constant

a. A real constant must have at least one digit


b. It must have decimal point
c. It could be either positive or negative
d. Default sign is +ve , same for mantissa
e. No commas or blanks are allowed within real constants
f. The mantissa part and exponent part should be separated by letter ‗e‘
g. The mantissa part may have positive or negative part
h. The exponent must be least of one digit and it must positive or
negative. Default is positive
i. Exponent should not have fraction part

Character constant
It is a single character enclosed in apostrophes (single quotation
marks) i.e pair of single quotes (' ')

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 22


Example: - 'a', 'c', etc.
Character constants have integer values that are determined by
computer character set. Several character constants and their values as
defined by ASCII set are as follows

Constant value
'A' 65
'a' 97
'3' 57
'0' 48

Escape Sequence
Escape sequence certain non printing characters as well as (" "),
Apostrophes, ?, !, can be expressed in terms of escape sequence always
begin when backward slash and is followed by one or more special
characters.

Example:- Line fed or new line can be represented as \n. Some escape
sequences are:-
Char Escape Sequence
Bell \a
Backspace \b
Hor. Tab \t
Ver. Tab \v
New line \n
Quotation mark \"
Apostrophe \'
Question mark \?
Back slash \\
Carriage Return \r

Rules for construction of character constant


I. A character constant is either a single alphabet , a single digit or a
single special symbol enclosed within a pair of single inverted
commas.
II. The minimum and maximum length of a character constant can be 1
character
III. The valid range of the character constant is –128 to 127 .

String constant

A collection of character enclosed within a pair of double inverted


commas is treated as character constant. It consists of any no. of
consecutive characters enclosed in quotation mark for eg:-
"green","2*(7+3)/k". The compiler automatically places a null character
(\0) at the end of every string constant as the last character within the
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 23
string. Several characters constant expressed in terms of escape
sequences are '\n', '\\', etc. And character constants and so on.

Symbolic constant
A symbolic constant is a name that substitutes for a sequence of
characters. The characters may represent a numeric constant, character
constant or string constant. A symbolic constant allows a name to
appear in place of a numeric constant, character constant or string.
When a program is compiled each occurrence of a symbolic constant are
replaced by its corresponding character sequence.
Symbolic constant are defined at the beginning of the program .The
symbolic constant may appear in the program in place of numeric
constant. A symbolic constant is defined by writing #define pi 3.14 then
the statement to find the area of circle will appear as

area = pi * radius * radius;


During the compilation process each occurrence of symbolic
constant will be replaced by its corresponding text so it appears as:-

area = 3.14 * radius * radius;


#define feature is one of the several features included in c pre-
processor.

Format Specifier

Type Size ( Bytes )


Character Data Type
Char or signed Char %c
String %s or %[ ^ \ n ]
Integer Data Type
Int or short int or Short %d
signed int
Unsigned int or Unsigned %u
short int

Signed long int %ld


Unsigned long int %lu
Float Data Type
Float %f
double %lf
Long double %Lf

Classification of operator

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 24


An operator is a special character or combination of characters that
operates on variables. There's 3 types of operators in C:
 unary,
 binary and
 ternary
They can be used to manipulate a variable with up to 3 arguments
at a time. Here I will explain you the differences between these types of
operators and give examples of what each one is.

Unary Operators
Unary operators are operators that only deal with one argument (which
is generally a single variable). In C, there's only a few of these as shown
in Table 1:

Operator Use
! negation
++ increment by 1
-- decrement by 1
Example
c = i++,
y = --I ,
z = ctr-- ,
p= ++ctr

Binary Operators
Binary operators are operators that deal with two arguments, both
generally being either variables or constants. Table 2 shows some
examples of binary operators found in C

Operator Use
+ addition
- subtraction
* multiplication
/ division
% remainder division
= assignment
boolean equality
==
comparision
> boolean greater than
< boolean less than
&& boolean AND
|| boolean OR

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 25


Example
X = a +b
Y=a*b
A >= c
z = A || B
p == q

Ternary Operators(?:)
Tertiary operators are operators that deal with three arguments which
can be anything from a constant to a complete boolean expression. The
ternary operator in C which is used to reduce if else statements to a
single line.
Example
Ch = ( ch > ‘A’ && ch <= ‘Z”) ? ch+32 : ch-32 ;
If ch is between ‗A‘ and ‗Z‘ ie capital letter ch will be stored with ‗a‘
and ‗z‘ respectively. Hence this single line will convert upper case
character to smaller case character.

Operators in C language
Operators are the symbols, which represent a particular operation
that can be performed on some particular data. The data itself can be
called as Operand. The operator operates on the operand.
C supports Rich set of operators. C has 45 different operators
depending on the function performed operators are classified as
1. Arithmetic operator
2. Increment and Decrement operator
3. Modulo Division Operator
4. Relational operator
5. Logical operator
6. Bitwise operator
7. Conditional operator
8. Assignment operator
9. Comma operator
10. Sizeof operator
11. Cast type operator
12. Address & Data type operator ( We will see this operators in details
in pointer chapter)
13. Arrow operator
14. Member or dot operator

Arithmetic Operators (+, -, /, *)


There are 5 arithmetic operators in c. They are as follows
Operators Purpose
+ addition
- subtraction
* multiplication
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 26
/ division

Important Points to be noted


1. It Works with all types of data types
2. Integer division gives truncated quotient if division is carried
out when both the operands are integer in single expression
the operation is called as integer operation. Integer arithmetic
always yields integer arithmetic. Division of one integer
quantity by another is referred to as integer division.
3. In Division if both the operand have same sign then result is
truncated towards zero.
Example
6/7 = 0
-6/-7 = 0
4. In division if one of the operand is negative, the direction of
truncation in implementation dependent. But –6/7 = 0 or = -1
is machine dependent.
5. An arithmetic operation involving only real operands is called
as real arithmetic.
Example
x = 6.0/7.0 = 0.857143
Y = 1.0/3.0 = 0.333333
Z = -2.0/3.0 –0.666667
6. Mixed mode operation is supported/i.e division between one
integer and real operand can be performed If either operand is
of the real type then only the real operation is performed and
the result in always in real number. Same operation can be
performed on different data in same expression.
7. The unary minus operator in effect multiplies its single
operand by –1.

Note: Multiplication, division, and remainder operator have same


precedence. If operators have same precedence level appear in same
expression the order in which they are evaluated depends on their
associatively i.e left to right. To change this rule parenthesis will be used
whatever is contained within the parenthesis will be evaluated first,
before the term outside the parenthesis. All the above-discussed
operators are binary operators.

Example based on arithmetic operator

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 27


#include<stdio.h> //include header file stdio.h
void main() //start of the program
{
//declaration of variables
int numb1, num2, sum, sub, mul, div, mod;
scanf (―%d %d‖, &num1, &num2); //inputs the operands

//addition of numbers and storing in sum.


sum = num1+num2;
printf(―\n Thu sum is = %d‖, sum); //display the output

//subtraction of numbers and storing in sub.


sub = num1-num2;
printf(―\n Thu difference is = %d‖, sub); //display the output

//multiplication of numbers and storing in mul.


mul = num1*num2;
printf(―\n Thu product is = %d‖, mul); //display the output

//division of numbers and storing in div.


div = num1/num2;
printf(―\n Thu division is = %d‖, div); //display the output

//modulus of numbers and storing in mod.


mod = num1%num2;
printf(―\n Thu modulus is = %d‖, mod); //display the output
}

Modulo operator (%)


This is also binary operator, The operator gives remainder of the
operation. Modulo division operator works only with the integer and
character type of data but not with the real numbers. Sign of the result
in modulo division operator depends on first operand.
E.g.:
- 7/6 = 1,
-7/6 = -1,
7/-6 = 1,
-7/-6 = -1

Increment and Decrement operator (++, --)


These two operators are unary operators because they need only
one operand. Increment operator causes it's operand to be incremented

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 28


by 1 whereas decrement operator causes it's operand to be decremented
by 1.
Increment and decrement operator can be utilized in two different
ways depending on whether the operator is written before or after the
operand. If the operator precedes the operand the operand will be altered
in value before it is utilized (++a , --m)for it's purpose in the program. If
the operator follows the operand then value of the operand will be altered
after it is utilized (m++, a--).
example

if i=1 then
printf ("i= %d", i);
printf ("i= %d", ++i);
printf ("i=%d",i);

will give o/p as

i=1
i=2
i=2
The first statement prints the original value of i. The second
statement first increments the value of i by 1 and then prints it's value.
The final value of i is printed by the last statement.
However the second statement instead ++i we write i++ then o/p
will be:-
i=1,i=1,1=2. This is because second statement uses initial value of
i and then increment i by 1 so third statement prints increased value of i.
i. Let a = 10
Y = a++
After the operation y = 10 and a = 11

ii. Let a = 40
Y = ++a
After the operation y = 41 and a = 41
iii. a++ or ++a are used alone then both has same effect.
Generally this operator are used for FOR, DO and WHILE Loops.

Relational Operator (>, <, <=, >=, ==, !=)


We often two quantities and depending on their relations program
take certain decision. These operator are used to compare two operands
to see whether they are equal to each other, unequal, or whether one is
greater then the other. These are Binary operators. The operand can be
variable, constant or expressions, which will give numerical value when,
evaluated. C has 6 relational operator. These are as follows.

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 29


Operator Meaning
< Less Than
> Greater Than
>= Greater than equal to
<= Less than equal to
== Equal to
!= Not Equal to

Relational operators need two operand for comparison of their values.


Hence there are called Binary Operator.
Example : C < d
A==b+3
f>=5.777
Alpa != ‗r‘
(a+b+c) >= (d-a-b)

Relational operators are used with if, do, and While loops. The last
two operators are also called as equality operator.
All these 6 operators are used to form logical expressions,
representing conditions that are either true or false. True is represented
by integer value 1 and false is represented by value 0 in integer
expression.
Example
I=1,
J=2,
K=3.

Expression Interpretation Value


K<J TRUE 1
(I+J)>=K TRUE 1
K!=3 FALSE 0
J==2 TRUE 1

Logical Operators (&& , ||, !)


In addition to relational & equality operators C contains two logical
operators they are

Operator Meaning
&& Logical AND
|| Logical OR
! Logical Not
These operators are used to test more than one condition and
make decision.

For Example
d>c && x == 45, AN expression of such type which combines two
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 30
or more relational expression is termed as logical expression or a
compound relational expression.
The result of logical and operation will be true when both the
operands are true the result of logical or operation will be true. If either
operand is true or if both the operands are true.
Example
if int i=7 and
float f=5.5 then
(i>=6)||(f<0) true 1.
if (i>=6)&&(f<0) false 0.

Logical AND has a higher precedence than logical OR, the


associatively is left to right. Unary operator (!) Negates the value of the
logical expression. This operator is known as logical not or logical
negation operator.
example
i<3 false then
!(i<3) true.

Conditional Operator (? , : )
The conditional operator are ? and : which also called as Ternary
operators because they take three operands. A conditional expression is
written in the form e

expr1 ? expr2 : expr3 ;

When evaluating a conditional expression expr1 is evaluating a


conditional expression expr1 is evaluated first if expr 1 is true i.e. non-
zero value then expr2 is evaluated and this becomes the value of
conditional expression. If expr1 is false i.e if it's value is zero then expr3
is evaluated and this becomes the value of the conditional expression
only one of the embedded expression is evaluated when determining the
value of a conditional expression. The conditional expression is most
oftenly used to assign one of the two to a variable depending upon some
condition.
Example
The assignment statement
large = x > y ? x : y ;
Assigns to large the value of x, if x is greater than y than otherwise
it assigns the value of y to larger.
Precedence of conditional expression operator is lower than all
other operators except assignment & operator the second operator expr2
may use operators that have lower precedence. However third operand
expr3 can not use an operator of lower precedence without using
parenthesis.
Example
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 31
c ? x = a : x = b ; would be interpreted as c ? x = a : ( x = b ) the
better way write
This expr is x = c ? a : b ;
The condition expression operator is right associate with respect to
it's first and third operand so a ? b : c ? d : e is interpreted as a ? b : ( c
? d : e ) the value of this expression would be b is true otherwise the
value of the expression would be e if c is false.

/* Example : to find the maximum value using conditional operator)


#include
void main() //start of the program
{
int i,j,larger; //declaration of variables
printf (―Input 2 integers : ‖); //ask the user to input 2 numbers

//take the number from standard input and store it

scanf(―%d %d‖,&i, &j);


larger = i > j ? i : j; //evaluation using ternary operator
// print the largest number

printf(―The largest of two numbers is %d \n‖, larger);


} // end of the program

Precedence and Associatively


Following table summarizes the precedence for all the operators.

operator category operators associatively


unary -,++,--,! Rl
arithmetic *,%,/ LR
add, sum
relational <,<=,>,>= LR
equality = =,!= LR
logical and && LR
logical or || LR
conditional ?= RL
assignment =, +=, -=, *= RL
/=,%=

This indicates that AND operator has a precedence lower than that
of any arithmetic or relational but higher than that of logical OR
operator. Logical operators‘ associates from left to right except unary
logical not, that associates from right to left.
Thus the expression a || b && c is interpreted as a || ( b &&
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 32
c).since &&has higher precedence than logical OR.
The expression! a&&b and ! a|| b are interpreted as (!a)&&b and
(!a)||b respectively, due to left to right associativity of logical AND and
logical OR.
The expression a && b && c, a||b||c are interpreted as (a && b )
&& c , (a||b)||c respectively.
The expressions a<b && c%d , a-b||c=d are interpreted (a<b) &&
(c%d),(a-b)||(c=d) since logical AND and logical OR have lower
precedence than relational and arithmatic operators.
!a>=b && c/d, a*b||!c!=d are interpreted as (c!a)>=b) && (c/d) , (
a * b ) || ( c ! c ) ! = d)

Bitwise logical operators( & , | , ^ ,~ , >> , << )


C has 6 bitwise operators. This operate on operand on a bit-by-bit
basis. They are as follows:-

Symbol operation
& Bitwise and
| Bitwise or
^ Bitwise ex-or
~ One's complement
<< Left shift
>> Right shift

All the above operators except complement operator are binary


operators and they take two operands these operators can be operated
only on integers data.

Bitwise AND operator


When two values are ANDed in c the binary representation of the values
are compared bit by bit. Each corresponding bit that is 1 in first value
and 1 in second value produces a 1 in corresponding with bit position of
result, anything else produces 0.

First bit Second Result(&)


Bit
0 0 0
0 1 0
1 0 0
1 1 1

e.g. if ABC and PQR are integers ABC = 18 and PQR = 32 then XYZ
= ABC & PQR will assign 2 to XYZ

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 33


ABC = 0000 0000 0001 0010 = 18
PQR = 0000 0000 0010 0010 = 34

XYZ = 0000 0000 0000 0010 = 02

Bitwise OR operator :-in this operation each bit i:e 1 in first value or in
second value will produce 1 in corresponding bit of result.

First bit Second Result(|)


Bit
0 0 0
0 1 1
1 0 1
1 1 1

For eg :- If x1 is 431 in octal and x2 is 152 in octal, than bitwise


or will produce 573 in octal.
i:e x1 0001 0001 1001 431
x2 0000 0110 1010 152

x3 0001 0111 0011 573

Bitwise EX-OR operator:-


Bitwise EX-OR works as follows:-if either bit is one then
corresponding bit of result is 1 else it is 0.

First bit Second Result(^)


Bit
0 0 0
0 1 1
1 0 1
1 1 0

Example
A1=431 & B2=152 C3=563 in octal.
A1 = 100 011 001  431
B2 = 001 101 010  152

C3 = 101 110 011  563

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 34


5 6 3
EX-OR of itself produces 0.

One's Complement operator:-its effect is to simply flip the bits of its


operand so each bit of operand that is 1 is changed to 0

Bit Result(~)
1 0
0 1

For Example if Value is 63456 in octal then taking ones


complement of this value will produce for Result = ~value is
The following result:-
Value 110 011 100 101 110 ( 63456 )

Result 001 100 011 010 001 ( 14321 )

Result 1 4 3 2 1

Left Shift operator (<<)


When a left shift operation is performed on a value the bits
contained in the value are shifted to left. Bits that are shifted out to the
higher order bit of data item are lost and 0's are always shifted into the
low order bit position of the value.
Example Let x1=6 then the expression x1 = x1<<2 will result in 03
shifted 2 place to the left which will result in 12,it is assigned to x1.
x1 = 0000 0110 = 03
x1<< 1 = 0001 1000 = 24

The operand on the left of << operator is the value to be shifted


while the operand on right hand side is the number. Of bit position the
value is to be shifted by. The operator works on Single data.

Right shift operator (>>)


Right shift operator shifts the bits of a value to write bits shifted
out of low order bit of value are lost. Right shifting unsigned value will
always result in 0's being shifted in on left.In case of signed number ,if
sign bit is 1(-ve number),then on some machine is will be shifted in and
on others 0's will be shifted in. The first type of operation is known as
arithmetic right shift and second is known as logical right shift
VAL1 is unsigned integer and VAL1=0155667 then shifting VAL1 1
place to right with statement VAL1 = VAL1 >> 1 will said to octal
0066733.
Example
VAL1 0 101 101 110 110 111
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 35
VAL1 0 110 110 111 011 011

Assignment operator and expressions( = )


These are used to assign the result of the to a variable they are
used to form assignment expression. The assignment operator is = the
general form of assignment statement is:-

variable = expression;

For example
Number = 7; assigns the value 7 to the variable number Variable
name always appears to the left of the equal to sign. In statement c = a +
b ; the arithmetic expression a + b is evaluated and the result is stored
in the variable c. If two operands in assignment expression are of
different data types then value of right hand side will automatically
converted to the type of identifier on the left.
Example
i is an integer even if the expression is i = 8.1 or I = 8.4 then
value of 8 is assigned to the variable i.
let j = 7 , the expression I = 2*(j/2); will give result 6.

Multiple assignment of the form


identifier1 = identifier2 =.......expression are allowed in 'c'
identifier1 = identifier2 = expression; is equivalent to
id1=(id2=expr)
For Example
i=j=5 then value of 5 will be assigned to i and j both.
Another assignment operators are += , *= , /= ,%= , -=
The assignment statement expr1 += expr2; this is equal to
expr1 = (expr1 + expr2)

In addition, C has a set of shorthand assignment operators of the form.

var oper = exp;

Here var is a variable, exp is an expression and oper is a C binary


arithmetic operator. The operator oper = is known as shorthand
assignment operator

Example
i +=15 is equivalent to i=i+15;
i-=15 is equivalent to i=i-15;
i*=15 is equivalent to i=i*15;

x*=-2*(y+z)/3 is equivalent to x = x*(-2*(y+z)/3)

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 36


Some Examples :
int Final = 100 ;
float value = 1.0;
char ch = ‗a‘ ;
The process of giving initial value to variable is called as
initialization. External and static variables are initialized to zero by
default. Automatic variables that are not initialized explicitly will contain
garbage.

Comma Operator ( , )
The comma operator can be used to link the related expression
together. The comma operator permits two different expressions to
appear in situation where only one expression would ordinarily be used.
The following program illustrate the use of the comma operator

main()
{
int a,b,c ;
c = ( a = 10 , b = 20 ,a+b)
printf(―%d‖,c);
}

Here firstly value 10 is assigned to a , followed by this 20 is assigned to b


and then the result of a+b is assigned to c.
Some applications of comma operator are
For (n=1,m=10;n<=m;m++,n++)
While(c = getch( ) ,c!=‘10‘)
T=x, x=y , y=T;

Sizeof operator
The size of operator is a compile operator and when used with
operand , it returns the number of bytes occupied by operand. The
operand may be a variable, a constant or a data type qualifier.
Examples
Long double sum;
N = sizeof (float);
M = sizeof (sum);
P = sizeof (long int);
Q = sizeof (‗A‘);

First expression will print 4 since float is always 4 byte long.


Second expression will print 10 since long double is always 10 byte
long.
Third expression will print 4 since long int is always 4 byte long.
Forth expression will print 1 , since char is always 1 bytes long
The sizeof operator is normally used to determine the length of
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 37
array and structures when their size are not known to the programmer.
It is used allocate memory space dynamically to variable during the
execution time.

Type Conversion
It is a process of converting the data type into another data type in
the process of programming .'c' permits converting variable of type into
another. Converting integer to floating point and vice versa . 'c' permits
integer values to be stored into variable that have been declared to be
floating point. The number is converted into floating point equivalent it's
value is not changed. 'C' also enables programmer to store floating point
into variables declared to be integer. In this case the value is changed
since number is truncated i:e it's fraction part is lost.
example
1)int a,c;
float b,d;
a = 3; /*assignment statement */
b = 987.654;
c = b; /*b has been stored in c*/

if now c is printed it will show 987 because 987.654 has been


truncated 987 whereas value of d is 3.0 which is equivalent to original
value 3.

2) x = 5 * 6.7 ;
In this mixed mode arithmetic expression one operand is of type
integer and another of type float. The integer value is automatically
converted into type float this type of conversion is known as implicit
conversion (or arithmetic conversion) 'C' programmer also can specify
explicitly how the values are to be converted in mixed mode expression.
This feature is known as cast operator or type casting. The name of
the data type to which the conversion is to be made is enclosed in
parenthesis and placed directly to be left value to be converted.
Example
int a=7;
float b;
b=(float)a+10;

The cast operator converts value of a to equivalent float representing


before the addition of 1.0 is carried out.

Program for Basic Conversions in C


main()
{
float f1=123.125,f2;
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 38
int i1,i2=-150;
char ch = ‗a‘;
i1=f1 ; /* floating point to int constant */
printf(―\n %f assigned to an integer produce %f‖,i2,f1);
f1 = i2/100; /* int divided by int */
printf(―\divided by 100 produce %f ―,i2);
f2 = i2 / 100.0 ; /* int divided by float */;
printf(―\n%d divided by 100.0 produce %f ―,i2);
} /* end of program main*/

Output :-
125.125000 assignment to int produce 123
-150 assignment to float produce –150.000000
-150 divided by 100 to produce is –1.00000
-150 divided by 100.0 to produce is –1.50000

// Program to illustrate use of Bitwise Operators.


#include <stdio.h>
#include <conio.h>
main()
{
int a,b,c;
char *format1,*format2;
clrscr();
format1 = "\n %04X %s %04X = %04X";
format2 = "\n %c%04X = %04X";
a = 0x0FF0; b = 0xFF00;
printf(" BITWISE OPERATIONS.\n\n");
c = a << 4; printf(format1,a,"<<",4,c);
printf(" Left shift 4 bits or one hex digit.");
c = a >> 4; printf(format1,a,">>",4,c);
printf(" Right shift 4 bits or one hex digit.");
c = a & b; printf(format1,a,"&",b,c);
printf(" AND means hex digit only when digits occur in both.");
c = a | b; printf(format1,a,"|",b,c);
printf(" OR means hex digit when digit exists in either value.");
c = a ^ b; printf(format1,a,"^",b,c);
printf(" Exclusive OR means digit for digits in only one value.");
c = ~a; printf(format2,'~',a,c);
printf(" NOT means digits where none before and vice Versa.");
c = -a; printf(format2,'-',a,c);
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 39
printf(" Two's compliment arithmetic in hexadecimal.");
printf("\n");
printf("\n\nPress any key to continue");
getch();
}

Example program that employs different kinds of operators. The


results of their evaluation are also shown in comparison

main() //start of program


{
int a, b, c, d; //declaration of variables
a = 15; b = 10; c = ++a-b; //assign values to variables
printf (―a = %d, b = %d, c = %d\n‖, a,b,c); //print the values
d=b++ + a;
printf (―a = %d, b = %d, d = %d\n, a,b,d);
printf (―a / b = %d\n, a / b);
printf (―a %% b = %d\n, a % b);
printf (―a *= b = %d\n, a *= b);
printf (―%d\n, (c > d) ? 1 : 0 );
printf (―%d\n, (c < d) ? 1 : 0 );
}

Sample program illustrating each data type

#include < stdio.h >

main()
{
int sum;
float money;
char letter;
double pi;

sum = 10; /* assign integer value */


money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */

printf("value of sum = %d\n", sum );


printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 40


}

Sample program output


value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06

C Programming Expressions
Arithmetic Expressions
An expression is a combination of variables constants and
operators written according to the syntax of C 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.

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c 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.

Example of evaluation statements 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.

main ()

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 41


{
float a, b, c x, y, z;
a = 9;
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);
printf (―y = %fn‖,y);
printf (―z = %fn‖,z);
}
.

output
x = 10.00
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


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

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 42


Type conversions in expressions
Implicit type conversion
C permits mixing of constants and variables of different types
in an expression. C automatically converts any intermediate values to the
proper type so that the expression can be evaluated without loosing any
significance. This automatic type conversion is know as implicit type
conversion

During evaluation it adheres to very strict rules and type


conversion. If the operands are of different types the lower type is
automatically converted to the higher type before the operation proceeds.
The result is of higher type.

The following rules apply during evaluating expressions

1. All short and char are automatically converted to int then

2. If one operand is long double, the other will be converted to long


double and result will be long double.
3.
If one operand is double, the other will be converted to double and
result will be double.
4.
If one operand is float, the other will be converted to float and
result will be float.
5. If one of the operand is unsigned long int, the other will be
converted into unsigned...long int and result will be unsigned long
int.
If one operand is long int and other is unsigned int then
a. If unsigned int can be converted to long int, then unsigned
int operand will be .converted as such and the result will be
long int.
b. Else Both operands will be converted to unsigned long int
and the result will be .unsigned long int.
6. If one of the operand is long int, the other will be converted to long
int and the result will be long int. .
7. If one operand is unsigned int the other will be converted to
unsigned int and the result will be unsigned int.

Explicit Conversion
Many times there may arise a situation where we want to force a type
conversion in a way that is different from automatic conversion.

Consider for example the calculation of number of female and


male students in a class

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 43


........................female_students
Ratio =........-------------------
........................male_students

Since if female_students and male_students are declared as integers, the


decimal part will be rounded off and its ratio will represent a wrong
figure. This problem can be solved by converting locally one of the
variables to the floating point as shown below.

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the
purpose of evaluation of the expression. Then using the rule of automatic
conversion, the division is performed by floating point mode, thus
retaining the fractional part of the result. The process of such a local
conversion is known as explicit conversion or casting a value. The
general form is

(type_name) expression

Operator precedence and associativity


Each operator in C has a precedence associated with it. 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.

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.

The table given below gives the precedence of each operator.

Order Category Operator Operation Associativity

1 Highest ( ) Function call L → R


precedence [ ] Left to Right

: :
.

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 44


2 Unary ! Logical negation R → L
~ (NOT) Right -> Left
+ Bitwise 1‘s
- complement
++ Unary plus
- - Unary minus
& Pre or post
* increment
Size of Pre or post
decrement
Address
Indirection
Size of operant in
bytes

3 Member Access .* Dereference L→R


→* Dereference

4 Multiplication * Multiply L→R


/ Divide
% Modulus

5 Additive + Binary Plus L → R


- Binary Minus

6 Shift << Shift Left L → R


>> Shift Right

7 Relational < Less than L → R


<= Less than or
> equal to
>= Greater than
Greater than or
equal to

8 Equality == Equal to L → R
!= Not Equal to

9 Bitwise AAND & Bitwise AND L→R

10 Bitwise XOR ^ Bitwise XOR L→R

11 Bitwise OR | Bitwise OR L→R

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 45


12 Logical AND && Logical AND L→R

14 Conditional ?: Ternary Operator R→L

15 Assignment = Assignment R→L


*= Assign product
%= Assign reminder
/= Assign quotient
+= Assign sum
-= Assign difference
&= Assign bitwise
^= AND
|= Assign bitwise
<<= XOR
>>= Assign bitwise
OR
Assign left shift
Assign right shift

Input and Output Statement


printf and scanf
Printf of used for display results and messages on output device
(like Monitor) i.e it performs the function of output, whereas scanf
performs the function read the data from the keyboard i.e. it performs
the function of input.
First argument to printf &scanf function is the format string.
This string specifies how the remaining arguments to function are to be
displayed for printf & how data is read is to be interpreted for scanf. Data
can be entered into computer from a standard input device by means of c
library function scanf. Scanf function is written as –

scanf (control string, arg1, arg2, arg3 , ……. , arg n);

Control string refers to string containing formatting (like %s, %d , %f)


information
arg1,arg2, ……… , argn represents pointer that indicates data item.
String contains group of characters, one group for each data item, each
character group must begin with % sign and followed by a conversion
character which indicate type corresponding type of data item

Printf function sends text information to a standard. output device.


Data can be displayed on standard output device by means of c library
function printf. Printf function is written as --

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 46


printf (control string , arg 1 , arg 2 , arg 3 , ……….. , arg n);

Control string refers to string containing textual information &


formatting information (like %d, % s, %f etc).
arg 1, arg 2 , arg 3 ,…. , arg n represents a list of variables .
Conversion characters for data that appears in format string are
specified in format specifiers.

Point to be taken care of with scanf


1. All function arguments, except the control string, must be pointers
to variables.
2. Format specifications contained in the control string should match
the arguments in order.
3. Input data items must he separated by spaces and must match the
variables receiving the input in the same order,
4. The reading will be terminated, when scant encounters an invalid
mismatch of data or a character that is not valid for the value
being read.
5. When searching for a value, scanf ignores line boundaries and
simply looks for the next appropriate character.

Format Codes

Code Meaning
%c Single Character
%d Decimal Integer
%e Floating Point
%f Floating Point
%g Floating Point
%h Short Integer
%i Decimal , Hexadecimal , Octal
%o Octal Integer
%s String
%u Unsigned integer
%x Hexadecimal

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 47


%[..] String of words
%[^\n] String

Prefix Letter
h for short integer
l for long integer or double
L for long double

Formatted IO Statement
Formatted input refers to an input data that has been arranged in
a particular format. For example, consider the following data:

143.75 421 ManojKavedia

This line contains three data in parts , arranged in a particular


form. Such data has to be read conforming to the format of its
appearance. For example, the first part of the data should be read into a
variable float, the second into int, and the third part into char.

Some important point about control string

scanf (control string, arg1, arg2, arg3 , ……. , arg n);

Control siring consists of three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of
each item.
3. Escape sequence characters such as \n, \t, and \b.

Formatting Integer Numbers


The field specification for reading an integer number is:

%Wd

1. The percent sign (%) indicates that a conversion specification


follows.
2. w specifies the minimum field width for the output. However - if a
number is greater than the specified field width, it will he printed
in full. overriding the minimum specification
3. d specifies that the a value to he printed in an integer. The number
is written right-justified in the given field width. Leading blanks
will appear as necessary. The following examples illustrate the
output of the number 2902 under different formats:

Printf(―%d‖,2902) 2 9 0 2

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 48


Printf(―%6d‖,2902) 2 9 0 2
Printf(―%2d‖,2902) 2 9 0 2
Printf(―%-6d‖,2902) 2 9 0 2
Printf(―%06d‖,2902) 0 0 2 9 0 2

Data can left-justified by placing a minus sign directly after the %


character. It is also possible to pad with zeros the leading blanks by
placing a 0 (zero) before the field width specifier as shown in the last item
above. Long integers may be printed by spec Id in the place of d in the
format specification.

Formatting Real Numbers


The output of a real number maybe displayed in decimal notation
using the following format specification

%w.p.f

The integer w indicates the minimum number of positions that are


to be used for the display of the value and the integer p indicates the
number of digits to be displayed after the decimal point (precision).
The value, when displayed, is rounded to p decimal places and
printed right justified in the field of w columns. Leading blanks and
trailing zeros will appear as necessary. The default precision is 6 decimal
places. The negative numbers will be p with the minus sign. The number
will be displayed in the form [-] mmm.nnn.
We can also display a real number in exponential notation by
using the specification

%w.p.e

Padding the leading blanks with zeros and printing with left-justification
is also possible by introducing 0 or — before the held width specifier w.
The following examples illustrate the output of the number x = 29.0272
under different format specifications;

Format Output
printf(―%7.4f‖,x) 2 9 . 0 2 7 2
printf(―%7.2f‖,x) 2 9 . 0 2
printf(―%-7.2f‖,x) 2 9 . 0 2
printf(―%f‖,x) 2 9 . 0 2 7 2
printf(―%10.2e‖,x) 2 . 9 0 e + 0 1

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 49


printf(―%11.4e‖,-x) -- 2 9 . 0 2 7 e + 0 1
printf(―%-10.2e‖,-x) 2 . 9 0 e + 0 1
printf(―%e‖,-x) 2 . 9 0 2 7 2 0 E + 0 1

Formatting Character
A single character can be displayed in a desired position using the format

%wc

The character will be displayed right-justified in the field of w columns.


We can make the display left-justify by placing a minus sign before the
integer w. The default value for w is I

Printing of Strings
The format specification for outputting strings is similar to that of real
numbers. It is of the form

%w.ps

where w specifies the field width for display and p instructs that only the
first p characters of the string are to be displayed. The display is right-
justified.
The following examples show the effect of a variety of specifications in
printing a string ―MSK Shahad 421001‖, containing 16 characters
(including blanks)

Format Output
0 1 2 3 4 5 6 8 9 0 1 2 3 4 5 6 7 8 9 0 1
%s M S K S H A H A D 4 2 1 0 0 1
%21s M S K S H A H A D 4 2 1 0 0 1
%21.10 M S K S H A H A D
%.5s M S K S
%-21.10s N E W S H A H A D
%5s N E W S H A H A D 4 2 1 0 0 1

Example of Formatted Data Types


Example-1:/*Printing of Integer Number */
main()
{

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 50


int x = 2902;
long y = 290272;
printf(―%d\n‖,x);
printf(―%10d\n‖,x);
printf(―%010d\n‖,x);
printf(―%-10d\n‖,x);
printf(―%10ld\n‖,y);
printf(―%10ld\n‖,-y);
gethc();
}

Example-2:/*Printing of Real Number */


main()
{
float p = 29.0272;
printf(―%7.4f\n‖,p);
printf(―%f‖,p);
printf(―%7.2f‖,p);
printf(―%-7.2f‖,p);
printf(―%07.2ld‖,p);
printf(―%f\n‖,p);
printf(―%10.2\n‖,p);
printf(―%12.4e\n‖,-p);
printf(―%-10.2e\n‖,p);
printf(―%e\n‖,p);
gethc();
}

Example-3 :/* Printing of Character */


main()
{
char ch = ‗A‘;
static char name[20] = ―Manoj S. Kavedia‖
printf(―\n Output of the following in Character\n\n‖);
printf(―%c\n%3c\n%5c\n‖,ch,ch,ch);
printf(―%3c\n%c\n‖,ch,ch);
printf(―\n‖);
printf(―Output of the Following String‖);
printf(―%s\n‖,p);
printf(―%20s\n‖,p);
printf(―%20.10s\n‖,p);
printf(―%.5s\n‖,-p);
printf(―%-20.10s\n‖,p);
printf(―%5s\n‖,p);
gethc();
}
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 51
Solved Program
1.Enter two numbers, and Add them. Show Addition with or without
using third variable.

# include <stdio.h>
# include <conio.h>
void main ( )
{

int a,b,c;
printf ("Enter first number :");
scanf ("%d",&a);
printf ("Enter second number :");
scanf ("%d",&b);
c = a+b; /* With Using Third Variable */

// a = a+b; /* Without Using Third Variable */

printf ("\n\n\n\t\t\tAddition is %d",c);


getch ( );
}

2.Enter two numbers, and Subtract second number from first. Show
result with or without using third variable.

# include <stdio.h>
# include <conio.h>
void main ( )
{

int a,b,c;
printf ("Enter first number :");
scanf ("%d",&a);
printf ("Enter second number :");
scanf ("%d",&b);
c = a-b; /* With Using Third Variable */

// a = a-b; /* Without Using Third Variable */

printf ("\n\n\n\t\t\tSubtraction Result is %d",c);


getch ( );
}

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 52


3.Enter Four numbers and find out their Average.

# include <stdio.h>
# include <conio.h>
void main ( )
{

int a,b,c,d;
float avg;
printf ("Enter first number :");
scanf ("%d",&a);
printf ("Enter second number :");
scanf ("%d",&b);
printf ("Enter Third number :");
scanf ("%d",&c);
printf ("Enter Fourth number :");
scanf ("%d",&d);
avg = (float) (a + b + c + d)/ 4;
/* Type Casting is done here, because this operation will produce a
floating value. */

printf ("\n\n\n\t\t\tAddition is %.2f",avg);


/* It will show the result in, two digits after the decimal. */
getch ( );
}

4.Enter two numbers, and Add them without using '+' operator.

# include <stdio.h>
# include <conio.h>
void main ( )
{

int a,b;
printf ("Enter first number :");
scanf ("%d",&a);
printf ("Enter second number :");
scanf ("%d",&b);
a = a -(-b);
printf ("\n\n\n\t\t\tAddition is %d",a);
getch ( );
}

5.Enter Radius , and find out Area of the Circle.

# include <stdio.h>
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 53
# include <conio.h>
void main ( )
{

float a,r;
printf ("Enter the radius of circle:");
scanf ("%f",&r);
a = 3.142857 * r * r; /* Also, a = (float) 22 / 7 * r * r; */
printf ("Area of circle = %f",a);
getch ( );
}

6.Enter Length and Breadth of a Rectangle and find out it's Area.

# include <stdio.h>
# include <conio.h>
void main ( )
{

int l,b,a;
printf ("\n\nEnter the Length of Rectangle :");
scanf ("%d",&l);
printf ("\n\nEnter the Bredth of Rectangle :");
scanf ("%d",&b);
a = l * b;
printf ("\n\n\t\tArea of Rectangle = %d",a);
getch ( );
}

7.Enter the degree in Celcius and change it to degree in Farhenite.

# include <stdio.h>
# include <conio.h>
main ( )
{
float f,c;
clrscr ( );
printf ("\nEnter the Degree Celcius :");
scanf ("%f",&c);
f = (c * 5/ 9) +32;
printf ("\n\n\t\tDegree in Ferhenite is = %.2f",f);
getch ( );
}

8.Swap the values of two variables with using a third variable.


Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 54
# include <stdio.h>
# include <conio.h>
main ( )
{
int a,b,c;
clrscr ( );
printf ("\nEnter the first Number( A ) :");
scanf ("%d",&a);
printf ("\nEnter the Second Number( B ) :");
scanf ("%d",&b);
c = a;
a = b;
b = c;
printf ("\n\n\n\t\tNow the first Number( A ) is : %d",a);
printf ("\n\n\t\tNow the Second Number( B ) is : %d",b);
getch ( );
}

9.Swap the values of two variables without using a third variable.

# include <stdio.h>
# include <conio.h>
main ( )
{
int a,b;
clrscr ( );
printf ("\nEnter the first Number( A ) :");
scanf ("%d",&a);
printf ("\nEnter the Second Number( B ) :");
scanf ("%d",&b);
a = a + b;
b = a - b;
a = a - b;
printf ("\n\n\n\t\tNow the first Number( A ) is : %d",a);
printf ("\n\n\t\tNow the Second Number( B ) is : %d",b);
getch ( );
}

10.Swap values of two variables without using third variable and


without using '+' operator.

# include <stdio.h>
# include <conio.h>
main ( )
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 55
{
int a,b,c;
clrscr ( );
printf ("\nEnter the first Number( A ) :");
scanf ("%d",&a);
printf ("\nEnter the Second Number( B ) :");
scanf ("%d",&b);
a = a * b; /* also , a = a - (-b); */
b = a / b; /* also , b = a - b; */
a = a / b; /* also , a = a - b; */

printf ("\n\n\n\t\tNow the first Number( A ) is : %d",a);


printf ("\n\n\t\tNow the Second Number( B ) is : %d",b);
getch ( );
}

11.Enter Basic Salary,T.A., D.A., and the percent of increment in


salary.Now calculate the Total Salary after increment.

# include <stdio.h>
# include <conio.h>
void main ( )
{

float s,in;
int ta,da;
printf ("\n\nEnter the salary in Rs. :");
scanf ("%f",&s);
printf ("\nEnter T.A. in Rs. :");
scanf ("%d",&ta);
printf ("\nEnter D.A. in Rs. :");
scanf ("%d",&da);
printf ("\nEnter the increment (in %):");
scanf ("%f",&in);
s + = ta + da + (s /100) * in;
printf ("\n\n\t\tSalary after increment is Rs %.2f",s);
getch ( );
}

12.Create a Marksheet. Enter marks, and calculate Total and


Percentage.

# include <stdio.h>
# include <conio.h>
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 56
void main ( )
{

int h,e,m,tot;
float per;
printf ("SUBJECT");
printf ("\t M.M.");
printf ("\t M.O.");
printf ("\n\nHindi");
printf ("\t 100 \t");
scanf ("%d",&h);
printf ("\nEnglish");
printf ("\t 100 \t");
scanf ("%d",&e);
printf ("\nMaths");
printf ("\t 100 \t");
scanf ("%d",&m);
printf ("\n\n\nTOTAL");
printf ("\t 300 ");
printf ("\t%d",tot=(h+e+m));
printf ("\n\nPERCENT");
per = (float) tot/3;
printf ("\t %.2f %",per);
getch ( );
}

13.Make this in the center (Horizontally) of the screen.


*
***
*****
***
*
# include <stdio.h>
# include <conio.h>
void main ( )
{
printf ("\n\n\n\n\n\n\n\n\t\t\t\t *");
printf ("\n\t\t\t\t ***");
printf ("\n\t\t\t\t*****");
printf ("\n\t\t\t\t ***");
printf ("\n\t\t\t\t *");
getch ( );
}

14.Enter any Number and find out it's Square and Cube.
For example, if no. is n then find out n2 and n3.
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 57
# include <stdio.h>
# include <conio.h>
void main ( )
{

int n;
long s,c;
printf ("Enter any Number : ");
scanf ("%d",&n);
s = (long)n*n;
c = (long)n*n*n;
printf ("\n\n\t\tSquare of %d = %ld",n,s);
printf ("\n\n\t\tCube of %d = %ld",n,c);
getch ( );
}

Exam Programs
1) Basic salary of employee is input through the keyboard. DA is
40% of basic salary & house rent allowance (HRA) is 20% of the
basic salary. Calculate his gross salary?
Ans :
#include<stdio.h>
#include<conio.h>
void main( )
{
float Basic, DA, HRA, GS;
clrscr( );
printf(―Enter the basic salary‖);
scanf(―%f‖, &basic);
DA = (40/100) * basic;
HRA = (20/100)* basic;
GS = DA + HRA + Basic;
printf (―Gross salary = %f ‖,GS);
getch ( );
}
2) Temperature of a city is Fahrenheit degrees is input to keyboard
write a program to convert this temperature into centigrade.
[TC = (TF-32)*5/9]
Ans :
#include<stdio.h>
#include<conio.h>
void main( )
{
float centi;
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 58
int faren;
printf(―Enter Fahrenheit temp‖);
scanf(―%d‖, &faren);
centi = (( float) faren -32) * 5 / 9;
printf(― cent temp = %f‖, cent);
getch( );
}
3) The length and breadth of the rectangle & radius of the circle are
input through key board. Write a program to calculate the area,
perimeter & the circumference of the circle.
Ans :
#include<stdio.h>
#include<conio.h>
void main( )
{
float l, b, r, area, perim, circumf;
clrscr( );
printf(―Enter length & breadth‖, l, b,);
scanf(―%f%f‖, &l,&b);
area = l * b;
perim = 2 * (l + b);
printf(―\n area =%f ‖, area);
printf(―\n perim = %f ‖, perim);
printf(―\n enter radius ‖,r);
scanf(―%f ‖, &r);
area = 3.14 * r * r;
circumf = 2 * 3.14 * r;
printf(―\n area = %f ‖,area);
printf(―\n circumf = %f ‖, circumf);
getch( );
}
4) Two numbers are input through keyboard into two locations C &
D. Write a program to interchange the content of C & D.
Ans :
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c;
clrscr( );
printf(―a = %d, b = %d ‖, a, b);
c = a;
a = b;
b = c;
printf(―\n a = %d, b = %d‖, a, b);
getch( );
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 59
}

Review Questions
Summer 2007 Marks
1. State different data types supported by ‗C‘ language (W-2007). 2
2. Write a ‗C‘ statement for each of the following: 2
i. Relational operator.
ii. Assignment operator.
3. State the use of increment and decrement operator and give its
precedence and Associativity. 4
4. Define the following: 4
i. Expressions
ii. Data types
iii. Bitwise operators
iv. Logical operators

Winter 2007
1. Explain the use of bitwise operator. 2
2. State the use of increment and decrement operators. Also give
difference between i++ and ++i with example. 4
3. What is variable? How to declare it? How variable differs from
constant? 4

Summer 2008
a) What is variable declaration and variable initialization? 2
b) What are the uses of printf( ) and scanf( )? 2
c) List different relational and logical operators. What will be the output
of following program? 4
#include<stdio.h>
void main( )
{
float a = 5, b = 2;
int c;
c = a % b;
printf(―%d‖,c);
}
d) State use of %c %d and %f. 4
Write output of following:
#include<stdio.h>
main( )
{
float y = 123.456;
printf(―%f %.3f %.1f \n\n‖, y, y, y);
}
e) Define the following: 4
1) Keyword
Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 60
2) Variable.
3) Data types
4) Constants.

Winter 2008
a) State four relational operators with its meaning. 2
b) State four printf format codes. 2
c) State the arithmetic and logical operators with its meaning. 4
d) Write a program to take marks of five subjects and display the total
and average. 4
e) State four rules of choosing variable‘s name. 4
f) What is the output of the following code? 4
void main( )
{
int i = 1, j = -1, k = 0, w, x, y, z;
w = i || j ||k ;
x = i && j && k ;
y = i || j && k ;
z = i && j && k ;
printf(« w=%d x=%d y=%d z=%d »,w,x,y,z) ;
}
Other:
1. Differentiate between unary, binary and ternary operators. 4
2. What is precedence and associativity of operators? 2
3. Explain the use of manual and automatic type casting with suitable.
Example. 4
4. What is comment? Explain its use. 2

Note : Prepared
Er.Manoj S. Kavedia
9324258878
8329988732

YouTube Channel
KavediaSir

Facebook
KavediaSir

Instagram
KavediaSir

Programming in C (Er.Manoj S. Kavedia /9324258878 /8329988732) Page 61

You might also like