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

Module 1 - C Programming

Introduction to C Programming

Uploaded by

preetha.cs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Module 1 - C Programming

Introduction to C Programming

Uploaded by

preetha.cs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

WHAT IS A COMPUTER?

A computer, in simple terms, can be defined as an electronic device which accepts data, performs the required
mathematical and logical operations at high speed, and outputs the result.

BRIEF HISTORY OF C
The C programming language is a structure oriented programming language, developed at Bell Laboratories
in 1972 by Dennis Ritchie.
• C programming language features were derived from an earlier language called “B” (Basic Combined
Programming Language – BCPL)
• C language was invented for implementing UNIX operating system
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and is commonly known as K&R C.
• In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.
• Many of C’s ideas & principles were derived from the earlier language B, thereby naming this new
language “C”.

Fig. Taxonomy of C Language

INTRODUCTION TO COMPUTERS

Any programming language is implemented on a computer. Right form its inception, to the present
day, all computer system (irrespective of their shape & size) perform the following 5 basic
operations. It converts the raw input data into information, which is useful to the users.

➢ Inputting: It is the process of entering data & instructions to the computer system.
➢ Storing: The data & instructions are stored for either initial or additional processing,
as & when required.
➢ Processing: It requires performing arithmetic or logical operation on the saved data
to convert it into useful information.
➢ Outputting: It is the process of producing the output data to the end user.
➢ Controlling: The above operations have to be directed in a particular sequence to be
completed.

Based on these 5 operations, we can sketch the block diagram of a computer.

Fig 1: Block Diagram of a Computer


➢ Input Unit: We need to first enter the data & instruction in the computer system, before
any computation begins. This task is accomplished by the input devices. (Eg:
keyboard, mouse, scanner, digital camera etc). This device is responsible for linking
the system with the external environment. The data accepted is in a human readable
form. The input device converts it into a computer readable form.

➢ Storage Unit: The data & instruction that are entered have to be stored in the computer.
Similarly, the end results & the intermediate results also have to be stored somewhere
before being passed to the output unit. The storage unit provides solution to all these
issues. This storage unit is designed to save the initial data, the intermediate result &
the final result. This storage unit has 2 units: Primary storage & Secondary storage.

Primary Storage: The primary storage, also called as the main memory, holds the data
when the computer is currently on. As soon as the system is switched off or restarted,
the information held in primary storage disappears (i.e. it is volatile in nature).
Moreover, the primary storage normally has a limited storage capacity, because it is
very expensive as it is made up of semiconductor devices.

Secondary Storage: The secondary storage, also called as the auxiliary storage,
handles the storage limitation & the volatile nature of the primary memory. It can
retain information even when the system is off. It is basically used for holding the
program instructions & data on which the computer is not working on currently, but
needs to process them later.

➢ Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit are
called as the Central Processing Unit (CPU). The CPU is the brain of the
computer. Like in humans, the major decisions are taken by the brain itself & other
body parts function as directed by the brain. Similarly in a computer system, all the
major calculations & comparisons are made inside the CPU. The CPU is responsible
for activating & controlling the operation of other units of the computer system.

Arithmetic Logic Unit: The actual execution of the instructions (arithmetic or logical
operations) takes place over here. The data & instructions stored in the primary
storage are transferred as & when required. No processing is done in the primary
storage. Intermediate results that are generated in ALU are temporarily transferred
back to the primary storage, until needed later. Hence, data may move from the
primary storage to ALU & back again to storage, many times, before the processing
is done.
Control Unit: This unit controls the operations of all parts of the computer but does
not carry out any actual data processing.It is responsible for the transfer of data and
instructions among other units of the computer.It manages and coordinates all the
units of the system.It also communicates with Input/Output devices for transfer of
data or results from the storage units.
➢ Output Unit: The job of an output unit is just the opposite of an input unit.
It accepts the results produced by the computer in coded form. It converts
these coded results to human readable form. Finally, it displays the
converted results to the outside world with the help of output devices ( Eg
:monitors, printers, projectors etc..).

