0% found this document useful (0 votes)
70 views35 pages

BPPCS103 203 Module1-Materials1

Uploaded by

sushmitha.xox
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
0% found this document useful (0 votes)
70 views35 pages

BPPCS103 203 Module1-Materials1

Uploaded by

sushmitha.xox
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

Introduction to Computer BPPCS103, Module-1

Principles of Programming using C

Semester 1st / 2nd


Principal of Programming using C
Category: IPCC/ESC
Stream: CSE (Common to CSE, ISE, AI&ML, CSE[IC], CSD)
(Theory / Practical)
Course Code : BPPCS103/BPPCS203 CIE : 50 Marks
Teaching Hours L : T : P : 2:0:2 SEE : 50 Marks
Total Hours : 40 Total : 100 Marks
Credits 3 SEE Duration : 3 Hrs

Module-1 (8 Hours of Pedagogy)


Basics of Programming: Introduction to computers, input and output devices, program design tools:
the meaning of Algorithms, Flowcharts, Pseudocode, Memory concepts.
C Fundamentals: Importance of ‘C’ Language, History, Structure of ‘C’ program, Sample ‘C’ Program,
Files used in a C program, Compilers, Compiling and executing C programs, variables, constants, data
types, Enumeration, Input/output statements in C.
Text Books
Reema Thareja, “Computer fundamentals and programming in C”, Oxford
1. University, Second edition, 2017.
Reference Text Books

1. E. Bala Guruswamy, “Programming in ANSI C”, 7th Edition, Tata McGraw-Hill.

Brian W. Kernighan and Dennis M. Ritchie, “The ‘C’ Programming Language”,


2. Second edition, Prentice Hall of India.

3. Yashwanth Kanethkar, “Let us C” ,13th Edition, BPB Publications.


Brian W. Kernighan, Dennis M. Ritchie, Programming Languages C with
4. Practicals, Margham Publications; 1 edition (2012).

Web links and Video lectures (e-Resources)


1. https://nptel.ac.in/courses/106/105/106105171/ MOOC courses can be
adopted for more clarity in understanding the topics and verities of problem
solving methods.
2. elearning.vtu.ac.in/econtent/courses/video/BS/15PCD23.htm
3. https://tinyurl.com/4xmrexre
Introduction to Computer BPPCS103, Module-1

CONTENTS OF MODULE-1
• Definition of Computer
• Characteristics of Computers
• Generations of Computers
• Types/Application of Computer
• Applications of Computers
• Input and Output Devices
• Program Design Tools
• Introduction to C Programming
• Input and Output Functions
Introduction to Computer BPPCS103, Module-1

Chapter 1
Introduction to Computers
1.1 COMPUTER
A computer, in simple terms, 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.
We all have seen computers in our homes, schools, and colleges. In fact, in today’s scenario, we find
computers in most aspects of our daily lives. For some of us, it is hard to even imagine a world
without them.

In the past, computers were extremely large in size and often required an entire room for
installation. These computers consumed enormous amounts of power and were too expensive to be
used for commercial applications. Therefore, they were used only for limited tasks, such as
computing trajectories for astronomical or military applications. However, with technological
advancements, the size of computers became smaller and their energy requirements reduced
immensely. This opened the way for adoption of computers for commercial purposes.

1.2 CHARACTERISTICS OF COMPUTERS


These days, computers have become a crucial part of our everyday lives, and we need
computers just like we need televisions, telephones, or other electronic devices at home. Computers
are basically meant to solve problems quickly and accurately. The important characteristics of a
computer (refer to Figure 1.1) are discussed in the following text.

Figure 1.1 Characteristics of computers

Speed Computers can perform millions of operations per second, which means that data that
Introduction to Computer BPPCS103, Module-1
mayotherwise take many hours to process is output as information in the blink of an eye. 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.

Accuracy: A computer is a very fast, reliable, and robust electronic device. It always gives
accurate results, provided the correct data and set of instructions are input to it. Hence, in the event
of an error, it is the user who has fed the incorrect data/program is responsible. This clearly means
that the output generated by a computer depends on the given instructions and input data. If the
input data is wrong, then the output will also be erroneous. In computer
terminology, this is known as garbage-in, garbage-out (GIGO).
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.
Diligence: Unlike humans, 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.
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 simultaneously. On the
PC that you use at home, you may play a game, compose and send e-mails, listen to music, etc.
Therefore, computers are versatile devices as they can perform multiple tasks of different nature at
the same time.
Memory: Similar to humans, computers also have memory. Just the way we cannot store
everything in our memory and need secondary media, such as a notebook, to record certain
important things, computers also have internal or primary memory (storage space) as well as
external or secondary memory. While the internal memory of computers is very expensive and
limited in size, the secondary storage is cheaper and of bigger capacity.
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 fordata storage. Some examples of secondary devices include floppy disks, optical disks (CDs
and DVDs), hard disk drives (HDDs), and pen drives.
No IQ: Although the trend today is to make computers intelligent by inducing artificial
Introduction to Computer BPPCS103, Module-1
intelligence (AI) in them, they still do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
Economical: Today, computers are considered as short term investments for achieving long-
term gains. 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.

