Vous êtes sur la page 1sur 52

Unit – 1

Unit - 1
Introduction
Computer Systems
Computer is the word which is derived from a Latin word Compute which is nothing but
calculate.
A computer is an independent machine containing:
CPU + ALU + Memory + Input + Output + Storage
Definitions of Computer
1. Computer is an electronic device which can perform arithmetic and logical operations and
stores the data.
2. A Computer is an electronic device that executes the instructions in a program or in other
words.
3. A device that computes especially a programmable electronic machine that performs high-
speed mathematical or logical operations and stores the data.
Beginning Terms of Computers:
• Hardware: the physical parts of the computer
• Software: The programs that tells the computer what to do. The set of Programs is called the
Software
• Data: It is collection of raw facts and figures
• Information: data which has been massaged into a useful form that is the processed data
which is called as Information.
• Program: A set of instructions which are given in a sequence order to perform the specific
operation.
• Output: The information or result which is given by the computer.
• Instruction: It is the command given to the Computer.
A computer system has Four Functions. They are
1. Accepts Data (Accept)
2. Processes Data (Process)
3. Produces Output (Output)
4. Stores Results (Store)
Input:
Everything we tell to the computer is Input
• Data is the raw facts given to the computer.
• Programs are the set of instructions that given to the computer.

C Programming Study Material Page No. 1


Unit – 1
• Commands are special code or key words that the user input to perform a task , like They
may also chosen by clicking on a command button
• User response is the user’s answer to the computer‘s question, such as choosing OK, YES or
NO or by typing in text.
Processing:
• Processing is the thinking that the computer does- the calculations, comparisons, and
decisions. People also process data.
• A series of actions taken towards achieving a particular end.
• The computers can’t think in the same way that people do. But what they do, they do
excellently well and very, very fast.
Output:
This is data that has been processed into useful form, now it is called as information.
Types of Output:
Hard copy: printed on paper or other permanent media
Softcopy: displayed on the screen or by other non permanent.
Categories of Output:
Text documents: including reports, letters etc.
Graphics: charts, graphs, pictures
Multimedia: combination of text, graphics, video, audio
Storage:
Storage refers to the media and methods used to keep information available for later use.
Main memory:
It is also called as Primary Storage. Main memory keeps tracks of what is currently being
processed. It‘s volatile, meaning that the power off erases all the data. Example of Main memory is
RAM.
Secondary Memory:
It is also called as Auxiliary Storage. It holds what is not currently being processed. It is
nonvolatile, meaning that turning the power off does not erase it.
Feature of Computers:
• Speed: A computer can do billions of actions per second.
• Reliability: Failures are usually due to human error, one way or another, Accuracy is there.
• Storage: A computer can keep huge amount of data.
• Versatility: A computer is able to adapt or be adapted to many different functions or
activities.

C Programming Study Material Page No. 2


Unit – 1
Peripherals of a computer are:
• Memory: RAM, Hard Disk, Cache Memory
• C.P.U: Mother Board, Switched Mode Power Supply, Floppy Drive, CD-RW, Mother Board
Consists of CMOS, PCI, Processor, Heat Sink Fan
• Input Devices: Keyboard, Mouse, Light Pen, Joy Stick, Scanner, Speech Input Devices,
Touch Screen, Touch Pad.
• Output Devices: Monitor, Printer, Plotter, Speakers
Computer:
It is a collection of devices that function as a unit. The most basic collection includes a
Computer CPU, a Monitor, a Keyboard, and a Mouse. The Computer CPU is normally a rectangular
box that sits on your desktop. The computer's CPU is actually a small electronic device inside the
case but the term is often used to refer to the whole collection of electronics inside the box.
Monitor:
The Computer Monitor is the computer user's window into the workings of the computer. It
consists of a television picture tube that had been modified to accept the type of video signal created
by the computer's electronics. Conventional televisions can be used as computer monitors if a
translation device is used to connect them. The picture quality leaves something to be desired.
Keyboard:
The Keyboard is the primary input device used to communicate with the computer. A
computer keyboard closely resembles a conventional typewriter keyboard with the addition of
numerous keys that are used specifically for computing functions.
Mouse:
Named for the resemblance of the wire coming out of it and a mouse's tail, the mouse was
introduced to computing in the early 1980's when Macintosh created its graphical user interface
(GUI). The mouse is another input device used to point at objects on the computer monitor and select
them. Using the mouse and keyboard in combination allows the computer user substantial latitude in
how to accomplish a wide variety of tasks.
Floppy Disk Drive:
Once the most advanced of storage devices, floppy diskettes are normally used a temporary
storage containers or transportation media for data. A standard floppy diskette can hold 1.44 MB of
computer data. This amounts to a rather large number of pages if translated to the paper standard for
textual information. Computer diskettes are not as reliable or fast as the internal storage drives on the
computer. They are also the primary vector of virus infection in the computer world.

C Programming Study Material Page No. 3


Unit – 1
Compact Disk-Read Only Memory
The Compact Disk-Read Only Memory (CD-ROM) disk itself is a collection of concentric
circles containing millions of pits and plateaus which correspond to on/off bits of data. Most disks of
this kind are "Read only" meaning that the computer can retrieve information from the disk, but
cannot place information on it. New developments have improved this technology to allow writing
and rewriting data to the disk. A different kind of hardware mechanism is needed to employ this
innovation.
Motherboard:
The motherboard is the main circuit board inside your PC. Every component at some point
communicates through the motherboard, either by directly plugging into it or by communicating
through one of the motherboards ports. The motherboard is one big communication highway. Its
purpose inside your PC is to provide a platform for all the other components and peripherals to talk
to each other.
Motherboard Chipset:
A motherboard chipset controls all the data that flows through the data channels (buses) of
the motherboard. The primary function of the motherboard chipset is to direct this data to the correct
areas of the motherboard, and therefore the correct components.
Components of a Motherboard:
The motherboard contains many connections for all type of components. Motherboards
contain expansion slots such as the ISA, PCI, AGP and DIMM sockets. It also contains external
connections for your onboard sound card, USB ports, Serial and Parallel ports, PS/2 ports for your
keyboard and mouse as well as network and Fire wire connections.
So the motherboard has a massive part to play in the workings of your PC. Components that
you buy all rely on the motherboard to have the correct connections are available and working. Its
best to buy a decent motherboard especially if you plan on buying extra's in the future.
Hard Disk Drive:
The hard disk drive is the primary storage location where data is permanently stored. Below
is an illustration of what the inside of the hard disk drive may look like. The four main components
of a hard disk drive are the platters, head arm, chassis, and the head actuator.
SMPS:
It is a Switched Mode Power Supply. It is taking the AC power from the switch board. And
this is used to coverts the AC power to DC power and supply that DC power to all the components in
the Computer System.

C Programming Study Material Page No. 4


Unit – 1
Hardware Concepts
The computer system mainly consists of 2 important components. They are
1. Central Processing Unit (CPU) or Processor.
2. Random Access Memory (RAM)
Any program is required to executed, it has to load into RAM. The instructions are fetched
into ALU then executed and results will be stored back into the RAM.

A Simple Computer
The above systems are called as Von-Neumann computers, or Serial Computers. Parallel
computers are non Von-Neumann type as they contain more than one processor, RAM.
The following are the different ware’s available.
1. Hardware: Materialistic thing which we can touch and feel.
2. Software: Ideological things which we cannot perceive and feel.
3. Firmware: It is a fixed and small program that internally controls various electronics
devices. POST software is Read only Memory is the example of firmware.
4. Freeware: Software which can use it freely.
5. Shareware: It is software which we can use for some time freely.
Some Novice HW Concepts:
Processor:
The processors are rated as 2.6GHz, 3GHz, etc., These numbers really convey the clock rate
at which the processor can work at most. They do not really convey the actual computational speed
of the computer. That is in terms of operations per second. The actual speed will be much smaller
than these numbers.
Computers use some elementary operations known as micro operations while executing the
user’s instruction. For example to execute the statement a=b+c, the following steps may be needed.
• b value has to be fetched from RAM to CPU
• c value has to be fetched from RAM to CPU
• Plus operation has to be performed.
• Results has to stored back in a, which is in the RAM

C Programming Study Material Page No. 5