So when we talk about a computer, we actually mean 2 things:


➢ Hardware- This hardware is responsible for all the physical work of the
computer.
➢ Software- This software commands the hardware what to do & how to do it.

Together, the hardware & software form the computer system.

This software is further classified as system software & application software.

System Software- System software are a set of programs, responsible for


running the computer, controlling various operations of computer systems
and management of computer resources. They act as an interface between
the hardware of the computer& the application software. E.g.: Operating
System

Application Software- Application software is a set of programs designed to solve a particular problem for
users. It allows the end user to do something besides simply running the hardware. E.g.: Web Browser,
Gaming Software

DATA AND INFORMATION


Computer accepts data, processes it, and produces information.
• Data refers to some raw facts or figures, and information implies the processed data.
• For example, if 12-1-96 is the date of birth of a student, then it is data (a raw fact/figure).
However, when we process this data (subtract it from the present date) and say that the age
of the student is 18 years, then the outcome is information.

CHARACTERISTICS OF COMPUTERS
• Speed: Computers can perform millions of operations per second. The speed of computers
is usually given in nanoseconds (ns) and picoseconds (ps), where 1 ns = 1×10-9 sec and 1
ps = 1×10-12 sec.
• Versatile: Computers can perform multiple tasks of different nature at the same time.
• Memory: Computers have internal or primary memory (storage space) as well as external
or secondary memory to store data and programs.
• Accuracy: A computer always gives accurate results, provided the correct data and
instructions are input to it. If the input data is wrong, then the output will also be erroneous.
This is called garbage-in, garbage-out (GIGO).
• Automation: Computers perform a task without any user intervention.
• Diligence: Unlike humans, computers never get tired of a repetitive task.
• No IQ: Computers do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
• Economical: Computers are considered as short-term investments for achieving long-term
gains. They save time, money, and energy.

GENERATIONS OF COMPUTERS
The word ‘Generation’, when applied to computing, refers to the different advancements in
computer technology. The focus of every new generation has been on miniaturization, speed,
power, and efficient computer memory.

First Generation (1940-1956): Vacuum Tubes


Vacuum tubes were used – basic arithmetic operations took few milliseconds, Bulky , Consume
more power with limited performance and high cost. Uses machine level language, Fixed point
arithmetic was used. Mercury delay line memories and Electrostatic memories as primary and
magnetic drums as secondary memory.

Advantage
Fastest calculating devices of their time

Disadvantages
Generated a lot of heat
Consumed a lot of electricity
Bulky in size
Prone to frequent hardware
Required constant maintenance because of the low mean time between failures
Limited commercial use
Very expensive

Second Generation (1956-1963): Transistors


Transistors were used in place of vacuum tubes, Small in size, Less power consumption and
better performance, and Low cost. Magnetic ferrite core memories were used as the main memory,
and Magnetic tapes and magnetic disks were used as secondary memory. Floating point arithmetic
operations, High-level languages (FORTRAN, COBOL ), and Compilers to translate to machine
language.
Advantages
Consumed less electricity
Generated less heat
Faster, cheaper, smaller, and more reliable
Could be programmed using assembly and high-level languages
Had faster primary memory and a larger secondary memory

Disadvantage
Transistors had to be assembled manually, which made commercial production of computers
difficult and expensive

Third Generation (1964-1971): Integrated Circuits


ICs were used, Small and Medium Scale Integration use in CPU, Smaller & better performance,
Comparatively lesser cost, Faster processors. Semiconductor memories (RAM & ROM) , pipelining,
Operating system, Time-sharing OS Cache and virtual memories High-level languages were
standardized by ANSI, the introduction of C, C++, Java

Advantages
Faster and could perform one million transactions per second
Smaller, cheaper, and more reliable
Faster and larger primary memory and secondary storage
Widely used for scientific as well as business applications
Supported time sharing operating systems

Disadvantages
Difficult to maintain
Got heated very quickly

