You are on page 1of 26

First Year Engineering, Sub Name: POP Code:22POP13 Module No.

:1

Module 1
Introduction To C
Introduction to computers:
COMPUTER GENERATIONS
The computer of each generation is smaller, faster and more powerful than preceding generation. There are five
computer generations.
➢ First Generation: The vacuum tubes were used for computation. Magnetic drums were used for memory
requirements. It consumed lot of space, power, and generated lot of power. ENIAC (Electronic
Numerical Integrator and Computer) used 18000 vacuum tubes, 1800 acquired sq. ft. room space and
consumed 180KW of power. The machine level language (0s and 1s) was used. Punched cards were used
for input and Paper for output. They were used for scientific work.
➢ Second Generation: The transistors were the most important component which replaced vacuum tubes.
Magnetic cores were used for memory. It was more reliable than first generation computer. The assembly
or symbolic language was used. The input and output mechanism remained same. The stored program
concept was introduced which stores both data and program.
➢ Third Generation: The Integrated circuits (IC) was the most important component. The transistors,
diodes, resistors, capacitors were integrated on a single chip. The high-level language was used like
BASIC, C, C++ and JAVA. Memory capacity increased and magnetic hard disk was used for secondary
generation. The third-generation computers also had OS and computer could rum programs invoked by
multi users.
➢ Fourth Generation: The Microprocessor was the most important component. With the help of LSI
(Large Scale Integration) and VLSI (Very Large-Scale Integration) the entire CPU is on a single chip. OS
have moved from MSDOS to GUI (Graphical User Interface) like windows. The networking technology
has also been improved. The size was reduced and the speed was increased.
➢ Fifth Generation: Artificial Intelligence and use of natural languages are the main features of this
generations. These systems are expected to interact with users in natural language. Speech recognition
and speech output should also be possible. Computers must be able to perform parallel processing. The
quad-core and octa-core was also introduced. Neural networks and expert systems have been developed.

1
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

COMPUTER TYPES
Apart from being classified by generations, computers can also be categorized by their size. The size of a
computer is often an indirect indication of its capabilities.
➢ Supercomputers: These are huge machines having most powerful and fastest processors. It uses
multiple CPUs for parallel data processing. Speeds are measured in flops (floating point operations per second).
The fastest operates at 34 petaflops. They are used for weather forecasting, analysis of geological data. They
have enormous storage, uses more power and generate lot of heat. They are used by government agencies.
➢ Mainframes: These are multi-user machines that support many users using the feature of time sharing.
It can run multiple programs even with a single CPU. The processor speed is measured in MIPS (Million
instructions per second). It is used to handle data, applications related to organization and online transactions in
banks, financial institutions and large corporations.
➢ Minicomputers/Midrange computers: It was introduced by DEC (Digital Equipment Corporation).
They can serve hundreds of users and are small enough to partially occupy a room. They are used in smaller
organizations or a department of a large one. They are not affordable to be used in home.
➢ Microcomputers: The microcomputer or PC is introduced by Apple and endorsed by IBM. This is a
single-user machine powered by a single-chip microprocessor. They are very powerful machines having
gigabytes of memory. They are both used in standalone mode and in a network. A microcomputer takes the
form of desktop, notebook (laptop) or a netbook (smaller laptop). PCs today are powered by 3 types of OS –
windows (7, 8 or 10), Mac OS X (Apple) and Linux. They are used for engineering and scientific applications
and for software development.
➢ Smartphones and Embedded Computers: The smartphone is a general-purpose computer i.e.,
capable of making phone calls. It has a powerful processor, with multiple cores, supports GBs of memory, and
runs developed OS (Android or iOS). It can be operated with keyboard, touch or stylus. Embedded Computers
or micro-controllers are very small circuits containing a CPU, non-volatile memory, input and output handling
facilities. They are embedded into many machines that we use – cars, washing machines, cameras etc. The
processor here runs a single unmodifiable program stored in memory.

2
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

The CPU comprises of following components:

➢ ALU (Arithmetic and Logic Unit)


3
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

➢ CU (Control Unit)
➢ Special-purpose registers
➢ A clock

The ALU is a “super calculator” carrying out all arithmetic tasks and Boolean operations (like
AND, OR and NOT). The CU controls the way data is moved between the various components of
computer. Both ALU and CU use the service of clock for synchronizing their Operations.