Unit – 1
Binary System:
The information, which it is stored or manipulated by the computer memory it will be done in
binary mode.
RAM:
This is also called as real memory, physical memory or simply memory. In order to run any
program, it has to be loaded into RAM. Whatever we store in this device, it will be available as long
as power supply is available for it. So this memory is also called as volatile memory.
RAM contains elementary memory devices known as Flip-Flop’s. A Flip-Flop can be
considered as a bi-state device such as an electrical switch. That is, we can set ON or unset OFF the
Flip-Flop state. If it is set, value ONE is assumed to be stored, otherwise ZERO is assumed to be
stored. That is, we can store one bit in a Flip-Flop. A series of Flip-Flops in the processor is called as
register.
Present computers allocate memory in multiples of eight Flip-Flops only. If the number what
we like to store in the computer memory is not exact multiple of eight Flip-Flops, then ZERO
padding will be done to the left hand side of the number and then the number is stored in the
computer memory.
Number System:
4 Bits = 1 Nibble
8 Bits = 1 Byte
10
2 Bytes = 1024 Bytes = 1 Kilo Byte
20
2 Bytes = 210 KB = 1024 KB = 1 Mega Byte
230 Bytes = 220 KB = 210 MB = 1024 MB = 1 Giga Byte
240 Bytes = 230 KB = 220 MB = 210 GB = 1024 GB = 1 Tara Byte
250 Bytes = 240 KB = 230 MB = 220 GB = 210 TB = = 1024 TB = 1 Peta Byte
ROM:
Read Only Memory is another important component in the computer system. Whatever we
store in this device cannot be modified or erased through software. However by applying hardware
methods such as sweeping through laser gun we can erase the content in ROM. This can be used to
store Power On Self Test (POST) software.
Power On Self Test:
Whenever we switch on a machine, we may require some special software to test the
workability of all the parts of the machine. This is called as POST software. This is usually kept on
ROM, because users cannot change this software. If all the parts are working fine then the Operating
System (OS) such as Disk Operating System, Microsoft Windows, Unix etc., are loaded into RAM
from the secondary memory device such as hard disks. Then the users can utilize the computer
services.

C Programming Study Material Page No. 6


Unit – 1
Software Concepts
Operating System:
An operating system is an interface between the Computer System and User. And it is a
media between the hardware and software. The OS provides software to the user to utilize the
computer resources. It can also be considered as a resource manager as it manages users, memory,
CPU, peripherals etc., among the users. Usually the OS is designed and developed to meet the
general requirements of the User.
System Software:
The software related to operating systems, network drivers, device drivers, etc., are called as
System Software. Development of this type of software needs the knowledge of basics of physical
devices. System software performs the tasks such as transferring data from memory to disk, or vice
versa, starts the computer system, shut down the computer system.
Examples: Operating System, Device Drivers, Network Drivers, shells and loaders
Application Software:
The application programs are software that enables the end-user to perform specific,
productive tasks, such as word processing, image manipulation. Application software performs the
tasks such as provides the user to edit the text, play the games, getting the data from the internet.
Examples: Games, Text Editors, Image Editors, Spreadsheet packages.
Programming languages:
A Programming language is used to develop the application software. It is used to develop
the software that satisfies the user’s requirements. The software developers use this programming
language to develop a new software such as game, banking system, reservation system etc.,
There are 3 types of programming languages. They are
Low level languages: These programming languages can be understood by the machine very easily.
And the examples of this low level language are Machine Language, Assembly Language.
Medium level languages: These programming languages are the Middle level languages. And the
examples of these medium level languages are C, C++.
High level languages: These programming languages are uniquely identified through their rich
grammar and structure, with which we can specify what we wanted in a straightforward manner. The
examples of these high level languages are C, C++, Java, FORTRAN, COBOL, BASIC.
No two processors will be having the same machine language or assembly language
instruction sets. Thus, programs written using processors Machine Language or Assembly language
will work only on that processor. So that Machine language or Assembly language is not portable.
High level language programs can work on variety of machines without many modifications. Thus,
they are portable and their value will be more.

C Programming Study Material Page No. 7


Unit – 1
Low level language programs are faster, while running compared to equivalent High level
language programs. They give freedom to directly interact with the parts of the computer system.
According to the Software Engineering principles, a good programming language should
have the following characteristics.
• It should have better readability
• Understandability
• Repair ability
• Upgradeability
• Conciseness
• Portability
Translators:
The translators are used to convert the programming written in one level language to another
level language. The following are the translators used in general.
• Assemblers
• Compilers
• Converters
• Interpreters
Assemblers:
An assembler takes Assembly Language Programs as input and converts them into Machine
Language. Even though the assembly language and machine language are low level languages, it is
require converting assembly language programs to machine language programs. Because, assembly
language programs are also not understand by the processor. Only machine language is the machine
understandable language.
Compilers:
The compilers take high level language programs as input and convert them into machine
language. Once converted into machine language program then that program can runs on any
machine. The examples of ‘C’ language compilers are Turbo C, Borland C, Sun C, Solaris C.
Converters:
The converters take one high level language program as input and convert it into another high
level language program.
Interpreters:
The interpreters also take high level language programs as input and convert them into
machine language. But the interpreters take High level language programs instructions one after
another and executes immediately. Usually, Interpreters are needed to identify run time errors, which
are also called as bugs.

C Programming Study Material Page No. 8


Unit – 1
Errors:
An error is a mistake done by anybody. In the programming language also there are number
of possible errors. So the errors during programming are classified as
• Compile time errors (Syntactical Errors)
• Run time errors (Bugs)
• Computational errors
Compile time errors:
These errors are also called as Syntactical errors. These errors occur when we violate the
programming language rules while writing the programs. Unless, we correct all the errors in our
program, it will not be converted into machine language. Unless machine language file is not
available, we cannot run our program.
Examples of this type of errors:
• In ‘C’ language all the executable statements are ended with semi colon. If we violate this
rule in our program, we get an error which we can call it as compile time error.
• In JAVA and ‘C’ language the program ends with the following symbol “}”. If we are not
giving that symbol in the ending of our program then the syntactical error will display by that
compiler or interpreter.
Run time errors:
These errors are also called as Bugs. The errors which occur during the execution of the
program are called as Run time errors. If the run time errors occur when the program execution then
the program will abnormally terminate. The program will stop its execution and come out of that.
Example of this type of errors:
• If programs violate the rules of the Operating System. For example, if our program tries to
access memory which is not allocated to us, we may get an error such as “Memory segment
violation”.
• Program contains an expression like1/0. Then the “Arithmetic Exception” will come.
Computational errors:
These errors are the ones, which will distort the final value of the program. These errors may
occur because of many reasons including the finite behavior of the computers such as finite word
size, etc. Also because of mathematical equations, and operations on them may lead to
computational errors.
Examples of this type of errors:
• In our program if the statements like 10/3 then the result would be 3.333333. Because most of
the computers give results accurately until six digits after the decimal point. This is also
technically called as precision. So in some applications such as astronomy, biology requires
high precision. Mistakes in the 40th decimal point may also lead to catastrophic results.
C Programming Study Material Page No. 9
Unit – 1
Problem Solving
Program Development Stages:
The typical program development involves
1. Preparing Algorithm
2. Preparing Flow Chart
3. Coding
4. Compiling and Executing.
Algorithm
An algorithm is a step by step process to solve a problem. Algorithm can be defined as a
well-defined computational procedure that takes single value or a set of values as inputs and
produces a single or multiple values as output. Thus it is a sequence of steps which transforms an
input into an output. A single problem may have multiple algorithms. Also, an algorithm is always a
language-free computational step.
In order to compare algorithms, we must have some criteria to measure the efficiency of our
algorithms. Suppose an algorithm has m input data. The time and space used by the algorithm are the
two main measures for the efficiency of the algorithm. The time is measured by counting the number
of key operations in sorting and searching algorithms, for example the number of comparisons,
searches, etc. This is because key operations are so defined that the time for the other operation is
much less than or at the most equal to the time for key operations. The space is measured by
counting the maximum of memory needed by the algorithm.
The complexity of an algorithm is a function which gives the running time and / or storage
space requirement of the algorithm in terms of the size of the input data. Normally, the complexity
will refer to the running time of the algorithm.
Example: Algorithm for finding the maximum of three numbers
1. Read three numbers (a, b, c)
2. If a is greater than b and c then print a as maximum. Otherwise compare b and c, if b is
greater than c then print b is maximum, else print c is maximum.
So as told above, algorithms are written in normal language. They will not contain any details about
the programming language. So that algorithm is independent of the programming language. Just it
contains approach for a problem.
Pseudo-code:
Pseudo-code is a simple instruction language to write any code. Pseudo-code consists of
short readable and formally-styled natural language used to explain specific tasks within a program's
algorithm. The main difference b/w an algorithm and a pseudo code is that, algorithm is written as
steps using natural language (English) whereas pseudo code consists of both natural language and
mathematical notations.
C Programming Study Material Page No. 10
Unit – 1
Flowchart
The pictorial representation or a diagrammatic representation of an Algorithm is called as
Flowchart. It is built using different types of boxes and symbols. The operation to be performed is
written in the box. All symbols are interconnected processing to indicate the flow of information
processing.
Uses of Flowchart:
1. Flowchart helps to understand the program easily.
2. As different types of boxes are used to specify the type of operation performed, it will be easy
to understand the complex programs.
3. Analyze the working of an algorithm and identify any pitfalls in the algorithm.
The following graphic symbols are used while preparing the flow chart.