1.3 GENERATION OF COMPUTER


First Generation (1942–1955)
Hardware Technology First generation computers were manufactured using thousands of vacuum
tubes(see Figure 1.3); a vacuum tube is a device made of fragile glass. 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.

Used for Scientific applications

Examples ENIAC, EDVAC, EDSAC, UNIVAC I, IBM 701

Highlights

• They were the fastest calculating device of those times

• Computers were too bulky and required a complete room for storage

• Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently

• Required air-conditioned rooms for installation

• Costly

• Difficult to use

• Required constant maintenance because vacuum tubes used fi laments that had limited life
time.Therefore, these computers were prone to frequent hardware failures

Figure 1.3 Vacuum tube


Introduction to Computer BPPCS103, Module-1

Second Generation (1955–1964)

Hardware Technology Second generation computers were manufactured using transistors (see
Figure 1.4). Transistors were reliable, powerful, cheaper, smaller, and cooler than vacuum tubes.
Memory Magnetic core memory was used as primary memory; magnetic tapes and magnetic disks
were used to store data and instructions. These computers had faster and larger memory than the fi
rst generation computers.
Software Technology Programming was done in high level programming languages. Batch
operating system was used.
Used for Scientific and commercial applications
Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC
Highlights
• Faster, smaller, cheaper, reliable, and easier to use than the first generation computers. They
consumed1/10th the power consumed by first generation computers
• Bulky in size and required a complete room for its installation

• Dissipated less heat than first generation computers but still required air-conditioned rooms

• Costly

• Difficult to use

Figure 1.4 Transistors


Introduction to Computer BPPCS103, Module-1

Third Generation (1964–1975)

Hardware Technology Third generation computers were manufactured using integrated chips
(ICs) (shown in Figure 1.5). ICs consist of several components such as transistors, capacitors, and
resistors ona single chip to avoid wired interconnections between components. These computers
used SSI and MSI technology. Minicomputers came into existence.
Note- Initially, ICs contained 10–20 components. This technology was called Small Scale Integration
(SSI). Later, it was enhanced to contain about 100 components. This was called MSI (Medium Scale
Integration).
Memory Larger magnetic core memory was used as primary memory; larger capacity magnetic
tapes and magnetic disks were used to store data and instructions.
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. This allowed users to invest only in the software they need.
Used for Scientific, commercial, and interactive online applications
Examples IBM 360/370, PDP-8, PADP-11, CDC6600
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 but still required air-conditioned rooms

• Costly

• Easier to use and upgrade.

Fourth Generation (1975–1989)

Hardware Technology Fourth generation computers were manufactured using ICs with LSI (Large
Scale Integrated) and later with VLSI technology (Very Large Scale Integration). Microcomputers
came into existence. Use of personal computers became widespread. High speed computer networks
in the form of LANs, WANs, and MANs started growing. Besides mainframes, supercomputers were
also used.
Introduction to Computer BPPCS103, Module-1

Figure 1.5 Integrated circuits


Memory Semiconductor memory was used as primary memory, large capacity magnetic disks were
usedas built-in secondary memory. Magnetic tapes and floppy disks were used as portable storage
devices.

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 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.
Used for Scientific, commercial, interactive online, and network applications
Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY-1, CRAY-2, CRAY-X/MP

Figure 1.6: VLSI Chip


Introduction to C BPPCS103, Module-1

Fifth Generation (1989–Present)


Hardware Technology Fifth generation computers are manufactured using ICs with ULSI
Ultra Large Scale Integrated) technology. The use of Internet became widespread and very
powerful mainframes, desktops, portable laptops, and smartphones are being used
commonly. Supercomputers use parallel processing techniques.

Memory Semiconductor memory is used as primary memory; large capacity magnetic


disks are used as built-in secondary memory. Magnetic tapes and floppy disks were used
as portable storage devices, which have now been replaced by optical disks and USB flash
drives.
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.

Highlights
• Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers
• Speed of microprocessors and the size of memory are growing rapidly.

Figure 1.7: ULSI Chip


Introduction to C BPPCS103, Module-1

1.4 CLASSIFICATION/TYPES OF COMPUTERS


