100% found this document useful (1 vote)
776 views

Popc Module 01 Notes With Question Bank

Uploaded by

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

Popc Module 01 Notes With Question Bank

Uploaded by

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

Principles Of Programming Using C Notes BPOPS203

MODULE 01
INRODUCTION TO C
1.1 Introduction
Computers have become the basic necessity of any organization with serious
objectives. They have made great inroads in everyone‘s everyday life and thinking. They are
used in engineering simulations, teaching, satellite control weather forecasting, etc. Literally,
there is no field left without the use of computers. Types of computers, characteristics, details
about software, input and output devices and role of computers in network is dealt in this
particular topic.

1.2 Definition of a Computer


You get many definitions of computer. Different authors interpret in different way.
I define it something like this:
“It is a electronic device capable of performing complex calculations at an
incomprehensive speed.”

1.3 Characteristics of Computers


The characteristics possessed by computers can be listed as follows:
1. Speed: Computers perform various operations at a tremendous speed. The
speed varies from few micro second (millionth of a second) to nanoseconds (billionth of a
second).
2. Accuracy: Computers are very accurate. They can perform their hundreds
and thousands of operations with great accuracy as their circuits have no mechanical parts to
wear and malfunction. They can run error-less for days at a time.
3. Reliability: Computer output is generally very reliable, subject to the
condition that the input data entering the computer should be correct and the program of
instructions should be reliable and correct. Incorrect input data and unreliable programs give us
computer errors and wrong results. Hence, the phrase
“GARBAGE IN – GARBAGE OUT (GIGO)”

1.4 Historical Development of Computers


The development of computing dates back from the early Sumerian civilization
(4000-1200 BC) when people started to keep records of transactions on clay tables. The actual
computing using a machine started around 3000 BC when Babylons invented the abacus and
Chinese people started usingthem around 1200 BC.
No significant development took place until seventeenth century. In 1642-43,
Blaise Pascal created a gear-driven adding machine named Pascalene. It was the first
mechanical adding machine. Later, in 1673-74, Leibnitz joined the crew with his version of
mechanical calculator named ―Stepped Reckoner‖ that could multiply. In 1801, Jacquard
constructed a Loom, which is the first machine programmed with punched cards. In 1822,
Charles Babbage designed and built his first Difference Engine, which is credited the first
mechanical computer. For this machine, Babbage is known as the ―Father of Computer‖.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 1
Principles Of Programming Using C Notes BPOPS203

Engine made by Babbage. A programming language (Ada) has been named after
her. In 1847-49, Babbage designed his second version of Difference Engine but he could not
complete it. The same machine was conceived in 1991 by the Science Museum in Kensington,
England, and it worked!
In 185, George Bool developed Boolean Logic, which is a system for symbolic and
logical reasoning and the basis for computer design. In 1890, computations for the US Census
were carried out by Herman Hollerith‘s punched card machine. Hollerith started Tabulating
Company, which eventually became IBM.
Before the 20th century, all the machines were mechanical. With the advent of
vacuum tubes, the electronics era of computers started. In 1944, Harvard Mark I, the first large
scale, automatic, general purpose, electromechanical calculator driven by a paper tape
containing the instructions was constructed. In the second version of this machine, Grace
Hopper, found the first computer bug, a bug beaten to death in the jaws of a relay, which she
glued into the logbook. The logbook is now in the National Museum of American History of
the Smithsonian.
The first electronic computer, ENIAC (Electronic Numerical Integrator And
Computer) was built in 1946. It was programmed through rewiring between the various
components. After this, many machines like EDVAC, IBM 701, 704 were built and some of
them were commercially successful at that time because they used transistors in place of
vacuum tubes thereby increasing the reliability and performance.

1.5 Computer Generations


Five Generations of Modern Computers
The development of computers has been divided into generations. Computers of
each generation have certain common characteristics in terms of components used, computing
power, reliability, etc.

First Generation (1945-1956)


The computers of this generation were entirely mechanical or electromechanical
that use vacuum tubes and relays. Some of the important machines of this generation were
Colossus, Mark I, ENIAC, EDVAC, etc. The machines were very slow (3-5 seconds per
calculation to few thousands of calculations per second) and inflexible (mostly built for special
purpose) and could perform basic operations. The machines were huge (e.g., ENIAC – 18000
ft3, 18000 vacuum tubes) and consume alot of power (160 KW for ENIAC).

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 2
Principles Of Programming Using C Notes BPOPS203

Second Generation Computers (1957-1963)