The CPU uses a few high-speed registers to store the current instruction and its data. One of the
registers, program counter, stores the address of next instruction to be executed. All program
instructions are executed using the fetch-decode-execute mechanism. An instruction is first fetched
from memory, decoded and then executed by CPU. The CPU can execute one instruction in one
clock pulse. Hence, faster the clock, faster is the execution. The CPUs today are rated in GHz
(gigahertz).

PRIMARY MEMORY
Memory: Collection of chips on motherboard, where all computer processing and program
instructions are stored.

Primary Memory: It is the main memory, which stores data and programs, which are currently needed
by CPU. The size is less than the secondary memory and it is costly.

1. RAM (Random Access Memory): It is the main memory, where the user can write
information into RAM and read information from it. It is accessible to users. The RAM is
randomly accessible by user. It is a volatile memory, which means the data, or information is
retained as long as power supply is ON. There are two types of RAM: SRAM and DRAM.

SRAM (Static) DRAM (Dynamic)


Stores information as long as power supply Loses data in a very short time.
is on, reloads every 2ms.
Multiple transistors are used to store 1 bit. One transistor is used to store 1 bit.
It is expensive, faster, bigger. It is inexpensive, slower, smaller.
It requires more power. It requires less power.
It is not required to be refreshed. It requires refresh.

2. ROM (Read Only Memory): It is a permanent memory that can be read but not written. It is
a non volatile memory, which means the data or information is retained even power supply is
not there. It contains a startup program BIOS (Basic Input Output System) which transfers
control to OS.
➢ PROM (Programmable Read Only Memory): It is programmed as per requirement of
customer’s choice. The programmer burns the data into PROM. The data once written
cannot be changed.
➢ EPROM (Erasable Programmable Read Only Memory): It can be rewritten (but only
once) even though it has been previously burned. It is erased by exposing it to UV-rays.

➢ EEPROM (Electrically Erasable Programmable Read Only Memory): It can be


4
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

erased and rewritten multiple times. The electric voltage is used to erase the data. The pen
drive we use today is of EEPROM.

3. Cache Memory: It holds those portions of program that are frequently used by CPU. It acts
as a buffer between CPU and RAM. The CPU first looks for the instructions in cache. It
executes faster than RAM, expensive and limited in size. It has multiple levels:
➢ L1 (Level 1) – smallest and fastest – 32 KB
➢ L2 (Level 2) – present closer to CPU – 256 KB
➢ L3 (Level 3) – shared by cores – 8 MB

4. Registers: The small number of ultra-fast registers integrated into the CPU represent the fastest
memory of the computer. The CPU does all its work here. Each register has the length of the
computer. The data is loaded into register before processing. Registers are numbered and a
program instruction specifies these numbers. Ex: OR1R2R3 which means multiplication
operation is performed on R1 and R2 is performed and stored in R3.

SECONDARY MEMORY
Secondary memory is not directly connected to CPU. It exists inside the machine and also
externally. It is a non-volatile, offline and long-term storage memory. It is slower, cheaper than
primary memory but the capacity is higher.

1. Hard disk/ Hard drive/ Fixed disk: It is the oldest secondary storage device. It has more
capacity but, the cost is less comparatively. It is commonly present in laptop with 500GB and
desktop with 1TB. It contains a spindle, which holds one or more platters made up of non-
magnetic material. It has two surfaces which is coated with magnetic material. Each surface
has serially numbered tracks and further broken into sectors or blocks. The disk runs with the
speed of 5400 and 7200 rpm.

2. Magnetic tape: The magnetic tape is made up of plastic film with one side coated with
magnetic material. It supports 1 TB or more, but 200 TB are also expected. The device is not
fully portable though because, a separate tape drive is required. The data is accessed
sequentially. This makes it unsuitable for backup.

Optical Disks (CD-ROM, DVD ROM, Blu-ray Disk): It is non-volatile read-only memory.
The CD-ROM and DVD-ROM, can hold large volumes of data (700MB to 8.5 GB). The Blu-
ray disk has the capacity upto 50 GB. A laser beam in their drives controls the read and write
operations. A laser beam is used to construct pits and lands by burning selected areas along
its tracks.

CD-R, DVD-R: Data can be recorded only once.


CD-RW, DVD-RW: Data can be recorded multiple times.

3. Flash Memory: It doesn’t have any moving parts, is based on the EEPROM. It is available in
various forms- pen drive, magnetic card (SD Card), solid state disk (SSD). They are portable,
need little power and quite reliable.
5
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

The memory stick or pen drive is the most common type of flash memory used on the
computer. It is a small, removable piece of circuit and it connects to the USB port of
computer.

The solid state disk is a bigger device meant to replace the traditional magnetic hard disk.