Computers can be broadly classified into four categories based on their speed, amount
of data that they can process and price (refer to Figure 1.8). These categories are as
follows:

• Supercomputers

• Mainframe computers

• Minicomputers

• Microcomputers

Figure 1.8: Classification of Computers

1.4.1 Supercomputers

Among the four categories, the supercomputer is the fastest, most powerful, and
most expensive computer. Supercomputers were first developed in the 1980s to process
large amounts of data and to solve complex scientific problems. Supercomputers use
parallel processing technology and can perform more than one trillion calculations in a
second.

1.4.2Mainframe Computers

Mainframe computers are large-scale computers (but smaller than


supercomputers). These are very expensive and need a very large clean room with air
conditioning, thereby making them very costly to deploy. As with supercomputers,
mainframes can also support multiple processors. For example, the IBM S/390
mainframe can support 50,000 users at the same time. Users can access mainframes by
either using terminals or via PCs. The two types of terminals that can be used with
mainframe systems are as follows:
Introduction to C BPPCS103, Module-1

Dumb Terminals

Dumb terminals consist of only a monitor and a keyboard (or mouse). They do not have
their own CPU and memory and use the mainframe system’s CPU and storage devices.

Intelligent Terminals

In contrast to dumb terminals, intelligent terminals have their own processor and thus
can perform some processing operations. However, just like the dumb terminals, they do
not have their own storage space. Usually, PCs are used as intelligent terminals to
facilitate data access and other services from 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. IBM is the
major manufacturer of mainframe computers. Some examples of mainframe computers
include IBM S/390, Control Data CYBER 176, and Amdahl 580.

1.4.3Minicomputers

As the name suggests, 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, the capabilities of minicomputers fall
between mainframe and personal computers.

1.4.4Microcomputers

Microcomputers, commonly known as PCs, are very small and cheap. The first
microcomputer was designed by IBM in 1981 and was named IBM-PC. Later on, many
computer hardware companies copied this design and termed their microcomputers as
PC-compatible, which refers to any PC that is based on the original IBM PC design.
Another type of popular PC is designed by Apple. PCs designed by IBM and other PC-
compatible computers have a different architecture from that of Apple computers.
Moreover, PCs and PC-compatible computers commonly use the Windows operating
system, while Apple computers use the Macintosh operating system (MacOS). PCs can be
classified into the following categories:

Desktop PCs

A desktop PC is the most popular model of PCs. The system unit of the desktop PC
can be placedflat on a desk or table. It is widely used in homes and offices.
Introduction to C BPPCS103, Module-1

Laptops

Laptops (Figure 1.9) are small microcomputers that can easily fi t inside a
briefcase. They are very handy and can easily be carried from one place to another. They
may also be placed on the user’s lap (thus the name). Hence, laptops are very useful,
especially when going on long journeys. Laptops operate on a battery and do not always
have to be plugged in like desktop computers.

Workstations

Workstations are single-user computers that have the same features as PCs, but
their processing speed matches that of a minicomputer or mainframe computer.
Workstation computers have advanced processors, more RAM and storage capacity than
PCs. Therefore, they are more expensive and powerful than a normal desktop computer.

Network Computers

Network computers have less processing power, memory, and storage than a
desktop computer. These are specially designed to be used as terminals in a networked
environment. For example, some network computers are specifically designed to access
data stored on a network (including the Internet and intranet)

Handheld Computers

The mid-1990s witnessed a range of small personal computing devices that are
commonly knownas handheld computers, or mobile computers. These computers are
called handheld computers because they can fit in one hand, while users can use the
other hand to operate them.

Handheld computers are very small in size, and hence they have small-sized
screens and keyboards. These computers are preferred by business travellers and mobile
employees whose jobs require them to move from place to place. Some examples of
handheld computers are as follows:

• Smartphones • Tablet PCs

Smartphones These days, cellular phones are web-enabled telephones. Such phones are
also known as smartphones because, in addition to basic phone capabilities, they also
facilitate the users to access the Internet and send e-mails, edit Word documents,
generate an Excel sheet, create a presentation, and lots more. Smartphones run an
advanced mobile operating system that enables it to run various applications. The four
Introduction to C BPPCS103, Module-1

major mobile operating systems are iOS, Android, BlackBerryOS, and Windows Mobile.
Smartphones also have a CPU, more storage space, more memory, and a larger screen
than a regular cell phone. In a nutshell, smartphone refers to a multi-functional mobile
phone handset that packs in varied functionalities from a camera to a web browser to a
high-density display.