Example: 1. To find the maximum of three numbers

C Programming Study Material Page No. 11


Unit – 1
Example: 2. To print the Fibonacci series for 1 to n value.

Coding:
After developing the algorithm and flow chart then we can start coding for the particular
problem. Here the algorithm and flowchart is common for all the programming languages. But the
coding is different from one programming language to another programming language. So here we
will see how the coding will done using ‘C’ Language.
Coding of program is usually accomplished by one or two possible methods, the most
common being the use of an editor. Some editors are line-oriented, while others are character-
oriented (full-screen editors). Some editors include both full-screen features and line-oriented
commands. UNIX operating system has ed, vi editors and TURBO C gives an menu driven interface
with many options.
Their IDE (Integrated Development Environment) puts all the tools you need for C program
development into a single, convenient screen display. Program files are saved with the extension .c
like test.c, add.c. There are several such IDEs available in the market targeted towards different
operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular
compilers that work under MS-DOS. And we can use the common editors like notepad, word pad in
Microsoft Windows operating systems.

Using Notepad
Notepad is a basic text editor you can use for simple documents or for creating Web pages.
Here we can create or edit files. To open Notepad, click Start, point to All Programs, point to
Accessories, and then click Notepad.

C Programming Study Material Page No. 12


Unit – 1
Using WordPad
You can use WordPad to create or edit text files that contain formatting or graphics. Use
Notepad for basic text editing. To open WordPad, click Start, point to All Programs, point to
Accessories, and then click WordPad.
Using Turbo ‘C’ Editor:
Turbo ‘C’ editor is an IDE (Integrated Development Environment). It is giving you a menu
driven approach with many options. Using this we can create the program, compile the program and
after that we can execute the program also. There are many options available in this editor. The
menus like File, Edit, Run, Compile, Options, Help etc., are available in this editor.
Compilation and Execution:
After writing the program using any of the editors we have to save the file. After saving the
file we need to compile it. Turbo C makes an object file with extension .obj after compiling and after
linking it. After that when we are executing the file Turbo C makes executable file with extension
.exe.
Program Development and Execution using Turbo C:
Assuming that you are using a Turbo C compiler here are the steps that you need to follow to
compile and execute your first C program
• Open Command Prompt in Microsoft Windows Operating System. For that click on the start
button and click on Run… then write cmd in the text box. Then the command prompt will be
opened.
• Then come to C:\>. That will be possible using change directory option. We can give cd\.
Then you can come to C:\>. Now start the compiler. The compiler TC.EXE is usually present
in C:\TC\BIN directory. For that you need to give C:\> cd tc/bin in the command prompt.
So now C compiler will start.
• Select New from the File menu.
• Type the program.
• Save the program using F2 under a proper name (say Program1.c).
• Use Alt+F9 to compile the program.
• Use Ctrl + F9 to execute the program.
• Use Alt + F5 to view the output.
Note that on compiling the program its machine language equivalent is stored as an EXE file
(Program1.EXE) on the disk. This file is called an executable file. If we copy this file to another
machine we can execute it there without being required to recompile it. In fact the other machine
need not even have a compiler to be able to execute the file.

C Programming Study Material Page No. 13


Unit – 1
Program Development Steps
A ‘C’ program has to pass through many phases for its successful execution and to achieve
the desired output. The various steps involved in the program development are as follows:
Editing Phase
In the editing phase, the C program is entered into a file through a text editor. UNIX
operating system provides a text editor, which can be accessed through the command ‘Vi’. Modern
compiler vendors provide Integrated Development Environment (IDE). The file is saved on the disk
with an extension of ‘C’. Corrections in the program at later stages are done through these editors.
Once the program has been written, it requires to be translated into machine language.
Compilation Phase
This phase is carried out by a program called as compiler. Compiler translates the source
code into the object code. The compilation phase cannot proceed successfully until and unless the
source code is error-free. The compiler generates messages if it encounters syntactic errors in the
source code. The error-free source code is translated into object code and stored in a separate file
with an extension ‘.obj’.
Linking Phase
In this phase, the linker links all the files and functions with the object code under execution.
For example, if a user uses a ‘printf’ function in his her program, the linker links the user programs,
object code with the object code of the printf function.
Execution Phase
In this phase, the executable object code is loaded into the memory and the program
execution begins. We may encounter errors during the execution phase even though compilation
phase is successful. The errors may be run-time errors and logical errors.

Program Development Steps


C Programming Study Material Page No. 14
Unit – 1
Computer Languages
A programming language is an artificial language designed to express computations that can
be performed by a machine, particularly a computer. Programming languages can be used to create
programs that control the behavior of a machine, to express algorithms precisely, or as a mode of
human communication.
Many programming languages have some form of written specification of their syntax (form)
and semantics (meaning). Some languages are defined by a specification document. For example, the
C programming language is specified by an ISO Standard. Other languages, such as Perl, have a
dominant implementation that is used as a reference.
The earliest programming languages predate the invention of the computer, and were used to
direct the behavior of machines. Thousands of different programming languages have been created,
mainly in the computer field, with many more being created every year. Most programming
languages describe computation in an imperative style, i.e., as a sequence of commands, although
some languages, such as those that support functional programming or logic programming, use
alternative forms of description.
Machine Language:
Machine code or machine language is a system of instructions and data executed directly by a
computer's central processing unit (CPU). Machine code may be regarded as a primitive
programming language or as the lowest-level representation of a compiled and/or assembled
computer program. Programs in interpreted languages are not represented by machine code however,
although their interpreter often is. Machine code is sometimes called native code when referring to
platform-dependent parts of language features or libraries. Machine code should not be confused
with so called byte code, which is executed by an interpreter.
Symbolic Language:
Most organisms communicate, but humans are unique in communicating via symbolic
language. Humans are thus a symbolic species: symbols have literally changed the kind of biological
organism we are. We think and behave in ways that are quite odd compared to other species because
of the way that language has defined us. Symbolic language has become the dominant feature of the
cultural environment to which we must adapt in order to grow.
The programming language that uses symbols for expressing operations and operands is
called as Symbolic Language. All modern programming languages are symbolic languages. The
symbolic language manipulates symbols rather than numbers.
High Level Language:
A high-level programming language is a programming language with strong abstraction from
the details of the computer. In comparison to low-level programming languages, it may use natural

C Programming Study Material Page No. 15


Unit – 1
language elements, be easier to use, or be more portable across platforms. Such languages hide the
details of CPU operations such as memory access models and management of scope.
This greater abstraction and hiding of details is generally intended to make the language user-
friendly, as it includes concepts from the problem domain instead of those of the machine used. A
high-level language isolates the execution semantics of computer architecture from the specification
of the program, making the process of developing a program simpler and more understandable with
respect to a low-level language. The amount of abstraction provided defines how high-level a
programming language is. The examples for the high-level languages are C, C++, Java, FORTRAN,
COBOL etc.

Creating and Running Programs