By 1948, the invention of the transistor greatly changed the computer‘s
development. The transistor replaced the large, cumbersome vacuum tube in
televisions, radios and computers. As a result, the size of electronic machinery has
been shrinking ever since. The transistor was at work in the computer by 1956.
Coupled with early advances in magnetic-core memory, transistors led to second
generation computers that were smaller, faster, more reliable and more energy-
efficient than their predecessors.
Throughout the early 1960s, there were a number of commercially successful
second-generation computers used in business, universities, and government. These
second generation computers contained transistors in place of vacuum tubes. They
also contained all the components we associate with the modern-day computer:
printers, tape storage, disk storage, memory, operating systems, and stored
programs. One important example was the IBM 1401. High-level languages such as
COBOL (Common Business-Oriented Language) and FORTRAN (Formula
Translator) came into common use during this time, and have expanded to the
current day. These languages replaced cryptic binary machine code with words,
sentences, and mathematical formulas, making it much easier to program a
computer. New types of careers (programmer, analyst, and computer systems
expert) and the entire software industry began with second-generation computers.
Third Generation Computers (1964-1971)
Though transistors were clearly an improvement over the vacuum tube, they still
generated a great deal of heat, which damaged the computer‘s sensitive internal
parts. The Integrated Circuits (IC) were invented and used to fit even more
components on a single chip. As a result, computers became ever smaller as more
components were squeezed onto the chip. Another third-generation development
included the use of an operating system that allowed machines to run many
different programs at once with a central program that monitored and coordinated
the computer‘s memory and other resources.
Fourth Generation (1971-Present)
After the integrated circuits, the only place to go was down – in size. Large Scale
Integration (LSI) could fit hundreds of components onto one chip. By the 1980s,
Very Large Scale Integration (VLSI) squeezed hundreds of thousands of
components onto a chip. Ultra Large Scale Integration (ULSI) increased that
number into the millions. It also increased their power, efficiency and reliability.
The Intel 4004 chip, developed in 1971, took the integrated circuit one step further
by locating all the components of a computer (central processing unit, memory, and
input and output controls) on a minuscule chip. Whereas previously the integrated
circuit had to be manufactured to fit a special purpose, now one microprocessor
could be manufactured and then programmed to meet any number of demands.
Soon everyday household items such as microwave ovens, television sets and

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 3
Principles Of Programming Using C Notes BPOPS203

automobiles with electronic fuel injection incorporated microprocessors.


Such condensed power allowed everyday people to harness a computer‘s power.
They were no longer developed exclusively for large business or government
contracts. By the mid-1970s, computer manufacturers sought to bring computers to
general consumers. These minicomputers came complete with user-friendly
software packages that offered even non-technical users an array of applications,
most popularly word processing and spreadsheet programs. Pioneers in this field
were Commodore, RadioShack and Apple Computers.
personal computer even more affordable. The number of personal
computers in use more than doubled from 2 million in 1981 to 5.5 million in 1982.
Ten years later, 65 million PCs were being used. Computers continued their trend
towards a smaller size, working their way down from desktop to laptop computers
(which could fit inside a briefcase) to palmtop (that could fit inside a pocket).
As computers became more widespread in the workplace, new ways to
harness their potential developed. As smaller computers became more powerful,
they could be linked together, or networked, to share memory space, software,
information and communicate with each other. As opposed to a mainframe
computer, which was one powerful computer that shared time with many terminals
for many applications, networked computers allowed individual
computers to communicate with each other. A global web of computer
circuitry, the Internet, for example, links computers worldwide into a
single network of information.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 4
Principles Of Programming Using C Notes BPOPS203

Fifth Generation (Present and Beyond)


Defining the fifth generation of computers is somewhat
difficult because the field is in its infancy. With artificial intelligence,
these computers will be able to hold conversations with its human
operators, use visual input, and learn from its own experiences. Using
recent engineering advances, computers are able to accept spoken word
instructions (voice recognition) and imitate human reasoning. The
ability to translate a foreign language is also moderately possible with
fifth generation computers. This feat seemed a simple objective at first,
but appeared much more difficult when programmers realized that
human understanding relies as much on context and meaning as it does
on the simple translation of words.
Many advances in the science of computer design and
technology are coming together to enable the creation of fifth-
generation computers. Two such engineering advances are parallel
processing, which replaces von Neumann‘s single central processing
unit design with a system harnessing the power of many CPUs to work
as one. Another advance is superconductor technology, which allows
the flow of electricity with little or no resistance, greatly improving the
speed of information flow. Computers today have some attributes of
fifth generation computers. For example, expert systems assist doctors
in making diagnoses by applying the problem-solving steps a doctor
might use in assessing a patient‘s needs. It will take several more years
of development before expert systems are in widespread use.

1.6 Computer Types


The computer is divided into three broad categories, and a
category has its own categories given as below:
1. On the basis of Work: Digital, Analog and Hybrid
Computer
2. On the basis of Size: Supercomputer, Mainframe,
Minicomputer and Microcomputer
3. On the basis of Brand: IBM PC and Apple/Macintosh
Computer
4. On the basis of Model: xT Computer (eXtra
echnology), AT Computer (Advance Technology) and PS/2 Computer

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 5
Principles Of Programming Using C Notes BPOPS203