Tablet PCs A tablet PC (see Figure 1.10) is a computing device that is smaller than a
laptop, but bigger than a smartphone. Features such as user-friendly interface,
portability, and touch screen have made them very popular in the last few years. These
days, a wide range of high-performance tablets are available in the market. While all of
them look similar from outside, they may differ in features such as operating system,
speed of data connectivity, camera specifications, size of the screen, processing power,
battery life, and storage capability.

1.5 APPLICATIONS OF COMPUTERS


When the first computers were developed, they were used only in the fields of
mathematics and science. In fact, the first effective utilization of computers was for
decoding

messages in military applications. Later on, computers were used in real-time control
systems, like for landing on the moon. However, with the advancement of technology, the
cost of computers and their maintenance declined. This opened the way for computers
to be extensively used in the business and commercial sector for information processing.
Today, computers are widely used in fields such as engineering, health care, banking,
education, etc. Let us discuss how computers are being effectively utilized to perform
important tasks.

Word processing Word processing software enables users to read and write
documents. Users can also add images, tables, and graphs for illustrating a concept. The
software automatically corrects spelling mistakes and includes copy–paste features
(which is very useful where the same text has to be repeated several times).

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. 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 (irrespective of the physical location of that person). Video
Introduction to C BPPCS103, Module-1

conferencing tools are becoming popular for conducting meetings with people who are
unable to be present at a particular place.

Digital video or audio composition Computers make audio or video composition and
editing very simple. This has drastically reduced the cost of equipment to compose music
or make a fi lm. Graphics engineers use computers for developing short or full-length
films and creating 3-D models and special effects in science fiction and action movies.

Desktop publishing Desktop publishing software enables us to create page layouts for
entire books. After discussing how computers are used in today’s scenario, let us now
have a look at the different areas where computers are being widely utilized.

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 geneticinformation to facilitate gene-based drug discovery and
development. The need for analysis has become even more important with enormous
amount of genomic information available publicly from the Human Genome Project.

Health care Last few years have seen a massive growth of computers and smartphone
users. Like in our daily lives, computers have also become a necessary device in the
health care industry. The following are areas in which computers.

o Storing records To begin with, computers are first and foremost used to
store the medical records of patients. Earlier, patient records were kept
on paper, with separate records dealing with different medical issues from
separate healthcare organizations.

o 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 variety of surgical procedures. In
such surgeries, a small incision is made, and then asmall surgical tool with
an attached camera is placed inside the patient’s body. This reduces the
risk of complications from a larger surgical wound, and minimizes damage
done to the patient’s body.

Better diagnosis and treatment Computers help physicians make better


diagnoses and recommend treatments. Moreover, computers can be used to compare
expected results with actual results in order to help physicians make better decisions.

Meteorology Meteorology is the study of the atmosphere. This branch of science


Introduction to C BPPCS103, Module-1

observes variables of Earth’s atmosphere such as temperature, air pressure, water


vapour, and the gradients and interactions of each variable, and how they change over
time. Meteorology has applications in many diverse fields such as the military, energy
production, transport, agriculture, and construction.

Multimedia and Animation Multimedia and animation that combine 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.

Retail Business Computers are used in retail shops to enter orders, calculate costs, and
print receipts. They are also used to keep an inventory of the products available and their
complete description.

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.
Computers are also used to generate most of the graphic art displays flashed on
scoreboards.
Travel and Tourism Computers are used to prepare tickets, monitor the train’s or
airplane’s route, and guide the plane to a safe landing. They are also used to research
about hotels in an area, reserve rooms, or to rent a car.

Simulation Supercomputers that can process enormous amount of data are widely used
in simulation tests. Simulation of automobile crashes or airplane emergency landings is
done to identify potential weaknesses in designs without risking human lives.

Astronomy Spacecraft’s are usually monitored using computers that not only keep a
continuous record of the voyage and of the speed, direction, fuel, and temperature, but
also suggest corrective action if the vehicle makes a mistake. The remote stations on the
earth compare all these quantities with the desired values, and in case these values need
to be modified to enhance the performance of the spacecraft, signals are immediately
sent that set in motion the mechanics to rectify the situation.

Education A computer is a powerful teaching aid and can act as another teacher in the
classroom. Teachers use computers to develop instructional material. Teachers may use
pictures, graphs, and graphical presentations to easily illustrate an otherwise difficult
concept. Moreover, teachers at all levels can use computers to administer assignments
and keep track of grades. Students can also give exams online and get instant results.
Introduction to C BPPCS103, Module-1

1.6 INPUT AND OUTPUT DEVICES


Input devices are hardware components that allow users to send information to a
computer, while output devices are hardware components that display or reproduce that
information:
• Input devices
These devices allow users to enter data into a computer. Some examples of input devices
include:
• Keyboard
• Mouse
• Microphone
• Webcam
• Scanner
• Output devices
These devices allow users to see, hear, or otherwise perceive the results of the computer's
processing. Some examples of output devices include:
• Monitor
• Printer
• Speaker
• Headphones
• Projector
• Braille reader