In ‘C’ to create a file we have to open Turbo C editor. In that type the program then save it
after that we need to compile the program then execute the program.
Writing the Program in ‘C’ Language:
To write a program in ‘C’ language, open the Turbo C editor. For that you need to follow the
below steps.
• Open Command Prompt in Microsoft Windows Operating System. For that click on the start
button and click on Run… then write cmd in the text box. Then the command prompt will be
opened.
• Then come to C:\>. That will be possible using change directory option. We can give cd\.
Then you can come to C:\>. Now start the compiler. The compiler TC.EXE is usually present
in C:\TC\BIN directory. For that you need to give C:\> cd tc/bin in the command prompt.
So now C compiler will start.
• Select New from the File menu.
• Type the program.
The Sample ‘C’ language program:
main()
{
printf(“ WELCOME TO C LANGUAGE “);
}

The above program we have to write in Turbo C editor. That looks like this

C Programming Study Material Page No. 16


Unit – 1

The sample C language program in Turbo C editor


Editing:
If there are any errors in the program or we want to modify the program content then we have
to edit the program in the Turbo C editor. For example in the above program we forget to give
semicolon “;” after the printf statement. Then the C compiler will give raise an error. That looks like
this

So in the above picture it shows that statement missing in function main. Now we need to
give the semicolon after the printf statement then again save the file and compile the file.
Compiling:
After saving the file we need to compile the compile. For compilation in Turbo C editor we
have to press Alt + F9. Then the file will be compiled by the compiler if there are no syntactical
errors in the program. After compiling the file we will get .obj file. If there are any errors in the
program then the file won’t be compiled and it will not be converted into .obj file. So for compiling
the file you need to press Alt + F9 or click on the compile menu on the menu bar then choose the
option called compile to OBJ. See the following picture.

C Programming Study Material Page No. 17


Unit – 1
Now after compiling the file Welcome.c we will get the file called Welcome.obj.
Linking:
The linker links all the files and functions with the object code under execution. For example,
in the above program we given a ‘printf’ function, then the linker links our program, object code
with the object code of the printf function.
In this phase, the linker links all the files and functions with the object code under execution.
For example, if a user uses a ‘printf’ function in his her program, the linker links the user programs,
object code with the object code of the printf function.
Linking is the process of combining various pieces of code and data together to form a single
executable that can be loaded in memory. Linking can be done at compile time, at load time (by
loaders) and also at run time (by application programs)
Executing:
After compiling and linking the file we will get .obj file. Then execute the file. Execution of
the file is nothing but run the particular program or application. So to run or execute the file you need
to press Ctrl+F9. Or click on the run menu on the menu bar and choose run option. It will be shown
in the below picture.

After executing the above program then we will get .exe file. When we are executing the
above program then we will get the output as shown in below picture. To see the output we need to
press Alt + F5. Then the output looks like this.

C Programming Study Material Page No. 18


Unit – 1
Basics of C Language
The programming language C was originally developed by Dennis Ritchie of Bell
Laboratories and was designed to run on a PDP-11 with a UNIX operating system. Although it was
originally intended to run under UNIX, there has been a great interest in running it under the MS-
DOS operating system on the IBM PC and compatibles. Due to the simplicity and ease of writing a C
compiler, it is usually the first high level language available on any new computer, including
microcomputers, minicomputers, and mainframes.
C is not the best beginning language because it is somewhat puzzling in nature. It allows the
programmer a wide range of operations from high level down to a very low level, approaching the
level of assembly language. There seems to be no limit to the flexibility available.
Powerful features, simple syntax, and portability make C a preferred language among
programmers for business and industrial applications. Portability means that C programs written for a
computer with a particular kind of processor say Intel can be executed on computers with different
processors such as Motorola, Sun Sparc, or IBM with little or no modification.
C language is widely used in the development of operating systems. An Operating System is
software that controls the various functions of a computer. Also it makes other programs on your
computer work.
Behind the Name – ‘C’ Language:
BCPL (Basic Combined Programming Language) is a computer programming language
designed by Martin Richards of the University of Cambridge in 1966. B is a programming language
that was developed at Bell Labs. It is almost extinct, as it was replaced with the C language. It was
mostly the work of Ken Thompson, with contributions from Dennis Ritchie, and first appeared circa
1969. The first version of UNIX was written in the low-level PDP-7 assembler language. Then they
developed a High-level language called 'B' and it got its name since it was developed based on BPCL
language.
Then Dennis Ritchie developed the Language 'C' due to the arrival of PDP-11 computer.
They named it as 'C' since the previous language they used was 'B' and they want to be named in
sequential order that is after ‘B’, 'C,' which follows sequential order.

C Language Usages:
‘C’s ability to communicate directly with hardware makes it a powerful choice for system
programmers. And the popular operating systems such as Unix and Linux are written entirely in C.
Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and
BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is
also used to develop any kind of application, including complex business ones.
The following is a partial list of areas where C language is used:
C Programming Study Material Page No. 19
Unit – 1
• Embedded Systems
• Systems Programming
• Artificial Intelligence
• Industrial Automation
• Computer Graphics
• Space Research
• Image Processing
• Game Programming
‘C’ Language is a Structure Programming Language:
C is a structured programming language, which means that it allows you to develop programs
using well-defined control structures, and provides modularity (breaking the task into multiple sub
tasks that are simple enough to understand and to reuse). C is often called a middle-level
language because it combines the best elements of low-level or machine language with high-level
languages.
Advantages of ‘C’ Language:
The ‘C’ Language is a very powerful language. And it is very easy to learn and write
programs. And the other advantages of the ‘C’ language are
• C is simple.
• There are only 32 keywords so C is very easy to master. Keywords are words that have
special meaning in C language.
• C programs run faster than programs written in most other languages.
• C enables easy communication with computer hardware making it easy to write system
programs such as compilers and interpreters.
• The big plus is that it is possible to do everything in 'C' while other languages make you to
write a procedure, subroutine or function in assembler code.
• 'C' has very good facilities for creating tables of constant data within the source file.
• 'C' is a small language with very few essential operations. All the heavy work is done by
explicit library function calls.
• 'C' allows you directly and conveniently access most of the internals of the machine (the
memory, input output slots, and CPU registers) from the language without having to resort to
assembler code.
• 'C' compilers have an optimization phase which can be invoked if desired. The output code
can be optimized for either speed or memory usage. The code will be just as good as that
produced by an assembly code programmer of normal skill real guru programmers can do
only slightly better.

C Programming Study Material Page No. 20


Unit – 1
Structure of C Program
The C language program should start with main() function. And the programmers have to
follow the structure and syntax of the C language. The below one is the structure of the C language
program.

Preprocessor directives
Global Variables Declaration
void main()
{
Local variables declaration
Executable Statements & Expressions
}
Return type subfunction (arguments)
{
Local variables declaration
Statements & Expressions
}