Fourth Generation (1971-1989): Microprocessors


Microprocessors as CPU, 8086, VLSI design, CRT screen, laser printers, Semiconductor
memory, hard disks, Floppy disks & magnetic tape memory. Less power consumption, High
performance, lower cost and very compact. Laptops and Smartphones GUI Based OS, TCP/IP
technology, LAN, WAN and Internet were developed

Advantages
Smaller, cheaper, faster, and more reliable
Consumed less electricity and generated less heat
Faster and larger primary memory and secondary storage
Could be used as general-purpose computers
GUIs enabled people to learn to work with computers very easily
Lead to widespread use of computers in offices and at homes
Networks allowed sharing of resources

Disadvantage
Not intelligent systems

Fifth Generation (Present and Beyond): Artificial Intelligence


Artificial intelligence and use of natural languages are the main features, may be capable of
producing human-like behavior.ULSI and nano technology, quantum computers. Extensive parallel
processing, multiple pipelines, multiple processors. Extensively distributed system connected by
communication networks.

• Gaming: Computers are programmed to play games such as chess and checkers. More recent
examples of such gaming systems include PlayStation by Sony.
• Expert systems: Computers are programmed to take decisions in real-world situations.
• Natural languages: Computers are programmed to understand and respond to natural human
languages.
• Neural networks: Systems are programmed to simulate intelligence by reproducing the physical
connections that take place in animal brains.
• Robotics: Computers are programmed to look, listen, and react to other sensory stimuli.

CLASSIFICATION OF COMPUTERS
Supercomputers
• Fastest, most powerful, and most expensive computer
• Used to process large amounts of data and to solve complex scientific problems
• Can support thousands of users at the same time
• Mainly used for weather forecasting, nuclear energy research, aircraft design, automotive
design, online banking, etc.
• Some examples of supercomputers are CRAY-1, CRAY-2, Control Data CYBER 205, and
ETA A-10

Mainframe Computers
• Large-scale computers, but smaller than Supercomputers
• Very expensive
• Need a very large clean room with air conditioning
• Used as servers on the World Wide Web
• Some examples are IBM S/390, Control Data CYBER 176, and Amdahl 580

Minicomputers
• Smaller, cheaper, and slower than Mainframes
• Can be used as servers in a networked environment
• Widely used in business, education, hospitals, government
• Some examples are AS/400 computers (IBM Corporation), Data General Corporation, and
Prime Computer

Microcomputers
Desktop PCs
• Most popular model
• Widely used in homes and offices

Laptops
• Very handy and easily portable
• Storage capacity is almost equivalent to that of a desktop computer
• For input, laptops have a built-in keyboard and a touchpad
• More expensive than desktop computers Microcomputers

Workstations
• Single-user computers
• Same features as PCs but with higher processing speed
• Have advanced processors, more RAM and storage capacity
• Can be used as servers in a networked environment

Network Computers
• Designed to be used as terminals in a networked environment
• Have less processing power, memory, and storage
• Those used to access Internet or Intranet are often known as Internet PCs or Internet boxes
• Some used in homes do not even have a monitor. They may be connected to a TV. They
are called WebTV

Handheld Computers
• Single-user computers
• Can fit in one hand
• Have small-sized screens and keyboards
• Some examples of handheld computers are
Personal Digital Assistants (PDA)
Cellular Phones
H/PC Pro Devices

COMPUTER LANGUAGES
Languages are a means of communication. Normally people interact with each other through a
language. On the same pattern, communication with computers is carried out through a language.
This language is understood both by the user and the machine. Just as every language like English,
Hindi has its own grammatical rules; every computer language is also bounded by rules known as
syntax of that language. The user is bound by that syntax while communicating with the computer
system.

Computer languages are broadly classified as:


Low Level Language: The term low level highlights the fact that it is closer to a language
which the machine understands.
The low level languages are classified as:
• Machine Language: This is the language (in the form of 0’s and 1’s, called binary
numbers) understood directly by the computer. It is machine dependent. It is difficult to
learn and even more difficult to write programs.
• Assembly Language: This is the language where the machine codes comprising of 0’sand
1’s are substituted by symbolic codes (called mnemonics) to improve their understanding.
It is the first step to improve programming structure. Assembly language programming is
simpler and less time consuming than machine level programming, it is easier to locate and
correct errors in assembly language than in machine language programs. It is also machine
dependent. Programmers must have knowledge of the machine on which the program will
run.
• High Level Language: Low level language requires extensive knowledge of the hardware
since it is machine dependent. To overcome this limitation, high level language has been
evolved which uses normal English, which is easy to understand to solve any problem.
High level languages are computer independent and programming becomes quite easy and
simple. Various high level languages are given below:

o BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.

o COBOL (Common Business Oriented language): A standardized language used for


commercial applications.
o FORTRAN (Formula Translation): Developed for solving mathematical and scientific
problems. One of the most popular languages among scientific community.

o C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.

o C++: Popular object oriented programming language, used for general purpose.

PROGRAMMING LANGUAGE TRANSLATORS


As you know that high level language is machine independent and assembly language though it is
machine dependent yet mnemonics that are being used to represent instructions are not directly
understandable by the machine. Hence to make the machine understand the instructions provided
by both the languages, programming language instructors are used. They transform the instruction
prepared by programmers into a form which can be interpreted & executed by the computer.
Flowing are the various tools to achieve this purpose:
• Compiler: The software that reads a program written in high level language and translates
it into an equivalent program in machine language is called as compiler. The program
written by the programmer in high level language is called source program and the program
generated by the compiler after translation is called as object program.
• Interpreter: it also executes instructions written in a high level language. Both complier
& interpreter have the same goal i.e. to convert high level language into binary instructions,
but their method of execution is different. The complier converts the entire source code
into machine level program, while the interpreter takes 1 statement, translates it, executes
it & then again takes the next statement.
• Assembler: The software that reads a program written in assembly language and translates
it into an equivalent program in machine language is called as assembler.
• Linker: A linker or link editor is a computer program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or
another object file.
BASIC ORGANIZATION OF COMPUTERS

Fig: Block Diagram of a Computer


Input: The process of entering data and instructions (also known as programs) into the computer
system

Storage: The process of saving data and instructions permanently in the computer so that they can
be used for processing. A computer has two types of storage areas:
Primary storage (main memory) is the storage area that is directly accessible by the CPU
at very high speeds
Secondary storage (secondary or auxiliary memory) supplements the limited storage
capacity of the primary memory
• Processing: The process of performing operations on the data as per the instructions specified
by the user (program)
• Output: The process of giving the result of data processing to the outside world (external to the
computer system)
• Control Unit: It is the central nervous system of the computer system that manages and controls
all the other components

INPUT AND OUTPUT DEVICES

Input Devices: An input device is used to feed data and instructions to the computer.

KEYBOARD
• Main input device for computers
• Most keyboards have between 80 and 110 keys, which include the following:
Typing keys
Numeric keys
Function keys
Control keys
Advantage
Easy to use and low-priced
Disadvantages
Cannot be used to draw figures
Moving the cursor to another position is very slow
MOUSE
• A pointing device that helps users to select items on screen by controlling the movement of
pointer
• Can be used to perform the following operations:
Point Click
Drag Scroll
Advantages
Low-priced
Easy to use and can be used to quickly place the cursor
Disadvantages
Needs extra desk space to be placed and moved easily
The ball must be cleaned to remove dust from it

TRACKBALL
• A pointing device to control the position of the cursor on the screen
• Usually used in notebook computers, where it is placed on the keyboard
Advantages
Provides better resolution
Occupies less space
Easier to use as compared to a mouse as its use involves less hand-and-arm movements
Disadvantage
The trackball chamber is often covered with dust, so it must be cleaned regularly