On the Basis of Work: Digital, Analog and Hybrid Computer


Digital Computers
Class of devices capable of solving problems by processing information in
discrete forms. It operates on data, including magnitudes, letters and symbols that are
expressed in binary code, i.e., using only the two digits 0 and 1. By counting, comparing and
manipulating these digits or their combinations according to a set of instructions held in its
memory, a digital computer can perform such tasks as to control industrial processes and
regulate the operations of machines; analyze and organize vast amounts of business data; and
simulate the behaviour of dynamic systems (e.g., global weather patterns and chemical
reactions) in scientific research.

Functional Elements
A typical digital computer system has four basic functional elements: (1) input-
output equipment,
(2) main memory, (3) control unit, and (4) arithmetic logic unit. Any of a
number of devices is used to enter data and program instructions into a computer and to gain
access to the results of the processing operation. Common input devices include keyboards and
optical scanners; output devices include printers and monitors. The information received by a
computer from its input unit is stored in the main memory or, if not for immediate use, in an
auxiliary storage device. The control unit selects and calls up instructions from the memory in
appropriate sequence and relays the proper commands to the appropriate unit. It also
synchronizes the varied operating speeds of the input and output devices to that of the
arithmetic logic unit (ALU) so as to ensure the proper movement of data through the entire
computer system. The ALU performs the arithmetic and logic algorithms selected to process
the incoming data at extremely high speeds—in many cases in nanoseconds (billionths of a
second). The main memory, control unit and ALU, together make up the Central Processing
Unit (CPU) of most digital computer systems, while the input-output devices and auxiliary
storage units constitute peripheral equipment.

Analog Computers
An analog computer is a computer which is used to process analog data. Analog
computers store data in a continuous form of physical quantities and perform calculations
with the help of measures. It is quite different from the digital computer, which makes use of
symbolic numbers to represent results. Analog computers are excellent for situations which
require data to be measured directly without converting into numerals or codes. Analog
computers, although available and used in industrial and scientific applications like control
systems and aircraft, have been largely replaced by digital computers due to the wide range of
complexities involved.
Analog computers were the earliest computer machines developed and were among
the most complicated machines for analog computation and process control. Analog data is not
discrete, but rather is of a continuous nature. Examples of such data are pressure, temperature,
voltage, speed and weight. An analog computer makes use of continuous values and not
discrete values. Because of this, processes with an analog computer cannot be repeated for
exact equivalent results. Unlike digital computers, analog computers are immune to
quantization noise. Some of the common computing elements found in analog computers are
function generators, integrators, comparators and multipliers. Depending on the application,
other specialized components can also be used. Programming on an analog computer involves

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 6
Principles Of Programming Using C Notes BPOPS203

There are certain advantages associated with analog computers. Real-time


operation and simultaneous computation is possible with the help of analog computers. Analog
computers can also provide the insight of the problems and errors in case of analog issues for
users.

Hybrid Computer
A hybrid is a combination of digital and analog computers. It combines the best
features of both types of computers, i.e., it has the speed of analog computer and the memory
and accuracy of digital computer. Hybrid computers are used mainly in specialized applications
where both kinds of data need to be processed. Therefore, they help the user to process both
continuous and discrete data. For example, a petrol pump contains a processor that converts
fuel flow measurements into quantity and price values. In hospital Intensive Care Unit (ICU),
an analog device is used which measures patient‘s blood pressure and temperature, etc., which
are then converted and displayed in the form of digits. Hybrid computers, for example, are used
for scientific calculations, in defense and radar systems.

On the Basis of Size: Supercomputer, Mainframe,


Minicomputer andMicrocomputer
Supercomputer
The most powerful computers in terms of
performance and data processing are the Supercomputers.
These are specialized and task specific computers used by
large organizations. These computers are used for research
and exploration purposes, like NASA uses supercomputers
for launching space shuttles, controlling them and for space
exploration purpose. The supercomputers are very
expensive and very large in size. It can be accommodated
in large air-conditioned rooms; some super computers can
span an entire building

Applications of Supercomputer
1. Used to forecast the weather and global climates
2. Used in military research and defence systems
3. In automobile, aircraft and space craft designing
4. In encrypting and decoding sensitive intelligence information
5. Used in seismography, plasma and nuclear research
6. Protein folding analysis
7. Study of DNA structure and gene engineering
8. Digital film rendering

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 7
Principles Of Programming Using C Notes BPOPS203