Preprocessor directives are lines included in the code of our programs that are not program
statements but directives for the preprocessor. These lines are always preceded by a hash sign (#).
The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor
digests all these directives before any code is generated by the statements. Example of this
preprocessor directive is #include<stdio.h>.
These preprocessor directives extend only across a single line of code. As soon as a newline
character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at
the end of a preprocessor directive. The only way a preprocessor directive can extend through more
than one line is by preceding the newline character at the end of the line by a backslash (\).
The variables which we are declaring before the main function are called as global variables.
These variables can be used in all the functions in the entire program.
The function main is very important, and must appear once, and only once in every C
program. This is the point where execution is begun when the program is run. Following the main
program name is a pair of parentheses which are an indication to the compiler that this is a function.
The two curly brackets are called as braces, are used to define the limits of the program itself. The
actual program statements go between the two braces and in this case, there are no statements
because the program does absolutely nothing.

C Programming Study Material Page No. 21


Unit – 1
The variables which we are declaring in the function are called as local variables. These
variables can be declared in the function only. The variables can be used within the function in which
it is declared.
A program can have any number of functions. One of them should be main function. Others
are called as user-define functions. We can write any number of user defined functions in the
program.

C Tokens:
In a C source program, the basic element recognized by the compiler is the "token." A token
is source-program text that the compiler does not break down into component elements. C tokens
include keywords, identifiers, constants, strings, special symbols & operators. Punctuation characters
such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.

Identifiers
Identifiers, or names, refer to a variety of things: functions, tags of structures, unions, and
enumerations, members of structures or unions, enumeration constants, typedef names, and objects.
An object, sometimes called a variable, is a location in storage, and its interpretation depends on two
main attributes: its storage class and its type.
In the C programming language, an identifier is a combination of alphanumeric characters,
the first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline. Two rules must be kept in mind when naming
identifiers.
• The case of alphabetic characters is significant. Using INDEX for a variable name is not the
same as using index and neither of them is the same as using InDeX for a variable name. All
three refer to different variables.
• Don’t give the space in between the identifier. Better to use an underline character instead of
space. Example: don’t give as student no, you have to declare as student_no.

Examples of identifiers:

int sno =115;


char sname =’b’; Identifier
float fee =1200.50;

C Programming Study Material Page No. 22


Unit – 1
Basic Data Types and Sizes
A C language programmer has to tell the system before-hand, the type of numbers or
characters he is using in his program. These are data types. There are many data types in C language.
A C programmer has to use appropriate data type as per his requirement.
C language data types can be broadly classified as
• Primary Data Type
• Derived Data Type
• User – Defined Data Type
Primary data type
All C Compilers accept the following fundamental data types
1. Integer int
2. Character char
3. Floating Point float
4. Double precision floating point double
5. Void void

The size and range of each data type is given in the table below
DATA TYPE RANGE OF VALUES
char -128 to 127
int -32768 to +32767
float 3.4 e-38 to 3.4 e+38
double 1.7 e-308 to 1.7 e+308
Integer Type:
Integers are whole numbers with a machine dependent range of values. C has 3 classes of
integer storage namely short int, int and long int. All of these data types have signed and unsigned
forms. A short int requires half the space than normal integer values. Unsigned numbers are always
positive and consume all the bits for the magnitude of the number. The long and unsigned integers
are used to declare a longer range of values.
Floating Point Types:
Floating point number represents a real number with 6 digits precision. Floating point
numbers are denoted by the keyword float. When the accuracy of the floating point number is
insufficient, we can use the double to define the number. The double is same as float but with longer
precision. To extend the precision further we can use long double which consumes 80 bits of
memory space.

C Programming Study Material Page No. 23


Unit – 1
Void Type:
Using void data type, we can specify the type of a function. It is a good practice to avoid
functions that does not return any values to the calling function.
Character Type:
A single character can be defined as a defined as a character type of data. Characters are
usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied
to char. While unsigned characters have values between 0 and 255, signed characters have values
from –128 to 127.
Size and Range of Data Types on 16 bit machine.
TYPE SIZE (Bits) Range
Char or Signed Char 8 -128 to 127
Unsigned Char 8 0 to 255
Int or Signed int 16 -32768 to 32767
Unsigned int 16 0 to 65535
Short int or Signed short int 8 -128 to 127
Unsigned short int 8 0 to 255
Long int or signed long int 32 -2147483648 to 2147483647
Unsigned long int 32 0 to 4294967295
Float 32 3.4 e-38 to 3.4 e+38
Double 64 1.7e-308 to 1.7e+308
Long Double 80 3.4 e-4932 to 3.4 e+4932

Datatype Keyword Equivalent


Character char
Unsigned Character unsigned char
Signed Character signed char
Signed Integer signed int (or) int
Signed Short Integer signed short int (or) short int (or) short
Signed Long Integer signed long int (or) long int (or) long
UnSigned Integer unsigned int (or) unsigned
UnSigned Short Integer unsigned short int (or) unsigned short
UnSigned Long Integer unsigned long int (or) unsigned long
Floating Point float
Double Precision Floating Point double
Extended Double Precision Floating Point long double

C Programming Study Material Page No. 24


Unit – 1
Constant and Variables
Instructions in C language are formed using syntax and keywords. It is necessary to strictly
follow C language Syntax rules. Any instruction that mismatches with C language Syntax generates
an error while compiling the program. All programs must confirm to rules pre-defined in C
Language. Keywords as special words which are exclusively used by C language, each keyword has
its own meaning and relevance hence, Keywords should not be used either as Variable or Constant
names.
Character Set:
The character set in C Language can be grouped into the following categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
White Spaces are ignored by the compiler until they are a part of string constant. White Space
may be used to separate words, but are strictly prohibited while using between characters of
keywords or identifiers.
C Character-Set Table:
Letters Digits
Upper Case A to Z 0 to 9
Lower Case a to z

Keywords:
Every word in C language is a keyword or an identifier. Keywords in C language cannot be
used as a variable name. They are specifically used by the compiler for its own purpose and they
serve as building blocks of a c program. The following are the Keyword set of C language.
.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 .size of .volatile
.do .if .static .while

C Programming Study Material Page No. 25


Unit – 1
White Space:
1. Blank Space
2. Horizontal Tab
3. Carriage Return
4. New Line
5. Form Feed
Special Characters:
, .Comma & .Ampersand
. .Period ^ .Caret
; .Semicolon * .Asterisk
: .Colon - .Minus Sign
? .Question Mark + .Plus Sign
' .Apostrophe < .Opening Angle (Less than sign)
" .Quotation Marks > .Closing Angle (Greater than sign)
! .Exclamation Mark ( .Left Parenthesis
| .Vertical Bar ) .Right Parenthesis
/ .Slash [ .Left Bracket
\ .Backslash ] .Right Bracket
~ .Tilde { .Left Brace
- .Underscore } .Right Bracket
$ .Dollar Sign # .Number Sign
% .Percentage Sign . .

Declaring Variable as Constant:


The values of some variable may be required to remain constant throughout the program. We
can do this by using the qualifier const at the time of initialization.
Example: const int max_marks=100;
The const keyword qualifier tells the compiler that the value of the int variable max_marks
may not be modified in the program. Always, const type has to be declared and initialized at the
same time.
Declaration of Variables
Every variable used in the program should be declared to the compiler. The declaration does
the following things.
1. Tells the compiler the variables name.
2. Specifies what type of data the variable will hold.
3. And ask the computer system to allocate memory to that variable

C Programming Study Material Page No. 26


Unit – 1
The general format of any declaration
datatype v1, v2, v3, ……….. vn;
Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Example:
int stu_no;
int number, salary;
double average, mean;
Rules for constructing variable names:
• A variable should be essentially a sequence of letters and or digits and the variable name
should begin with a character.
• A variable name should not be a keyword. A variable name should starts with either alphabet
or an underscore. Variable name should not start with a number.
• Both uppercase and lowercase letters are permitted.
• The underscore character is also permitted in identifiers.
• A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers
allow variable names whose length could be up to 247 characters.
• No commas or blanks are allowed within a variable name.
• No special symbol other than an underscore can be used in a variable name.
• Use appropriate variable names that means if we want to calculate simple interest, it is always
advisable to construct meaningful variable names like prin, roi, noy to represent Principle, Rate
of interest and Number of years rather than using the variables a, b, c.
User defined type declaration:
In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables. The general syntax is
typedef type identifier;
Here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to the
data type.
Example:
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be later used to declare
variables as follows:
salary dept1, dept2;
average section1, section2;

C Programming Study Material Page No. 27


Unit – 1
Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and
section2 are indirectly float data type.
The second type of user defined datatype is enumerated data type which is defined as follows.
Enum identifier {value1, value2 …. Value n};
The identifier is a user defined enumerated datatype which can be used to declare variables
that have one of the values enclosed within the braces. After the definition we can declare variables
to be of this ‘new’ type as below.
enum identifier V1, V2, V3, ……… Vn
The enumerated variables V1, V2, ….. Vn can have only one of the values value1, value2
….. value n
Examples:
enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;
Defining Symbolic Constants:
A symbolic constant value can be defined as a preprocessor statement and used in the
program as any other constant value. The general form of a symbolic constant is
# define symbolic_name value of constant
Valid examples of constant definitions are:
# define marks 100
# define total 50
# define pi 3.14159
These values may appear anywhere in the program, but must come before it is referenced in
the program. It is a standard practice to place them at the beginning of the program.

Use of printf() and scanf() functions:


In order to read and write, we can use standard library functions printf() and scanf(). Both
these functions definition is available in stdio.h. The printf function is used to print the data on the
console. The printf() function is a standard in built function for printing a given line which appears
inside the double quotes. Whatever message we wanted to be displayed on the screen is to be
included in between two double quotes and send to printf. And printf call also has to be terminated
with a semicolon.

C Programming Study Material Page No. 28


Unit – 1
If we want to print the values of the variables, we have to use printf() function. This function
requires two things to be specified.
1. A format specifier which is designed according to our output requirement. Here we can use
the notations such as %d, %f given in the below table.
2. List of variables whose values to be printed on the screen.

The scanf() function is used to read data from the keyboard. And it needs two things.
1. What type of data and how many data it has to take from the keyboard. This is specified with
a format string according to the rules given in the following table. It we want to instruct
scanf() to read four float values then, we have to give “%f %f %f %f” as the first argument.
2. Where to store the values which are read from the keyboard. That is, we are required to
supply memory locations where the data has to stored. This is achieved by using the address
operator &. If we want to read data into variable v, we have to say &v. Here v is a variable,
&v is the address or memory location of that variable. So we have to supply address of the
variable after the format specifier.

The following are the various format specifiers and their meaning:
%c Print a character
%d Print a Integer
%i Print a Integer
%e Print float value in exponential form.
%f Print float value
%g Print using %e or %f whichever is smaller
%o Print actual value
%s Print a string
%x Print a hexadecimal integer (Unsigned) using lower case a – f
%X Print a hexadecimal integer (Unsigned) using upper case A – F
%a Print a unsigned integer.
%p Print a pointer value
%hx hex short
%lo octal long
%ld long
%% Outputs a percent sign.

C Programming Study Material Page No. 29


Unit – 1
Comments:
The comments are the non executable statements in C language. There are two ways to give
comments in C language. They are single line comments and multi line comments.
• Single line comments can give using // symbol.
• Multi line comments can give using /* .... */.
Examples: This is the comment
void main() // this is the main function

/* this is used for the multi


line comments in the c language */

The /* .... */ and // comments and will not be executed, the compiler simply ignores these
statements. These are essential since it enhances the readability and understandability of the
program. It is a very good practice to include comments in all the programs to make the users
understand what is being done in the program.
Though comments are not necessary, it is a good practice to begin a program with a comment
indicating the purpose of the program, its author and the date on which the program was written.
Any number of comments can be written at any place in the program. For example, a comment can
be written before the statement, after the statement or within the statement.
The normal language rules do not apply to text written within /* .. */. Thus we can type this
text in small case, capital or a combination. This is because the comments are solely given for the
understanding of the programmer or the fellow programmers and are completely ignored by the
compiler.
Comments cannot be nested.
Example: /* Cal of SI /* Author date 01/01/2010 */ */ is invalid.

C Programming Study Material Page No. 30


Unit – 1
Operators Introduction
An operator is a symbol which helps the user to command the computer to do a certain
mathematical or logical manipulations. Operators are used in C language program to operate on data
and variables. C has a rich set of operators which can be classified as
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
Arithmetic Operators
All the basic arithmetic operations can be carried out in C. All the operators have almost the
same meaning as in other languages. Both unary and binary operations are available in C language.
Unary operations operate on a single operand, therefore the number 5 when operated by unary – will
have the value –5. And binary operator needs two operands such as, the numbers 6 and 9 when
operated by binary + will have the value 6 + 9 as 15.

Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator for remainder

Examples of arithmetic operators are:


x+y
x-y
-x + y =
a*b+c
-a * b
a/b
a%b
Here a, b, c, x, y are known as operands. The modulus operator is a special operator in C
language which evaluates the remainder of the operands after division.

C Programming Study Material Page No. 31


Unit – 1
Example Program:
#include<stdio.h> //include header file stdio.h
void main() //tell the compiler the start of the program
{
int num1, num2, sum, sub, mul, div, mod; //declaration of variables
printf(“ Please Enter Two Numbers :: “); //asking user to enter no’s
scanf (“%d %d”, &num1, &num2); //inputs the operands
sum = num1+num2; //addition of numbers and storing in sum.
printf(“\n The sum is = %d”, sum); //display the output
sub = num1-num2; //subtraction of numbers and storing in sub.
printf(“\n The difference is = %d”, sub); //display the output
mul = num1*num2; //multiplication of numbers and storing in mul.
printf(“\n The product is = %d”, mul); //display the output
div = num1/num2; //division of numbers and storing in div.
printf(“\n The division is = %d”, div); //display the output
mod = num1%num2; //modulus of numbers and storing in mod.
printf(“\n The modulus is = %d”, mod); //display the output
}

Output
Please Enter Two Numbers :: 10 5
The sum is = 15
The difference is = 5
The product is = 50
The division is = 2.0
The modulus is = 0

Integer Arithmetic:
When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5
be 2 integer numbers. Then the integer operation leads to the following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5

C Programming Study Material Page No. 32


Unit – 1
In integer division the fractional part is truncated.
Floating point arithmetic:
When an arithmetic operation is preformed on two real numbers or fraction numbers such an
operation is called floating point arithmetic. The floating point results can be truncated according to
the properties requirement. The remainder operator is not applicable for floating point arithmetic
operands.
Let x = 14.0 and y = 4.0 then
x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50
Mixed mode arithmetic
When one of the operand is real and other is an integer and if the arithmetic operation is
carried out on these 2 operands then it is called as mixed mode arithmetic. If anyone operand is of
real type then the result will always be real thus 15/10.0 = 1.5.

Relational Operators
Often it is required to compare the relationship between operands and bring out a decision
and program accordingly. This is when the relational operator comes into picture. Relational
operators are also binary operators. That is they need two operands. The result of relational operator
will be true or false, numerically 1 or 0. C supports the following relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

If you want to compare a and b for equality then you should write a == b, not a = b because a
= b means you are assigning the value of b to a. It is required to compare the marks of 2 students,
salary of 2 persons then we can use the relational operators. A simple relational expression contains
only one relational operator and takes the following form.
exp1 relational operator exp2

C Programming Study Material Page No. 33


Unit – 1
Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions and evaluated
values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as if, while
and for statements to decide the course of action of a running program.
Example Program:
main()
{
int a,b,c,d,e,np;
printf(" ENTER FIVE STUDENT MARKS :: ");
scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
np=((a>=40)+(b>=40)+(c>=40)+(d>=40)+(e>=40));
printf(" THE NO. OF STUDENTS PASSED ARE :: %d",np);
}
In the above program we are reading students marks from the user and finding out number of
students passed in that particular subject. So that will be possible using relational operator >= . We
are comparing every student marks with 40 marks and if it is true then it will return 1 that means
true. So here the np variable we are using to find out how many one’s will come. So the np is nothing
but the no. of students passed.
Output:
ENTER FIVE STUDENT MARKS :: 45 67 28 34 56
THE NO. OF STUDENTS PASSED ARE :: 3

Logical Operators
C has the following logical operators; they compare or evaluate logical and relational
expressions.
A B A && B A || B
Operator Meaning
T T T T
&& Logical AND
T F F T
|| Logical OR
F T F T

! Logical NOT F F F F

C Programming Study Material Page No. 34


Unit – 1
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true then
the whole compound expression is true.
Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true
only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one
of the 2 expressions is true.
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false
and evaluates to false if the expression is true. In other words it just reverses the value of the
expression. The logical operators && and || are the binary operators. And this not operator is a unary
operator. The unary negation operator ! converts a non-zero operand into 0, and a zero operand in 1.
For example
A !A
! (x >= y) the NOT expression evaluates to true only if the value of x is either
T F
greater than or equal to y.
F T

Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression.
Example Statement with simple Statement with
x=a+b assignment operator shorthand operator
Here the value of a + b is evaluated a=a+1 a += 1

and substituted to the variable x. In a=a–1 a -= 1


addition, C has a set of shorthand a = a * (n+1) a *= (n+1)
assignment operators of the form. a = a / (n+1) a /= (n+1)
var oper = exp; a=a%b a %= b

C Programming Study Material Page No. 35


Unit – 1
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
x + = 1 is same as x = x + 1

main( )
{
int a,b,c,d;
printf("ENTER VALUES OF a, b, c, d");
scanf("%d %d %d %d",&a,&b,&c,&d);
a += b*c+d;
printf("\n a = %d",a);
}

Input
a = 5, b= 5, c = 7, d = 8.
Output
ENTER VALUES OF a, b, c, d
5578
a = 48

Increment / Decrement Operators


C provides two unusual operators for incrementing and decrementing variables. The
increment operator ++ adds 1 to its operand, while the decrement operator -- subtracts 1. We have
frequently used ++ to increment by 1. These two operators are the unary operators that mean they
require only one operand.

Operators Postfix Prefix


Increment i++ ++i
Decreemnt i-- --i

x = x+1; is the same as ++x;


and x = x–1; is the same as x––;
Unary increment / decrement operators are applicable to integer type of variables only (which
includes int, char, long) but not to constants or expressions. Postfix increment / decrement operator if
applied to a variable in an expression then the current value of the variable is used in evaluating the
expression and then the variable value will be incremented / decremented by one.
C Programming Study Material Page No. 36
Unit – 1
Similarly prefix increment / decrement operator when applied to a variable in an expression,
firs the value of the variable is increment or decremented by one and then the modified value of the
variable is used in evaluating the expression.
Example Program:
#include<stdio.h> First current value of i, that is 10 is assigned to j
void main() and then i will be increment by one.

{
int i=10, j, k; First i value is incremented by one and then this
modified value is assigned to k.
j = i++;
printf(“%d %d”, i, j);
k = ++i;
printf(“%d %d”, i, k);
}
Output: i = 11, j = 10, i = 12, k = 12;

Conditional Operators
C language supports another type of operator known as conditional operator or compact if.
This is a ternary operator. So it needs 3 operands. This operator can be used in either of the following
styles.
1. (expr) ? expr1 : expr2;
2. var = (expr) ? expr1 : expr2;
In the first style, expr1 will be evaluated if expr is true else expr2 will be evaluated. Where
as in the second style, expr1 is evaluated if expr is true and its value is assigned to var. otherwise the
value of expr2 will be assigned to var.
Note: In C language any value if it is positive or negative is logically considered as true. And only
zero will be logically considered as false. So true means numerical value is 1 and false is 0.

Example Program:
main()
{
int y;
printf(" ENTER A YEAR ");
scanf("%d",&y);
((y%400==0)||((y%4==0)&&(y%100!=0)))?printf(" LEAP YEAR "):
printf(" NOT A LEAP YEAR ");
}
C Programming Study Material Page No. 37
Unit – 1

Here we used both conditional operator and logical operators also. || and && are the logical
operators we used here. And in that expression if that is true then the first printf() statement will
execute, that means the LEAP YEAR will be displayed on console. Otherwise the second printf()
statement will be executed, that means NOT A LEAP YEAR will be displayed on console.

Output:
ENTER A YEAR 1999
NOT A LEAP YEAR
ENTER A YEAR 2000
LEAP YEAR

COMMA Operator:
You can combine multiple expressions in a single expression using the comma operator.
Example Program:
main()
{
int i,j,k;
k = (i = 4, j = 5);
printf("k = %d",k);
}

Input
i = 4, j = 5.
Output
k = 5.
For example, you can write: k = (i = 4, j = 5). Here the expression is evaluated from left to
right, that is, i = 4 is evaluated first then j = 5 is evaluated. The value of the rightmost expression is
specified as output, thus k will get the value 5.

C Programming Study Material Page No. 38


Unit – 1
Expressions
An expression is a combination of variables constants and operators written according to the
syntax of C language.
Arithmetic Expressions:
In C every expression evaluates to a value that is 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 ()
{
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 = %f \n”,x);
printf (“y = %f \n”,y);
printf (“z = %f \n”,z);
}