The magnetic card is used mainly in cameras and the most popular is the micro- SD card.

4. Floppy Diskette: This is represented by a rectangular plastic case containing a thin magnetic
disk. It was available in two sizes (5.25” and 3.5”), offering capacities of 1.2 MB and 1. MB.
It is unsuitable for backup purpose.

✓ Difference between Primary memory and Secondary memory

Primary Memory Secondary Memory


The size of the primary memory is small. The size of the secondary memory is
larger.
Stores the programs and data currently It is used to store large amount of data and
needed by the CPU. programs
Expensive. Inexpensive.
Volatile in nature. Non-volatile in nature.

PORTS AND CONNECTORS

Devices like scanners, printers are connected to a computer through docking points called ports. It is
impossible to use wrong connector for a port. At present systems offer only fewer types compared
to old ones.

➢ USB (Universal Serial Bus): This replaced serial and parallel ports in motherboard. Most
computers offer four USB ports to support scanners, printers and mice. It has four lines, two each
for data and power. The current USB 3.0 can transfer 1 GB file in 20 seconds. The smaller variant,
the micro-USB port is used in smartphones.

➢ SERIAL PORT: This port transfers one bit at a time serially. They are offered in 9-pin and
25-pin configuration. They were used for connecting keyboard, mice, and modems.

➢ PARALLEL PORT: This port is used to transfer data parallelly 8 bits at a time. This is
implemented using 25 pins and usually for printers.

➢ VGA (Video Graphics Array): This 15-pin port allows transfer of analog video data to the
monitor. This is replaced with DVI (Digital Video Interface) which uses digital data i.e. used by flat
LCD panels.

➢ RJ45 port: This port is used by Ethernet network. Even though computer connects
wirelessly, the wired RJ45 remains as a useful option.

➢ PS/2 port: This port has replaced serial port. It has 6 pins but occurs as a pair in two
6
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

different colors. The ports and connectors for keyboard are purple, while the mouse uses green port.
USB has invaded this area also.

➢ HDMI (High Definition Multimedia Interface): This is used for transferring audio and
video between computers and HDTVs, projectors and home theaters.

INPUT DEVICES
Input devices are needed to interact with the OS to perform tasks. Ex: Keyboard, Mouse,
Joystick, Stylus, Scanner etc.

➢ Keyboard: Every computer supports a keyboard – either a physical or touchscreen. The


keyboard has QWERTY layout and contains large number of symbols. Each letter, numeral or
symbol is known as a character, which represents smallest piece of information. Each character has a
unique values called the ASCII (American Standard Code for Information Interchange) value.

➢ Pointing Devices: GUI (Graphical User Interfaces) like windows need a pointing device to
control the movement of cursor on the screen. This is implemented as mouse in desktop and touchpad
in laptop. The earliest form has a rotating ball and two buttons. The left button is used for selecting (by
clicking once) and execute (by clicking twice). The right button is used to check and change
attributes. The optical mouse uses infrared laser/LED, the wireless mouse uses radio frequency
technology.

Scanner: A scanner is a device that creates a digital image of a document by optically scanning it.
The flatbed scanner doesn’t exceed more than A4 size. It is operated with by using special software.
The document to be scanned is placed on a glass plate covered by lid. Modern scanners have OCR
(Optical Character Recognition) facility which extracts text as a stream of characters i.e. converting
image file to text file and MICR (Magnetic Ink Character Recognition) reads the codes using
hand held barcode readers.

OUTPUT DEVICES
The information produced can be heard or seen with the help of output devices. Some of the
output devices are monitor, speaker, printer, plotter etc.

➢ Monitor: The monitor is an integral part of computer which displays both text and graphics.
The performance is measured in terms of image quality, resolution, energy consumption.

CRT (Cathode Ray Tube) Monitors: The CRT monitors have a rarefied tube containing three
electron guns. The guns emit electrons create images. They usually have resolution of 640*840
pixels. They are large, heavy, energy efficient and produces lot of heat.

LCD (Liquid Crystal Display) Monitors: The image is formed by applying voltage on crystals.
The backlight is provided by fluorescent light. They consume less power, generate less heat and have
increased life span.

7
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

➢ Impact Printers: It produces the hardcopy of output. The impact printers are old, noisy. But,
still dot-matrix printer is in usage.

Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins. When the pins
fire against the ribbon, an impression is created on the paper. The speed is 300 cps and doesn’t
produce high quality output. It can produce multiple copies.