TOUCHPAD
• A small, flat, rectangular stationary pointing device with a sensitive surface of 1.5’’–2’’
• Users have to slide their fingertips across the surface of the pad to point to a specific object on
the screen
• The surface translates the motion and position of the user’s fingers to a relative position on the
screen

Advantages
Occupies less space
Easy to use
Built in the keyboard so no need to carry an extra device

HANDHELD DEVICES
• Joystick: A cursor control device widely used in computer games and CAD/CAM
applications
• Stylus: A pen-shaped device to enter information or write on the touch screen of a handheld
device
• Touch screen: A display screen that can identify the occurrence and position of a touch
inside the display region. The user can touch the screen by using either a finger or a stylus

Optical Input Devices


• Use light as a source of input for detecting or recognizing different objects such as characters,
marks, codes, and images
• Some optical devices are:
Barcode reader
Image scanner
Optical character recognition (OCR) devices
Optical mark readers (OMR)
Magnetic ink character recognition (MICR) devices

Barcode Reader
• Works by directing a beam of light across the barcode and measuring the amount of light reflected
back
Advantages
Low-priced, portable, and easy to use
Disadvantages
Must be handled with care
Can interpret information using a limited series of thin and wide bars. To interpret other
unique identifiers, the bar display area must be widened

Image Scanner
Captures images, printed text, photographs, etc., and converts them into digital images for editing
and display on computers
Advantages
Any document can be scanned and stored in a computer for further processing
Scanned and stored document will never deteriorate in quality with time
Disadvantages
Scanned documents are bigger in size as compared to other equivalent text files
Scanned documents are uneditable

Optical Character Recognition (OCR)


The process of converting printed materials into text or word processing files that can be easily
edited and stored
Advantages
Printed documents can be converted into text files
These files occupy less space and are editable
Disadvantages
Cannot recognize all types of fonts
Documents that are poorly typed or have strikeover cannot be recognized

Optical Mark Recognition (OMR)


The process of electronically extracting data from marked fields, such as checkboxes and fill-in
fields, on printed forms
Advantage
Works at very high speeds. Can read up to 9,000 forms per hour
Disadvantages
Difficult to gather large amount of information
Some data may be missing in the scanned document
A sensitive device, it rejects an OMR sheet if it is folded, torn, or crushed
Magnetic Ink Character Reader (MICR)
• Used to verify the legitimacy of paper documents, especially bank checks
•Consists of magnetic ink printed characters that can be recognized by high-speed magnetic
recognition devices
Advantage
Ease of readability and high security
Disadvantage
Expensive equipment

Audio/Video Input Devices


Audio Input Devices
• Used to either capture or create sound
• Enable computers to accept music, speech, or sound effects for recording and/or editing
• Some examples are microphones and CD players
Video Input Devices
• Used to capture video from the outside world into the computer
• Some examples are digital cameras and web cameras

OUTPUT DEVICES
Electromechanical devices that accept digital data from the computer and convert them into human
understandable form

Softcopy Output Devices


• Produce an electronic version of an output. For example, a file that is stored on a hard disk, CD,
or pen drive and is displayed on the computer screen
Features :
Output can be viewed only when the computer is on
A user can easily edit soft copy output
It cannot be used by people without a computer
Searching for data in a soft copy is easy and fast
Electronic distribution of material is cheaper, easy, and fast

Monitors
•Used to display video and graphics information generated by the computer through the video card
• Similar to television screens but they display information at a much higher quality
• Come in three variants:
Cathode ray tube (CRT) monitor
Liquid crystal display (LCD) monitor
Plasma monitor

CRT Monitor
Specialized vacuum tubes in which images are produced when an electron beam strikes a
phosphorescent surface
Advantages
Provide good quality images
Low-priced
Disadvantages
Occupy a large space on the desk
Bigger in size and weight and therefore not easily portable
Power consumption is higher than in other monitors

LCD Monitor
• Thin, flat, electronic visual displays that use the light modulating properties of liquid crystals
• Replacing CRT displays at a fast pace
Advantages
Very compact and lightweight
Consume less power
Little or no flicker of images
Cause less eye fatigue
Disadvantages
More expensive than CRTs
Images are not very clear when tried to view from an angle