Mainframe Computer
Although Mainframes are not as powerful as
supercomputers, but certainly they are quite expensive nonetheless,
and many large firms and government organizations uses
mainframes to run their business operations. The Mainframe
computers can be accommodated in large air- conditioned rooms
because of its size. Supercomputers are the fastest computers with
large data storage capacity, Mainframes can also process and store
large amount of data. Banks educational institutions and insurance
companies use mainframe computers to store data about their
customers, students and insurance policy holders.

Popular Mainframe Computers


� Fujitsu‘s ICL VME
� Hitachi‘s Z800

Applications of Mainframe Computer


1. Government and civilian
2. Credit card processing
3. Bank
4. Marketing
5. Business data processing in large organization
6. Air traffic control system
7. Industrial design

Minicomputer
Minicomputers are used by small businesses and firms. Minicomputers are also
called as ―Mid- range Computers‖. These are small machines and can be accommodated on a
disk with not as processing and data storage capabilities as supercomputers and mainframes.
These computers are not designed for a single user. Individual departments of a large company
or organizations use Minicomputers for specific purposes. For example, a production
department can use Minicomputersfor monitoring certain production process.

Popular Minicomputers
� K-202

� Texas Instrument TI-990


� SDS-92

� IBM Mid-range Computers

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 8
Principles Of Programming Using C Notes BPOPS203

Microcomputer
Desktop computers, laptops, personal digital assistants (PDAs), tablets and
smartphones are all types of microcomputers. The microcomputers are widely used and the
fastest growing computers. These computers are the cheapest among the other three types of
computers. The Microcomputers are specially designed for general usage like entertainment,
education and work purposes. Well-known manufacturers of Microcomputers are Dell, Apple,
Samsung, Sony and Toshiba.
Desktop computers, Gaming consoles, Sound and Navigation system of a car,
Netbooks, Notebooks, PDAs, Tablet PCs, Smartphones, Calculators are all type of
Microcomputer.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 9
Principles Of Programming Using C Notes BPOPS203

1.7 Basic Structure of Computer


.

CPU

Memory
Unit

Input Output
Unit Control Unit
Unit

Arithmeticand
Logic Unit

 Input device accepts the coded information as source program i.e. high level
language. This is either stored in the memory or immediately used by the
processor to perform the desired operations.

 The program stored in the memory determines the processing steps.


Basically the computer converts one source program to an object program.
i.e. into machine language.

 Finally the results are sent to the outside world through output device. All of
these actions are coordinated by the control unit.

 Input unit: - The source program/high level language program/coded


information/simply data is fed to a computer through input devices keyboard
is a most common type.

 Whenever a key is pressed, one corresponding word or number is translated


into its equivalent binary code over a cable & fed either to memory or
processor. Joysticks, trackballs, mouse, scanners etc are other input devices.

 Memory unit: - Its function into store programs and data. It is basically to two
types 1. Primary memory 2. Secondary memory 1. Primary memory: - Is the

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 10
Principles Of Programming Using C Notes BPOPS203

one exclusively associated with the processor and operates at the electronics
speeds programs must be stored in this memory while they are being
executed.

 The memory contains a large number of semiconductors storage cells. Each


ALU Processor Control Unit www.edutechlearners.com 3 of 268
COMPUTER ORGANIZATION capable of storing one bit of information.
These are processed in a group of fixed site called word.

 To provide easy access to a word in memory, a distinct address is associated


with each word location.

 Addresses are numbers that identify memory location.

 Number of bits in each word is called word length of the computer. Programs
must reside in the memory during execution.

 Arithmetic logic unit (ALU):- Most of the computer operators are executed in
ALU of the processor like addition, subtraction, division, multiplication, etc.
the operands are brought into the ALU from memory and stored in high speed
storage elements called register.

 The control and the ALU are may times faster than other devices connected
to a computer system.

 This enables a single processor to control a number of external devices such


as key boards, displays, magnetic and optical disks, sensors and other
mechanical controllers.

 Output unit:- These actually are the counterparts of input unit. Its basic
function is to send the processed results to the outside world.

Examples:- Printer, speakers, monitor etc.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 11
Principles Of Programming Using C Notes BPOPS203

1.8 Central Processing Unit (CPU)


The central processing unit (CPU) is the unit which performs most of the processing
inside a computer. To control instructions and data flow to and from other parts of the
computer, the CPU relies heavily on a chipset, which is a group of microchips located on the
motherboard.
The CPU has two components:
1. Control Unit: It extracts instructions from memory and decodes and executes
them.
2. Arithmetic Logic Unit (ALU): It handles arithmetic and logical operations.
To function properly, the CPU relies on the system clock, memory, secondary
storage, and data and address buses. This term is also known as a central processor,
microprocessor or chip.

The CPU is the heart and


CPU
brain of a computer. It receives data input,
executes instructions and processes Control
Instructions
Unit
information. It communicates with
Processor
input/output (I/O) devices, which send
and receive data to and from the CPU.
Additionally, the CPU has an internal bus Combina-
tional Logic Output
for communication with the internal cache Input

