Mod 1
Mod 1
Syllabus: Introduction to computers, input and output devices, designing efficient programs. Introduction
to C, Structure of C program, Files used in a C program, Compilers, Compiling and executing C
programs, variables, constants, Input/output statements in C.
1.1 Computer
A computer can be defined as an electronic device that is designed to accept data, perform the
required mathematical and logical operations at high speed, and output the result.
m
1.2 Characteristics of Computers
co
e.
Figure 1.1. Characteristics of computers
dg
1. Speed
Computers can perform millions of operations per second.
The speed of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond
= 1 × 10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds.
2. Accuracy
ue
3. Automation
Besides being very fast and accurate, computers are automatable devices that can perform a task
without any user intervention.
The user just needs to assign the task to the computer, after which it automatically controls
different devices attached to it and executes the program instructions.
4. Diligence
Computers never get tired of a repetitive task. It can continually work for hours without creating
errors.
Even if a large number of executions need to be executed, each and every execution requires the
same duration, and is executed with the same accuracy.
5. Versatile
Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fields.
For example, they are used as personal computers (PCs) for home use, for business-oriented
tasks, weather forecasting, space exploration, teaching, railways, banking, medicine, and so on,
indicating that computers can perform different tasks simultaneous
Memory
Computers have internal or primary memory (storage space) as well as external or secondary
memory.
The computer stores a large amount of data and programs in the secondary storage space.
The stored data and programs can be retrieved and used whenever required.
Secondary memory is the key for data storage. Some examples of secondary devices include
m
floppy disks, optical disks (CDs and DVDs), hard disk drives (HDDs), and pen drives.
6. No IQ
Although the trend today is to make computers intelligent by inducing artificial intelligence
co
(AI) in them, they still do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
7. Economical
Today, computers are considered as short-term investments for achieving long-term gains.
e.
Using computers also reduces manpower requirements and leads to an elegant and efficient way
of performing various tasks.
Hence, computers save time, energy, and money. When compared to other systems, computers
can do more work in lesser time.
For example, using the conventional postal system to send an important document takes at least
dg
two to three days, whereas the same information when sent using the Internet (e-mail) will be
delivered instantaneously.
Instructions written by the users are performed sequentially until there is a break in
the current flow.
Input/Output and processing operations are performed simultaneously. While data is being
read/written, the central processing unit (CPU) executes another program in the memory that
is ready for execution.
m
co
Figure 1.2. Von Neumann architecture (a) Shared memory for instructions and data (b)
Separate memories for instructions and data
of numbers.
1890: a punched card system was designed for the calculations.
1936: Turing machine were designed, which were capable of computing anything that is
computable.
1941: It was the first time a computer could store information in its main memory.
1943–1944:
ue
m
1993: The Pentium microprocessor introduced the use of graphics and music on PCs.
1994: PC games became popular.
1996: developed the Google search engine at Stanford University.
1999: The term Wi-Fi was introduced when users started connecting to the Internet without
wires.
co
2001: Apple introduced Mac OS X operating system, which had protected memory architecture
and pre-emptive multi-tasking, among other benefits. To stay competitive, Microsoft launched
Windows XP.
2003: The first 64-bit processor, AMD‘s Athlon 64, was brought into the consumer market.
2004: Mozilla released Firefox 1.0 and in the same year Facebook, a social networking site, was
launched.
e.
2005: YouTube, a video sharing service, was launched. In the same year, Google acquired
Android, a Linux-based mobile phone operating system.
2006: Apple introduced MacBook Pro, its first Intelbased, dual-core mobile computer.
2007: Apple released iPhone, which brought many computer functions in the smartphone.
dg
2009: Microsoft launched Windows 7 in which users could pin applications to the taskbar.
2010: Apple launched iPad, which revived the tablet computer segment.
2011: Google introduced Chromebook, a laptop that runs on the Google Chrome operating
system.
2015: Apple released the Apple Watch. In the same year, Microsoft launched Windows 10.
ue
Memory
Electromagnetic relay was used as primary memory and
Punched cards were used to store data and instructions.
Software Technology
Programming was done in machine or assembly language.
Memory
Magnetic core memory was used as primary memory;
m
Magnetic tapes and magnetic disks were used to store data and instructions.
These computers had faster and larger memory than the first generation computers.
Software Technology
co
Programming was done in high level programming languages. Batch operating system
was used.
Highlights
Faster, smaller, cheaper, reliable, and easier to use
They consumed 1/10th the power consumed by first generation computers
dg
Bulky in size
Dissipated less heat than first generation computers
Costly
Difficult to use.
ue
Memory
Larger magnetic core memory was used as primary memory; larger capacity magnetic
tapes and magnetic disks were used to store data and instructions.
Highlights
Faster, smaller, cheaper, reliable, and easier to use than the second generation computers
They consumed less power than second generation computers.
Bulky in size and required a complete room for installation
Dissipated less heat than second generation computers
Costly
Easier to use and upgrade
Software Technology
Programming was done in high level programming languages such as FORTRAN,
COBOL, Pascal, and BASIC.
Time sharing operating system was used.
Software was separated from the hardware.
m
Use of personal computers became widespread.
High speed computer networks in the form of LANs, WANs, and MANs started
growing.
co
Memory
Semiconductor memory was used as primary memory; large capacity magnetic disks
were used as built in secondary memory.
Magnetic tapes and floppy disks were used as portable storage devices.
e.
Software Technology
Programming was done in high level programming language such as C and C++.
Graphical User Interface (GUI) based operating system (e.g. Windows) was
introduced. It had icons and menus among other features to allow computers to be used
dg
as a general purpose machine by all users.
UNIX was also introduced as an open source operating system. Apple Mac OS and MS
DOS were also released during this period.
All these operating systems had multi-processing and multiprogramming capabilities.
Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY1, CRAY-2, CRAY-X
Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
vt
Memory
Semiconductor memory is used as primary memory;
large capacity magnetic disks are used as built-in secondary memory.
portable storage devices like optical disks and USB flash drives are used.
Software Technology
Programming is done in high-level programming languages such as Java, Python, and
C#.
Graphical User Interface (GUI)-based operating systems such as Windows, Unix, Linux,
Ubuntu, and Apple Mac are being used.
These operating systems are more powerful and user friendly than the ones available in
the previous generations.
Used for Scientific, commercial, interactive online, multimedia (graphics, audio, video), and
network applications.
Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param supercomputer
m
Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
co
Speed of microprocessors and the size of memory are growing rapidly.
High-end features available on the microprocessors
They consume less power than computers of prior generations.
m
the mainframe system.
Mainframe computers are typically used as servers on the World Wide Web.
They are also used in organizations such as banks, airline companies, and universities, where a
large number of users frequently access the data stored in their databases.
co
3. Minicomputers
Minicomputers are smaller, cheaper, and slower than mainframes.
They are called minicomputers because they were the smallest computer of their times. Also
known as midrange computers.
Minicomputers are widely used in business, education, hospitals, government organizations, etc.
e.
While some minicomputers can be used only by a single user, others are specifically designed to
handle multiple users simultaneously.
Minicomputers can also be used as servers in a networked environment.
dg
4. Microcomputers
Microcomputers, commonly known as PCs, are very small and cheap.
Many computer hardware companies copied this design and termed their microcomputers as
PC-compatible.
PCs can be classified into the following categories:
Desktop PCs, Laptops, Workstations, Network Computers and Handheld Computers.
ue
m
1.6 Applications of Computers
1. Word processing
Word processing software enables users to read and write documents.
Users can also add images, tables, and graphs for illustrating a concept.
co
The software automatically corrects spelling mistakes and includes copy–paste features.
2. Internet
The Internet is a network of networks that connects computers all over the world.
It gives the user access to an enormous amount of information, much more than available in any
library.
e.
Using e-mail, the user can communicate in seconds with a person who is located thousands of
miles away.
Chat software enables users to chat with another person in real-time.
Video conferencing tools are becoming popular.
dg
4. Desktop publishing
Desktop publishing software enables us to create page layouts for entire books.
5. e-Business
e-Business or electronic business is the process of conducting business via the Internet.
This may include buying and selling of goods and services using computers and the Internet.
vt
Companies today use e-commerce applications for marketing, transaction, processing, and
product and customer services processing.
Business-to-consumer or B2C: In this form of electronic commerce, business companies
deploy their websites on the Internet to sell their products and services to the customers. On
their websites, they provide features such as catalogues, interactive order processing system,
secure electronic payment system, and online customer support.
Business-to-business or B2B: This type of electronic commerce involves business transactions
performed between business partners (customers are not involved). For example, companies use
computers and networks (in the form of extranets) to order raw materials from their suppliers.
Companies can also use extranets to supply their products to their dealers.
Consumer-to-consumer or C2C: This type of electronic commerce enables customers to carry
business transactions among themselves. For example, on auction websites, a customer sells
his/her product which is purchased by another customer.
Electronic banking Electronic banking, also known as cyber banking or online banking,
supports various banking activities conducted from home, a business, or on the road instead of a
physical bank location.
6. Bioinformatics
Bioinformatics is the application of computer technology to manage large amount of biological
information.
Computers are used to collect, store, analyse, and integrate biological and genetic information to
facilitate gene-based drug discovery and development.
Bioinformatics is an interdisciplinary field of molecular biology, computer science, statistics,
and mathematics.
7. Health care
m
Computers have also become a necessary device in the health care industry. The following are
areas in which computers are extensively used in the health care industry:
Storing records: computers are first and foremost used to store the medical records of patients.
Surgical procedures Computers are used for certain surgical procedures. They enable the
surgeon to use computer to control and move surgical instruments in the patient‘s body for a
co
variety of surgical procedures.
Better diagnosis and treatment Computers help physicians make better diagnoses and
recommend treatments.
9. Meteorology
Meteorology is the study of the atmosphere. Meteorology has applications in many diverse
fields. Some of the applications include the following:
ue
Weather forecasting It includes application of science and technology to predict the state of the
atmosphere (temperature, precipitation, etc.) for a future time and a given location.
Aviation meteorology Aviation meteorology studies the impact of weather on air traffi c
management.
Agricultural meteorology Agricultural meteorology deals with the study of effects of weather
and climate on plant distribution, crop yield, water-use efficiency, plant and animal
vt
development.
Nuclear meteorology Nuclear meteorology studies the distribution of radioactive aerosols and
gases in the atmosphere. Maritime meteorology Maritime meteorology is the study of air and
wave forecasts for ships operating at sea.
Multimedia and Animation Multimedia and animation that combines still images, moving
images, text, and sound in meaningful ways is one of most powerful aspects of computer
technology. We all have seen cartoon movies, which are nothing but an example of computer
animation.
12. Sports
In sports, computers are used to compile statistics, identify weak players and strong players by
analysing statistics, sell tickets, create training programs and diets for athletes, and suggest
game plan strategies based on the competitor‘s past performance.
14. Simulation
m
Simulation of automobile crashes or airplane emergency landings is done to identify potential
weaknesses in designs without risking human lives.
15. Education
A computer is a powerful teaching aid and can act as another teacher in the classroom. Teachers
co
use computers to develop instructional material.
17. Robotics
Robots are computer-controlled machines mainly used in the manufacturing process in extreme
dg
conditions where humans cannot work.
Input: This is the process of entering data and instructions (also known as programs) into the
computer system. The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner, and trackball.
m
Figure 1.4. Block diagram of a computer
Storage: Storage is the process of saving data and instructions permanently in the computer so that
co
they can be used for processing.
A computer has two types of storage areas:
Primary storage: Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds. Primary storage space is very expensive and
therefore limited in capacity.Another drawback of main memory is that it is volatile in nature; that
is, as soon as the computer is switched off, the information stored gets erased. Hence, it cannot be
e.
used as a permanent storage of useful data and programs for future use. Example of primary storage
is random access memory (RAM).
Secondary storage Also known as auxiliary memory. It is cheaper, non-volatile, and used to
permanently store data and programs of those jobs that are not being currently executed by the CPU.
dg
Output: Output is the process of giving the result of data processing to the outside world. The
results are given through output devices such as monitor, and printer. Since the computer accepts
data only in binary form and the result of processing is also in binary form, the result cannot be
directly given to the user. The output devices, therefore, convert the results available in binary codes
into a human-readable language before displaying it to the user.
ue
Control: The control unit (CU) manages and controls all the components of the computer system. It
is the CU that decides the manner in which instructions will be executed and operations performed.
It takes care of the step-by-step processing of all operations that are performed in the computer.
The CPU is a combination of the arithmetic logic unit (ALU) and the CU. The CPU is better
known as the brain of the computer system because the entire processing of data is done in the
vt
ALU, and the CU activates and monitors the operations of other units (such as input, output, and
storage) of the computer system.
Processing: The process of performing operations on the data as per the instructions specified by
the user (program) is called processing. Data and instructions are taken from the primary memory
and transferred to the ALU, which performs all sorts of calculations.
1.8 Motherboard
The motherboard, also known as the main board or the parent board is the primary component
of a computer. It is used to connect all the components of the computer.
Characteristics of a Motherboard
A motherboard can be classified depending on the following characteristics:
Form factor
Chipset
Type of processor socket used
Input–Output connectors
Form factor: Form factor refers to the motherboard‘s geometry, dimensions, arrangement, and
electrical requirements.
Integrated components: Some of the motherboard‘s components are integrated into its printed
circuitry. These include the following:
The chipset is a circuit that controls the majority of the computer‘s resources such as the bus
m
interface with the processor, cache memory, RAM, and expansion cards.
CMOS clock and battery
BIOS
System bus and expansion bus
co
Chipset: The chipset is an electronic circuit that basically coordinates data transfers between the
different components of the computer.
Some chipsets may include a graphics or audio chip, which makes it unnecessary to install a
separate graphics card or sound card.
e.
CMOS clock and battery: The real-time clock (or RTC) is a circuit that is used to synchronize the
computer‘s signals. When the computer is switched off, the power supply stops providing electricity
to the motherboard. The CMOS chip is powered by a battery located on the motherboard.
dg
Processor socket: The processor (also called the microprocessor) is the brain of the computer. The
processor is characterized by its speed or frequency, which is the rate at which it executes
instructions.
RAM connectors RAM is the primary storage area that stores data while the computer is running.
However, its contents are erased when the computer is turned off or restarted.
ue
Expansion slots: Expansion slots are compartments into which expansion cards can be inserted.
Such cards render new features or enhance the computer‘s performance.
I/O connectors: The motherboard has a number of input– output sockets on its rear panel, some of
vt
which include:
A serial port to connect some old peripherals
A parallel port to connect old printers
USB ports to connect more recent peripherals such as mouse and pen drive.
RJ45 connector (also known as LAN or Ethernet port) to connect the computer to a network.
It corresponds to a network card integrated into the motherboard.
Video graphics array (VGA) connector to connect a monitor. This connector interfaces with
the built-in graphics card.
Audio plugs that include the line in, line out, and microphone to connect sound speakers, hi-
fi system, or microphone. This connector interfaces with the built-in sound card.
m
co
e.
dg
Pseudocode: is a detailed yet readable description of what a computer program must do, expressed in a
formally-styled natural language rather than in a programming language. Pseudocode is sometimes used
as a detailed step in the process of developing a program. It allows designers or lead programmers to
express the design in great detail and provides programmers a detailed template for the next step of
writing code in a specific programming language.
Algorithm: In its purest sense, an algorithm is a mathematical process to solve a problem using a finite
number of steps. In the world of computers, an algorithm is the set of instructions that defines not just
what needs to be done but how to do it. In an algorithm,
Flow Chart: A flowchart is a diagram that describes a process or operation. It includes multiple steps,
which the process "flows" through from start to finish. Common uses for flowcharts include developing
business plans, defining troubleshooting steps, and designing mathematical algorithms.
m
co
e.
dg
ue
vt
m
co
e.
dg
Step 2: Read r
Step 3: a= 3.142*r*r
p= 2* 3.142*r
Step 4: Print a, p
Step 5: Stop
vt
m
Step 1: Start
Step 2: Read n1, n2
Step 3: sum = n1 + n2
sub = n1 - n2
co
mul = n1 * n2
div = n1 / n2
Step 4: Print sum, sub, mul, div
Step 5: Stop
Step 3: A= 6*s*s
V= s*s*s
Step 4: Print A, V
Step 5: Stop
vt
Start
Read P, T, R
SI= (P*T*R)/100
m
Print SI
Stop
co
2. Draw the flowchart to compute the area and perimeter of a circle.
Start
e.
Read r
dg
A = 3.142*r*r
P = 2* 3.142*r
Print A, P
ue
Stop
vt
Start
Read l, b
A = l*b
P = 2*(l + b)
Print A, P
Stop
4. Draw the flowchart to compute the area and perimeter of a triangle when three sides are given.
Start
Read a, b, c
m
s = (a + b + c)/2
A = sqrt(s*(s-a)*(s-b)*(s-c))
P=a +b + c
co
Print A, P
e. Stop
Start
Read n1, n1
ue
sum=n1+n2
sub=n1-n2
mul=n1*n2
div=n1/n2
mod=n1%n2
vt
Stop
Start
Read P, T, R
CI= P*(1+R/100)T-P
Print CI
Stop
m
Read r
co
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
e. Print A, V
Stop
dg
Read s
ue
A= 6*s*s
V= s*s*s
vt
Print A, V
Stop
1. Draw the flowchart to convert from degrees in Fahrenheit to degrees in Celsius.
Start
Read f
c=(5/9)*(f-32)
Print c
m
Sto
co
e.
dg
ue
vt
1. Write a Pseudo code for printing the number and its square starting from 4 to 9.
Begin
Input 4
square=4*4
Print 4,16
do the same for each of the other numbers from 5 to 9
End
or
Start with the number 4
Compute its square
Print the number and its square
do the same for each of the other numbers from 5 to 9
m
2. Write a Pseudo code to compute the Simple Interest.
Begin
Input P, T, R
SI= (P*T*R)/100
co
Print SI
End
End
vt
Write a Pseudo code to calculate the area and perimeter of rectangle.
Begin
Input l, b
A=l*b
P=2*(l+b)
Print A, P
End
6. Write a Pseudo code to calculate the area and perimeter of triangle when three sides are given.
Begin
Input a, b, c
s= (a + b + c)/2
A= sqrt(s*(s-a)*(s-b)*(s-c))
m
P= a + b +c
Print A, P
End
co
Begin
Input r
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Print A, V
End
e.
8. Write a Pseudo code to calculate the area and perimeter of cube.
Begin
Input s
dg
A= 6*s*s
V= s*s*s
Print A, V
End
Begin
Input f
c=0.56*(f-32)
Print c
End
vt
Introduction to C :
m
co
e.
C is a general purpose, procedural, structured computer programming language developed by
Dennis Ritchie in the year 1972 at AT&T Bell Labs. C language was developed on UNIX and was
invented to write UNIX system software. C is a successor of B language. There are different C standards:
K&R C std, ANSI C, ISO C.
dg
Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used to write
ue
complex programs. The C compiler combines the features of assembly languages and high-level
languages, which makes it best suited for writing system software as well as business packages.
Some basic characteristics of C language that define the language and have led to its popularity as a
programming language are listed below:
vt
-level programming.
m
Perl, etc) are based on C.
run on another
co
compute with little or no modification.
e.
dg
4.3 Uses of C
C is a very simple language that is widely used by software professionals around the globe. The
uses of C language can be summarized as follows:
ue
implementation of other languages. Major parts of popular operating systems like windows, UNIX,
Linux are still written in C.
-user applications.
The basic concepts of a C program can be explained by writing the structure of a C program. The
structure of a C program is nothing but the rules that are to be followed while writing a C program.
m
co
1.Comments
At the beginning of each program is a comment with a short description of the problem to
be solved.
e.
dg
2. Preprocessor directives
program.
Ex: #include<stdio.h>
#include<math.h>
are the files that the compiler includes in the beginning of the program.
perform
function library.
.h says this file is a header file.
3. Global Declarations
iables that are declared above (before) the main program are called global variables.
m
functions.
co
this section the functions are declared.
statements which comprise the ‗body‘- this is called the action portion of the program.
Ex: #include<stdio.h>
ue
main()
1. Declaration section
2. Executable section
Declaration section
section.
int a;
float b;
Here, the variable sum is declared as an integer variable and it is initialized to zero. The variable
variable.
Executable section
The instructions
m
can be input/output statements, expressions to be evaluated, simple assignment statements, control
statements such as if statement, for statement etc.Each executable statement ends with ―;‖.
co
#include<stdio.h>
void main()
{
e.
printf(―Hello World‖);
}
dg
1. At times the programmer may want to use the same subroutines for different programs. To do
this, he would just compile the code of the subroutine once and link to the resulting object file
m
2. At times the programmer may want to change or add the subroutines and reflect those changes in
all the programs. For doing this, he will have to only change the source file for the subroutines,
co
recompile the source code and then recompile and re-link the program. This tells us that including a
header file will make it easier at all levels of the program. If we need to modify anything then
changes are made only in the subroutines after which all the changes will be reflected.
e added at the start of the source code so that they can be used by more than
3. Object files
binary code of the function definitions.
4. Executable file
object files are linked by the linker for producing a binary file which will be
m
executed directly.
co
Compiling and Executing C Programs
e. e that consists of the statements of the
program written in C language. This source file usually contains ASCII characters and can be
dg
produced with a text editor, such as Windows notepad, or in an Integrated Design Environment.
However, even the object file is not an executable file. Therefore, in the next step, the object
m
Every C program uses standard header files, which are written as part of the source code for
modular C programs.
co
The compilation process shown in Figure 4.4 is done in two steps.
In the first step, the preprocessor program reads the source file as text, and produces another text
file as output. The output of the preprocessor is a text file which does not contain any
e.
preprocessor statements. This file is ready to be processed by the compiler.
dg
ue
The linker combines the object file with library routines (supplied with the compiler) to produce
the final executable file.
In modular programming, the source code is divided into two or more source files. All these
vt
source files are compiled separately thereby producing multiple object files.
These object files are combined by the linker to produce an executable file (Figure 4.5).
m
co
Using Comments
The compiler ignores the comments when forming the object file means that the comments
// is used to comment a single statement. This is known as a line comment. A line comment
can be placed anywhere on the line and it does not require to be specifically ended as the end of
vt
/* is used to comment multiple statements. A /* is ended with */ and all statements that lie
within these characters are commented. This type of comment is known as block comment.
C Tokens
co
keywords are basically a sequence of characters that have a fixed meaning.
e.
int, float, if, while, void etc are valid keywords.
Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).
dg
List of keywords:
ue
vt
2. Variables: A variable is a data item whose value changes during the execution of program.
3. Constants: A constant is a data item which will not change during the execution of a
program.
‗\0‘.
5. Operators: Operator is a symbol (or token) that specifies the operation to be performed on
Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=)
m
6. Special characters: [ ], { }, ( ) etc. used in the program to execute the code correctly and helps
CHARACTER SET IN C :
co
character set that defines the
program.
a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters
ue
c. Special characters: Include symbols such as, % & ) < > * S / ) [ " etc.,
d. White space characters: These characters are used to print a blank space on the screen.
co
print the message on a new line on the screen. Like the newline character, the other escape
4.10 Identifiers
functions.
Some rules have to be followed while forming identifier names. They are as follows:
except the underscore ‗_‘.
character must be avoided because several compiler-defined identifiers in the standard C library
m
have underscore as their first character.
be of any reasonable length. They should not contain more than 31 characters.
co
They can actually be longer than 31, but the compiler looks at only the first 31 characters of the
name.
EMP_NO
2. Invoking the compiler to process the source code and produce an object file.
a. During this process the compiler checks for the errors and gives the platform to debug the errors if
exists, if there exists no errors compiler converts source code into machine understandable language
and stores as object file with the ―.O‖ extension using the command : gcc filename.c –o filename –
lm OR gcc filename.c
3. Linking all the object files and libraries to produce an executable file.
a. In this step all the object files, libraries and header files are linked to produce an executable file.
b. The executable file contains a set of instructions understood by the computer.
c. This executable file is executed using a command ./a.out or ./filename to get the desired output.
co
1. A C program to print “WELCOME TO JIT”.
#include<stdio.h>
void main()
{
e.
printf(―\n WELCOME TO JIT‖);
}
#include<stdio.h>
void main()
{
int a,b,c;
ue
}
3. A C program to calculate the circumference and area of a circle.
#include<stdio.h>
void main()
{
float r,area,circum;
printf(―\n Enter the value of radius:‖);
scanf(―%f‖,&r);
circum=2*3.142*r;
area=3.142*r*r;
printf(―\n The circumference of a circle is: %f‖,circum);
printf(―\n The area of a circle is:%f‖,area);
}
4. A C program to calculate the Simple Interest
#include<stdio.h>
void main()
{
float p,t,r,si;
printf(―\n Enter the values of p,t and r values‖);
scanf(―%f%f%f‖,&p,&t,&r);
si=(p*t*r)/100;
printf(―Simple Interest=%f‖,si);
}
m
5. A C program to calculate the area of triangle by using the values of sides of a triangle.
#include<stdio.h>
#include<math.h>
co
void main()
{
float area,a,b,c,s;
printf("Enter the values for its sides a,b,c:\n");
scanf("%f%f%f",&a,&b,&c);
s=(a+b+c)/2;
e.
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n The area of the triangle=%f \n",area);
}
dg
#include<stdio.h>
#include<math.h>
ue
void main()
{
float area,l,b;
printf("Enter the values for l and b:\n");
scanf(―%f%f‖,&l.&b);
area=0.5*l*b;
vt
#include<stdio.h>
void main()
{
int a,b;
printf(―\n Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
if(a>b)
{
printf(―\n A is largest―);
}
else
{
printf(―\n B is largest‖);
}
}
8. A C program to determine whether the given number is positive or negative.
#include<stdio.h>
void main()
{
m
int num;
printf("\n Enter the number:\n");
scanf("%d",&num);
if(num>0)
printf("\n Given number is Positive\n");
co
else
printf("\n Given number is Negative\n");
}
9. A C program to check whether the given number is even or odd.
#include<stdio.h>
e.
void main()
{
int rem,n;
dg
#include<stdio.h>
vt
void main()
{
int a,b,c;
printf(―\n Enter the values of a,b and c:‖);
scanf(―%d%d%d‖,&a,&b,&c);
if(a>b && a>c)
{
printf(―\n A is largest―);
}
else if(b>c && b>a)
{
printf(―\n B is largest‖);
}
else
{
printf(―\n C is largest‖);
}
}
Types of C Tokens:
Keywords Ex: if, for, while etc
m
Special Symbols Ex: [ ], { }, ( )
1. Keywords:
Keywords are the tokens which have predefined meaning in C language, whose meaning cannot be
co
changed by the user.
They are also called reserved words.
C Keywords are case sensitive. Therefore all C keywords must be written in small letters.
int ,float,if,while,void etc are valid keywords.
e.
Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).
List of keywords:
auto double int struct
break else long switch
dg
2. Identifiers: Identifiers are the names given to various program elements such as variables, constants, function
names, array names etc.
vt
3. Constants: A constant is a data item which will not change during the execution of a program.
4. Operators: Operator is a symbol (or token) that specifies the operation to be performed on various types of
data.
Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=) and Assignment
operator (=) etc.
5. Special Symbols: [ ], { }, ( ) etc used in the program to execute the code correctly and helps to write a complex
codes by special symbols.
char
double
void
i. int:
An int is a keyword which is used for defining integers in C language.
m
Using int the programmer can inform the compiler that the data associated with this should be
treated as integer.
Using „int‟ compiler determines the size of the data (2 bytes) and reserve space in memory to store
the data.
Integer data types namely:
co
1. short int 2. int 3.long int
Type Size
short int 2 bytes
int 2 bytes
e. long int 4 bytes
Ex: int a,b,c;
ii. float:
dg
iii. double:
It is a keyword which is used to define long floating point numbers in C language.
vt
iv. char:
It is a keyword which is used to define single character or a sequence of characters called String in C
language.
Using this keyword, the compiler determines the size of the data and reserve space in memory to
store the data.
Each character stored in the memory is associated with a unique value called an ASCII (American
Standards Code for Information Interchange).
Size of char
16/32-bit Machine 1 byte
Ex: char ch; // ch variable stores a single character Ex: ch= ‗a‘;
char s[20]; // s variable stores a string(group of characters) Ex: s= ―jit dvg‖;
v. void:
It is an empty data type, since no value is associated with this data type.
It does not occupy any space in the memory.
Size of void
m
16/32-bit Machine 0
co
Constants
A constant is a data item which will not change during the execution of a program.
The constants cannot be modified in the program.
e. Decimal
Integer Octal
dg
Hexadecimal
Numeric
Constant
Fractional form (Ex: 0.56,-9.5)
Floating
Point Exponent form (Ex: 634e-5)
ue
„Declaration‟ tells the computer which storage locations or variables to use in the program.
All variables must be declared before used.
Ex: int a,b,c;
char c;
Initialization
A variable may also be initialized in its declaration. The name is followed by an assignment operator (=)
sign in an expression.
m
Ex: int i=5;
float pi=3.142;
A semicolon(;) terminates every complete statement in C and variables are separated by (,) commas.
The line containg #include does not need (;) because it is a compiler directive, not a C statement.
co
The main() program header does not need (;) because it is not a complete C statement.
**Variable
A variable is a name given to a memory location within the computer that can hold one value at a
e.
time.
OR
A variable is a data item whose value changes during the execution of program.
dg
m
Declaring/Defining a Variable
It is a method of informing the compiler to reserve the memory space for the program data based on
the type of variables.
co
Syntax: datatype v1,v2,…….,vn ;
a + b Expression
a b
_
Operators
Classification of operators
The operators in C can be classified based on:
The number of operands an operator has.
The type of operation being performed.
m
i) Unary operator: An operator which acts on only one operand to produce the result is called Unary
operator.
Ex: -10,-a,*b,++a,a++,b-- etc.
co
ii) Binary operator: An operator which acts on two operands to produce the result is called Binary
operator.
Ex: a+b, a*b, 10/5 etc
iii) Ternary operator: An operator which acts on three operands to produce the result is called
Ternary operator.
Ex: a ? b : c;
e.
2. ***Classification of operators based on type of operation
Arithmetic Operators Ex: +, - , * etc.
dg
i) Arithmetic Operators
The operators that are used to perform arithmetic operations such as addition, subtraction,
multiplication, division and modulus are called arithmetic operators.
These operators perform operations on two operands and hence they are called binary operators.
Operator Symbol Example Result
Addition + 4+2 6
Subtraction - 4-2 2
Division / 4/2 2
Modulus % 4%2 0
(Remainder)
% (modulus operator) divides the first operand by second and returns the remainder.
% (modulus operator) cannot be applied to floating or double.
m
% operator returns remaining value (remainder) of an integer division.
ii) Assignment Operators
An operator which is used to assign the data or result of an expression into a variable (also called
memory location) is called an assignment operator.
co
Assignment operator is denoted by ‗=‘ sign.
Ex: a=b; //value of b is copied into variable a
Ex: a=10;
dg
a=b;
a=a+b;
Area= l*b; //Result of Expression l*b is copied into variable area.
b). Shorthand Assignment Statement
The operators such as +=, -=, *=, /= and %= are called shorthand assignment operators.
Ex 1: a=a+10; // simple assignment
ue
is equivalent to
expr1 = (expr1) op (expr2) ;
i.e., x*=y+1 means x=x*(y+1) ;
1. Post Increment
It increments the value after (post) the operand value is used. i.e., operand value is used first and
m
then the operand value is incremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a++; // b=a=20, a=a+1= 20+1
co
printf(―%d‖,a); // a=21
printf(―%d‖,b); // b=20
}
2. Pre Increment
It increments before (pre) the operand value is used. The operand value is incremented by 1 and this
e.
incremented value is used.
Ex: void main()
{
int a=20,b; // a=20, b?
dg
Decrement Operator
ue
'--' is a decrement operator. This is a unary operator. It decrements the value of a variable by one.
Post Decrement Ex: a--
Decrement
Operator Pre Decrement Ex: --a
1. Post Decrement
vt
It decrements the value after (post) the operand value is used. i.e., operand value is used first and
then the operand value is decremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a--; // b=a=20, a=a-1= 20-1
printf(―%d‖,a); // a=19
printf(―%d‖,b); // b=20
}
2. Pre Decrement
It decrements before (pre) the operand value is used. The operand value is decremented by 1 and
this decremented value is used.
Ex: void main()
{
int a=20,b; // a=20, b?
b=--a; // a=--a=a-1= 20-1, b=a=19
printf(―%d‖,a); // a=19
printf(―%d‖,b); // b=19
}
Eg:
Initially a=10, b=5, c=20 simplify the following expression
W = a++ + ++b + c++ - ++a
= 10 + 6 + 20 - 12
a=11 b=6 c=21 a=12
w = 24
m
i. X = --a + b-- + ++c – a++ - --b
= 9 + 5 + 21 - 9 - 5
a=9 b=4 c=21 a=10 b=5
= 21
co
a= 10 b= 5 c= 21 x= 21
All the relational operators are having a same priority and left to right associativity.
The relational operators have lower precedence than arithmetic operators.
Equality operators
C supports two kinds of equality operators to compare their operands for strict equality or inequality.
equal ==
not equal ! =
Equality operators have lower precedence than the relational operators.
Eg: a=10, b=6
i. C=a>b
C=10>6 10 is greater than 6 so the operator returns value 1, indicating true
C=1
ii. C=a<b
C=10<6 10 is not less than 6, so the operator returns value 0, indicating false
C=0
iii. C=a>=b
C=10>=6
C=1
iv. C=a<=b
C=10<=6
C=0
v. C=a==b
C=10==6 ==checks whether 10 is equal to 6, if equal return 1, else returns 0
C=0
m
vi. C=a!=b
C=10!=6 != checks whether 10 is not equal to 6, if not equal returns 1, else returns 0
C=1
co
v) Logical operators
The operators that are used to combine two or more relational expressions are called logical
operators.
The output of relational expression is true or false, the output of logical expression is also true or
false.
e.
Logical operators available in C:
Operators
not !
dg
and &&
or ||
Logical NOT: The logical NOT operator is denoted by ‗!‘. The output of not operator can be true or false. The
result is true if the operand value is false and the result is false if the operand is true.
vt
Logical AND: The logical AND operator is denoted by ‗&&‘. The output of and operator is true if both the
operands are evaluated to true. If one of the operand is evaluated false, the result is false.
Logical OR: The logical OR operator is denoted by ‗||‘. The output of or operator is true if and only if at least one
of the operands is evaluated to true. If both the operands are evaluated to false, the result is false.
Ex:
i. Given A=10, Evaluate C=!A
A=10 other than value 0, any value is treated as 1. So, A=1
C = !A
C = !1
C=0
ii. Given A=10, B=15, Evaluate C = A&&B
A=10 treated as A=1 (Because other than value 0, any value is treated as 1)
B=15 treated as B=1 (Because other than value 0, any value is treated as 1)
C = A&&B
= 1 && 1
C= 1
iii. Given A=20, B=25, Evaluate C = A || B
A = 20 treated as A=1 (Because other than value 0, any value is treated as 1)
B = 25 treated as B=1 (Because other than value 0, any value is treated as 1)
C = A || B
= 1 || 1
C=1
m
An operator that operates on the three operands is called ternary operator.
Syntax:
(expr1)? expr2: expr3;
co
Where,
- expr1 is evaluated first.
- If expr1 is evaluated to true, then expr2 is evaluated.
- If expr1 is evaluated to false, then expr3 is evaluated.
e.
Example:
1. Write a C program to find the biggest of two numbers using conditional operator.
#include<stdio.h>
dg
void main()
{
int a,b,big;
printf(―Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
big=(a>b)?a:b;
ue
printf(―Big=%d‖,big);
getch();
}
2. Write a C program to find the smallest of two numbers using conditional operator.
vt
#include<stdio.h>
void main()
{
int a,b,small;
printf(―Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
small=(a<b)?a:b;
printf(―Small=%d‖,big);
getch();
}
Bit-wise XOR ^
m
Bit-wise OR |
These may only be applied to integral operand. i.e., char, short, int and long whether signed or unsigned.
co
a. Bit-wise Negate or One‟s Complement(~)
The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified operand is called
One‟s complement operator.
Ex:
i. Let A= 15, Evaluate B = ~A
Convert A = 15 to binary representation and apply Bitwise Negate to binary values
ue
#include<stdio.h>
void main()
{
int a=10,b;
b=~a;
printf(―~%d=%d‖,a,b);
}
Output: ~10=245
Binary Representation(8 bit representation):
10 = 0 0 0 0 1 0 1 0
245= 1 1 1 1 0 1 0 1
MSB is discarded
0 0 0 0 0 1 0 1 a=5
m
b=10
0 0 0 0 1 0 1 0
0 is appended at LSB
co
b = 10
Output: 5<<1 = 10
b=a>>num;
Ex:
i. Let a=10, Evaluate b = a>>1
LSB is discarded
vt
0 0 0 0 1 0 1 0 a=10
0 0 0 0 0 1 0 1 b=5
0 is appended at MSB
b=5
Write a C program to show the usage of Right Shift operator.
#include<stdio.h>
void main()
{
int a=10,b;
b=a>>1;
printf(―%d>>1=%d‖,a,b);
}
Output: 10>>1=5
m
Ex:
co
Binary Representation: (8 bit representation)
10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
02 = 0 0 0 0 0 0 1 0
C =2
e.
Write a C program to show the usage of ‗&‘ operator.
#include<stdio.h>
void main()
{
dg
int a=10,b=6;
c=a&b;
printf(―%d&%d=%d‖,a,b,c);
}
Output: 10&6=2
ue
e. Bit-wise OR (|)
If the corresponding bit positions in both the operands are 0, then OR operation results in 0,
otherwise OR operation results in 1.
Ex:
Let a=10, b=6. Evaluate c = a | b
Binary Representation: 10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
14 = 0 0 0 0 1 1 1 0
C=14
Write a C program to show the usage of ‗|‘ operator.
#include<stdio.h>
void main()
{
int a=10,b=6;
c=a|b;
printf(―%d|%d=%d‖,a,b,c);
}
Output: 10|6=14
m
If the corresponding bit positions in both the operands are different, then XOR operation results in
1, otherwise XOR operation results in 0.
0^0=0
0^1=1
1^0=1
co
1^1=0
Ex:
Let a = 10 and b = 6. Evaluate c = a^b
Binary Representation:
10 = 0 0 0 0 1 0 1 0
e.
06 = 0 0 0 0 0 1 1 0
12 = 0 0 0 0 1 1 0 0
C= 12
#include<stdio.h>
void main()
{
int a=10,b=6;
c=a^b;
printf(―%d^%d=%d‖,a,b,c);
ue
getch();
}
Output: 10^6=12
vt
i) Comma operator
Comma Operator has the least precedence among all the operators and it is left associative operator.
Comma Operator is used in the declaration to separate the variables.
Ex: int a,b,c;
It can be used to separate the items in the list.
Ex: a=12,345,678;
It can be used to combine two or more statements into a single statement.
Ex: sum=a+b,sub=a-b,mul=a*b,div=a/b,mod=a%b;
ii) sizeof()
‗sizeof()‘ operator is used to determine the number of bytes occupied by a variable or a constant in the
memory.
Ex: sizeof(char) 1 byte
sizeof(int) 2 bytes
sizeof(float) 4 bytes
Arithmetic Expressions
The expression consisting of only arithmetic operators such as +, -, *, / and % are called arithmetic
expressions.
m
Mathematical Expression C Equivalent Expression
S=(a + b +c) /2
( )( )( ) area=sqrt(s*(s-a)*(s-b)*(s-c))
co
x=sqrt(2*3.142*n)
a/b
x=-b/(2*a)
e.
a*x*x+b*x+c
dg
ue
vt
m
Right to Left Associativity: In an expression, if there are two or more operators having the same priority and
are evaluated from right-to-left, then the operators are called Right to Left associative operators. We normally
denote using R L. They are also called Right associative operators. This process of evaluating from right to
left is called right associtivity.
co
Ex: i=j=k=10.
Precedence and Associativity Chart
= , += , -= , *= , /=
,%=
16 Comma operator , LR
vt
ue
dg
e.
co
m
Evaluate the expression 100/20<=10-5+100%10-20==5>=1!=20.
m
co
e.
dg
ue
vt
m
co
e.
dg
ue
vt
**Type Conversion
The process of converting the data from one data type to another data type is called Type
Conversion.
Implicit Conversion 1/2.0 1.0/2.0=0.5000
Type
Conversion Explicit Conversion 1/(float)2 1.0/2.0=0.5000
C compiler converts the data type with lower rank to the data type with higher rank. This process of
conversion of data from lower rank to higher rank automatically by the C compiler is called
“Implicit type Conversion”.
char short int int unsigned int long int float double
Lower Rank Higher Rank
Data types Data types
m
If one operand type is same as that of other operand type, no conversion takes place.
Ex: int + int = int, float + float = float
If one operand type is ‗int‘ and other operand type is ‗float‘, then the operand with type int is promoted to
co
‗float‘ (because float is up in ladder compared with int).
The programmer can instruct the compiler to change the type of the operand from one data type to
another data type. This forcible conversion from one data type to another data type is called
e.
“Explicit type Conversion” (Type Casting).
Syntax:
(type) Expression
dg
Print and Format: The function printf (print+f) prints the data in the specified memory location or
variables after “formatting” the data.
printf(): print format
There are two simple forms of printf:
1. One that has just a literal string (a sequence of characters within quotation marks)
General form: printf (“……….”);
literal string
Ex : printf (―welcome to jit‖);
Literal string is placed within a parenthesis. The symbols within that string are printed.
2. One that has values of one or more expressions to be printed.
General form : printf (“………” , ……);
(i) (ii)
(i) Control String, including conversion characters
(ii) list of variables or expressions to be printed.
Ex: printf (― %d%f%c‖ , x,y,z);
m
**Guidelines/Rules for printf()
A printf() always contains a string or format string in quotation marks.
The control string may or may not be followed by some variables or expressions whose value we want
printed.
co
Each value to be printed needs a ‗conversion specification‘ like %d to hold its place in the control string.
This conversion specification describes the exact way the value is to be printed.
When printf() is executed each conversion specification is replaced by the value of the corresponding
e.
expression, then print according to the rules in specification.
The symbols \n or \t in control string tell the machine to skip to new line or tab. It affects the appearance of
the output but not displayed as part of it.
dg
A word or blank space or punctuation symbols within the control string will print exactly as it appears.
If there are variables or expressions to be printed, commas are used to separate them from the control string
and each other, once comma is used as separator, it is not necessary to add blank spaces (not allowed).
ue
m
2.2.2 Formatted input Function: scanf () function
The function scanf (scan+ f) means scan the data in the buffer and format the data.
co
Scan and Format: if data is in buffer, it is converted into appropriate data type using format string
with the help of conversion codes.
scanf() function is used to read the data from the keyboard.
Syntax:
scanf (―format string‖, address list);
e.
Ex : scanf (―%d%f%c‖,&x,&y,&z);
A format specifiers starts with % sign and is followed by conversion code (i.e., d, f, c, s)
Address list is a list of variables, each variable name must be preceded by an (&) ampersand symbol.
The numbers of variables must be equal to the number of format specifiers.
‗&‘ is an ‗Address of‘ operator. It gives the location number used by the variable in memory.
ue
1 + 1 + 1 = 3 variables
1 + 1 = 2 variables
The variables present in scanf must represent the address of memory locations.
Ex1: int a;
scanf(―%d‖,&a); //valid
The type conversion specified in each format specifier must match with the corresponding type of variable
present.
Ex1: int a;
scanf(―%d‖,&a);
//valid
integer integer value
Ex2: int a;
scanf(―%f‖,&a);
m
//invalid
float integer value
co
Format specifiers used in scanf()
Data type Format specifier Description
int %d Converts the data into decimal signed integer
%o Converts the data into octal integer
%x or %X Converts the data into hexadecimal integer
e. %u Converts the data into unsigned integer.
float %f Converts the data into floating point value without Exponent
%e or %E Converts the data into floating point value with exponent
char %c Converts the data into character
dg
%s Converts the data into string
double %lf Converts the data into long float
long int %ld Converts the data into long integer.
Example Programs:
1. Write a C program to calculate the sum of two numbers.
ue
#include <stdio.h>
void main() Enter the values for a, b:
{ 10 20
int a,b,sum; Sum = 30
printf (―Enter the values for a,b:\n‖);
scanf (―%d%d‖,&a,&b);
vt
sum = a+b ;
printf (―sum=%d‖ ,sum);
}
vt
ue
dg
e.
co
m