Plasma Monitor
Thin and flat monitors widely used in televisions
Advantages
• The technology used in plasma monitors allows producing a very wide screen
• Very bright images can be formed
• Not heavy and are thus easily portable
Disadvantages
• Very expensive
• High power consumption
• Since the images are phosphor-based, at times, they may suffer from flicker visions

Projectors
• A device that takes an image from a digital source and projects it onto a screen or another surface
• Can be broadly classified into two categories:
LCD projectors use their own light to display the image on the screen/wall. The room
must be first darkened, else the image formed will be blurred.
Digital light processing (DLP) projectors use a number of mirrors to reflect light. When
using a DLP projector, the room may or may not be darkened because it displays a clear
image in both situations.

Hard Copy Output Devices


• Produce a physical form of output. For example, the content of a file printed on paper
Features :
A computer is not needed to see the output
Editing and incorporating the edits in the hard copy is difficult
Output can be easily distributed to people who do not have a computer
Searching for data in a hard copy is a tiring and difficult job
Distribution of a hard copy is not only costly but slower as well

Printers
A device that takes text and graphics information obtained from a computer and prints it on a paper

Impact printers
• Print characters by striking an inked ribbon against the paper
Advantages
Enable users to produce carbon copies
Low-priced
Disadvantages
Slow
Poor print quality, especially in the case of graphics
Can be extremely noisy
Can print only using the standard font

Dot matrix Printers


• Print characters as a pattern of dots
• Have a print head (or hammer) that consists of pins representing the character or image
• The print head prints by striking an ink-soaked cloth ribbon against the paper

Daisy Wheel Printers


• The print head is a circular wheel
• To print a character, the wheel is rotated in such a way that the character to be printed is
positioned just in front of the printer ribbon

Band Printers
• Printing mechanism uses a metal loop or band to produce typed characters
• The set of characters is permanently embossed on the band, and this set cannot be changed unless
the band is replaced

Line Printers
• High-speed printers in which one typed line is printed at a time
• Used in data centers and industrial environments

Non-Impact Printers
• Much quieter as their printing heads do not strike the paper
• Offer better print quality, faster printing, and the ability to create prints that contain sophisticated
graphics
• Use either solid or liquid cartridge-based ink, which is either sprayed, dripped, or electrostatically
drawn onto the page

Advantages
Produce prints of good quality
Noiseless, fast
Can print text in different fonts
Disadvantage
Expensive as ink cartridges used by them are costly

Inkjet Printers
• The print head has several tiny nozzles, also called jets. As the paper moves past the print head,
the nozzles spray ink onto it, forming characters and images
• Cartridges have to be changed frequently

Laser Printers
• Work at very high speeds and produce high-quality text and graphics
• A laser beam ‘draws’ the document on a drum which is coated with a photo-conductive material
• After the drum is charged , it is rolled in a toner (a dry powder type of ink)
• The toner sticks to the charged image on the drum and transferred onto a piece of paper

Plotters
• Used to print vector graphics with high-print quality
• Widely used to draw maps, in scientific applications, and in CAD, CAM, and CAE
Drum plotters
• Used to draw graphics on paper that is wrapped around a drum
• Usually used with mainframe and minicomputer systems
Flatbed plotters
• The paper is spread on the flat rectangular surface of the plotter, and the pen is moved over it
• Less expensive, and are used in many small computing systems Plotters

STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.
Based on this structure, we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include <stdio.h>
void main(void)
{ int number;
printf( "Please enter a number: " ); scanf( "%d", &number );
printf( "You entered %d", number );
return 0;}
Stepwise explanation:
#include
The part of the compiler which actually gets your program from the source file is called
the preprocessor.

#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an
instruction to the compiler to make it do something. It tells the C compiler to include the
contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special place,
by the fact that the filename is enclosed in <> characters