Daisy-wheel Printer: It employs a wheel with separate characters distributed along its outer edge.
The wheels can be changed to obtain different set of fonts.

Line Printer: For heavy printing, the line printer is used. It uses a print chain containing the
characters. Hammers strike the paper to print and it rotates at the speed of 1200 lpm. It is also noisy
and is of low-quality.

➢ Non-Impact Printers: They are fast, quiet and of high resolution. The most commonly used
non-impact printers are laser and ink-jet printers. The thermal printer is not discussed here because
it uses heat to print on high-sensitive paper.

Laser Printer: It works like a photocopier and uses toner i.e. black magnetic powder. The image is
created in the form of dots and passed from drums on to the paper. It has built-in RAM which acts as
buffer and RAM to store fonts. The resolution varies from 300 dpi to 1200 dpi and the speed is
about 20 ppm.

Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high pressure as it
moves along the paper. The separate cartridges are available for different colors. The resolution is
about 300 dpi, can print 1 to 6 pages/min.

Designing efficient programs:


ALGORITHM & FLOWCHART
ALGORITHM:
The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means a procedure or a
technique. Software Engineer commonly uses an algorithm for planning and solving the problems. An
algorithm is a sequence of steps to solve a particular problem or algorithm is an ordered set of unambiguous
steps that produces a result and terminates in a finite time
Algorithm has the following characteristics
• Input: An algorithm may or may not require input

• Output: Each algorithm is expected to produce at least one result

• Definiteness: Each instruction must be clear and unambiguous.

• Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after finite number
of steps

8
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Algorithm and flowchart include following three types of control structures.


1. Sequence: In the sequence structure, statements are placed one after the other and the execution takes place
starting from up to down.
2. Branching (Selection): In branch control, there is a condition and according to a condition, a decision of
either TRUE or FALSE is achieved. In the case of TRUE, one of the two branches is explored; but in the case
of FALSE condition, the other alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch
control.
3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed repeatedly based on certain
loop condition e.g. WHILE, FOR loops.

Advantages of algorithm
• It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
• An algorithm uses a definite procedure.
• It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
• Every step in an algorithm has its own logical sequence so it is easy to debug.

HOW TO WRITE ALGORITHMS


Step 1 Define your algorithms input: Many algorithms take in data to be processed, e.g. to calculate the area
of rectangle input may be the rectangle height and rectangle width.
Step 2 Define the variables: Algorithm's variables allow you to use it for more than one place. We can define
two variables for rectangle height and rectangle width as HEIGHT and WIDTH (or H & W). We should use
meaningful variable name e.g. instead of using H & W use HEIGHT and WIDTH as variable name.
Step 3 Outline the algorithm's operations: Use input variable for computation purpose, e.g. to find area of
rectangle multiply the HEIGHT and WIDTH variable and store the value in new variable (say) AREA. An
algorithm's operations can take the form of multiple steps and even branch, depending on the value of the input
variables.
Step 4 Output the results of your algorithm's operations: In case of area of rectangle output will be the
value stored in variable AREA. if the input variables described a rectangle with a HEIGHT of 2 and a WIDTH
of 3, the algorithm would output the value of 6.

FLOWCHART:
The first design of flowchart goes back to 1945 which was designed by John Von Neumann. Unlike an
algorithm, Flowchart uses different symbols to design a solution to a problem. It is another commonly used
programming tool. By looking at a Flowchartone can understand the operations and sequence of operations
performed in a system. Flowchart is often considered as a blueprint of a design used for solving a specific
problem.
Advantages of flowchart:
• Flowchart is an excellent way of communicating the logic of a program.
• Easy and efficient to analyze problem using flowchart.
• During program development cycle, the flowchart plays the role of a blueprint, which makes program
development process easier.
• After successful development of a program, it needs continuous timely maintenance during the course of its
operation. The flowchart makes program or system maintenance easier.
• It is easy to convert the flowchart into any programming language code.

9
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Flowchart is diagrammatic /Graphical representation of sequence of steps to solve a problem. To draw a


flowchart following standard symbols are use

10
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

The language used to write algorithm is simple and similar to day-to-day life language. The variable names are
used to store the values. The value store in variable can change in the solution steps. In addition some special
symbols are used as below
Assignment Symbol ( or =) is used to assign value to the variable.
e.g. to assign value 5 to the variable HEIGHT, statement is
HEIGHT 5
or
HEIGHT = 5
The symbol ‘=’ is used in most of the programming language as an assignment symbol, the same has been used
in all the algorithms and flowcharts in the manual.
The statement C = A + B means that add the value stored in variable A and variable B then assign/store the
value in variable C.
The statement R = R + 1 means that add I to the value stored in variable R and then assign/store the new value
in variable R, in other words increase the value of variable R by 1