1.7 PROGRAM DESIGN TOOLS:


1.7.1 THE MEANING OF ALGORITHMS

Algorithms are step-by-step procedures designed to solve specific problems and


perform tasks efficiently in the realm of computer science and mathematics. These
powerful sets of instructions form the backbone of modern technology and govern
everything from web searches to artificial intelligence. Here's how algorithms work:

• Input: Algorithms take input data, which can be in various formats, such as numbers,
text, or images.

• Processing: The algorithm processes the input data through a series of logical and
mathematical operations, manipulating and transforming it as needed.
Introduction to C BPPCS103, Module-1

• Output: After the processing is complete, the algorithm produces an output, which
could be a result, a decision, or some other meaningful information.

• Efficiency: A key aspect of algorithms is their efficiency, aiming to accomplish tasks


quickly and with minimal resources.

• Optimization: Algorithm designers constantly seek ways to optimize their


algorithms, making them faster and more reliable.

• Implementation: Algorithms are implemented in various programming languages,


enabling computers to execute them and produce desired outcomes.
Introduction to C BPPCS103, Module-1

1.7.2 FLOWCHARTS
A flowchart is a pictorial (graphical) representation of an algorithm. A flowchart is
drawn using different kinds of symbols. A symbol is used for a specific purpose. Each
symbol has name.

Flowcharts use different shapes of boxes to denote different type of instructions. ANSI
recommended a number of different rules and guidelines to help standardize the
flowcharting process.
▪ Algorithms are represented using flowcharts
▪ Flowchart symbols are standardized by ANSI
▪ Flowchart helps to divide a large complex problem into small manageable ones
▪ Generally, algorithm is first represented as a flowchart and then expressed in a
programming
language.
▪ While preparing a flowchart, the sequence, selection and iterative structures may be
used wherever
required.

Rules for Drawing a Flowchart


▪ It should contain only one start and one end symbol
▪ The relevant symbols must be used while drawing a flowchart
▪ The direction of arrows should be top to bottom and left to right
▪ It should be simple and drawn clearly and neatly
▪ Be consistent in using names, variables in the flow chart
▪ Use properly labeled connectors to link the portions of the flowchart on different
pages
▪ The branches of decision box must be label
Introduction to C BPPCS103, Module-1
Introduction to C BPPCS103, Module-1

1.7.3 MEMORY CONCEPTS


Computer memory is a fundamental computer function that stores data and
instructions for quick access. It's made up of small bits, or cells, arranged in a grid and
typically uses a binary system of 1s and 0s
Here are some concepts related to computer memory:
Primary and secondary memory
The two main types of computer memory are primary and secondary:
Primary memory: Also known as the main memory, this includes RAM, cache, and
registers. It provides fast access to data and instructions that are currently in use.
Secondary memory: This includes non-volatile storage devices like hard disk drives
(HDDs) and solid state drives (SSDs). It offers larger storage capacity, but slower
access speeds compared to primary memory.
RAM-Random access memory (RAM) is a type of primary memory that stores operating
system data, application programs, and other data. More RAM allows a computer to
run more programs and processes simultaneously without slowing down.
Introduction to C BPPCS103, Module-1

Cache memory-Cache memory is faster than RAM because it's located closer to the
processor. This design allows the processor to quickly access frequently used data
and instructions.
ROM-Read-only memory (ROM) is nonvolatile and is used in the booting process of a
computer.
EEPROM-Electrically erasable programmable read-only memory (EEPROM) allows data
to be deleted and uploaded using an electric current
Introduction to C BPPCS103, Module-1

Chapter-2
Introduction to C

2.1 INTRODUCTION
The programming language C was developed in the early 1970s by Dennis Ritchie
at Bell Laboratories to be used by the UNIX operating system. It was named C' because
many of its features were derived from an earlier language called B'. Although C was
designed for implementing system software, it was later on widely used for developing
portable application software. C is one of the most popular programming languages. It
is being used on several different software platforms. In a nutshell, there are a few
computer architectures for which a C compiler does not exist. lt is a good idea to learn C
because few other programming languages such as C++ and Java are also based on C
which means you will be able to learn them more easily in the future.

Fig. 9.1: Taxonomy of C Language


Introduction to C BPPCS103, Module-1

2.1.1 Characteristics of C