C Programming Study Material Page No. 39


Unit – 1

output
x = 10.00
y = 7.00
z = 4.00

Type Conversions
Some times it is required to convert the one data type to another data type. That is called as
type conversion. Type conversion occurs when the expression has data of mixed data types, for
example, converting an integer value into a float value, or assigning the value of the expression to a
variable with different data types.
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 losing any significance. This automatic type conversion is known as implicit type
conversion
During evaluation it holds 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.
In type conversion, the data type is promoted from lower to higher because converting higher
to lower involves loss of precision and value. For type conversion, C maintains a hierarchy of data
types using the following rules:
1. Integer types are lower than floating-point types.
2. Signed types are lower than unsigned types.
3. Short whole-number types are lower than longer types.
4. The hierarchy of data types is as follows: double, float, long, int, short, char.
The following rules apply during evaluating expressions:
All short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and result will be
long double.
2. If one operand is double, the other will be converted to double and result will be double.
3. If one operand is float, the other will be converted to float and result will be float.
4. 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.
5. If one operand is long int and other is unsigned int then

C Programming Study Material Page No. 40


Unit – 1
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
Ratio = female_Students / 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.

Conditional expressions
A conditional expression contains the expression with condition. The following is the syntax
of the conditional expression.
var = (expr) ? expr1 : expr2;
The expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2 is
evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that
is the value. Only one of expr1 and expr2 is evaluated. Thus to set z to the maximum of a and b, z =
(a > b) ? a : b; /* z = max(a, b) */
It should be noted that the conditional expression is indeed an expression, and it can be used
wherever any other expression can be. For example, if f is a float and n an int, then the expression (n
> 0) ? f : n is of type float regardless of whether n is positive.