memory, called the backside bus. The


main bus for data transfer to and from the Main
Memory
CPU, memory, chipset, and AGP socket
is called the front-side bus.
The CPU contains internal memory units, which are called registers. These registers
contain data, instructions, counters and addresses used in the ALU‘s information processing.
Some computers utilize two or more processors. These consist of separate physical CPUs
located side by side on the same board or on separate boards. Each CPU has an independent
interface, separate cache, and individual paths to the system front-side bus. Multiple processors
are ideal for intensive parallel tasks requiring multitasking. Multicore CPUs are also common,
in which a single chip contains multiple CPUs.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 12
Principles Of Programming Using C Notes BPOPS203

Overview of C
INTRODUCTION
 A program is a set of instructions for a computer to perform a specified task. C is
a high level language.
 Programs written in C are easy to create, read and understand. C is a general
purpose programming
 A language which was developed by Dennis Ritchie at Bell Lab in 1972.

BASIC CONCEPTS OF A C PROGRAM

Preprocessor directives
Comment lines
Global Declarations
void main()
{
declaration section
statements
input statement
operational statements
output ststements
}

Preprocessor Directives
• The preprocessor accepts the source program and prepare the
source program for compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the
specified file-contents in the beginning of the program.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 13
Principles Of Programming Using C Notes BPOPS203

• For ex:
#include<stdio.h>
Global Declarations
Variables which are declared globally can be used by or
accessible from any function present
in a program.
main()
Function is a set of statements which performs a specific task.
• Every C program should have a function called as main().
• This the first function to be executed always.
• The statements enclosed within left and right brace is called
body of the function. The main() function is divided into 2 parts:
1) Declaration Section
• The variables that are used within the function main() should be
declared in the declaration-section only.
• The variables declared inside a function are
called local-variables. Ex: int a,b,c;
2) Executable Section
• This contains the instructions given to the computer to perform a
specific task.
• The task may be to
→ display a message
→ read data
• Comments are portions of the code ignored by the compiler. The
comments allow the user to make simple notes in the source-code.
// this is an example for single line comment
/* this is an example
for multiple line
comment */

Example:
// C program to add two numbers
#include<stdio.h>
void main()
{
int a, b, c;

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 14
Principles Of Programming Using C Notes BPOPS203

printf(―enter the values of a and b\n‖);


scanf(―%d%d‖,&a,&b);
c=a+b;
printf(―the result is %d\n‖,c);
}

HOW TO LEARN C LANGUAGE?


English is a universal language used to communicate with others.

In the same way, C is a language used to communicate with computer. In other words,
C is used to instruct computer to perform particular task.

The task can be

→ simple task like adding 2 numbers or


→ complex task like building a railway reservation system
Before you play the game, you should learn rules of the game. So that you can play
better and win easily. In the same way, to write C programs, you should learn rules of
C language.

STEPS TO LEARN C LANGUAGE


Step 1: Before speaking any language, you should first learn alphabets. In the same
way, to learn C language, you should first learn alphabets in C.
Step 2: Then, you should learn how to group alphabets in particular sequence to
form a meaningful word. In the same way, in C language, you should learn
tokens (i.e. words).
Step 3: Then, you should learn how to group the words in particular sequence to
form a meaningful sentence. In the same way, in C language, you should learn
instruction (i.e. sentence).
Step 4: Then, you should learn how to group the sentences in particular
sequence to form a meaningful paragraph. In the same way, in C language, you
should learn program (i.e. paragraph).

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 15
Principles Of Programming Using C Notes BPOPS203

CHARACTER SET

Character-set refers to the set of alphabets, letters and some special characters that are
valid in C language.

There are 256 characters in a Character set.

For example, the characters in C are:

→ Letters A-X, a-z, both upper and lower


→ Digits 0-9
→ Symbols such as + - * / %
→ White spaces \t \n

C TOKENS
A token is a smallest element of a C program.

One or more characters are grouped in sequence to form meaningful words. These
meaningful words are called tokens.

The tokens are broadly classified as follows

→ Keywords ex: if, for, while


→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "sri"
→ Operators ex: + - * /
→ Special symbols ex: [], (), {}

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 16
Principles Of Programming Using C Notes BPOPS203

KEYWORDS
A token which have predefined meaning in C language is called a keyword.
• Keywords are tokens which are used for their intended purpose only.
• Keywords are the instructions given to the Compiler.
• Each keyword has fixed meaning and that cannot be changed by
user. Hence, they are also called reserved-words.
• There are 32 keywords . int, float, char, double, void, case,
switch, if, else, elseif, return, auto, register, static, const, for, while, do-while,
default etc.

Rules for using keywords