<stdio.h>
stdio.h is the name of the standard library definition file for all STanDard Input and Output
functions.
Your program will almost certainly want to send information to the screen and read things
from the keyboard, and stdio.h is the name of the file in which the functions that we want to
use are defined.
The function we want to use is called printf. The actual code of printf will be tied in later
by the linker.
The ".h" portion of the filename is the language extension, which denotes an include file.

void
This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.

main
In this particular example, the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given a
name by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the program
execution starts from main.

(void)
This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for
every open brace there must be a matching close one.
Braces allow us to group pieces of program together, often called a block.
A block can contain the declaration of variable used within it, followed by a sequence of
program statements.
In this case the braces enclose the working parts of the function main.

; (semicolon)
The semicolon marks the end of the list of variable names, and also the end of that
declaration statement.
All statements in C programs are separated by ";" (semicolon) characters.
The ";" character is actually very important. It tells the compiler where a given statement
ends.
If the compiler does not find one of these characters where it expects to see one, then it
will produce an error.

scanf
In other programming languages, the printing and reading functions are a part of the
language.
In C this is not the case; instead they are defined as standard functions which are part of
the language specification, but are not a part of the language itself.
The standard input/output library contains a number of functions for formatted data
transfer; the two we are going to use are scanf (scan formatted) and printf (print formatted).

printf
The printf function is the opposite of scanf.
It takes text and values from within the program and sends it out onto the screen.
Just like scanf, it is common to all versions of C and just like scanf, it is described in the
system file stdio.h.
The first parameter to a printf is the format string, which contains text, value descriptions
and formatting instructions.

FILES USED IN A C PROGRAM


Source File- This file contains the source code of the program. The file extension of any c file is
.c. The file contains C source code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which contains the C function declarations
and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o, meaning
relocatable format machine code that is usually not directly executable. Object files are produced by
an assembler, compiler, or other language translator, and used as input to the linker, which in turn
typically generates an executable or library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links the various
object files to produce a binary file that can be directly executed.

COMPLIATION & EXECUTION OF A C PROGRAM

ELEMENTS OF C

Every language has some basic elements & grammatical rules. Before starting with rogramming,
we should be acquainted with the basic elements that build the language.

Character Set
Communicating with a computer involves speaking the language the computer understands. In C,
various characters have been given to communicate.

Character set in C consists of;


Types Character Set
Lower case a-z
Upper case A-Z
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or space

Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the computer. There are only 32 keywords
available in C. Below figure gives a list of these keywords for your ready reference.

Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline.

Two rules must be kept in mind when naming identifiers.


1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDeX" for a variable.
All three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.

Data Type
In the C programming language, data types refer to a domain of allowed values & the operations
that can be performed on those values. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. There are 4 fundamental data
types in C, which are- char, int, float &, double. Char is used to store any single character; int is
used to store any integer value, float is used to store any single precision floating point number &
double is used to store any double precision floating point number. We can use 2 qualifiers with
these basic types to get more types.

There are 2 types of qualifiers-


Sign qualifier- signed & unsigned Size qualifier- short & long

The data types in C can be classified as follows:


Constants
A constant is an entity that doesn’t change whereas a variable is an entity that may change. C
constants can be divided into two major categories:
• Primary Constants
• Secondary Constants
Here our only focus is on primary constant. For constructing these different types of constants
certain rules have been laid down.

Rules for Constructing Integer Constants:


An integer constant must have at least one digit.

a) It must not have a decimal point.


b) It can be either positive or negative.
c) If no sign precedes an integer constant it is assumed to be positive.
d) No commas or blanks are allowed within an integer constant.
e) The allowable range for integer constants is -32768to 32767. Ex.: 426, +782,-8000, -7605

Rules for Constructing Real Constants:


Real constants are often called Floating Point constants. The real constants could be written in
two forms—Fractional form and Exponential form.

Rules for constructing real constants expressed in fractional form:


a) A real constant must have at least one digit.
b) It must have a decimal point.
c) It could be either positive or negative.
d) Default sign is positive.
e) No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -
48.5792