Algorithm & Flowchart to find the sum of two numbers


Algorithm
Step-1 Start
Step-2 Input first numbers say A
Step-3 Input second number say B
Step-4 SUM = A + B
Step-5 Display SUM
Step-6 Stop

11
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Characteristics of C:
➢ C is easy to learn.
➢ C is a general-purpose language.
➢ C is a structured and procedural language.
➢ It is portable.
➢ It can extend itself.
Examples of C:
➢ Operating system
➢ Language compilers
➢ Assemblers
➢ Text editors
➢ Databases

C Character Set:
➢ A C character set defines the valid characters that can be used in a sourceprogram. The
basic C character set are:
1. Letters: Uppercase: A,B,C,….,D
Lowercase: a,b,c,…..,d
2. Digits: 0,1,2,…..,9
3. Special characters: ! , . # $ ( ) } { etc
4. White spaces: Blank space, Horizontal tab space, carriage return, new linecharacter, form
feed character.

Basic concepts in C program:


This section will introduce a number of features of the C language which must be included inevery
program, even though they do not appear in the pseudo code. The basic
Structure of C program is shown below

12
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Documentation section
Link section
Definition section
Global declaration section
main() section
{
Declaration part
Executable part
}

Sub program section


Function 1
Function 2
-
-
Function n

Every c program is made up of one or more preprocessor commands, global declarations, and one or
more functions.
* Documentation section consists of a set of comment line giving the name of the program, the author,
and other details. Compiler ignores these comments when it translates the program into executable code.
C uses 2 different formats
1. Block comments /*this is multi line comments*/
2. Line comments //this is single line comments
* The Link section provides instruction to the compiler to link functions from system library
* The definition section defines all symbolic constants
* Global Declaration section: there are some variables that are used in more than onefunction, such a
variable are called global variable and are declared in the global declaration section that is outside of all
functions.
* Every C program must have one main ( ) function section. This section contains two parts declaration
part and executable part
* Declaration part declares all the variables used in the executable part
* There is at least one statement in an executable part. These two part must appear at the beginning of
the brace and ends at the closing brace. All statement in the declaration and executable part ends with
semicolon.
* The sub program section contains all the user defined functions that are called in the main function

Here is a small program that displays a sentence “Welcome to C world ” on the monitor screen:
/* C program to display welcome to C world */
#include<stdio.h>
void main( )
{
printf(“Welcome to C World”);
}

• This program doesn’t have all the parts of typical C program.


• The first line begins with /* and ending with */ is the comment line which is used to enhance
program readability and understanding.
• The second line It has preprocessor directive #include which includes a header file stdio.h, the
standard input /output headerfile . The definitions of printf and scanf functions are defined in this
headerfile. Hence this line we need to include.
• The third line is main(), this is the special function used by C system to tell where the program
starts. Every program have exactly one main function. The empty pair of parenthesis following
13
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

main indicates that main has no arguments. Void indicates that main function does not return any
value to operating system. By default main returns integer value to operating system.
• The opening brace “{ “ in the 4th line marks the beginning of the function main and closing brace
“}” at the last line indicates the end of the function.
• All the statements between these braces form the function body. The function body contains set
of instruction to perform the given task.
• In this program the function body contains only one executable statement printf. The printf is a
predefined function for printing output. It prints everything within the double quote. In this it will
print Welcome to C World on the monitor.

C Tokens: In C program the smallest logically meaning full individual units are known as c tokens. C
has 6 Different types of tokens. C programs are written using these tokens and syntaxof the language.
1. Identifier Example : sum ,amount
2. Keywords Example: float, while
3. Constants Example: -15.5, 100
4. Strings Example: “abc”, “hello”
5. Special symbols Example: {},[]
6. Operator Example:+,-,/

Let us discuss each one of them in detail:


Identifiers: Identifier are name given by programmers to data objects and other objects such as variables,
functions, and arrays in C. These are user defined names and consist of sequence letters, digits or
underscore. To frame identifiers we have to follow certain rules.
Here are the important rules:
1. Identifier should contain only alphabets (A-Z), (a-z), numerals(0-9) and underscore (_)
2. Identifier should start with alphabet or underscore, but not numeric character
3. First 31 characters in an identifier are significant, rest of characters are neglected
4. No reserve words (keywords) of C language can be used as identifiers
5. Identifiers are case sensitive