• Keywords cannot be used as a variable or function.
• All keywords should be written in lower letters.

IDENTIFIERS

Identifiers do not have any predefined meaning in C language.


• As the name indicates, identifier is used to identify various entities
of program such as variables, constants, functions etc.
• Identifiers are not the instructions given to the Compiler
• In other words, an identifier is a word consisting of sequence of
→ Letters
→ Digits or
→ "_"(underscore)
• For ex:
area, length, breadth

Rules for Constructing an Identifier:

1) The first character must be a letter or an underscore, and then


followed by any number of digits, letters and underscores.
2) Keywords cannot be used as an identifier.
3) No extra symbols and spaces are allowed (other than letters, digits
and underscore)
4) Identifier should not have two consecutive underscores.
5) Length of an identifier can be up to a maximum of 31 characters

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 17
Principles Of Programming Using C Notes BPOPS203

Example to Identify valid /Invalid Identifiers:

1. num
Valid identifier
2. a_one
valid identifier as first character begins with letter
3. 2sum
Invalid Identifier because first character begins with digit
4. $sum
Invalid because no extra symbols are allowed other than under score
5. for
Invalid as for is a keyword
6. area length
Invalid because no spaces are allowed

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 18
Principles Of Programming Using C Notes BPOPS203

File Used in C Program


A C program uses four types of files as follows:

Source Code File

 This file includes the source code of the program.


 The extension for these kind of files are '.c'. It defines the main and
many more functions written in C.
 main() is the starting point of the program. It may also contain other
source code files.

Header Files

They have an extension '.h'. They contain the C function declarations and
macro definitions that are shared between various source files.

Advantages of header files:


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 in any file in which the functionalities of this subroutine are
required.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 19
Principles Of Programming Using C Notes BPOPS203

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

Standard header files


C provides us with some standard header files which are available easily.
Common standard header files are:
i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.
The header files are added at the start of the source code so that they can be used by
more than one function of the same file.

Object files

They are the files that are generated by the compiler as the source code file is processed.
These files generally contain the binary code of the function definitions.
The object file is used by the linker for producing an executable file for combining the
object files together. It has a '.o' extension.

Executable file

This file is generated by the linker.

Various object files are linked by the linker for producing a binary file which will be executed
directly.They have an '.exe' extension.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 20
Principles Of Programming Using C Notes BPOPS203

Compilers in C

 A compiler is a special program that translates a programming language's source


code into machine code, bytecode or another programming language.

 The source code is typically written in a high-level, human-readable language such


as Java or C++.

 A programmer writes the source code in a code editor or an integrated development


environment (IDE) that includes an editor, saving the source code to one or more
text files.

 A compiler that supports the source programming language reads the files, analyzes
the code, and translates it into a format suitable for the target platform.

 Compilers that translate source code to machine code target specific operating
systems and computer architectures.

 This type of output is sometimes referred to as object code (which is not related
to object-oriented programming).

 The outputted machine code is made up entirely of binary bits -- 1s and 0s -- so it


can be read and executed by the processors on the target computers.

 For example, a compiler might output machine code for the Linux x64 platform or
Linux ARM 64-bit platform

The complete set of escape sequences are:


Escape Sequences purpose

\b Backspace
\f Form feed
\n Newline
\r Return

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 21
Principles Of Programming Using C Notes BPOPS203

\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
Example:

#include<stdio.h>
void main()
{
printf(―Welcome to C \n‖);
printf (―Hello\tWorld\n‖);

}
Output:

Welcome to C
Hello World

Data types
C supports 5 primary data types:
1) int
• An int is a keyword which is used to define integers.
• Using int keyword, the programmer can inform the compiler that
the data associated with this keyword should be treated as integer.
• C supports 3 different sizes of integer:
→ short int
→ int
→ long int
2) float
• A float is a keyword which is used to define floating point numbers.
3) double
• A double is a keyword used to define long floating point numbers.
4) char
• A char is a keyword which is used to define single character.
5) void
• void is an empty data type. Since no value is associated with this
data type, it does not occupy any space in the memory.
• This is normally used in functions to indicate that the function does not
return any value.

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 22
Principles Of Programming Using C Notes BPOPS203

VARIABLES

A variable is an identifier whose value can be changed during execution of the program.
In other words, a variable is a name given to a memory-location where the
data can be stored.
• Using the variable-name, the data can be
→ stored in a memory-location and
→ accessed or manipulated

Rules for defining a variable


1) The first character must be a letter or an underscore, and then
followed by any number of digits, letters and underscores.
2) Keywords cannot be used as a variable.
3) No extra symbols and spaces are allowed (other than letters, digits
and underscore)
4) Variable should not have two consecutive underscores.
5) Length of a variable can be up to a maximum of 31 characters