C Programming Study Material Page No. 41


Unit – 1
Example Program:
main()
{
int a,b,max;
Conditional Expression
printf(" ENTER TWO NUMBERS :: ");
scanf("%d %d",&a,&b);
max=(a>b)?a:b;
printf(" THE MAX NO. :: %d",max);
}

Output:
ENTER TWO NUMBERS :: 4 6
THE MAX NO. :: 6

In the above program the conditional expression is denoted with bold letters. In that first a
compare with b and if a is maximum that is a is greater than b then, a value that is the value
contained by a is assigned to max variable. Otherwise the value contained by b is assigned to max.
This is the program to find out the maximum of two numbers only. The below program is for finding
out maximum no among three numbers.

Example Program:
main()
{
int a,b,c,max;
printf(" ENTER THREE NUMBERS :: "); Conditional Expression

scanf("%d %d %d",&a,&b,&c);
max=((a>b)&&(a>c)?a:(b>c)?b:c);
printf(" THE MAX NO. :: %d",max);
}

Output:
ENTER THREE NUMBERS :: 4 6 3
THE MAX NO. :: 6

C Programming Study Material Page No. 42


Unit – 1
Precedence in Arithmetic Operators
An arithmetic expression without parenthesis will be evaluated from left to right using the
rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C.
High priority * / % Low priority + -
Rules for evaluation of expression
• First parenthesized sub expression left to right are evaluated.
• If parentheses are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
• The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
• Arithmetic expressions are evaluated from left to right using the rules of precedence. When
Parenthesis is used, the expressions within parenthesis assume highest priority.
Operator Precedence and Order of Evaluation:
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. 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 precedence ( ) Function call L→R
[] Left to Right

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

C Programming Study Material Page No. 43


Unit – 1
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 AND & Bitwise AND L→R
10 Bitwise XOR ^ Bitwise XOR L→R
11 Bitwise OR | Bitwise OR L→R
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
16 Comma , Evaluate L→R

C Programming Study Material Page No. 44


Unit – 1
Bit – Wise Operators
The smallest element in memory on which we are able to operate as yet is a byte; and we
operated on it by making use of the data type char. We haven’t attempted to look within these data
types to see how they are constructed out of individual bits, and how these bits can be manipulated.
Being able to operate on a bit level is very important in programming, especially when a program
must interact directly with the hardware. This is because, the programming languages are byte
oriented, whereas hardware tends to be bit oriented.
Bitwise Operators
One of C’s powerful features is a set of bit manipulation operators. These permit the
programmer to access and manipulate individual bits within a piece of data. Bitwise operators only
work on a limit number of types. They are only int and char but not float and double. Bitwise
operators fall into two categories: binary bitwise operators and unary bitwise operators. Binary
operators take two arguments, while unary operators only take one.
A bitwise operation operates on one or more bit patterns or binary numerals at the level of
their individual bits. On older microprocessors, bitwise operations are slightly faster than addition
and subtraction operations and usually significantly faster than multiplication and division
operations. On modern architectures, this is not the case.
Bitwise operators interpret operands as strings of bits. Bit operations are performed on this
data to get the bit strings. These bit strings are then interpreted according to data type. There are six
bit operators: bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~), left
shift(<<), and right shift(>>).The various Bitwise Operators available in C are shown below.

There are 4 classes of bitwise operators broadly. They are logical operators, shift operators,
rotation operation and mask operations.
Bitwise Logical Operators
The bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~) operators are
called as bitwise logical operators.

C Programming Study Material Page No. 45