Examples of valid identifier


food, counter_7, max_1, min_1
Examples of Invalid identifier
$num //$ is special character
int //keyword

name 1 //space not allowedIdentifiers can


be further classified as:
1. Keywords
2. Standard identifiers Ex: printf, scanf
3. programmer defined identifier Ex: sum, avg

Keyword: Keyword or reserved word have predefined meanings and these meanings cannot be changed.
Keyword serves as building blocks for program statements. All keywords are in lowercase letters. Below
table shows all keywords in ANSI C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
14
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

The keywords const, signed, and volatile are new with the ANSI standard; enum and voidare new
since the first edition, but in common use.

Constants: They are data values that do not change during program execution. Main types of
constants are:
1. Integer constants
2. Real constants
3. Character constants

Example:
#include<stdio.h>
#define PI 3.142 //constant
int main()
{
const int PI=3.142;
printf("%f", PI);
PI=20;
printf("\n%d", PI);
}

Integer constants are numerals without decimal portions. By default all C language integers are of
signed integer type. An integer constant consisting of a sequence of digits is taken to be octal if it begins
with 0 (digit zero), decimal otherwise. Octal constants do not contain the digits 8 or 9. A sequence of
digits preceded by 0x or 0X (digit zero) is taken to be a hexadecimal integer. The hexadecimal digits
include a or A through f or F with values 10 through 15.
An integer constant may be suffixed by the letter u or U, to specify that it is unsigned. It may also
be suffixed by the letter l or L to specify that it is long. Various integer constants examples are given in
the table:

Example Value Type


+564 564 signed int/ just int
789U 789 unsigned int
037 Octal 37 int

Real constants A floating constant consists of an integer part, a decimal part, a fraction part,an e or E,
an optionally signed integer exponent and an optional type suffix, one of f, F, l, or
L. The integer and fraction parts both consist of a sequence of digits. Either the integer part, or
the fraction part (not both) may be missing; either the decimal point or the e and the exponent (not both)
may be missing. The type is determined by the suffix; F or f makes it float, L or l makes it long double. By
default all C language real numbers are of double type. Following table describes various examples of
real constants:

Example Value Type


564.35 564.35 double
789.555f 789.555 float
0.65e5 65000 double

Character constants can be single character enclosed within single quotes or a ‘\’ (backslash) followed
by any character. ‘\’ is called escape character as it alters the meaning of character following it.
Following are the complete list of escape sequence.

15
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Data Types: A data type defines the type of data that is stored in a variable. A data in a variable can be
any type for example data can be either numeric or string. A data type determines how much storage memory
should be allocated to a variable. ANSI C supports three classes of data type
1. Primary or build in or fundamental data type (int, char, float, double, void)
2. Derived data type (arrays, structures, functions, pointers, unions)
3. User defined data type (typedef, enum)
Here we will be discussing only fundamental datatype. Other will be discussed in latter units.All C
compiler support five fundamental data types namely
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double) and
5. void

Integer type: Integers are whole numbers with range of values supported by particular machine. Data type
that can store non-decimal numbers in memory. The keyword int is used to declare variables of integer type.
For 16 bit machine the range of integer is -32768 to +32767. In order to control over the range of numbers
and storage space, C has three classes of integers.
Data type Keyword Size in Bytes Size in Bits

Short short int 1 8


integer
integer int 2 16

Long long int 4 32


integer

Floating point type: data type that can store decimal numbers in memory locations are called float/real data
types. The floating point numbers are defined in C by the keyword float. If the accuracy provided by float
number is not sufficient, double type can be used. It gives double precision. Following table gives various
sizes available in floating data types.

Data type Keyword Size in Bytes Size in Bits

Float float 4 32
Double double 8 64
Long long 10 80
double double
Character type: Data type used to store single character in memory locations is called character type. The
16
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

keyword char is used for character type Each of these characters has numerical value associated with them
called ASCII values. (ASCII stands for American Standard Code for Information Interchange.)
for example: letter ‘a’ has ASCII value 97 (binary equivalent is 0110 0001) and letter ‘b’ has value 98
(binary equivalent is 0110 0010). In same order ASCII value of ‘x’ is 120 (0111 1000).
Here are some of the important ranges within the ASCII character set:48 – 57:
the digits ‘0’ through ‘9’
65 – 90: the capital letters ‘A’ through ‘Z’
97 – 122: the lowercase letters ‘a’ through ‘z’

Following table represents the size of character type and its keyword.Some
important range s within ASCII character set
Data type Keyword Size in Bytes Size in Bits