Rules for constructing real constants expressed in exponential form:


a) The mantissa part and the exponential part should be separated by a letter e.
b) The mantissa part may have a positive or negative sign.
c) Default sign of mantissa part is positive.
d) The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
e) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex. +3.2e-5,
4.1e8, -0.2e+3, -3.2e-5

Rules for Constructing Character Constants:


a) A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
b) The maximum length of a character constant can be 1 character.
Ex.: ‘M’, ‘6’, ‘+’

VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. When
you decide your program needs another variable, you simply declare (or define) a new variable
and C makes sure you get it. You declare all C variables at the top of whatever blocks of code
need them. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – datatype variablename;
Eg:
int page_no; char grade; float salary; long y;

Declaring Variables:
There are two places where you can declare a variable:
• After the opening brace of a block of code (usually at the top of a function)
• Before a function name (such as before main() in the program) Consider various
examples:

Suppose you had to keep track of a person's first, middle, and last initials. Because an initial is
obviously a character, it would be prudent to declare three character variables to hold the three
initials. In C, you could do that with the following statement:

1. main()

char first, middle, last;

// Rest of program follows

2. main()

{ char first; char middle; char last;


// Rest of program follows

Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If
we want we can assign some initial value to the variables during the declaration itself. This is
called initialization of the variable.

Eg- int pageno=10;

char grade=’A’;
float salary= 20000.50;

INPUT-OUTPUT IN C

When we are saying Input that means we feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in functions
to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer
screen.

Functions printf() and scanf() are the most commonly used to display out and take input
respectively. Let us consider an example:

#include <stdio.h> //This is needed to run printf() function. int main()


{
printf("C Programming"); //displays the content inside quotation return 0;
}

Output:
C Programming

Explanation:

Every program starts from main() function.


printf() is a library function to display output which only works if #include<stdio.h>is
included at the beginning.
Here, stdio.h is a header file (standard input output header file) and #include is command
to paste the code from the header file when necessary. When compiler encounters
printf()function and doesn't find stdio.h header file, compiler shows error.
return 0; indicates the successful execution of the program.

Input- Output of integers in C

#include<stdio.h> int main()


{
int c=5;

printf("Number=%d",c); return 0;
}

Output
Number=5

Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this
conversion format string matches with remaining argument, i.e, c in this case, value of c is
displayed.

#include<stdio.h> int main()


{ int c;
printf("Enter a number\n"); scanf("%d",&c); printf("Number=%d",c); return 0;
}
Output
Enter a number 4
Number=4

The scanf() function is used to take input from user. In this program, the user is asked an input
and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and
value is stored in that address.

Input- Output of floats in C

#include <stdio.h> int main()


{
float a;
printf("Enter value: "); scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d return 0;
}

Output

Enter value: 23.45 Value=23.450000

Conversion format string "%f" is used for floats to take input and to display floating value of a
variable.

Input - Output of characters and ASCII code


#include <stdio.h> int main()
{
char var1;
printf("Enter character: "); scanf("%c",&var1); printf("You entered %c.",var1);
return 0;
}

Output
Enter character: g You entered g.

Conversion format string "%c" is used in case of characters.

ASCII code
When character is typed in the above program, the character itself is not recorded a numeric
value (ASCII value) is stored. And when we displayed that value by using "%c", that character is
displayed.

#include <stdio.h> int main()


{
char var1;
printf("Enter character: "); scanf("%c",&var1);
printf("You entered %c.\n",var1);
/* \n prints the next line(performs work of enter). */ printf("ASCII value of %d",var1);

return 0;
}

Output:
Enter character:
g 103
When, 'g' is entered, ASCII value 103 is stored instead of g.

You can display character if you know ASCII code only. This is shown by following example.

#include <stdio.h> int main()


{
int var1=69;
printf("Character of ASCII value 69: %c",var1); return 0;
}

Output
Character of ASCII value 69: E

The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b'
is 98 and so on to 'z' is 122.

You might also like