Unit – 1
Bitwise AND Operator:
A bitwise AND takes two binary representations of equal length and performs the logical
AND operation. The bitwise-AND operator compares each bit of its first operand to the
corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
x y x&y
0 0 0
0 1 0
1 0 0
1 1 1

For example:
0101 (decimal 5)
(AND) & 0011 (decimal 3)
= 0001 (decimal 1)
In the C programming language family, the bitwise AND operator is "&" (ampersand).
Again, this operator must not be confused with its Boolean "logical and", which treats its operands as
Boolean values, and is written "&&" (two ampersands).
Bitwise OR Operator:
A bitwise OR takes two bit patterns of equal length, and produces another one of the same
length by matching up corresponding bits and performing the logical inclusive OR operation. And it
compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1,
the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1

For example:
0101 (decimal 5)
(OR) | 0011 (decimal 3)
= 0111 (decimal 7)
In the C language family, the bitwise OR operator is "|" (pipe). Again, this operator must not
be confused with its Boolean "logical or", which treats its operands as Boolean values, and is written
"||" (two pipes).

C Programming Study Material Page No. 46


Unit – 1
Bitwise XOR Operator:
A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR
operation on each pair of corresponding bits. The result in each position is 1 if the two bits are
different, and 0 if they are the same. The bitwise-exclusive-OR operator compares each bit of its first
operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the
corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0

For example:
0101 (decimal 5)
(XOR) ^ 0011 (decimal 3)
= 0110 (decimal 6)
In the C programming language family, the bitwise XOR operator is "^" (caret). Assembly
language programmers sometimes use the XOR operation as a short-cut to set the value of a register
to zero. Performing XOR on a value against itself always yields zero, and on many architectures, this
operation requires fewer CPU clock cycles than the sequence of operations that may be required to
load a zero value and save it to the register.
Bitwise NOT Operator:
The bitwise NOT, or complement, is a unary operation that performs logical negation on each
bit, forming the ones' complement of the given binary value. Digits which were 0 become 1, and 1
become 0. It is a unary operator. Because it needs only one operand.
x ~x
0 1
1 0

For example:
(NOT) ~ 0111(decimal 7)
= 1000 (decimal 8)
In many programming languages, the bitwise NOT operator is "~" (tilde). This operator must
not be confused with the "logical not" operator, "!" (exclamation point), the C language makes a
value of 0 to 1 and a value other than 0 to 0. The "logical not" is not a bitwise operation.

C Programming Study Material Page No. 47


Unit – 1
Example Program:
The below program illustrates the all logical bit wise operators.

main()
{
int c1,c2,c3;
printf("ENTER VAULES OF c1 and c2");
scanf("%d,%d",&c1,&c2);
c3 = c1 & c2;
printf("\n Bitwise AND i.e. c1 & c2 = %d",c3);
c3 = c1 | c2;
printf("\n Bitwise OR i.e. c1 | c2 = %d",c3);
c3 = c1 ^ c2;
printf("\n Bitwise XOR i.e. c1 ^ c2 = %d",c3);
c3 = ~c1;
printf("\n ones complement of c1 = %d",c3);
}
Input
c1 = 4;
c2 = 6;

Output:

ENTER VALUES OF c1 and c2


4
6
Bitwise AND i.e. c1 & c2 = 4
Bitwise OR i.e. c1 | c2 = 6
Bitwise XOR i.e. c1 ^ c2 = 2
ones compliment of c1 = -5

C Programming Study Material Page No. 48


Unit – 1
Bitwise Shift Operators
The bitwise shift operators take two arguments. One is bit pattern and second one is
the number of bits have to shift. And there are two types of bitwise shift operators. They are
left shift and right shift. Left shift is denoting with “<<” and right shift is denoting with “>>”.
Left Shift Operator:
In this left shift the bits are shifted to left from the original position. And in the right most
bit 0 will be added. This operation shown in below figure.

Logical Left Shift


For example:
c3 = c1 << 2;
This is a left-shift operation. The bits are shifted left by two places. c1 indicates the operand
that should be an expression returning a whole number. 2 indicates a shift that should not be
negative, and its value must be less than the number of bits allocated to that data type.
It is evaluated as follows: if the c1 value is 4. Then
c1 is 0000 0100
It is shifted 2 bits to the left to produce
0001 0000
While shifting, the high-order (left) bits are discarded. Since a vacuum is created on the right
side, it is filled with 0s to get 0001 0000. Thus the value is 16.

Right Shift Operator:


In this right shift the bits are shifted to right from the original position. And in the left most
bit 0 will be added. This operation shown in below figure.

Logical Right Shift

C Programming Study Material Page No. 49


Unit – 1
For example:
c3 = c1 >> 2;
This is a right-shift operation. The bits are shifted right by two places. c1 indicates the
operand that should be an expression returning a whole number. 2 indicates a shift that should not be
negative, and its value must be less than the number of bits allocated to that data type.
It is evaluated as follows: if c value is 4. Then
c1 is 0000 0100
It is shifted 2 bits to the right to produce
0000 0001
While shifting, the low-order (right) bits are discarded. The left most bits are replaced with
zeros. Now the c3 value will be 1.
Example Program:
The following program illustrates the bitwise shift operators.
main()
{
int c1,c3;
printf("ENTER THE VAULE OF c1");
scanf("%d",&c1);
c3 = c1<<2;
printf("\n left shift by 2 bits c1 << 2 = %d",c3);
c3 = c1>>2;
printf("\n right shift by 2 bits c1 >> 2 = %d",c3);
}

Output:
ENTER THE VALUE OF c1
4
left shift by 2 bits c1 << 2 = 16
right shift by 2 bits c1 >> 2 = 1

C Programming Study Material Page No. 50


Unit – 1
Bit Rotation
Another form of shift is the circular shift or bit rotation. In this operation, the bits are
rotated as if the left and right ends of the register were joined. The value that is shifted in on the right
during a left-shift is whatever value was shifted out on the left, and vice versa. This operation is
useful if it is necessary to retain all the existing bits, and is frequently used in digital cryptography.
In Circular Shift also there are two types. They are Left Circular Shift or rotate left, and Right
Circular Shift or rotate right.
Left Circular Shift or Rotate Left:
In this the bits are shifted towards left from the original position. And whatever bit is there in
the left most position that bit will be added to the right most position. The operation is shown in the
following figure.

Left Circular Shift or Rotate Left


Right Circular Shift or Rotate Right:
In this the bits are shifted towards right from the original position. And whatever bit is there
in the right most position that bit will be added to the left most position. The operation is shown in
the following figure.

Right Circular Shift or Rotate Right

C Programming Study Material Page No. 51


Unit – 1
Bit Masks
The mask operation is mainly used for two purposes. First one is if we want to fix the value
of any position as 1 or 0 or to know the value of any position in the bit pattern. We can use mask
operation with using AND operation. The AND operator can be used to check the status of the bits of
this attribute byte. Suppose we want to check whether a file is a hidden file or not. A hidden file is
one, which is never shown in the directory, even though it exists on the disk. From the above bit
classification of attribute byte, we only need to check whether bit number 1 is ON or OFF. If 1 then
it is ON, if 0 then it is OFF.
For example:
In any of the bit pattern we want to know the bit position 3. And here we don’t know the
original bit pattern. So that will be finding out using the mask operation whether the 3 bit is ON or
OFF. That we can do using AND operator by using the bit pattern 11111111.
10111001 (Original bit pattern user doesn’t know this)
(AND) & MASK 11111111
Result 10111001.
So if we do like this, even though the user don’t know the original bit pattern also he will get
the result and know that the third bit if zero that is OFF.
The second, and equally important use of the AND operator and mask operation is in
changing the status of the bit, or more precisely to switch OFF a particular bit. If the first operand
happens to be 00000111, then to switch OFF bit number 1, our AND mask bit pattern should be
11111101. On applying this mask, we get,

00000111 Original bit pattern


11111101 AND mask
--------------
00000101 Resulting bit pattern

Here in the AND mask we keep the value of all other bits as 1 except the one which is to be
switched OFF. Therefore, irrespective of whether the first bit is ON or OFF previously, it is switched
OFF. At the same time the value 1 provided in all the other bits of the AND mask keeps the bit
values of the other bits in the first operand unaltered.

C Programming Study Material Page No. 52

Vous aimerez peut-être aussi