C is a robust language whose rich set of built-in functions and operators can be
used to write 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 andhave led to its popularity as a programming language are listed
below.
• C is a high-level programming language, which enables the programmer to
concentrate on the problem at hand and not worry about the machine code
on which the program would be run.
• Small size C has only 32 keywords. This makes it relatively easy to learn as
comparedto other languages.
• C makes extensive use of function calls.
• C is well suited for structured programming. In this programming approach, C
enablesusers to think of a problem in terms of functions/modules where the
collection of all the modules makes up a complete program. This feature
facilitates ease in program debugging, testing, and maintenance.
• Unlike PASCAL it supports loose typing (as a character can be treated as an integer
and vice versa).
• Structured language as the code can be organized as a collection of one or more
functions
2.1.2Uses 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:
• C language is primarily used for system programming The portability, efficiency,
the ability to access specific hardware addresses, and low runtime demand
on system resources make it a good choice for implementing operating
systems and embedded system applications
• C has been so widely accepted by professionals that compilers, libraries, and
interpreters of other programming languages are often written in C.
• For portability and convenience reasons, C is sometimes used as an intermediate
language for implementation of other languages. Examples of compilers
which use C this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak,
Introduction to C BPPCS103, Module-1

and Vala.
• Basically, C was designed as a programming language and was not meant to be
used as a compiler target language. Therefore, although C can be used as an
intermediate language it is not an ideal option.
• C is widely used to implement end-user applications.

2.2 STRUCTURE OF AC PROGRAM


A C program is composed of pre-processor commands, a global declaration
section, and one or more functions (Figure 2.2). The pre-processor directives contain
special instructions that indicate how to prepare the program for compilation. One of the
most important and commonly used pre-processor commands is include which tells the
compiler that to execute the program, some information is needed from the specified
header file.

Fig. 2.2: Structure of a C program

A C program contains one or more functions, where a function is defined as a


group of C statements that are executed together. The statements in a C function are
written in a logical sequence to perform a specific task. The main() function is the most
importantfunction and is a part of every C program. The execution of a C program begins
Introduction to C BPPCS103, Module-1

at this function.
All functions (including main( ) ) are divided into two parts the declaration
sectionand the statement section. The declaration section precedes the statement section
and is used to describe the data that will be used in the function. Note that data declared
within a functionare known as local declaration as that data will be visible only within
that function. Stated in other terms, the life-time of the data will be only till the function
ends.
The statement section in a function contains the code that manipulates the data to
perform a specified task. From the structure given above we can conclude that a program
can have any number of functions depending On the tasks that have to be performed, and
each function can have any number of statements arranged according to specific
meaningfulsequence.

2.3 WRITING THE FIRST C PROGRAM