Character char 1 8

Void type: It is a special data type that has no value but can be used for only one operation thatis assignment.
It can also be used as generic type.

Variables
Variables are named memory locations that have type such as integer or character to store data values,
these data values will change during program execution. Variables are also called identifier, because it is
used to identify value.
Rules for naming variable
1) The first character must be an alphabetic character (lower-case or capital letters) or an underscore ‘_’.
2) All characters must be alphabetic characters, digits, or underscores.
3) The first 31 characters are significant; however length should not be more than 8characters.
4) Cannot duplicate a reserved word. A reserved word is one which has special meaning to C.
5) Uppercase and lowercase are significant.
6) White space is not allowed

Primary Variable declaration: All variables must be declared before use, although certain
declarations can be made implicitly by content. A declaration specifies a type, and contains a list of one or
more variables of that type.
Syntax of variable declarationdata-type
v1,v2,---vn ;
Where data-type can be any basic datatype,and v1, v2 .. vn are the names of the variable.Variables are
separated by commas. A declaration ends with semicolon(;).

Example
int lower, upper, step;
Variables can be distributed among declarations in any fashion; the lists above could well be written as
int lower; int upper; int
step;

The latter form takes more space, but is convenient for adding a comment to each declarationfor
subsequent modifications.

Variable Initialization: Once you declared variable, the next step is to assign value to variable. The process
of assigning values to a variable is called initialization of variable. You can assign values to a variable by
using (= ) assignment operator.
17
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Syntax:
Variable _name=value;
Following examples illustrates the same:
int a=25, x=55, c=77;
float p=25.5, q=30.55;
char ch=’A’;

a 25 x 55 p 25.5 ch A

Files in c program
1. Every .h header file pre-compiles with it’s corresponding .c file and creates a header object file(.o file).
2. Before compiling our main.c file it first go through the pre-processor, then compiler compiles it into
assembler and creates object file (main.o).
3. Then linker link the main.o with required header objects and libraries and creates a executable file
(program.exe).

1. Source file(.c): These files contain function definitions, and the entire program logics, these files
are human readable and by convention their names end with .c .
2. Header file(.h): These files contain function prototypes and various pre-processor statements. They
are used to allow source code files to access externally-defined functions and by convention their
names end with .h.
3. Object file(.o): These files are produced as the output of the compiler. They consist of function
definitions in binary form, but they are not executable by themselves and by convention their names
end with .o.
4. Binary executables file(.exe): These files are produced as the output of a program called a
“linker“. The linker links together a number of object files to produce a binary file that can be
directly executed. It contains symbols that the linker can extract from the archive and insert into an
executable as it is being built. And by convention their names end with .exe in windows.
5. Dynamic Library file(.so, .dylib, .dll): A dynamic library (.so files for most POSIX
systems, .dylib for OSX and .dll files for Windows) is dynamically linked at runtime by the
program. These are also sometimes referred to as shared libraries because one library image can be
shared by many programs. Dynamic libraries have the advantage of taking up less disk space if
more than one application is using the library. Also, they allow library updates (bug fixes) without
having to rebuild executables. And by convention .dll is used for their naming in windows,
and .so is used in MacBook and .dylib is used in OSX.

Compilers, Compiling and executing C program.


 Interpreter:
18
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

 Converts any programming language code to machine level code: “line by line.”
 Compiler:
 Compiler takes “complete program code” and coverts it to machine level code.

19
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Input/output statements in C:

1. READING A CHARACTER

➢ The simplest way of all input/output operations is reading a character from the ‘standard input’ unit
(usually keyboard) and writing it to the ‘standard output’ (usually the screen).
➢ Reading a single character can be done by using the function getchar and it does not have any
parameter.

Syntax: variable_name = getchar( );


Where, variable_name is valid and has been declared in char type.

Example: char name;


name = getchar( );

➢ The getchar function can also be used to read the characters successively until thereturn key is
pressed.
2. WRITING A CHARACTER

➢ Writing a single character can be done by using the function putchar.


20
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Syntax: putchar(variable_name);

Where, variable_name is valid and has been declared in char type.


Example: name=’y’;
putchar(name);

Will display the character y on the screen


Example:
#include<stdio.h>
int main()
{
char grade;
printf("enter grade: ");
grade=getchar();
printf("your grade is: ");
putchar(grade);
}

String input/output function: gets( ) and puts( )


➢ gets and puts are line oriented input output functions available in the <stdio.h> header
file.
➢ gets( ): Alternative method to read strings is gets( ) (read it as get string) function
which is an unformatted string input function. Advantage of gets( ) is it can read multi-word
strings.
➢ Example: char name[10];
gets(name);

Say input is:


N E W Y O R K

The complete string “NEW YORK” is read by gets( ).

➢ puts( ): This function can be used to display entire string on monitor screen
without the help of %s specifier.
Example: char name[ ] = “Bengaluru”
puts(name);
puts( ) will display the string value stored in parameter passed to it on monitor. In thiscase it is—Bengaluru.

21
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Example:

#include<stdio.h>
int main()
{
char name[10];
printf("enter your name: ");
gets(name);
printf("your name is: ");
puts(name);
}

FORMATTED INPUT { scanf() }

➢ Formatted input refers to an input data that has been arranged in particularformat.
➢ Ex: 152 Rajesh
➢ In the above example the first part contains integer and the second part containscharacters. This is
possible with the help of scanf function.

Syntax: scanf(“control string”, arg1, arg2,…..,argn);

➢ The control string specifies the field form in which data should be entered and the arguments arg1,
arg2,…..,argn specifies the address of the location where the data is stored.
➢ The width of the integer number can be specified using %wd.

Example-2:

– scanf(“%2d %2d”, &a, &b);

%2d→ two digit integer

%2d → two digit integer


4567 25

➢ The input field may be


a=45 b=67* in the place of field width.
skipped using

Note: 25 is not at all stored


Example-3:

– scanf(“%2d %*d %2d”, &a, &b);

%2d→ two digit integer

%*d → skip this integer


45 25 63

a=45
22
25 is skipped
b=63
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

➢ The scanf function can read single character or more than one character using %cor %s.

Rules for scanf:


➢ Each variable to be read must have a specification
➢ For each field specification, there must be a address of proper type.
➢ Never end the format string with whitespace. It is a fatal error.
➢ The scanf will read until:
• A whitespace character is found in numeric specification.
• The maximum number of characters have been read
• An error is detected
• The end of file is reached
➢ Any non-whitespace character used in the format string must have a matchingcharacter in the
user input.

❖ The below table shows the scanf format codes commonly used.

Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[ ] Read a string of word

The l can be used as a prefix for long integer. Ex: %ld

FORMATTED OUTPUT { printf() }

➢ The printf function is used for printing the captions and results.

Syntax: printf(“control string”, arg1, arg2, ….., argn);

➢ Control string contains three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.

23
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

➢ The printf can contain flags (0 + - )


0→ fill in extra positions with 0’s instead of spacesa=7777
printf(“a = %07d”, a);

%07d Width of 7 memory space is allocatedand


0 0 0 7 7 7 7 padded with leading zeros

- Left justify text instead of right justify texta=7777;


printf(“a = % -7d”, a);
% -7d
Width of 7 memory space is allocatedand
7 7 7 7 printed from left side (left justify)

+ Print sign of number (whether positive or negative)

➢ Example with format specifier %d:


a=10, b=77;
printf(“%d %d”, a , b);

Output:
10 77

➢ Example with format specifier %f:


x=10.776;
printf(“%6.3f ”, x );

%6.3f 6.3f means totally 6 locations are allocated out of


which 3 is for number ofdecimal places.
1 0 . 7 7 6

➢ Example with \n and \t:


a=10, b=77, c=88;
printf(“a=%d\n b=%d\tc=%d”, a , b, c);

24
First Year Engineering, Sub Name: POP Code:22POP13 Module No.:1

Output:

a=10
b=77 c=88

➢ Example with size value:


a=10, b=7777, c=88;
printf(“a=%4d\n b=%7d”, a , b);

%4d Width of 4 memory space is allocated and


printed from rightside
1 0

%7d Width of 7 memory space is allocated and


printed from right side (rightjustify)
7 7 7 7

❖ The below table shows the scanf format codes commonly used.

Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal integer
%x Print a hexadecimal integer
%[ ] Print a string of word

The l can be used as a prefix for long integer. Ex: %ld

25
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 1

➢ General syntax of field-width/size for different data types:


• %wd → Example: %6d
• %w.pf → Example %6.2f
• %w.ps → Example %10.4s
– w means total field size/width
– p means precision (tells how many decimal places to be printed in case offloat)
and
– How many characters to be printed in case of strings

Examples: 9 8 7 6

a=9876;

printf(“%d”, a); 9 8 7 6

printf(“%6d”,a); 9 8 7 6

printf(“%-6d”,a); 9 8 7 6

printf(“%3d”,a);

26

You might also like