Examples:
Valid variables:
A11
Aaa
A_5
abcd
principle_amount,
sum_of_digits

Invalid
variables:
3fact //violates rule 1
sum= sum-of-digits 62$ //violates rule 3
for int if //violates rule 2
Declaration of Variable
• The declaration tells the complier
→ what is the name of the variable used
→ what type of date is held by the variable

The syntax is shown below:

Datatype v1,v2..

int a,b;
char ch1, ch2;

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 23
Principles Of Programming Using C Notes BPOPS203

CONSTANTS

A constant is an identifier whose value remains fixed throughout the execution of the
program.
• The constants cannot be modified in the program.
• For example:
1, 3.14512,‘a‘

• Different types of constants are:


1) Integer Constant
• An integer is a whole number without any fraction part. It consists of
sequence of digits.

• There are 3 types of integer constants:

a. Binary constants : 0 and 1 values

b. Decimal constants (0 1 2 3 4 5 6 7 8 9)
Combination of digits from 0-9 is called decimal constant.
For ex: 0, -9, 22

c. Octal constants (0 1 2 3 4 5 6 7)
Combination of digits with 0-7 with prefix 0 is called Octal
constant.
For ex: 021, 077, 033

d. Hexadecimal constants (0 1 2 3 4
5 6 7 8 9 A B C D E F)
Combination of digits
with 0-9 and then followed with A-F.

It must begin with 0x.

For ex: 0x7f, 0x2a, 0x521

2) Floating Point Constant


• The floating point constant is a real number.
• The floating point constants can be represented using 2 forms:
i) Fractional Form
• A floating point number represented using fractional form has an
integer part followed by a dot and a fractional part.
• For ex:
0.5, -0.99

ii) Scientific Notation (Exponent Form)


• The floating point number represented using scientific notation has
three parts namely: mantissa, E and exponent.
• For ex:
9.86E3 imply 9.86*103

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 24
Principles Of Programming Using C Notes BPOPS203

3. Character Constant
• A symbol enclosed within a pair of single quotes(' ‗) is called a
character constant.
• Each character is associated with a unique value called an ASCII
(American Standard Code for Information Interchange) code.
• For ex:
'9', 'a', '\n'

4. String Constant
• A sequence of characters enclosed within a pair of double quotes(―)
is called a string constant.
• The string always ends with NULL (denoted by \0) character.
• For ex:
"9" "a" "hello" "\n‖

5. Escape Sequence Characters/Backslash Constants


• An escape sequence character begins with a backslash and is
followed by one character.
• A backslash (\) along with some characters give rise to special
print effects by changing (escaping) the meaning of some characters.

INPUT/OUTPUT STATEMENTS

In C Language input and output function are available as C compiler functions or C


libraries provided with each C compiler implementation. These all functions are
collectively known as Standard I/O Library function. Here I/O stands for Input and
Output used for different inputting and outputting statements. These I/O functions are
categorized into three processing functions. Console input/output function (deals with
keyboard and monitor), disk input/output function (deals with floppy or hard disk), and
port input/output function (deals with a serial or parallel port). As all the input/output
statements deals with the console, so these are also Console Input/Output functions.
Console Input/Output function access the three major files before the execution of a C
Program. These are as follows:

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 25
Principles Of Programming Using C Notes BPOPS203

 stdin: This file is used to receive the input (usually is keyborad file, but can
also take input from the disk file).
 stdout: This file is used to send or direct the output (usually is a monitor
file, but can also send the output to a disk file or any other device).
 stderr: This file is used to display or store error messages.

Input Ouput Statement

Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).

Input means to provide the program with some data to be used in the program and

Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.

There are mainly two of Input/Output functions are used for this purpose. These
are discussed as:

 Unformatted I/O functions


 Formatted I/O functions

Unformatted I/O functions

There are mainly six unformatted I/O functions discussed as follows:

 getchar()
 putchar()
 gets()

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 26
Principles Of Programming Using C Notes BPOPS203

 puts()
 getch()
 getche()

getchar()

This function is an Input function. It is used for reading a single character from the
keyboard. It is a buffered function. Buffered functions get the input from the keyboard and
store it in the memory buffer temporally until you press the Enter key.

The general syntax is as:


v = getchar();

where v is the variable of character type. For example:


char n;
n = getchar();

A simple C-program to read a single character from the keyboard is as:


/*To read a single character from the keyboard using the getchar()
function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}

putchar()

This function is an output function. It is used to display a single character on the


screen. The general syntax is as:
putchar(v);

where v is the variable of character type. For example:


char n;
putchar(n);

A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:
/*Program illustrate the use of getchar() and putchar() functions*/
#include <stdio.h>
main()
{

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 27
Principles Of Programming Using C Notes BPOPS203

char n;
n = getchar();
putchar(n);
}
gets()

This function is an input function. It is used to read a string from the keyboard. It is also a
buffered function. It will read a string when you type the string from the keyboard and
press the Enter key from the keyboard. It will mark null character (‗\0‘) in the memory at
the end of the string when you press the enter key. The general syntax is as:

gets(v);

where v is the variable of character type. For example:


char n[20];
gets(n);

A simple C program to illustrate the use of gets() function:


/*Program to explain the use of gets() function*/
#include <stdio.h>
main()
{
char n[20];
gets(n);
}

puts()

This is an output function. It is used to display a string inputted by gets() function. It is also
used to display a text (message) on the screen for program simplicity. This function
appends a newline (―\n‖) character to the output.

The general syntax is as:


puts(v);

or
puts("text line");

where v is the variable of character type.


Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27
Page 28
Principles Of Programming Using C Notes BPOPS203

A simple C program to illustrate the use of puts() function:

/*Program to illustrate the concept of puts() with gets() functions*/


#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}

The Output is as follows:


Enter the Name
Geek
Name is:
Geek

getch()

This is also an input function. This is used to read a single character from the keyboard like
getchar() function. But getchar() function is a buffered is function, getchar() function is a
non-buffered function. The character data read by this function is directly assigned to a
variable rather it goes to the memory buffer, the character data is directly assigned to a
variable without the need to press the Enter key.

Another use of this function is to maintain the output on the screen till you have
not press the Enter Key. The general syntax is as:
v = getch();

where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
getch();
}

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 29
Principles Of Programming Using C Notes BPOPS203

The output is as follows:


Enter the Char
Char is L

getche()

All are same as getch(0 function execpt it is an echoed function. It means when
you type the character data from the keyboard it will visible on the screen. The
general syntax is as:
v = getche();

where v is the variable of character type.

A simple C program to illustrate the use of getch() function:


/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}

The output is as follows:


Enter the Char L
Char is L

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 30
Principles Of Programming Using C Notes BPOPS203

Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has been
arranged in a particular format. There are mainly two formatted I/O functions
discussed as follows:

 scanf()
 printf()

scanf()

The scanf() function is an input function. It used to read the mixed type of data
from keyboard. You can read integer, float and character data by using its
control codes or format codes. The general syntax is as:
scanf("control strings",arg1,arg2,..............argn);

or
scanf("control strings",&v1,&v2,&v3,................&vn);

Where arg1,arg2,……….argn are the arguments for reading and


v1,v2,v3,……..vn all are the variables.

The scanf() format code (spedifier) is as shown in the below table:

Format Code Meaning

%c To read a single character

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%e To read a float value exponential

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%g To read double float value

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 31
Principles Of Programming Using C Notes BPOPS203

%h To read short integer

%i To read an integer (decimal, octal, hexadecimal)

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

%s To read a string

%[..] To read a string of words from the defined range

%[^] To read string of words which are not from the defined range

Example Program:
/*Program to illustrate the use of formatted code by using the formatted
scanf() function */
#include <stdio.h>
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
printf()

This ia an output function. It is used to display a text message and to display the
mixed type (int, float, char) of data on screen. The general syntax is as:
printf("control strings",&v1,&v2,&v3,................&vn);

or
printf("Message line or text line");

Where v1,v2,v3,……..vn all are the variables.

The control strings use some printf() format codes or format specifiers or
conversion characters. These all are discussed in the below table as:

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 32
Principles Of Programming Using C Notes BPOPS203

Format Code Meaning

%c To read a single character

%s To read a string

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%e To read a float value exponential

%g To read double float value

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

Example Program:
/*Below the program which show the use of printf() function*/
#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 33
Principles Of Programming Using C Notes BPOPS203

QUESTION BANK
1. Define Computer. Explain the organization of basic
computer model with a neat diagram.
2. Explain the generation of computers
3. List and explain the types of computers
4. List and explain any 4 input and output devices.
5. With a suitable example, Explain the basic structure of C
program
6. What are the basic data types available in C.
7. Define the variable, Explain the rules to declare a variable
with an example.
8. Write a c program
i. Find the area of circle
ii. Area of rectangle
iii. Area of square
iv. Area of parallelogram
v. Area of Triagle
vi. Volume of a sphere
vii. Newtons law of motion

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 34
Principles Of Programming Using C Notes BPOPS203

viii. Perimeter of a circle


ix. Addition of 4 numbers
x. Subtraction of 2 numbers
xi. Multiplication of 4 numbers
xii. Printing your home address

9. List and explain Files used in C program.


10. Explain Variables and Constants in C programming.
11. Explain Formatted I/O functions with an example
for each.
12. Explain Unformatted I/O functions with an example
for each

Prepared By, Shanta Kallur, Dept. Of CSE, KLEIT, Hubballi-27


Page 35

You might also like