To Write a C program, we first need to write the code. For this, open a text editor.
If you are a Windows user you may use C Notepad and if you prefer working on
UNIX/Linux you can use emacs or vi. Once the text editor is opened on your screen, type
the following statements:
#include<stdio.h>
int main( )
{
printf(" Welcome to the world of C Program”);
return 0;
}
Output
Welcome to the world of C Program

#include <stdio.h>
This is a pre-processor command that comes as the first statement in our code. All
pre-processor commands start with symbol hash (#). The #include statement tells the
compiler to include the standard input/output library or header file (stdio.h) in the
program.

int main ()
Introduction to C BPPCS103, Module-1

Every C program contains a main() function which is the starting point of the
program. Int is the return value of the main() function. After all the statements in the
programhave been written, the last statement of the program will return an integer value
to the operating system.

{ } The two curly brackets are used to group all the related statements of the main
function. All the statements between the braces form the function body. The function
body contains a set of instructions to perform the given task.

printf(" Welcome to the Note world of C ");


The printf function is defined in the stdio.h file and is used to print text on the
screen. The message that has to be displayed on the screen is enclosed within double
quotes and put inside brackets. ‘\n’ is an escape sequence and represents a newline
character. It is used to print the message on a new line on the screen. Like the newline
character, the other escape sequences supported by C language are shown in Table 9.1.

return 0;
This is a return command that is used to return the value 0 to the operating system
to give an indication that there were no errors during the execution of the program.

Table 9.1: Escape sequences used in C programs


Introduction to C BPPCS103, Module-1

2.4 FILES USED IN AC PROGRAM


Every C program has four kinds of files associated with it (Figure 2.3). These include:

2.5 COMPILING AND EXECUTING C PROGRAMS

C is a compiled language. So once a C program is written, you must run it through


aC compiler that can create an executable file to be run by the computer. While the C
program is human-readable, the executable file, on the other hand, is a machine-readable
file available in an executable form.
The mechanical part of running a C program begins with one or more program
source files, and ends with an executable file, which can be run on a computer. The
programming process starts with creating a source file that consists of the statements of
the program writtenin C language. This source file usually contains ASCII characters and
can be produced with a text editor, such as Windows notepad, or in an Integrated Design
Environment. The source file is then processed by a special program called a compiler.
The compilation process shown in Figure 2.4 is done in two steps. In the first step,
thepre-processor program reads the source file as text, and produces another text file
as output.

Source code lines which begin with the # symbol are actually not written in C but in the
pre- processor language. The output of the pre-processor is a text file which does not
contain any pre-processor statements. This file is ready to be processed by the compiler.
The linker combines the object file with library routines (supplied with the compiler)
to produce thefinal executable file.
Introduction to C BPPCS103, Module-1

Fig. 2.4: Preprocessing before compilation

In modular programming, the source code is divided into two or more source files.
All these source files are compiled separately thereby producing multiple object files.
These object files are combined by the linker to produce an executable file (Figure 2.5).

Fig. 2.5: Modular programming-the complete compilation and execution


process

2.6 USING COMMENTS

Many a time the meaning or the purpose of the file code is not clear to the
reader. Therefore it is a good programming practice to place some comments in the code
to help the reader understand the code clearly Comments are just a way of explaining
what a program does. It is merely an internal program documentation. The compiler
ignores the comments when forming the object file means that the comments are non-
executable statements.

C supports two types of 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 the line automatically ends the line.
/* 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.
Introduction to C BPPCS103, Module-1

2.7 C TOKENS

Tokens are the basic building blocks in C language. You may think of a token as the
smallest individual unit in a C program. This means that a program is constructed using
a combination of these tokens. There are six main types of tokens in C. They are shown in
Figure 2.6.

Fig. 2.6: Tokens used in C

2.8 CHARACTER SET IN C


Like in natural languages, computer languages also use a character set that defines
thefundamental units used to represent information. In C, a character means any letter
from English alphabet, a digit or a special symbol used to represent information. These
characters when combined together form tokens that act as basic building blocks of a C
program. The character set of C can therefore be given as:
a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters
b. Digits: Include numerical digits from 0 to 9
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.They are shown in Figure 2.7.

Fig. 2.7: White space characters used in C


Introduction to C BPPCS103, Module-1

2.9 KEYWORDS
Like every computer language, C has a set of reserved words often known as keywords that
cannot be used as an identifier. All keywords are basically a sequence of characters that have a fixed
meaning. By convention al1 keywords must be written in lowercase (small) letters. Table 2.2 shows
the list of keywords in C.

Table 2.2: Keywords used in C

2.9 IDENTIFIERS/VARIABLES
Identifiers, as the name suggests, help us to identify data and other objects in the program.
Identifiers are basically the names given to program elements such as variables, arrays, and
functions. Identifiers may consist of sequence of letters, numerals, or underscores.

2.9.1 Rules for Forming identifier Names

Some rules have to be followed while forming identifier names. They are as follows:

• Identifiers cannot include any special characters or punctuation marks (like #,s, ^, ?, .,
etc.) except the underscore_.
• There cannot be two successive underscores.
• Keywords cannot be used as identifiers.
• The case of alphabetic characters that form the identifier name is significant.For
example, "FIRST' is different from 'first' and 'First'.

Examples of valid identifiers include:

roll_number, marks, name, emp_number, basic_pay, HRA,DA,


dept_code, DeptCode, RollNo, EMP_NO
Examples of invalid identifiers include:

23 student, %marks, @name, #emp_number,basic.pay,


-HRA, (DA), &dept_code, auto
Introduction to C BPPCS103, Module-1

2.10 BASIC DATA TYPES IN C


C language provides very few basic data types. Table 2.3 lists of the basic data types, their
size, range, and usage for a C programmer on a 16-bit computer.

Table 2.3: Basic data types in C

Table 9.4 shows the variants of basic data types. As can be seen from the table, we have
unsigned char and signed char. Do we have negative characters? No, then why do we have such data
types? The answer is that we use signed and unsigned char to ensure portability of programs that
store non-character data as char.

While the smaller data types take less memory, the larger types incur a performance penalty.
Although the data type we use for our variables does not have a big impact on the speed or memory
usage of the application, we should always try to use int unless there is a special need to use any
other data type.
Introduction to C BPPCS103, Module-1

2.11 VARIABLES
A variable is defined as a meaningful name given to a data storage location in computer
memory. When using a variable, we actually refer to address of the memory where the data is stored.
C language supports two basic kinds of variables numeric and character.

2.11.1 Declaring variables

Each variable to be used in the program must be declared. To declare a variable, specify the
data type of the variable followed by its name. The data type indicates the kind of values that the
variable will store.

Variable names should always be meaningful and must reflect the purpose of their usage in
the program. The memory location of the variable is of importance to the compiler only and not to
the programmer. Programmers must only be concerned with accessing data through their symbolic
names. In C, variable declaration always ends with a semicolon, for example:

int emp_num;

float salary;

char grade;
double balance_amount; unsigned short int
acc_no;

2.12 CONSTANTS
Constants are identifiers whose values do not change. While values of variables can be
changed at any time, values of constants can never be changed. Constants are used to define fixed
values like mathematical constant pie or the charge on an electron so that their value does not get
changed in the program even by mistake.

A constant is an explicit data value specified by the programmer. The value of the constant is
known to the compiler at the compile time. C allows the programmer to specify constants of integer
type, floating point type, character type, and string type (Figure 2.8).

Fig. 2.8: Constants in C


Introduction to C BPPCS103, Module-1

2.12.1 Declaring Constants

To declare a constant, precede the normal variable declaration with const keyword and
assign it a value. For example,

const float pi = 3.14;

The const keyword specifies that the value of pi cannot change. However, another way to
designate a constant is to use the pre-processor command define. Like other pre- processor
commands, define is preceded with a # symbol. Although #define statements can be placed
anywhere in a C program, it is always recommended that these statements be placed at the beginning
of the program to make them easy to find and modify at a later stage. Look at the example given
below which defines the value of pi using define.

#define pi 3.14159

#define service_tax 0.12

2.13 INPUT/OUTPUT STATEMENTS IN C

2.13.1 Formatting Input/Output


C language supports two formatting functions printf and scanf. printf is used toconvert data
stored in the program into a text stream for output to the monitor, and scanf is used to convert the
text stream coming from the keyboard to data values and stores them in program variables.

2.13.2 printf()

The printf function (stands for print formatting) is used to display information required by
the user and also prints the values of the variables. For this, the print function takes data values,
converts them to a text stream using formatting specifications in the controlstring and passes the
resulting text stream to the standard output. The control string may contain zero or more conversion
specifications, textual data, and control characters to be displayed.

printf("control string", variable list);

The function accepts two parameters-control string and variable list. The control string may
also contain the text to be printed like instructions to the user, captions, identifiers,or any other text
to make the output readable.

Examples:

printf("\n The number is %6d", 12);


Introduction to C BPPCS103, Module-1
O/p: The number is 12

printf("\n The price of this item is %09.2f rupees", 123.456);

O/p: The price of this item is 000123.45 rupees

printf("\n The number is %06d", 1234);

O/p: The number is 001234

2.13.3 scanf()

The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard. The scanf function takes a text stream from the keyboard, extracts and formats data from
the stream according to a format control string and then stores the data in specified program
variables. The syntax of the scanf() function can be given as:

scanf("control string", arg1, arg2, arg3,….argn);

The control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arguments arg1, arg2,, argn, i.e., the
arguments are actually the variable addresses where each piece of data is to be stored.

Ex:
int num; scanf("%d", &num);

The scanf function reads an integer value (because the type specifier is %d) into the
address or the memory location pointed by num.

float salary; scanf("%f ", &salary) ;

The scanf function reads a floating point number (because the type specifier is %f) into the
address or the memory location pointed by salary.

char ch; scanf("%c ", &ch);

The scanf function reads a single character (because the type specifier is %c) into the address
or the memory location pointed by ch.

char str[10]; scanf("%s ", str);

The scanf function reads a string or a sequence of characters (because the typespecifier is %s)
into the address or the memory location pointed by str. Note that in case of reading strings, we do
not use the & sign in the scanf function.

Example program:
Write a program to demonstrate the use of printf and scanf statements to read and printvalues
Introduction to C BPPCS103, Module-1
of variables of different data types.

#include <stdio.h>int main()


{
int num; float amt; char
codes;double pi;
char msg[10];
printf("\n Enter the value of num ");scanf("%d",
&num)
printf("\n Enter the value of amt: ");scanf("%f",
&amt) ;
printf("\n Enter the value of pi : ");scanf("%e", &pi);
printf("\n Enter the value of code: ");

scanf("%c", &code);
printf("\n Enter the message :");scanf("%s",
msg);
printf("\n NUM = %d \n AMT = %f \n PI %e \n POPULATION OF INDIA = %1d \nCODE = %c \n
MESSAGE = %s", num, amt, pi, population_of_india, code, msg); return 0;
}
OUTPUT:

Enter the value of num 5 Enter the value of


amt: 123.45Enter the value of pi: 3.14159
Enter the population of India: 12345Enter the value
of code: c
Enter the message : Hello

NUM = 5
AMT = 123.450000PI = 3.141590e+00
POPULATION OF INDIA = 12345CODE = c
MESSAGE = Hello

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy