Untitled

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 70

00Q. Why to prefer this book?

If you could answer these questions you need not prefer this.

Q1. How can you define Electronics?


Q2. Computer works with Binary system why?
Q3. C Has two compilers! Do you know?
Q4. 1 byte = 8 bits ! Why not 10?
Q5. C is middle level language. What does it mean?
Q6. C is structured programming language. What is structured programming?
Q7. RAM is Random Access Memory. It is its abbreviation or definition?
Q8. What is CACHE memory and what is its purpose.
Q9. What happens when we don’t use & in scanf().

Can you answer these questions? If not, come across from first page with a
great patience. You will become a good professional.

When we look at computer the external devices like CPU, monitor,


Keyboard and mouse are visible.

Think when we type “5” on keyboard it is displayed on monitor. The


question is how it is transferred from keyboard to the monitor.

It is through wires. Then through wires how it is transferred?

Key Board Monitor

Between the keyboard and monitor there is a box called CPU (Central
Processing Unit) to which all the devices are connected.

Now think that, there is a battery in the keyboard with transformers to


increase the voltage. When we press 5 on keyboard, the battery produces some
voltage and the transformers increase/decrease it to 5 volts and then
transmitted over the wires towards the monitor. And there is a Volta meter in
the monitor that checks voltage, and if the voltage is 5 then displays 5 on
screen.

Do you find any disadvantages if the computer works with above


technology.

Questions ?
a. how can the text be transferred
b. what about high voltages, if we need to transfer 20000, the wire
through which the voltage passes must be so thick, that the computer
size is again increased to a large room size.
c. What about Ohm’s law ?

The Ohm’s law concept plays a major role here in this technique. The
concept of ohm is resistance. When 5 volts is transferred from keyboard
through the medium (wire), as every medium has a resistance, there will be a
dropping of voltage at destination. So the computer will not have accuracy
during data transfer.

Conclusion: if there is no accuracy, we need not use computer.

So the computers work with a different way. There will be number of wires
connecting each device in the computer. When a key is pressed on keyboard,
the value is converted into binary system and transferred over the wires
between devices with the help of electricity pulses.
Conclusion: the computer works with electricity pulses.

During data transfer, the data is converted into binary system and
wherever ZERO need to be passed there will not be an electrical pulse on the
wire and wherever ONE need to be passed there will be a pulse on that wire.

Example: think, someone applied body spray stands at a distance from you,
still you get that fragrance. It is because of the wind movement. The air
moves from place to place and takes the fragrance along with it. So as the
electricity pulses in the system. The electricity pulses transfer from one
place to another with in the system. They carry the data in binary format
form one place to another place. This is called Electronics.

As the computer is electronic device, it too works with binary system.

As the subject electronics itself is a deal with binary system and


electrical pulses, all the electronic devices like calculator, watches,
computers etc work with binary system.

Computer Organization:

Ex:
Kitchen
When we need to understand something new, it is easy to compare and
understand. The best organization what we know is kitchen.

Bowl

Stove

Make Ready
Location
Dad
Fridge

mom

Let us identify each part of the kitchen.

Fridge : used to store, so that we can use in future.


Stove : the actual part that performs process in the kitchen.
Make ready location : the location where the vegetables are stored
temporarily prior to process, and it is a central location which connects
all other parts of kitchen. (where generally mom cuts, washes etc).
Dad : if no vegetables are available, they are brought from outside. What we
need to remember is when vegetables are brought from outside, they are placed
in make ready location and what ever need to be sent for processing are sent
to bowl and that need to be used in future are sent to fridge from this
location.
Mom : is the person who CONTROLS, CO-ORDINATES AND ORGANISES all these
processes.
There is one standards that can be identified in the kitchen. The
vegetables can be placed in different locations like can in bowl (during
processing), can be in fridge (to store for future) and can be in make ready
location (for keeping ready prior process).But the vegetables placed with in
bowl is only processed.

Computer
cache

ALU

Main Memory

Input
Devices
Hard Disk

OS

Devices Purpose

ALU The part of the computer that actually


(Arithmetic Logical Unit) performs process.

Cache The location where the data is stored


(CPU Registers) during processing.

Main Memory The location where the data is stored


(RAM) prior to its process.

Hard disk used to preserve data to use in future.


(Storage device)

Input devices used to give input, the given input is


primarily stored in main memory.

OS (Operating System) is a system software that controls co-ordinates


and organizes all the processes of the system.

Comparing :
as in kitchen the fridge is used to store vegetables, in the system the
hard disk is used to store data.

As the make ready location in kitchen, in computer the data is


transferred from hard disk / keyboard into the main memory prior to process.

The data from main memory (RAM) is copied into cache memory for getting
processed as in kitchen the vegetables are transferred into bowl.

As in the kitchen the stove processes vegetables that are stored only
in bowl, in the system, the data copied into cache memory is only processed
by the ALU. i.e. ALU can not process the data that is in any other memory.

The ALU and cache memory (CPU Registers) are integrated into a single
chip called micro processor.
When we do any work with computer, our work is primarily stored into
RAM so RAM is called primary memory of the system. Later it can be
saved/stored into hard disk for future use.
Components of electronic devices:
the components of electronic devices are classified into two types,
viz., hardware components and software components.

The physical components of the system are called hardware components.

Think of a simple example, where you are jumping from a height of


around 30 feet and there is a net kept on ground, if you jump you will be
injured. If your friends hold net tight at a height, and then if you jump,
you will safely land on the net with out injuries.

As your friends come under net and holds it tight, the software
in binary system gets loaded into the circuits of the hardware devices and
make them to work as they are supposed.

The software is defined as set of instructions for a particular


purpose.

The software designed to control mouse, gets loaded into mouse circuit
and makes mouse to work as mouse. But it can not control keyboard.

The software is classified into two types, viz., system software and
application software.

Have a comparison between you and a rickshaw puller. He eats, you eat, he
talks, you talk, he listens and you listen. But what is the difference
between him and yourself?

He can not use computers and you can use. He can not work with math and
you can. A man to live like man should eat, listen, think etc. but who knows
computers can work better, who knows math can do well.

So, for human being, eating, listening etc are like system software and
working with computers, maths etc. is accessories. A man can do with out
computers and science. But by keeping knowledge of these things his features
are enhanced.

Similarly, the software that is must for running a computer system is


called system software and the software by applying which we can enhance
features of system are called application software.

The system software includes BIOS (Basic Input Output System), Drivers
and Operating system.

BIOS : is software stored in a chip called ROM (Read Only Memory) and used in
POST Operation.

Drivers : It is the software that loads into the circuit of hardware devices
and controls then directly.

Operating system: this software works as an interface (mediator) between user


and computer by coordinating all the processes with in system.

Functions of Operating system:

It provides file management. i.e. lets user to create a file, name it,
change its name, modify its content and delete it if not required.
It provides directory management. The directories are used for logical
grouping of the files for better organizing. The OS permits user to create
directories/ folder, name/rename them, move them from one location to another
and delete them if not required.
Basic Terms : the following are the basic terms used with computer systems.

POST : Power On Self Test. This is a process done by the system itself.
During this process the systems checks itself whether all the hardware
devices are connected properly or not.

? why system should check itself, as we connect hardware devices, we must


check them. Is it?

Think the hardware devices are controlled by the system software called
drivers. The drivers are stored in hard disk. The system loads drivers of all
devices during booting up. Unless the drivers are loaded the system won’t
work.

The fact is We don’t load drivers, but the drivers are loaded by the
system itself. So the system must check up whether the hardware devices are
connected properly or not.

This is something like taking attendance of students by a teacher, for


which each student is assigned with a roll number. Similarly all the
hardware devices of the system are identified with a numeric value (like roll
number) called interrupt number.

In colleges, the roll numbers are stored in attendance register.


Similarly, the interrupt numbers of the hardware devices are stored and
managed by software called BIOS (Basic Input Output System), that is stored
in the chip called ROM.

So when the system is switched on, the Micro processor taking help of
interrupt numbers stored in BIOS available in ROM, checks whether all the
hardware devices connected properly or not. This process is called POST.

Booting up :

Think, the standards maintained in a cinema hall, where the ticket


issue person must be with in the ticket counter to issue tickets. Similarly,
the cashier of a bank must be with in the cash counter to perform money
transactions in bank.

If the cashier is with you at your home, can you perform money
transaction with bank (through him)? The answer is no. he must be in the
place where he must be.

Even in the systems, there is something like cashier and cash counter.
The Main memory i.e. RAM of the computer is something like cash counter and
the Operating System is something like cashier.

The operating system when available with in main memory, then only we
can perform any transaction with the system.

When the POST is completed in the system, the microprocessor starts


loading OS files into the main memory. The OS gets loaded by itself and loads
the drivers of all hardware devices into main memory so that the user can use
the computer through them.

This process is called booting up. The term booting is picked up from
American army. During 2nd world war, when they need soldiers to make ready
them self, they use to say “boot up”. So the term boot up refers make ready
by it self.

So when the computer is switched on the POST is performed first, in


which the system identifies all the hardware components connected to it, and
then the booting up is performed, during which the systems loads drivers of
all hardware devices and OS into the main memory, the RAM.
Version: it is a term used to refer modal. If we come across mobile phones,
Nokia is a company that released 3310,3315,6600,6630 etc modals of mobile
phones.

The version is release of the same software/hardware device with new


enhancements with new name/number.

The Microsoft is a company that released windows operating system in


different versions like windows-95,98,ME (Millennium Edition), 2000 family,
XP (Experience), 2003 server and vista.

Similarly, the Intel is a company that released number of versions of


microprocessors with numbers 4044, 8080, 8085, 8086, 8088, 80286, 80386,
80486, Pentium, P–II, P-III and PIV, duel core, and core2 Duo and similarly,
the AMD released with names athlon, duron, sempron etc.

Each micro processor version has a difference in their clock speed,


size of cache memory and number of instructions in its ALU.

Micro Processor :

The micro processor basically includes two parts. BIU (Bus Interface
Unit) and EU (Execution Unit).

The BIU works as a mediator between the Execution unit and the main
memory. It remembers from which part of main memory the data need to be
loaded into cache and to which part of main memory the result from cache to
be sent. This is also called Control Unit.

The EU includes basically three things.


a. clock
b. cache memory and
c. ALU

Clock : this is similar to normal clock, where normal clock moves seconds
needle once in a second, but the micro processor’s clock released electrical
pulses.

Its speed is measured in Hertz. 1 Hz means one clock pulse per second.
This clock pulse let the system to transfer data once from one location to
another OR lets micro processor to perform once process in a second.

The speed of micro processor is further measured in Kilo Hz, Mega Hz


and Giga Hz. Where Kilo refers 103 and Mega refers 106 and Giga refers 109 .

Now the micro processor P-IV available in the market works with a speed
of 3.2 Giga Hertz. i.e. it performs 3200000000 processes per second.

Cache memory : During process the data is stored in cache memory. The cache
memory is also called CPU registers. The P-IV has 512 KB of cache memory.

ALU : This is Arithmetic Logical Unit. When this is designed, it is stored


with number of instructions like what to be done when + given and * given
etc. These are called Instruction set.

The P-II has around 1.2 million instructions.

When an instruction 2*3 is given to system, first the “2*3” is


stored in main memory. During process the 2 and 3 are copied into
the CPU registers and the * is submitted to ALU. The ALU performs
the process * on the data 2 & 3 stored in cache and the result is
stored in cache itself. Once the process is completed, the result 6
is copied into main memory and then displayed on to screen.

The same is the sequence of work performed for all types of


processes.
Languages : Languages are used for communicating.

? Can a person communicate with computer with out knowing languages. Of


course YES.

When talking about people who use computers, these are classified into
two types, USERS and PROGRMMERS.

The user need not know languages. Keeping knowledge of using devices is
good enough to the user to use computer. But programmer programs the system.

? What is this program? What are the locations where we used the terms
program?

TV Program, Radio program, Entertainment program etc, here we have the


sense of PLAN for the term program. Similarly, observe the situation, where
there is an organization, where there is an employee and a manager.

The manager gives work to the employee and the employee performs all
the work.

The manager might ask employee like, “come to office at 9 a.m., prepare
accounts by 11 o’ clock, feed them into system by 12 o’ clock and brake up at
1 p.m.”. This can be understood as a program given by the manager to the
employee.

Here we have the sense “giving instructions” for the term “program”.
The same is in the case of computer.

The programmer gives instructions to the computer to fulfill the


requirement of the user. This is called programming. For giving instructions
to computer one must have knowledge of Languages.

Conclusions:
 Languages are used for programming.
 Programming is nothing but giving instructions to the system.
 Programmer programs the computer to fulfill the requirement of
user, i.e. the programmer gives instructions to the computer to
act as per the requirement of the user. This is called
programming.

These languages are classified into two types, viz. Low level languages and
high level languages.

Low Level Languages:


The languages that are capable of accessing CPU registers (cache
memory) and ALU instruction set directly are called low level languages.

Ex : Assembly Language.

NOTE : If we consider the micro processor 8085, it has 8 bytes of cache


memory. Each byte of memory cell is identified with a name viz., AH, AL, BH,
BL, CH, CL, DH, DL. It looks like

AH AL

BIU BH BL
CH CL
DH DL

ALU
When we develop a program in assembly language, the language has some
Mnemonics like “mov” to store data into a specific register. Like “mov 5, ah”
stores the value 5 into the register (memory location) that has name “ah”.
“add ah, bh” add the value stored in ah and bh.

No other language is capable of accessing the CPU registers directly


like assemble language.

Conclusion:
 The assembly language is low level language.
 Using low level languages we can access the CPU registers
directly.
 i.e. system can be programmed with low level languages directly.
 i.e. the system understands low level languages only.

User need not understand all these. But this is mandatory for a programmer.

System understands only low level languages, means the system can be
programmed only with low level languages DIRECTLY.

Problems with Low level languages: A program designed in Low level language
i.e. the instructions given in low level language for a computer can not be
executed on other systems, because of change in number of registers in micro
processor and change in number of instructions.

Let us consider the micro processor 8085 designed by Intel Company has
71 instructions but P-IV of the same company has more than 1.2 million
instructions. Similarly, the model 4044 has 4 CPU registers and P-IV has
around 512 KB of CPU registers.

For example if we consider P-I has two instructions + and – and P-II
has three instructions +, - and *, then the instruction given “2 * 3” for P-
II micro processor can not be executed on P-I micro processor as P-I’s ALU
does not have the instruction *, i.e. the ALU of P-II does not know what to
do when * instruction is given.

This is called hardware dependant OR specific. So the Low level


programs are hardware dependant. i.e. a program designed in Low level
language for one micro processor can not be executed on other micro
processors.

What happens if still low level languages are being used?


All users must use similar type of microprocessors and there
can not be a development in hardware technologies OR when even a new
micro processor is developed, all the previous programs designed in
low level languages must be redesigned for new modal micro processor.

High Level Languages: To overcome the problem of processor specific-ness OR


hardware dependency, the High Level languages are developed. But the high
level languages are not capable of accessing CPU registers and ALU
instructions directly.

It is not “high level languages are user understandable”. It is


that the high level languages do not have features of accessing CPU
registers directly.

Think, if somebody asks you to cook and not to use utensils/ bowls
and stove during cooking! Is it possible to cook with out using them?
The same with system even. When an instruction needs to be executed,
the data need to be stored into CPU registers and Instruction is to
be submitted to the ALU. With out using ALU and CPU Registers, the
instruction can not be executed in system.
As the high level languages are not capable of accessing system
resources to execute program, they must be converted into low level programs
for execution.

The software mechanisms like compilers and interpreters are used for
conversion of high level code into low level code. The interpreter converts
high level code into low level code line after line, where as the compiler
converts the entire high level code into low level code at once. As the
system executes only one line of instruction at a time, the compiler when
converts all lines into low level code at once, saves it to the hard disk as
a file, so that it can be further loaded into main memory (RAM) during
running. When compared the compilers are faster than interpreters.

COMPILERS : INTERPRETERS
Converts entire code at once Converts line after line

Generates a file Will not generate a file

faster slower
We can give a better definition to the compilers/interpreters by
understanding the following example.

Let us consider keeping in mind that, for example PI has +,- two
instructions in its ALU and PII has +,- and * also.

We have the code 2*3, and this is high level code. When this code is
compiled on PII, the compiler / interpreter converts 2*3 high level code into
2*3 low level code.

When the same code is compiled on PI, the compiler checks whether the
instruction * is available with in the ALU or not. As in our example, we
considered PI has only + and -, the compiler converts this into its
equivalent code as 2+2+2.

Conclusion: the compiler OR interpreter converts High Level Code into


“PROCESSOR APPROPRIATE” Low Level Code.

The above is only an example to realize the fact. Do not get a


question raised what happens when “/” given. The ALU s have millions
of instructions and for out understanding, we considered simple
arithmetic operations to realize the fact.

? What to choose for conversion? A compiler OR an interpreter!


It is no way the choice of the programmer. Based on the purpose of the
language, the software itself is provided with appropriate conversion
mechanism.
If we consider the language C, OR C++ they have two compilers, where as
the language java has one compiler and one interpreter. The HTML has only one
interpreter.

? Why C has two compilers?


(Keep in mind that we are programmers.)

 If we (programmer) develop a program in low level language and


produce to the user, as the low level code is processor
dependant, it runs only on similar type of processor. If user’s
micro processor is different, the program will not run.
 If we develop a program in high level language and compiled on
our system and generated low level code if given to the user,
still there is no guarantee that it runs on user’s system, as the
compiler converts high level code into PROCESSOR APPRIPRIATE low
level code, the code generated on our system runs on our micro
processor, and might not match with the user’s micro processor.
 If we produce high level code to the user, and compile the high
level code on user system, then the compiler on user system
generates the code that matches with the micro processor of
user’s system, and then the program can be executed.
 But there is a problem in ‘GIVING HIGH LEVEL CODE TO USER”. The
user might change the high level code either purposefully or by
mistake. Once the high level code is modified and re compiled,
the previous low level code is deleted and new low level code is
placed in the system, by which the program corrupts.
 To over come the above problem (of corruption of high level
code), and provide security to the high level code, the two
compiler technique is implemented in many languages.

Two Compiler Technique:

In this mechanism, the high level code is converted into intermediate


code using the first compiler and the intermediate code is given to the user.
On user system, the intermediate code is further converted into low level
code and then used.

In this case, as the high level code is not given to the user, there is
no chance of corrupting high level code and it is kept secured at development
center. As the intermediate code is in symbols (Mnemonics) if a symbol is
deleted, the program will not be compiled into low level code.

The computers are named for accuracy. “NO EXECUTION IS BETTER THAN
WRONG EXECUTION”.

The intermediate code generated by the 1 st compiler of C is called


object code and saved with extension “.obj”. This object code is given to
user, and on user system, this is again compiled into low level code using
the 2nd compiler of C.

 The High Level code is hardware and software independent.


 The Low level code is hardware dependent.
 The intermediate code of all languages is operating system dependent.
(Other than Java).

Special Symbols:

~ : Tilde @ : atte...available at
# : Hash ^ : caret
& : ampersand * : Asterisk
() : parenthesis []: brackets
{} : Braces <>: Angled Brackets
_ : underscore | : pipe line

Basic History: The C is developed by a team of people under leadership of


Dennis Ritchie in the year 1972 (Recollect! We understood the requirement of
2 phases of compilations during project development, and this problem of
security to high level code was realized by the team of Dennis Ritchie in the
year 1972. So it is not a new technique and we need to just understand. It is
not something new, but already existing). It was developed on a system
consisting of UNIX operating system and later the 83% of UNIX is re-
constructed in C language by Dennis Ritchie.

It combines different features of its prior languages like B, BCPL


(Basic Combined Programming Language), and has become a richest language.
Accessing of CPU registers is actually the feature of Low Level Languages,
and high level languages can not access CPU registers. Though the C is a high
level language, it is capable of accessing CPU registers directly. So it is
called middle level language.
Programming Languages: All the software has its own environment. The
environment of programming languages is called Runtime Environment. The RE
includes number of components using which programmer can develop programs.
(Using which programmer can give instructions to the computer).

The components of RE are called Tokens. The token can be defined as


predefined tool, using which we can develop programs.

Tokens of C:

1. Editor : Editor is something used to edit (do modification to existing


thing, create some thing new). The C for dos and windows operating systems
has a special blue colored editor, with different menus for program
development, compilation and execution.

2. Keywords : The term key has a meaning important (key person of the
organization, key element etc.) . Every programming language has its own
reserved set of words called keywords. These are used to give some special
instructions to the system during program development.

3. Variables : It is one that is capable of varying/changing its value.


During execution of program, the program takes input from user, do process on
the data taken input and give results to the user. The data need to be stored
for undergoing process, for which we need to reserve some memory in the main
memory (RAM).

The memory space reserved in RAM to store data temporarily during


running of program for undergoing process, as it is capable of varying its
values is called variable.

The variable (reserved memory) is managed by naming them. The rules for
naming variables are as follows :

 The name must be less than 8 characters in case of UNIX or DOS


operating systems. In case of windows, the variable name can have
up to 32 characters.
 It should start with alphabet and can have numbers.
 No special symbol is permitted other than underscore. (Underscore
is used to differentiate between words when the name has more
than one word).
 No keywords are permitted as variable names
 Duplicate names are not permitted

4. Compilers : The C RE has two compilers to convert high level code into
object code and then into executable code.

5. Data types:
The data is defined as a value/detail available that has no meaning in
user environment. Ex : 3500-00. we might understand the value is rupees three
thousand and five hundreds. But we have no understanding that what to do with
this or why we have this value or what exactly it is. Information is defined
as the data that has a meaning in user environment. Ex : P-IV processor cost
is 3500-00.

Now the same 3500-00 is useful for us as it specifies it is cost of P-


IV micro processor.

Many programming languages have data “type specifications”, to treat


data perfectly. For example, the value 25 looks as numeric value, but if the
25 is marks in a subject, then it must be “added” with marks in other subject
to calculate total marks. If the same 25 is roll number OR house door number,
then we don’t get a situation of performing any numeric operation on the data
25. in such a situation the data values like door number, roll number, phone
number etc must be treated as text data. Thus the data types are used for
providing proper treatment to data.
The different data types are

Date type Keyword Memory Size Range/ Capacity Format


specifiers

Character char 1 byte -128 to 127 %c

Integer int 2 bytes -32768 to 32767 %d

Float float 4 bytes -3.4 e18 to 3.4 e18 %f

Double double 8 bytes -1.7 e108 to 1.7 e108 %lf

The data types are used when declaring variables. Variable declaration is
nothing but, reserving memory and naming it (prior to its use). While
declaring variables we specify what type of data to be stored in variable.

The data type keywords are used to declare variables. When we use the
keyword int and declare a variable, the keyword int reserves 2 bytes of
memory and lets that memory to treat the value stored as integer.

The variable when declared occupies standard memory space. Because, the
variable is declared first and then used in the program. The data is stored
into variable during running of program and the Runtime Environment doesn’t
know how much data is stored into that variable. The OS allocates fixed
memory for the variable.

Once the variable has a fixed (limited) size memory occupied, it also
has restriction on data storage, and it is called range of data type or
capacity of data type. It is measured with the formula 2 n , where n is number
of bits.

The range of int data type is -32768 to 32767 OR 0 to 65536 OR 0 to


216 OR -215 to 215 . Similarly it is -128 to 127 in case of character data type.
In technology, the positive and negative numbers both are given equal
preference. (As the user may need to work with both positive and negative
numbers).

In normal life, 1 is first positive number and ZERO is neutral number.


In case of computer systems, the ZERO is the first positive number. As 0 is
first +ve number, the range on positive side is always one less than the –ve
side.

When 5 is pressed on keyboard it is converted into 101 binary system


and then transmitted. What about alphabets. It is meaningless or impossible
to convert A into binary system. So the Computer system / key board are
designed such that, each key on the keyboard has a numeric code value, and
when a key is pressed its corresponding code number is converted into binary
system and then transmitted.

This code is developed by the organization ANSI (American National


Standards Institute) and called ASCII (American Standard Code for Information
Interchange) code. The standard keyboard can produce 256 symbols. So the code
numbers are given from -128 to 127.

* so the range of char data type is represented as -128 to 127 ASCII.

For example if we type ‘A’ on keyboard, its ASCII code is 65 and 65 is


converted into binary system and then transmitted.

If we press one key on keyboard, one unit of data is transferred from


keyboard to the main memory (RAM). If we press any key on keyboard, its
corresponding ASCII code is converted into binary system and then
transferred. The largest ASCII value is 128 if the sign is not considered.
Think, if a key is pressed, and its ASCII value is 128 (-ve) then, when
128 is converted into binary system it is 10000000 (2) . i.e. it is converted
into 8 binary digits.

So when one unit of data need to be transferred, it is converted into 8


binary digits maximum. The BInary digiTS in short called bits. So 1 unit of
data is converted into 8 bits. And 8 bits is called 1 byte. (So 1 byte is 8
bits).

The format specifiers are used to specify in which format the data has
to be stored into variables.

Observe the simple situation, where we have content H 2O and two storage
locations, a bucket and a cloth bag. Our situation is to store H 2O into these
storage locations. We can store H2O into a bucket in liquid form. But for
storing the same into a cloth bag, it must be converted into solid form and
then store. Here if we observe, there are three things to be considered the
content, storage location and the format in which we store.

Similarly, when we press a key 5 on keyboard, its ASCII value is 53 and


53 is converted into binary system and stored. If we have a char variable and
an int variable, then the data storage pattern in different.

If we store 5 into char variable, the 5, its corresponding ASCII value


53 is converted into binary system and stored into the char variable.

But if the same 5 is needed to be stored into an int variable, then the
value 5 as it is converted into binary system and stored. So that when using
the value (for processing), it is processed as 5 numeric value but not as 53.

This “how data to be stored” is represented with format specifier. When


we need 5 to be stored into a char variable we use the format specifier “%c”
and when in int variable we use “%d”.

6. Functions: if we come across, DOS is an operating system that is


command driven. i.e. for working with DOS one know the DOS commands.
Similarly, the Windows is menu driven software. So for working with Windows,
one should know the menus and how to use them.

The C programming language can be said as function driven. Function is


nothing but a process. Functions in C are identified with a pair of
parenthesis.

Functions can also be understood as set of code identified with a name,


something like an abbreviation. Every function will have two things a
definition and a call.

The function definition is nothing but the process to be executed when


the function called. And the function call is invocation / activation of the
definition.

The C has number of functions pre-defined and we can call them to


develop required program.

Ex: printf() and scanf() etc.

7. Library files: Any thing that is available with system can be kept only
on a storage media. Any thing that is available on storage media is called a
file.

All the pre-defined functions of C are grouped into files and kept
stored on hard disk, called Library files. As these files are linked to the
program at header part, these are also called header files. These files are
identified with extension (.h).
Ex : printf(), scanf() are defined in the library file stdio.h

8. Pre-processor: when we develop a program and execute it, the RE


executes the program with the help of Operating system. Here we consider the
RE as processor, and not the micro processor.

When we develop a program and use pre-defined functions to develop


process, the function definitions must be linked to the program. Unless
function definition is linked, it can not be called. (some thing like, unless
we connect a fan, it is meaningless of switching on. Here Fan has a
definition of rotating and switching on is something like calling its
definition).

Linking of definition must be performed prior to the starting of


program. So linking is a process to be done PRIOR to actual process (where
the program that needs to be executed is actual process).

The pre-processor of C is identified with a hash # symbol to the RE.


(Realize, the program is executed by RE. the RE should link library files
first and then compile our program into object code. And the # is an
indication to RE that the code typed in the like which starts with # must be
performed prior to compilation).

In pre-processor, we can perform different activities like linking


library files and developing macros. For each type of process the C has a
special directive.

9. Directives: The Directives are used to direct the RE about the kind of
process to be performed in pre-processor.

Include: is a pre-processor directive that directs the RE to link


specified library file.

Ex : #include<stdio.h>

Define: is a directive used to develop macros. Macro is nothing but


large. Large in the sense, not something that is big / large in size
physically. It is something large to remember.

Recollect the value of PI, is it 3.14 OR 3.1428 or some thing more than
that. It is 3.1428571428571428571428571428571 and so on. It is difficult to
remember this value with our little brains. So instead of remembering such a
large value, we can develop a micro for this macro value.

Ex : #define PI 3.142814

Whenever in the program we need this value to be referred, we need not


remember value and type it. We can simply use the micro of this macro “PI”.

Program development:
Programming is nothing but giving instructions to the computer to
fulfill the requirement of the users.

If remember the basic functionality of the system, the system takes


input, do process and gives output. This is the functionality need to be
remembered by user. But as a programmer, we need to give instructions to the
system to take input from user, do required process and also we must give
instructions to the system to produce output to the user.

When we (programmer) develop a program, we must concentrate on three


things.

1. Managing user interface : This is nothing but providing


interactivity between user and system. The interactivity is nothing
but taking input and giving output.
2. Data storage : when user gives input we (the programmer) need to
reserve some memory (variables) and store data temporarily during
running of program. So data storage is managed using variables.

3. Process : it is carried out with the help of Operators, like +, -, *


etc.

While managing user interface, we need to give instructions to computer


to handle keyboard and monitor so that we (programmer) can make system to
take input from user and produce output to the user, for which we use the
pre-defined functions, called IO Functions.

IO Functions:

printf() : this is an output function defined in the library stdio.h,


used to provide output on to the screen (monitor).

Syntax :
i. printf(“message to be displayed”);
ii. printf(“Format specifiers”, source variables);
iii. printf(“message with format specifiers”, source variables);

we can use any above syntax as required in the program. During program
development, we might require displaying simple messages on monitor OR we
might get a requirement of displaying results. The results are generally
stored in variables (that are in RAM). When we need values to be displayed
from main memory on to screen, we need to specify in which format they have
to be displayed. So we can use a format specifier for this purpose.

Ex :
int a,b,c;
a=5;
b=10;
c=a+b;

printf(“The sum of %d and %d is %d”,a,b,c);

In above example the values of a, b and c replaces the format


specifiers specified in the same sequence in which they are mentioned.

When learning languages we use the terms syntaxes and semantics.


Syntax is nothing but how it should look like, OR its formation, or
simply the grammar of the language (i.e. where to place comma, dot,
semicolon etc).

Semantics is nothing but reasoning for the concept.

For example, printf() is a function that produces output onto monitor


is its semantics and printf(“message”) is its syntax.

We can consider a variable as a seat reserved in a bus. If we


realize, there is a seat in the bus that is reserved for us, and it
is identified with a number. Similarly, the variable is reserved
memory identified with a name.

The memory cells in RAM are given with a sequence number for
each cell similar to the seats in a bus. When we declare an int
variable, the OS reserves two bytes of memory and names it. The
first byte cell number is called address of the variable.
Think, some body has traveled in a bus in seat number 27 and
once his journey is over, he left the bus. And when you reserved a
seat in the same bus for your journey, the same seat numbered 27 is
reserved for you. Assume, the person who traveled in that seat is
previous journey left his water bottle in that seat, then when you
board the bus, you will have the seat that is reserved for you with
a water bottle, Where the water bottle doesn’t belongs to you, and
it is GARBAGE as per as you concerned.

Similarly, when we declare a variable, the OS reserves some


memory for the variable and names it. If the same memory was used
by any previous program and stored with some value, the value still
exists in that variable, which is not required for our program. So
this is called a garbage value.

scanf() : this function is used to take input from keyboard. This


function works as a post man, takes input from keyboard and stores into the
address specified.

When a variable is declared during running of program, it is allocated


with memory in RAM. The operator & is used to retrieve the address of the
variable of current program.

address is first byte number of the memory reserved for a variable

Syntax : scanf(“format specifiers”, address of destination variables.

Ex: int a;
scanf(“%d”, &a);

NOTE : when using scanf(), the format specifiers are mentioned


with in double quotes and there should not be spaces, commas
between the format specifiers.

Simple structure of a C program:

main()
{
Declaration of variables

Instructions to computer
to fulfill the requirement of user
}

The C RE automatically links the basic functionality like printf(),


scanf() definitions to the program. So when working with pure C environment,
we need not #include<stdio.h> for using printf() etc. But when using C++
environment to develop a C program, we must include the required libraries
for using the pre-defined functions.

Points to remember :

 All keywords, pre-defined functions in C must be typed in lower cased


letters i.e. small letters, because C is case sensitive language.
 Variables must be declared first then used.
 Variable declaration is not permitted after the first line of code for
process.
 Each statement must be terminated with a semicolon. The semicolon is a
terminator like full stop for a sentence in simple English.
 The comma is used as a separator while declaring variables.
 When the program is typed, it must be saved to hard disk first. We can
use File menu of the editor to save or the short cut key F2 to do so.
 Once the program is saved, it must be compiled with the first compiler
with the short cut key Alt + F9. The first compiler converts the High
Level code into intermediate code and saves it to the hard disk as a
file with extension .obj.
 Then Use the short cut key Ctrl + F9 to activate the second compiler
that converts the intermediate code (.obj file) into low level code and
saves with extension .exe.
 The second compiler has a software mechanism that loads this low level
code into main memory (RAM) for execution.
 When the program executes, the blue colored editor is kept hidden and
the program executes in Operating System’s environment (DOS Mode). Once
the program’s last statement is executed, the editor comes in front.
This is performed vary faster where the user can not view the results
displayed by the last line of code. User can use the short cut key Alt
+ F5 to hide the editor to view results.
 Entire program must be placed as definition of main function.

? It is a simple saying that every C program starts with main(). Why?

Think! a function has a definition and not called, then it will not be
executed.

Again a function is called and has no definition, still as there is no


definition it will not be executed.

Every function must have a definition and can be called any number
of times.
The function definition includes the process to be executed when
the function is called.
The function call is nothing but invocation of the definition.

The function definition looks like


Function_name()
{
Process to be executed;
}
And the function call looks like
Function_name() ;

If we observer “printf(“welcome”); ” is a function call, it has its


definition in stdio.h library and the definition will be executed
when we call it as above.

Similarly, when we write program, it looks as

main()
{
Coding;
}
And the above is a definition
The definition executes when the function is called. Then who calls the
main()?

The programming language’s Runtime Environment calls main() so we must


define main().

We place our code as definition to main() because it is called by


Runtime Environment of the language.

Observe the following:

 The C, C++ and Java Runtime Environments call main(); so the programs
of C, C++, and java must be placed as definitions of main().
 The Runtime Environment of C# (C Sharp) calls Main() (The “M” is
capital here), so the C# programs must be placed as definition of
Main().
 Coming across the RAD (Rapid Application Development) tool Visual
Basic, the VB Runtime Environment calls form_load(); so we give
definition to the form_load() in the language VB.

The compilers include number of internal mechanisms, like the 1 st compiler


of C has following software mechanisms and it is activated with the short cut
key Alt+F9.

1. Syntax checker
2. Symantec checker
3. Linker ( Links library)
4. Compiler -> generates .Obj file (saved to disk)
The Syntax checker checks for syntax errors and the semantic checker analyses
the code and identify requirements of memory etc. The linker links the
library files to the program and then the compiler compiles the code into
intermediate code.

Observe here, the total mechanism is called compiler. But a small


program that actually converts code is called compiler.

The second compiler that is activated with the short cut key Ctrl+F9
has following parts:

1. 2nd compiler (generates .exe file and stores to disk)


2. Loader (loads the saved file into Main Memory for execution)

A simple program to add two numbers:

main()
{
int a,b,c;

clrscr();

printf(“Enter two numbers”);


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

c=a+b;
printf(“The sum is %d”,c);
}
Think when user runs this program on system, being a programmer, its
out duty to provide appropriate messages on screen to the user. So we
call the function printf () at beginning to let user understand what
he is supposed to do.

The call of function clrscr() clears the previous screen.

Questions to practice:

1. Write a program to take input of one number and display it on the


monitor.
2. Write a program to take input of two numbers and perform all arithmetic
operations on them.
3. Take input of Number of inches and display its equivalent number feet.
4. Take input of number of feet and convert into inches and display
5. Take input of temperature in Fahrenheit and convert into centigrade and
display.
6. Take input of temperature in centigrade and convert into Fahrenheit and
display.
7. Take input of your name and display.
8. Take input of a two digit number and display in reverse order
9. Take input of a three digit number and display in reverse order.

Operators :

When we develop a project, we concentrate on three things, user


interface, data storage and process. The process is managed by the operators.

Operators are basically classified into three types based on number of


operands they take.

Unary operators, Binary Operators and Ternary Operator.

Binary Operators :

The operators that take two operands are called binary operators. These
are further classified into five types based on their purpose, viz.

 Arithmetic Operators : these are used to perform basic arithmetic


operations on numbers. They are +, - , *, / and %.

The +,- and * operations results only one value. But when the division
is performed on two integers, we get two results, the quotient and the
remainder.

We can use the operator / to get quotient and the operator % called
modulus to get remainder.

NOTE: The modulus operator can be used only with integer data type.

 Comparison operators: these are also called relational operators. The


operators are <, <=, >, >=, == and !=.

The == is used to check equity of two operands, and the ! is not. When
using comparison operators, they take two numbers as operands and give a
result of either true/false.

The mathematician called George Bool is the first person to evaluate


algebraic equations based on true / false logic. So the true/false are named
after him as Boolean values.
These operators are used to develop conditional expressions.

 Assignment Operator : this is simple =. This operator assigns R.H.S


value to L.H.S variable. So L.H.S. must be a variable.

For example, int a =5; is a correct statement. But int a; 5=a; is wrong.

 Logical Operators: these operators are used to combine two condition.


They are && (Logical and), || (logical or) and ! (logical not).

These operators are used to combine two conditions, where the conditions
are developed using comparison operators. So the operands of these operators
are Boolean values and the result is also a Boolean value.

 Mixed Assignment Operators : The arithmetic operators along with


assignment operator performs dual operations. Observe the following
code:
int a,b;
a=5;
b=a+2;

in above code, the value of a is added with 2 and stored into the
memory location named b.

we can also write a=a+2; in this statement the value of a is added with
2 and stored back into a again.

A=a+2 can be written as a+=2. the difference is we use 4 characters


instead of 5 characters for the same purpose.

Operators : +=, -=, *=, /= and %=

Unary Operators : the operators that take single operand are called unary
operators.

For example, the code a=a+2 can be written as a+=2; similarly, a=a+1
can be written as a+=1 OR also as a++.

Here the operator ++, as accepts only one operand, called unary
operator.

Operators : ++, --, - (negation operator).

Are there the operators **, // and %% also available? If not, why?
Because, the ++ increases value by one and –- decreases value by
one. If ** would be available, it would multiply by one, which
gives same value.

As the **, // and %% give no meaning, these operators are not


developed.

The ++ is called increment and - - is called decrement operators. The


increment OR decrement operations can be performed either pre-process OR
post-process operations.

In Pre-process incrementing, first the value is incremented and then


the process is performed. In post-process incrementing, first process is
performed and then the value is incremented. The pre-process increment’s
syntax is “++variable”, and post-process is “variable++”.

int a,b;
a=5;
b=a++; as this is post increment, first the value of a(5) is copied
into b and then a is incremented to 6. So b will be 5 and a will be 6.
and

b=++a; as this is pre increment, first the value of a(5) is incremented


to 6 and then it is copied into b. So b will be 6 and also a will be 6.

Similarly,

int a=5;

printf(“%d ”,a++); will display 5 and make a value to 6. And


printf(“%d ”,++a); will make a value to 6 and then display.

Remember, when you have a process in the same line of increment


/decrement operation, the pre/post makes a difference. If no
process is given in the line of unary operators, then pre and post
both operations make no difference.

Ternary operator : the operator is ? :

Syntax : (condition) ? statement1 : statement2;

The condition is developed using comparison operators, and they give a


result of either true or false. Based on the result, if the result is true,
the statement 1 will be executed by skipping the statement2, and vice versa.

Ex : for displaying user about biggest of two numbers, the code would look
like,

(a>b)?printf(“a is big”):printf(“b is big”);

Where the a and b are variables, into which the user has already given input.
If the result of a>b is true, the printf(“a is big”) will be executed and if
the result is false, the other executes.

We can also place nested ternary operators. Nested is nothing but placing one
with in another. For example, finding biggest of three numbers code would
look like:

(a>b) ? ( (a>c)?printf(“a is big”):printf(“b is big”) ):


( (b>c)?printf(“b is big”):printf(“c is big”) );

Boolean manipulation in C language:

When a line of code is executed, the data is copied into cache memory
and the process is submitted to ALU with in micro processor. When a
comparison / relational operator is submitted to ALU, if the result is true
then the ALU sends an electrical pulse to the RE and if the result is false,
then no pulse.

No pulse represents ZERO in binary format, and a pulse represents NON-


ZERO. So we can also use this logic for developing program.
(a>b) ? printf(“a”) : printf(“b”) ; is very equal to
(a/b) ? printf(“a”):printf(“b”); as in a division if numerator is big
the quotient is non-zero and when denominator is big the quotient is
always zero. ( this logic works only for positive integers).

Similarly the code to display even/odd messages based on user input


can be either (a%2 ==0)? Printf(“even”) : printf(“Odd”); OR can also
be (a%2 ) ? printf(“Odd”) : printf(“even”);
Questions to practice :

1. Take input of name and age, and display whether the person is eligible
for voting or not.
2. Take input of two numbers and find out biggest of two numbers.
3. Take input of two integers and find out the biggest of two numbers with
out using comparison operators.
4. Take input of three numbers and find out biggest of three.
5. Take input of a number and find out whether it is an even number or
not.
6. Take input of a three digit number and find out whether it is a
palindrome or not.
7. Take input of a three digit number and find out whether it is an
Armstrong number or not.
8. Take input of money you have and display whether you can go to movie or
not.
9. Write a program for finding whether given number is an odd number or
not.
10. Write a program to take input of name, gender and age and display
whether the person is minor or major.

Controlling constructs: Every programming language has its own constructs for
controlled execution of programs. The C too has 2 kinds of program
controlling constructs, viz.

 Branching and
 Iteration

Branching : It is a software mechanism used to divide the program into number


of parts and execute required part based on condition. It is supported with
keywords if and else.

Syntax :

if(condition)
Statement 1;
else
statement 2;

This too works similar to ternary operator. The if accepts a condition,


if the result of the condition is true, the statement under if will be
executed and statement under else will be skipped and vice versa.

Ex :
if( a>b )
printf(“a is big”);
else
printf(“b is big”);

the above code executes very similar to ternary operator code.


In such a case, which one to be preferred, either ternary operator OR
branching in “this case”.

Think “? : ” is an operator, and branching is a software mechanism.


For finding biggest of two numbers, we can prefer a simple operator
than a large software mechanism. In above case, you should prefer
ternary operator.

Branching is nothing serious and this is so simple. But a programmer must


remember some points while working with branching.
Points to remember:

 If should have condition


 Else should not have condition
 Else is optional to if (i.e. we may place else or might not place based
on requirement).
 But every else should have its corresponding if.
 If we need to place more than one statement under any part, then the
statements must be grouped using a pair of braces.
 If we get a requirement of placing a condition with else, OR if we get
a requirement of dividing the program into number of parts (more than
2) then we can place if with else to have a condition, thus leading to
form if-else-if ladder.

Consider the following examples to realize the facts with branching.

1) if(a>b)
printf(“a is big”);
printf(“hi”);

input : 5 and 10
output : hi

input : 10 and 5
output : a is big hi
because the printf(“hi”) is an independent statement, it will be
executed on both the situations when the condition results true and also
false. it is made as independent statement by the ; after the printf(”a is
big”);

2) if(a>b);
printf(“hi”);
printf(“hello”);

now “hi hello” both displayed on both the situations as the condition
is terminated with the ; placed after if.

There is no rule that there should not be a ; after if. it raises


error when else is placed.

3) if(a>b)
printf(“a is big”);
else;
printf(“b is big”);

now when input is 5 and 10 output will be “ b is big”. but when the
input is 10 and 5 then output will be “a is big b is big”, both displayed
because, the printf(“b is big”); has become an independent statement by
placing a ; after else. (This will not raise error. but gives wrong output).

4) if(a>b);
printf(“a is big”);
else
printf(“b is big”);
now the Runtime Environment raises error. the error is not “ ; placed
after if”. but it is “misplaces else”. Because, as per the note above we know
“every else must have its corresponding if. it has a meaning that the
statement before else must be under influence of if. but in above coding, the
statement printf(“a is big”) is not under if as the if is terminated with ;.

solution : remove ; after if

5) if(a>b)
printf(“a is big”);
printf(“a = %d”,a);
else
printf(“ b is big”);

even now we get same error “misplaced else”. Because, the if’s
influence is terminated with printf(“a is big”). printf(“a = %d”,a); has
become an independent statement.

solution : we need to group both the statements under if using braces, like,

if(a>b)
{
printf(“a is big”);
printf(“a = %d”,a);
}
else
printf(“ b is big”);

Nested branching : again nested has a sense of placing an if with in another.

for example, finding biggest of three number, the code looks like

if(a>b)
{
if(a>c)
printf(“a is big”)
else
printf(“c is big”);
}
else
{
if(b>c)
printf(“b is big);
else
printf(“c is big”);
}

We can observe that every else in above code has its corresponding if.

Logical operators: As earlier discussed, these are used to combine two


conditions. (Where the conditions are developed using comparison operators).

&& is used when we have two conditions, and we need statements to be


executed when both the conditions are true.

ex : if( a>b && a>c)


printf(“a is big”);

|| is used when we have two conditions and we need statements to be


executed when any one condition is true.
ex : if(ch==’a’ || ch==’e’ || ch==’i’|| ch==’o’ ||ch==’u’)
printf(“Vowel”);
else
printf(“Consonant”);

in above example the ch is a character variable.

Leap Year concept: as a day has not exactly 24 hours, it is 23 hrs,


59 min. and some seconds, every day some time is left, once this time
is accumulated, it becomes an extra day after four years. So there is
an extra day after four years and that year is called a leap year.
But after four years even, a full of 24 hours is not accumulated.
This giving one extra day after every four years, leads to giving of
an extra day after hundred years. So the people who prepare almanacs
(calendars) made the year after hundred years as not leap year. But
even this is not a full of 24 hours. So for rounding off a leap year
is given after every 400 years. The people who make almanacs could
not think beyond this.

Conclusion: So, leap year comes after every four years but skipped
after every hundred years but comes after every four hundred years
again.

So the logic for leap year is as follows :

if( year%4 ==0 && year%100 !=0 || year%400 ==0)


printf(“leap year”);
else
printf(“Not leap year”);
NOTE : The nested branching can be used as alternate to usage of logical
operators. the above leap year program code can also be written as,

if(y%4==0)
{
if(y%100!=0)
printf(“leap”);
else
{
if(y%400==0)
printf(“leap”);
else
printf(“not leap”);
}

}
else
printf(”not leap year”);

OR
if(y%4!=0)
printf(”not leap year”);
else
{
if(y%100==0)
{
if(y%400==0)
printf(“leap”);
else
printf(“not leap”);
}
else
printf(“leap”);
}

if-else-if ladder:
When we need to divide a program into number of parts and execute only
one amongst them, we prefer using if-else-if ladder.

OR
when we get a requirement of placing a condition with else, we can take
help of if, by forming a chain of if-else-if.

for example, we need to display results of a student based on his marks. the
code can be written as:

if(avg < 35)


printf(“Fail”);
if(avg < 50)
printf(“III class”);
if(avg < 60)
printf(“II Class”);
if(avg < 75)
printf(“I Class”);
if(avg > 75)
printf(“Distinction”);

But in above code, as each if is an independent if, when the value 25 is set
to the variable avg, all the ifs run and displays fail, III class, II class,
I class and also distinction. It is because, there is no control on ifs.

We can go for a better logic for above program as,

if(avg < 35)


printf(“Fail”);
if(avg > 35 && avg < 50)
printf(“III class”);
if(avg > 50 && avg < 60)
printf(“II Class”);
if(avg > 60 && avg < 75)
printf(“I Class”);
if(avg > 75)
printf(“Distinction”);

Now the above code executes and gives correct results. But think about
the statement if(avg > 35 && avg < 50), in which the ALU need to perform
three processes, i. avg>35 ii. avg<50 and iii. && operation on both the
results.

so when the input is 80, 11 processes are performed and when the input
is 25 still 11 processes are performed.

if we prefer the logic as follows:

if(avg < 35)


printf(“Fail”);
else if(avg < 50)
printf(“III class”);
else if(avg < 60)
printf(“II Class”);
else if(avg < 75)
printf(“I Class”);
else
printf(“Distinction”);
Think, if the condition is true, the statement under in executes and if
false, then the statement under else executes. if the result is true, the
statements under else will not be running. In above logic, if the input is
25, the first condition becomes true, and its else will not be running. if
the else not running anything after that will not be running.

so if the input is 25 only one process is done. As else is not at


all a process and it is false part of the condition of if, there will be a
total number of 4 processes performed if the input is 80.

And anyway, think of the logic,

if(avg <35)
printf....
else if(avg <50)
......
The else has a meaning that the if has become false, i.e. the avg > 35. so we
need not place the same avg > 35 again in 2 nd condition. (as it becomes
meaningless).

Buffers :

It is a temporary storage available with all hardware devices in which


data is stored either before getting into main memory OR after coming out of
main memory.

ENTER

Observe the above diagram, when user presses a key on keyboard the data
is transferred from keyboard into keyboard buffer and monitor buffer. What
ever is placed on monitor buffer can only be displayed onto screen. So what
typed is displayed on monitor. The data typed is held in the keyboard buffer
till user presses ENTER. Once user pressed enter, the data from keyboard
buffer is transferred into main memory (RAM). This is how the data flows with
in system.

IO Functions :

The IO Functions are classified in two ways. i. Formatted/ unformatted


IO functions and ii. Standard / console IO functions.

i.
a. Formatted IO Functions : The IO Functions in which user can specify
format specifiers are called formatted IO functions, i.e. the user can
specify the format in which the data need to be displayed.
Ex: printf() , scanf() etc.
b. Unformatted IO functions : The IO functions in which user can not
specify format specifiers are called unformatted IO functions. i.e. these are
format specific. They display data in the format in which they are designed
to display.

Ex :

putchar() : used to display single character on to screen. This can be


used as alternate to the printf(“%c”,...);

Ex : putchar(‘A’); will display ‘A’ onto screen and also


putchar(65); will display ’A’ as 65 is ASCII code of ‘A’.

getchar() : used to take input of single character from keyboard and


store in the specified variable. This is alternate to scanf(“%c”,..

char ch;
ch=getchar();

puts() : displays string(Group of characters) onto screen. This is


alternate to printf(“%s”,...

The printf() displays and leaves cursor on same line and the puts()
display text onto screen and places cursor in the next line.

Ex : puts(“hello”);

gets(): used to take input of a string. This is alternate to


scanf(“%s”,...

ex: gets(name); where name is declared as char name[20];

ii.
The functions that are defined in stdio.h library are called standard
IO functions and the functions defined in conio.h library are called console
IO functions.

The difference is when programmer uses stdio functions, the user need
to type data and press ENTER and when programmer uses conio functions, the
user need not use ENTER pressed.

But when using console IO functions, the data flow bypasses different
buffers.

clrscr(): This is a Console output functions, used to clear the


previous elements on screen (Monitor buffer).

getche() : This function is used to take input of single character. But


when programmer uses this function, the input bypasses keyboard buffer (but
not monitor buffer). So when using this function, the user need not press
Enter after giving input. This is similar to getchar().

getch(): This is similar to getche(). But the data bypasses both


keyboard and monitor buffers and directly stored into RAM. So even here user
need not press ENTER and the data typed is not visible on screen as the input
bypasses monitor buffer also.
When using standard IO functions, the user presses ENTER after giving
input of data. In Computer systems, every key pressed on keyboard can
be treated as character data. Observer the following code.

scanf(“%c%c”,&c1,&c2);
in above code we are taking input of two characters, when user works
with this program, user types a character, press ENTER and again type
another character and press ENTER. This is what user expects of doing
for giving input of two characters.
But when user types, the 1st character and presses ENTER, the
scanf() reads 1st character from keyboard buffer and stores into c1
and reads ENTER and stores into c2. In this case, as ENTER (“\n”) is
stored into c2, the scanf() instruction is completed and rest of the
program continues. In this case, user feels that the program takes
input of only one character. But the scanf() took input of 2nd
character(as ENTER). The actual problem is the scanf() reads what
ever is available in the keyboard buffer. And the buffer is stored
with whatever user typed, viz. 1st character and ENTER. If ENTER
character is still available in buffer, the scanf()/getchar() reads
this ENTER character and stores.

To overcome this problem, we the programmer must clear/clean


the keyboard buffer so as, once the 1st character is read from buffer
into main memory, there is nothing (Including the ENTER typed by
user) exists in the buffer so that the scanf() reads it from buffer.

The function fflush() can be used to clear the buffers.

The keyboard buffer is referred with built in macro “stdin” and


monitor buffer with “stdout” and printer buffer with “stdprn”,
defined in the library “stdio.h”.
We need to specify which buffer to be cleared to the function
fflush(), as fflush(stdin).

Remember, when we make right click on screen and select “refresh”


from the pop up menu, the built in process performed is
fflush(stdout).

Similarly, we must use the statement “fflush(stdin)”, when we


need to take input of a single character and when there is a previous
input exists to the character input.(So that the ENTER of previous
input is not stored into the character variable).

Questions to practice :
1 Take input of name and age, and display whether the person is eligible for
voting or not.
2 Take input of two numbers and find out biggest of two numbers.
3 Take input of two integers and find out the biggest of two numbers with out
using comparison operators.
4 Take input of three numbers and find out biggest of three.
5 Take input of a number and find out whether it is an even number or not.
6 Take input of a three digit number and find out whether it is a palindrome
or not.
7 Take input of a three digit number and find out whether it is an Armstrong
number or not.
8 Take input of money you have and display whether you can go to movie or
not.
9 Take input or year and find out whether it is a leap year or not.
10 Write a program for finding whether given number is an odd number or not.
11 Write a program to take input of name, gender and age and display whether
the person is minor or major.
Take input of student's no, name and marks in six subjects, sum the marks
and display following messages as per the percentage.
Percentage Message to be displayed
> 35 % III class
12 >50 % II class

> 60 % I class

>75 % Distinction
Take input of Electricity meter number, starting reading and ending
reading, and calculate billing as follows.
Total Units Tariff in Rs. per unit
13 < 100 units 1.40 Ps.
< 200 units 2.75 Ps.
< 400 units 3.50 Ps.
>400 units 5.00Ps.
Take input of Sales Executive No, Name and sales performed. Calculate his
commission as per following rates.
Sales Performed in Rs. Rate of Commission
between 100 and 1000 8 %
14 between 1001 and 3000 13 %
between 3001 and 7000 17 %
between 7001 and 10000 20 %
more than 10000 25 %
15 Write a program to swap two numbers.
16 Write a program to swap two numbers with out using the third variable.
17 Take input of a single character and display whether it is an vowel or
consonant.
18 Take input of the sequence number of day and display its equivalent day of
the week.
19 Take input of a number between 1- 12 and display its corresponding month.
Take input of name and age of a student and display whether, which game he
is authorized to play.
Age group Game permitted to play.
Less than 16 No games
20 between 16 and 20 Cricket
between 21 and 22 Boxing
between 23 and 25 Foot ball
between 26 and 30 Chess
above 30 No Games.
21 Take input of Employee's number name and salary. Calculate HRA,TA, DA, Tax,
GPF, Gross salary and net salary as per following tariffs:
Basic Salary TA DA HRA TAX GPF
< 5000 15% 20% 25% 0 % 12%
< 12000 18% 24% 30% 8% 15%
< 18000 21% 27% 35% 16% 20%
> 18000 24% 30% 38% 20% 25%
Iteration: It is nothing but chain reaction. The loops are used to
implementing iteration. When we get a requirement of executing statements
repeatedly for number of times, we can write the code to be executed once and
place with in a loop.

The loop is a software mechanism that repeatedly executes statements


for number of times. Here we observe, there are two states, one the
statements being executed and the other is stopped execution status. when we
need to work with two states, we use a Boolean logic, i.e. we use a condition
to work with loops.

when we need statements to be executed for number of times, we


need to concentrate on how many number of times. This is managed by a
condition. but for each execution, we need to count how many times it is
already executed. So we must keep a count of executions done. And when we
need to count, we must start with a number from where the counting must
start.

So, for working with loops, one should have knowledge of three thing.

 Placing initialization part (starting value of counting)


 Placing a proper condition ( so that the loop terminates at a
given point)
 Placing proper counter ( to keep a count of number of
executions).

The loops are supported with keywords while, for and do-while.

While Loop:

syntax and flow control:

initialization;

while( Condition )
false/true
{

statements to be executed;

Counter;

Rest Of the Program

The while takes a condition, if it is false, the program control comes


out of the loop. if the condition is true, the statements placed with in loop
block are executed (along with counter), and from the end of the loop block,
the program control is transferred back to the condition again. This looping
back process is continued till the condition with the while becomes false.

ex :
int i;
i=0;
while(i < 5)
{
printf(“hi”);
i++;
}

The above code gives output of hi displayed for five times, and every
time ‘i’ is incremented. Once ‘i’ becomes 6, as the condition becomes false,
the loop terminates, and rest of the program executes.

Similarly the code,

int i;
i=0;
while(i < 5)
{
printf(“%d ”,i);
i++;
}

will display numbers from 0 to 5 (i.e. the current value of i).

Thinking about data type ranges.


if we have a code:
int a,b,c;
a=20000;
b=20000;
c=a+b;
printf(“%d “, c); what is expected output. is it 40000? NO.
Because the integer can store a largest number 32767, we get output
displayed as -25536.
This is because, when manipulating values, when the system
reaches the end of the range, it continues counting from starting
value of the range.

if assuming int’s range as -5 to 4, then if we display a


value 6, it displays -4.

observe the numbers in range

-5 -4 -3 -2 -1 0 1 2 3 4

when counting 6 from 0, 0,1,2,3,4 and then again continuing from -5


and then -4. so -4 is displayed. The same in case of all data
types.

observe the following code.

int i=0;

while(i< 32768 )
{
printf(“hi”);
i++;
}

how many times the above code executes? it is infinite times,


because, once the i becomes 32767, it executes and when it is made
++, the value of i becomes -32768, and it is less than 32768 is
true, and it continues for infinite times.
observe the following code:
i=10;
while(i<20);
{
printf(“hi”);
i++;
}
what is expected output. The program flow control is as show below.
i=10;
while(i<20) ;
{
printf(“hi”);
i++;
}
As there is nothing to execute ( as ; is placed after while ) nothing
executes. as the bloc of code is not under while (as while is terminated with
;), i++ is never made and the loop executes for infinite times. But the user
feels as such the system is hung.

For loop :

the syntax of for loop is similar to the syntax of while loop.

initialization;

for ( ;Condition; )
false/true
{

statements to be executed;

Counter;

Rest Of the Program

But the for loop has two semicolons placed before and after the
condition. Every time loop runs, the program control comes to the location
that is “before first semicolon” for the first time and goes to the
condition. Every time, the program control is passed to the location that is
“after the second semicolon” for every time from the end of loop body, the
initialization can be shifted to the first part and the counter to the second
part. Thus the syntax and flow control of the for loop looks as:
for (init ;Condition;counter )
false/true

statements to be executed;

Rest Of the Program

so , i=0;
for( ; i<5; )
{
printf(“%d “, i);
i++;
}
is similar to for(i=0;i<5;i++) printf(“%d “,i);

The above syntax is not the proper syntax, but it is our logic that we
placed.

Do- while loop:


Syntax and flow control:

initialization;

do
{

statements to exceute;

counter;

while(condition ); true
false

rest of the program

the do-while loop executes the loop body once for the first time, and checks
the condition, if the condition is true, the program control is passed from
while to the do and this cyclic process is continued till the condition is
true. Once the condition of the while becomes false, the program control is
passed from the loop to the rest of the program.

Observe the following code:

i=0;
while(i<5)
{
printf(“%d “,i);
i++;
}

can be coded as

for(i=0;i<5;i++)
printf(“%d “,i);

and can also be coded as

i=0;
do
{
printf(“%d “,i);
i++;
}while(i<5);

All the three loops give same results. A program that can be done with
for loop can be done with while loop and also with do-while loop. This is
something similar to the apple juice that can be made with sumith mixi can
also be made with maharaja mixi.

But observe the following code.

i=5;
while(i<0)
{
printf(“%d “,i);
i++;
}

will give no results, as the first time itself the condition is false.

similarly, for(i=5;i<0;i++) printf(“%d “,i); will also give no results. but

i=5;
do
{
printf(”%d “,i);
i++;
}while(i<0);

will display the value 5.

The standard of structured programming language is sequential


execution. In above code, first the loop block gets executed and then the
condition gets checked.

The loops are classified into two types, entry controlled loops and
exit controlled loops.

The loops that have loop control (condition part)at the beginning of
the loop body are called entry controlled loops. ex : while and for loops.
The loops that have loop control(condition) placed at the end of loop
body are called exit controlled loops. ex: do-while loop.

when we get a requirement of executing statements of loop body at least


once with out checking condition, then we can prefer the do-while loop.

We can use operators, branching and loops with in a loop. When a loop
is used with in another it is called nested loops.
Questions to practice:

Other controlling constructs:

The C also has number of keywords, functions for controlled execution


of programs.

continue : This is a keyword used to skip execution of the loop once. This
keyword skips execution of rest of the loop body and passes control back to
the loop.

int i;

i=0;
while(i<10)
{
i++;
if(i==5)
continue;
printf(“%d “,i);
}
The above code will display numbers from 1 to 10 by skipping the
value5. We need to remember that continue skips rest of the loop, so we must
place counter before continue when using with in while loop. In case of for
loop as the counter is placed with in loop signature, it is not required.

But we must remember that the continue skips “rest of the loop body”,
so the continue can not be the last statement.

break : This is a keyword that breaks execution of the loop, OR breaks the
condition at all. So the loop will not be continued with execution and the
program control is passed to rest of the program.

int i;
i=0;
while(i<10)
{
if(i==5)
break;
printf(“%d “,i);
i++;

}
printf(“hi”);

The above code gives a result of numbers displayed from 0 10 4 and then
“hi”. Once the i value becomes 5 the loop breaks and executes rest of the
program.

exit(int):

This is a function defined in the library “process.h”, used to


terminate the program and pass control back to the operating system.
int i;
i=0;
while(i<10)
{
if(i==5)
exit(0);
printf(“%d “,i);
i++;

}
printf(“hi”);

In above code, the values 0 to 4 are displayed and the program terminates,
and the “hi” is not displayed as the program terminated. Once the program
terminated/aborted, the editor comes onto screen.

The kind of program termination needs to be intimated to the operating


system with a numeric value as argument to the function.

Think if a simple example, you have grown well and capable of assisting your
father at your home. Of course the entire house is managed by the father and
he needs to take care of every thing at home. Assume, a bulb needs to be
replaced in your house. When you were a kid, your father used to do it. But
now your father asks you to do so. You take help of a stool/ chair/ladder and
started changing the bulb.

You will only come down in three cases, one on completion of work,
second you understood that the work is not required now, and the last you
were doing the work and you got a shock and fall down.

As every aspect is taken care by your father, once you fall down, the
father leaves all his works, and takes care of you first and then continue
his work. The father can only identify you faced a problem and fell down only
when you shout/scream.

Similarly, in computer systems, the operating system manages all the


resources (as father in a house).

The program can be terminated in three ways, either normal termination


on completion of total execution, or aborting the program. The program
aborting can be either normal abortion or abnormal abortion.

Normal abortion is terminating program with exit(), when the previous


code is not using any system resources. And abnormal abortion is terminating
the program when the previous code is using system resources.

When abnormally the program in aborted, the Operating system has to be


informed, so that the Operating systems leaves all its currently performing
tasks and gives higher priority to take over the control of resources being
used by the program.

This normal abortion of program can be specified by passing ZERO as


argument to the exit() and abnormal abortion with a non-zero value. So we use
exit(0) when the previous code of exit() does not use any system resources,
and exit(1) when the previous code of exit() uses system resources.

goto : This is a keyword used to jump the program execution to the specified
location identified with a label.

int i;

i=0;
start :
printf(“%d “,i);
i++;
if(i<5)
goto start;

printf(“hi”);

The above code executes and gives output of numbers from 0 to 4 and
displays hi at the end. But,

int i;

i=0;

start :
goto end;
printf(“%d “,i)
i++;

end :
goto start;

The above code, jumps between the labels start and end for infinite
times, leading to give a result of system hang.

One of the standards of structured programming languages is sequential


execution of program. As the goto breaks the standards of structured
programming, it is suggested to programmers not to use goto in programs.

sleep(int ) : This is a function defined in “dos.h” library, used to suspend


execution of program by specified number of seconds.

for(i=0;i<5;i++)
{
printf(“%d “,i);
sleep(1);
}

The above code displays values from 0 to 4 displayed with a delay of


one second for each number.

gotoxy(int x-axis, int y-axis) : This is a function defined in “conio.h”


library file, Used to place the cursor in specified location. As the printf()
displays data from the location of cursor being displayed, we can use this
for specific display.
for(i=0;i<10;i++)
{
gotoxy(20,10);
printf(“%d”,i);
sleep(1);
}
Will display a stop watch that runs for 10 seconds.

Kbhit() : This is a function defined in the library “conio.h”, used to read


keyboard hit when infinite loops are developed. This function returns 1/true
when a key is hit on keyboard.
for(i=0;i<24;i++)
for(j=0;j<60;j++)
for(k=0;k<60;k++)
{
gotoxy(30,15);
printf(“%d : %d : %d”,i,j,k);
sleep(1);
if(kbhit())
exit(0);
}
The above code runs for 24 hours and if user needs to terminate, he can
hit any key on keyboard. Once a key is hit, the program terminates.

NOTE : When developing coding for displaying multiple records of


data, the screen is capable of displaying 25 lines, in such a case,
if 100 records are displayed, first 75 records are scrolled up faster
and last 25 records only get displayed. In such a case, we can use
the getch() to hold screen after specific number of records. Observe
the following code for example:
for(i=0;i<100;i++)
{
printf(“%d\n”,i);
if(i%20==0)
{
printf(“press any key to continue…”);
getch();
}
}

Sl. Question
No.
1 Write a program to display numbers from 0 to 20.
2 Write a program to display even numbers from 0 to 20.
3 Write a program to display Odd numbers from 0 to 20.
4 Write a program to display multiplication table.
5 Write a program to display multiples of 3 between 1 to 50
Write a program to display numbers from 1 to 50 by skipping multiples
6 of 5
Write a program to find out whether given number is a palindrome or
7 not.
Write a program to display where given number is an armstroing number
8 or not.
9 Write a program to find out sum of n terms.
10 Write a program to display factorial of n terms.
Write a program to display whether given number is prime or not. (develop
11
at least two logics)

Write a program to display stars like


* * * *
12 * * * *
* * * *
* * * *
Write a program to display stars like
*
13 * *
* * *
* * * *
Write a program to display stars like
* * * *
14 * * *
* *
*
15 Write a program to display stars like
*
* *
* * *
* * * *
Write a program to display stars like
* * * *
* * *
16 * *
*

Write a program to display stars like


*
* *
17 * * *
* * * *

Write a program to display stars like


* * * * * * *
18 * * * * * *
* * * *
* *
19 Write a program to display prime numbers between 1 to 100.
20 Write a program to display prime numbers between given numbers
21 Write a program to display Palindromes between given numbers
22 Write a program to display Armstrong numbers between given numbers.
Write a program to display numbers in following fashion:
7 8 9
23 4 5 6
1 2 3
24 Write a program to display all characters and their ascii values.
25 Write a program to display stop watch.
Write a program to display numbers as follows :
1
26 1 2
1 2 3
1 2 3 4
Write a program to display numbers as follows :
1
27 2 3
4 5 6
7 8 9 10
Write a program to display numbers as follows :
1
28 2 2
3 3 3
4 4 4 4
Write a program to display numbers as follows :

1
29 1 2
1 2 3
1 2 3 4
30 Write a program to display numbers as follows :
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Write a program to display numbers as follows :(pascal triangle)

1
1 1
31 1 2 1
1 3 3 1
1 4 6 4 1

Functions : The functions are used to divide a program into number of


modules (parts).

Remember when we develop a project/program, we must consider three


things, User Interface, Data Storage and Process. The process is developed
using operators and is divided into modules/parts using functions.

? Why to divide the program into parts. Understand the following standards.
The software projects are classified into three categories. Small projects
(that have less than 2 lakhs of lines of code), medium projects (that have
between 2 to 6 lakhs of lines of code) and large projects (that have more
than 6 lakhs of lines of code).

When we write a code for more than 15 or 20 lines of code in main


function, it gives a burden on brains. Imagine, can you type 200 lines of
code in main(). It is very difficult. So we divide the program into parts.

Once we come to the functions, the functions are identified with a pair
of parenthesis. Every function must have a definition and can be called any
number of times.

Function definition is nothing but the process to be executed when the


function is called, and the function call is nothing but invocation of the
definition.

SO when developing a program, we only give definition to the function


and we only call in our program. (Its engineering, we only create and we only
use).

Remember, the functions are not for the sake of the user. They are for
the flexibility for the programmer that he can develop programs easily.

Before getting into functions we must realize a fact with variables and
their declarations. This is referred as storage classes.

Storage classes: The term storage classes refer accessibility of the


variables. The C has many storage classes, viz.

Auto variables, extern variables, register variables and static variables.

i. Auto variables : The variables declared with data type keywords are
called auto variables. i.e. all the variables we used till now are auto
variables. We can also use the keyword auto to declare auto variables. But it
is not mandatory.

These auto variables are classified into two types. Local variables and
Global variables.
a. Local variables : The variables declared with in a function
definition are called local variables and these are accessible only
with in the definition in which they are declared. i.e. these
variables can not be used in other function definitions.
b. Global Variables : the variables declared outside of all function
definitions are called global variables. The global variables are
accessible.
int x;
main()
{
int a;

}
int y;

aa()
{
int b;
}
int z;
bb()
{
int c;
}

In above code, the a, b and c are local variables for the functions
main(), aa() and bb() respectively. Where as the x, y and z are global
variables, where the variable “x” can be used in all the functions, “y” can
be accessed in aa() and bb() but not in main() and the global variable “z”
can be used only in bb() and not accessible in the functions defined prior to
z’s declaration, i.e. in main() and aa().

As the global variables can be accessed any where in the program, there
is a chance that we can modify the values of global variables even by
mistake. (as in a project there can be hundreds of variables, and it is
difficult to a programmer to remember their names and remember whether they
are local or global). So it is suggested to programmers reduce usage OR do
not use global variables in the programs to have data secured.

ii. extern variables : In olden days, the languages like Pascal, basic,
Fortran etc, have no capacity of accessing system resources directly. So when
a program was developed in those languages, the required code for accessing
system resources used to be developed in C language and used those language’s
Runtime Environment.

In such a case, when the code written in C language need to be used in


other runtime environments, th code in C must be declared as “extern” with
the keyword “extern”.

The variables and also functions can be declared as “extern”.

iii. Registered Variables: Keeping picture that explains internal


organization and processing with in the system in mind, let us understand a
fact.

When we use a code,

for(i=0;i<5;i++)
---------
The i is set to zero first and then for the process i<5, the value of i
is transferred from main memory (where the variable is declared) into the CPU
Registers (cache memory with in micro processor) for one time. Once the
condition is true, rest of the loop body executes, and then for i++ the I is
again transferred from RAM to CACHE for second time. Once it is incremented,
again the incremented value is transferred from CACHE to RAM into the
variable for 3rd time.

For one execution of loop, the data need to be transferred for three
times. So for the above loop the data need to be transferred between RAM ad
CACHE for 15 times. Imagine, in olden days when the system had a speed in
kilo hertz, if the data transfer consumes more time, the program execution
becomes very slow.

To reduce this time delay caused by data transfer, we can declare the
variable with in the CACHE, i.e. in CPU Registers with the keyword
“register”.

These register variables were much useful when working with systems
that work with less speed. The variables that need to change their values
frequently for number of times can be declared as register variables. In
general the variables used for loops are declared as register variables.

But these register variables affect system process very much. As in


olden processors like 8085 which have only 8 registers in their cache, if a
register variable is declared and it occupies 2 bytes, the left registers are
6. Now there can be only two numbers stored and added at a time. If register
variable is not declared, there can be three integers added at a time.

So there is an advantage of reducing time consumption of data transfer


and also a disadvantage of processing less number of data elements at a time.

We can declare only integer variables as register variables. When we


declare variables, the memory is allocated by the operating system. (Remember
the functions of operating system, it performs memory management also). So
when we declare register variables, the operating system checks availability
of registers in CACHE and if registers are not free (used for some other
process), the operating system declares the variables in Main Memory and
treats them as normal variables.

iv. Static variables: These are used to preserve values in the variable even
when the variable goes out of scope. This will be discussed later the
discussion of functions.

Functions: when a program is divided into functions, as to maintain the data


security, we prefer using local variables than global variables. In such a
case, as the local variables are not accessible in other function
definitions, we need to pass the data values from one function to another
through the parenthesis. So the functions concept in C is designed with
parenthesis to pass values between functions. The values/variables specified
with in parenthesis are called arguments.

Consider the following example (that is not with proper syntaxes):

main()
{
int a,b;
clrscr();
a=5;
b=6;
add(a,b); * 1
}

add(x,y) *2
{
Printf(“The sum is %d”,x+y);
}
In above example program, the values 5 and 6 are stored in a and b in main
function. For processing them in the function add(), the a and b are passed
as argument at the function call of add() at mark 1.

At the definition of add() at mark 2, the variables x and y are


declared for receiving values passed from function call. The value of a is
copied into x and the value of b is copied into y, and this is the internal
mechanism. The values copied into x and y are processed in the definition of
add().

Understand that addition of two numbers need not be done as above,


using functions, it can be done in the main() definition it self.
Here our target is not adding two numbers. Our target is
identifying function call, function definition and passing values
from one function to another, for which we took example of
addition of two numbers.

Terminology : we use two sets of terms while working with functions. One is
calling function and called function, and the other is function call and
function definition.

The programmer must analyze the terms calling function and called
function first and then he should realize the relationship between function
call and definition.

main()
{
int a,b;
clrscr(); Calling Function
a=5;
b=6;
add(a,b); call
}

add(x,y) definition
{
Printf(“The sum is %d”,x+y); called function
}

If we observer the above diagram, the called function is nothing but a


function definition. If the definition is called by/in a function then it
becomes “called function” otherwise it is simply a function definition.

The term calling function is used for the function definition in which
the other function is being called.

Simply the function that calls other function is called “calling


function” and the function that gets called is a “called function”.

As already discussed, the variables/ values passed through parenthesis


are called arguments. The arguments specified in function call are called
actual arguments and the arguments specified at function definition are
called formal arguments.
As the arguments that are specified at function call actually hold
values, they are called actual arguments. And the arguments at definition are
declared, for the formality of receiving the values passed from function
call, so they are called formal arguments.

The functions are capable of returning values also.

It is because, when the values are passed from function call to the
definition, in definition we develop coding to perform process on the data
values received. From calling function to the called function values can be
communicated/passed through the parenthesis. But we might get a requirement
of sending called back from called function to the calling function to use
them further. The values can be returned with the keyword return from called
function to the calling function to the location of function call.

Points to remember while returning values :


 We can return only one value at a time.
 The return is the last statement to be executed.
 If a statement is placed after return, the RE raises warning
specifying “unreachable code”.
 A function can have only one return executed for one call.

If we need not return any value from the definition, then we must
specify the return type of the function with “void”. Void is a data type that
stores null.

 We define main in our program as the runtime environment calls


main.
 Return is used to send values back to the function call (to use
them further)
 If we return a value from main(), it is sent to the RE.
 We can not open RE and store the value and use further. So we
declare main as void main().

Syntaxes:

Function call : function_name(actual argments);

The actual arguments can be either variable names or values. O data


type specification is mentioned here.
Ex: add(a,b);

Function definition :
Return_type function_name (Formal arguments)
{
Process to be done when the function called;
}
The return type is nothing but the data type of the value being
returned from definition.
Formal arguments are nothing but variables with declarations. As these
are local to the user defined function and being used for first time they
must have declaration.
The formal arguments can be declared in two ways, either in the
parenthesis itself in function signature or in the first line after the
function signature before opening brace. The later is supported only by C
language, not in any other languages.

Ex : int add(int a, int b)


{
return a+b;
}
OR
int add(a,b)
int a,b;
{
return a+b;
}
Forward declaration: when a function is defined later its call, it must be
declared first.

Return_type function_name (parameters);

Parameters is nothing but the data type specifications of the


arguments.
A program with proper syntaxes looks as follows:

int add(int, int); (1)

void main()
{
int a,b;
clrscr();
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);

printf(“The sum is %d”,add(a,b)); (2)


getch();
}

int add(int a, int b) (3)


{
return a+b;
}

In above program the statement at mark 1 is forward declaration. At


mark 2, the function add is called. At marks 3 the function add is defined.
The result returned is sent back to the calling function to the location of
appropriate function call.

The getch() is used to hold screen at the end of program. As it is an


input function, the program waits till user presses a key on keyboard,
meanwhile user can view results. (It is just a logic. But it is not alternate
to Alt + F5).

Points to remember:
 The number of actual arguments must be matching with the number
of formal arguments.
 The data type of actual arguments and their sequence must be
matching with data type and sequence of format arguments.
 If the function is defined later the function call it must have
forward declaration and if the function is defined prior to its
call, the forward declaration is not required.
 The returned value from definition is passed/ replaces the
appropriate function call.
 There is no hard and fast rule to use functions in specific way.
Programmer need to realize/understand the problem and divide into
functions with simple common sense.
 Any code placed in the program can be only with in a definition.
Any process can not be placed coded global.
 A function can be called with in definition of a function or with
in call of a function if the return type of definition matches
with the argument of function in which it is called.
A program in different ways to understand functions:

int palin(int);
void palin(int); void main()
void main() {
{ int n;
int n; clrscr();
printf("Enter a number");
clrscr(); scanf("%d",&n);
printf("Enter a number");
scanf("%d",&n); if(n== palin(n))
printf(“Palindrome”);
palin(n); else
} printf(“not”);
}
void palin(int n)
int palin(int n)
{ {
int x,t,r; int t,r;
x=n; r=0;
r=0; while(n>0)
{
while(n>0) t=n%10;
{ r=r*10+t;
t=n%10; n/=10;
}
r=r*10+t; Return r;
n/=10; }

int palin(int);
void main()
{
int n;
clrscr();
printf("Enter a number");
scanf("%d",&n);

if(palin(n)) printf(“Palindrome”);
else printf(“not”);
}
int palin(int n)
{
int t,r,x=n;
r=0;
while(n>0)
{
t=n%10;
r=r*10+t;
n/=10;
}
if(x==r) return 1;
else return 0;
}
A function can also be called with in call of another function.

{
---
Printf(“the sum is %d”, add(a, add(b,c) ) );
---

}
int add(int a, int b)
{
return a+b;
}

If a function is called with in itself (with in its definition itself),


then it is called recursion. Proper controls /conditions must be placed to
restrict development of infinite recursion.

Ex :
Void disp(int,int);

Void main()
{
int n;
printf(“Enter a number for which multiplication table required”);
scanf(“%d”,&n);

disp(n,1);
}

Void disp(int n,int i)


{
printf(“%d * %d = %d\n”,n,I,n*i);
i++;
if(i<11)
disp(n,i);
}

Static Variables :

Observer the following code:

void main()
{
disp();
disp();
disp();
}

void disp()
{
int a=0;
printf(“%d “,a);
a++;
}
when the above program is executed, the output looks as three zeros. but not
“0 1 2”. because the variable “a” is allocated with memory for each call of
the function in main().

When the first time function definition executes, the variable “a” is
said to be in the scope of RE. But once the execution is completed fully, the
variable “a” goes out of scope. i.e. it is no more existing in memory. For
the second call, it again gets allocated with fresh memory. In this kind of
working, the values held by the variable in previous execution are not
available for current execution.

If we need the variable’s value updated in previous execution need to


be utilized in current execution, then the variable must be declared as
“static”.

The static variables are allocated with memory once and used by the
function till program execution is completed.

void disp()
{
static int a=0;
printf(“%d “,a);
a++;
}
now, the above code gives output “0 1 2”.

Arrays : The term arrays has a simple meaning of arrangement. The array can
be defined as “user defined data type used to store number of values of
similar data type with same name” OR “grouping of variables of same data type
that are of similar type in purpose”.

Think on a simple problem, we have to find out biggest of two numbers,


then we write a logic:

if(a>b)
printf(“a is big”);
else
printf(“b is big”);

for finding biggest of three numbers, we develop a logic :

if(a>b)
{
if(a>c)
printf(“a is big”);
else
printf(“c is big”);
}
else
{
if(b>c)
printf(“b is big”);
else
printf(“c is big”);
}

Think of the situation where we need to find out biggest of four, five
or six numbers. Imagine the situation where your class has sixty students.
All students’ total marks are calculated and stored and you have to find out
biggest of sixty to give ranking. How difficulty it is to develop logic to
find out biggest of sixty when using sixty independent variables.

To overcome the above problem, we prefer using arrays.


Think of your kitchen, where different vessels are used to store rice
and different food grains. But for storing spices, your mom prefers a box
with small cups arranged in a specific fashion, to store each type of spice.

That is an array of cups. Think of your cupboard, it is partitioned in


to number of equal divisions. Think of desks in your college. All these are
arrays.

Array of cups, array of desks, array of partitions, and similarly, we


prefer using array of variables in our program to store and manipulate data
easily.

Remember you can also write a program with out using arrays. But for
faster and easy development of process, we prefer storing data into arrays.

The arrays are manipulated with special symbol [].


syntax of declaration :
data_type array_name [ number of elements / bounds / range];

ex : int arr[5]; the 5 can be called either bound or range. now the
“arr” is capable of storing 5 integers.

When an array is declared, as all the elements are stored with same
name, for treating each element independent, all the elements are given by a
numeric value for identification. This is something like, a text book has
number of pages, i.e. the text book is nothing but array of papers, in which
each paper is identified with page number. The similar way, the array
elements are also given with page numbers by the Runtime Environment, for
identification called index numbers.

The index number of the first element starts with ZERO by default
because ZERO is the first positive number.

The above declared array will have memory allocated as follows in RAM:
Index
0 1 2 3 4 Numbers

Array
Elements
20 22 24 26 28 Address of
Each Element
arr Array Name

The [] are used to specify number of elements to be stored in array at


the time of declaration and the same [] are used to specify index number of
elements while manipulating with array.

The array can also be initialized at the time of declaration, by


specifying values with in { }. Here we need not specify the size of array,
the Runtime Environment automatically allocates based on number of
initializers ( number of values given for initialization).

Ex : int arr[]={1,2,3,4,5,6};

For taking input into the elements of array, the index number must be
referred with in [].

ex :
scanf(“%d”,&arr[0]);
scanf(“%d”,&arr[1]);
scanf(“%d”,&arr[2]);
scanf(“%d”,&arr[3]);
scanf(“%d”,&arr[4]);

If we observe the above code, we did same code for number of times
repeatedly. So here we can use loops.

int a,b;
a=0;

for(b=10;b<15;b++)
scanf(“%d”,& arr[ a++ ] );

the variable b is used to run the loop for five times and the variable
a is used to refer the index number (where index number is increased by one
for each input).

instead of using two variables, we can use one variable to control loop
and also to refer the index number of array element.

for(i=0;i<5;i++)
scanf(“%d”, &arr[i]);

Remember, when using the same variable for both the purposes, the loop should
start with ZERO, but not with ONE.

The array when declared, all the elements of array will have contiguous
memory allocation. As all the elements are contiguous, and identified with
same name, it is easy for the programmer to develop logic.

Strings: string is nothing but group of characters. The strings are managed
with character arrays. We use a special format specifier “%s” to work with
strings.

When data is stored in character array, the c Runtime environment


stores a NULL character represent as ‘\0’ at the end of the array, so that
the “%s” displays data from character array till null character. i.e. the
null character is used to differentiate between the strings and other values.

While taking input using “%s”, the scanf cannot read blank spaces
between words. So if two words are given input with a blank space between,
only first word is stored.

To read spaces or to place restrict while taking input of string data


or to specify the kind of data to be taken input we can use [] as a format
specifier.

ex: scanf(“%[a-j][l-z]”,name); will read all characters from a-j and l-z
but not k. so it reads till ‘k’.

for example if the input is DINAKAR it stores DINA

scanf(“%[a-z, ]”,name); or scanf(“%[^\n]”,name); can be used to read


blank spaces.

The ^ called caret has a simple English meaning “missing”, used to represent
that “something is missing in the line of text” written. Similarly in C the
‘^’ represents to miss specific characters. In the above code the scanf()
takes input by missing “\n” i.e. it reads data till next line character i.e.
ENTER pressed.

char name[20];
name = “arc”;
The above code raises error “Lvalue required”, because assignment
operator is binary operator. It cannot work with more than one operand on
either side.
The C has a library string.h that provides no of functions for easy
handling of strings.

strcpy() : this is used to copy given string into specified char [].

Syntax: strcpy(char dest[],char src[])

Ex : strcpy(name,”arc”);

strlen() : this function returns number of characters available in the


string.

printf(“%d”, strlen(name));

strcat() : used to concatenate (append at end) a string to the existing


string.

Strcat(name,” intellectuals”); concatenates the string “ intellectuals”


to the existing string “arc’ in the array name.

strcmp() : this function compares two strings lexicographically.

For example:

a a
0

1 r r

2 c c

\0 \0
3

If there are two char arrays allocated with memory as above and stored
with values, then each element of the 1st array is compared with same indexed
element of the 2nd array, and returns the ASCII difference between the values.

If there is a difference between ASCII values of 0 indexed elements,


the difference is returned and no next elements will be compared. If both the
characters are same, then the next elements will compared till there is a
difference found. If no difference is found till end, then ZERO is returned
specifying that both the strings are same. This is called LEXICOGHAPHIC
Comparison.

This function is used to sort strings in specific order.

Ex :
printf(“%d”, strcmp(“arc”, “book”)); returns -1 as a’s ASCII code is 97
and b’s is 98. thus 97-98 is -1. if it could be printf(“%d”, strcmp(“arc”,
“book”));, it would have returned 1.

Multi Dimensional Arrays:

Think of a simple situation. You need to take input of 6 subject marks


for 5 students. You can declare m1,m2,m3,........,m30 so on. And also you can
declare int marks[30].

It is easy to declare marks[30] as, 5 students and each 6 subject


marks. But when we need to display 4 th student’s 3rd subject marks, it will be
difficult to display/manipulate directly, as we need to calculate index
number in which the specified marks are stored.

To overcome this problem of calculating index numbers and manipulating,


we can declare multi dimensional arrays. The multi dimensional array is
nothing but array of arrays.

In an array we can have any number of dimensions. Each dimension is


represented with a [] symbol.

Syntax : data_type arr_name[d1][d2][d3]...[dn];


Ex : int marks[5][6];
When using the multi dimensional arrays, as there are multiple
dimensions, each dimension must be specified with in each [] for each
dimension.

As these support multiple references for each value, it will be easy to


develop logics in the program.

Though we declare multi dimensional array, the memory allocated is


contiguous. Or example, the array int arr[2][3] will have memory allocated as
follows :

0 1 2 0 1 2

0 1
arr

Similarly, the 3 dimensional array int arr[2][3][2] is allocated with memory


as follows:

0 1 2 0 1 2

0 1 0 1 0 1 0 1 0 1 0 1
0 1
arr
In practical life time programming, a programmer will not get a
situation of working with more than 2 dimensions.

When we work with a 2 dimensional array, though the memory is allocated


is allocated continuously, we logically, feel the allocation of memory as
follows for the array int arr[2][3].
0 1 2

arr

We logically understand the memory as rows and columns but actually the
memory is allocated contiguously.

int a[2][3] can be understood as it is int array of arrays. OR it can


also be understood as a has two parts and each part further has three parts,
which are called subscript.

The 2 dimensional arrays are not for using as matrix of simple maths.
The matrices programs are suggested to practice as to get grip on two
dimensional arrays. Otherwise, observe the following declarations of
variables to realize the requirement of multi dimensional arrays.

int no[60],total[60], marks[6][6];


float avg[60];
char name[60][20];

above variables can be used store data of sixty students.

Sl Question
1 Take input of five elements into an array and display them.
2 Take input of five elements into an integer array and copy them into
another array and display them.
3 Take input of five elements into an integer array and copy them int to
another array in reverse order and display them.
4 Take input into two integer arrays each of five elements and copy into
third array and display them.
5 Take input your name and display it in reverse order with out using
STRING.H Library
6 Write a program to take input of five integers in to array and display
their sum.
7 Write a program to take input of five integers in to array and display
their Product.
8 Take input of five elements into an integer array and find out biggest
element
9 Take input of five elements into an integer array and find out smallest
element
10 Take input of five elements in to an array and display them in ascending
order using Selection Sort

11 Take input of five elements into an integer array and display them in
descending order using Selection Sort.
12 Take input of five elements into an array and sort them into ascending
order using Bubble Sort.
13 Take input into an array of 10 elements and find out number of duplicated
elements in it.
14 Take input into an array of 10 elements and find out number of even numbers
and odd numbers in it.
15 Take input into a string i.e. char array and check whether the string is
palindrome or not with out using string.h.
16 Take input of five names and sort them in alphabetical order and display.
Take input of your name and display as follows :
Ex. Name="arc"
display : a
17 a r
a r c

18 Take input of an array of students and six subjects marks display the marks
and sum.
Develop a program using multi dimensional arrays to run a college, by
19 taking input of 10 student’s details like no, name, marks in six subjects,
calculate totals, average and display by sorting them, based on user’s
choice. (Display a menu to user first from which user selects what to do)
20 User two dimensional arrays to implement matrices addition.
21 User two dimensional arrays to implement matrices multiplication

Pointers:

This is one of the simple topics of C. observe memory mapping of simple


variables and how we work with them.

When we declare a variable int a; the memory is allocated with in RAM as


follows:

40

20 21
a

Main Memory (RAM)

In above memory a is a variable. The address of a is 20 and the 40 is


the garbage value stored in a.

When we take input using scanf(), we write code as

Scanf(“%d”,&a); What happens if we don’t use & in scanf().


Recollect the functionality of scanf(). It takes input from keyboard and
stores into the address specified.
If the code is &a, which represents “20”, the scanf() reads data from
keyboard and stores into the location whose address is 20. if the code what
we wrote was scanf(“%d”,a); then what would happen.

When variable name is referred, the value stored in the variable is


represented. So “40” is given to scanf() to store data and scanf() reads from
keyboard and stores into the memory cell whose address is 40. (but not in
20).

* When the question is asked “what happens if & not used”, don’t answer the
system wont take input. But it takes input and stores in different location.
But when we display, as the value input is stored in some other location, the
garbage value itself is displayed.

It is something like, when your mom gives you a necklace and asks to keep it
in a locker, you actually kept in some other location (as the scanf() stored
the input into memory cell 40). If you search in the locker, you wont find it
as you didn’t keep it there, similarly, when you display a’s value it wont be
displayed as the data is stored in some other location addressed 40.

If you understood the above situation, it is easy to realize the


pointers.

20 21
a

Main Memory (RAM)

Remember the above diagram of memory allocated for variable “a”, and
identify the output for following lines of code.

printf(“%d ”, a); it gives output 5


printf(“%d ”, &a); it gives output 20

observe the operator & takes a variable name and results its address,
similarly, the C has a special operator *. The * operator takes address of a
variable and gives value at given address. So

printf(“%d ”, *&a); again gives output 5

Make it on system and understand. When we give an address to the *


operator, it gives value stored in that address.

So, if we store this &a (address of 20) in another variable b, the


memory looks like,

20
a

20

b
When we display now,

printf(“%d ”,a); gives 5


printf(“%d ”,&a); gives 20
printf(“%d ”,b); gives 20
printf(“%d ”,*&a); gives 5
printf(“%d ”,*b); gives 5

Now for assigning &a to b, the b must be declared as int *b. this is
called a pointer. The pointer is used to manipulate data by referring the
addresses of memory directly.

When we develop a project, we concentrate on three things, User


interface that is managed with IO functions, Process that is managed with
operators and data storage that is managed with variables or arrays.

The data management is done either naming the memory cells or by


manipulating with the memory addresses.

For working with memory by naming, we use variables and arrays. But for
working with memory with its addresses, we must use pointers.

This can also be understood as memory can be manipulated in two ways,


either by naming them or with their addresses.

Observer the follow code and its memory management:

int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;

The memory looks as follows :

5 10

20 30
a b

20 30

p q

Now printf(“%d”,a) is very much equal to printf(“%d”,*p), and


printf(“%d”,&a) is equal to printf(“%d”,p).

Similarly, instead of scanf(“%d”, &a ) can also be written as


scanf(“%d”,p);

That is to the scanf() we must specify the address of location where


the data must be stored, it can be either &a or p, as both are same.
If we write a code as p=q, then the address held by the pointer q is
stored into the pointer p and both p and q will point to the same memory
location 30, i.e. the variable “b”.

If we write a code *p=*q, then the value at pointer q is copied as


value at the location pointed by p.

So,

int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;

and p=q;

printf(“%d %d”, *p,*q) will display 10 and 10. and


printf(“%d %d”,a,b) will display 5 and 10.

Here the address held by q is stored into the pointer p. but not values
of a and b are manipulated. (only addresses are manipulated). Whereas the
code

*p=*q;

Will not modify the addresses held by the pointers, p points to a and q
points to b, but the value of b is copied into a. so,

printf(“%d %d”, *p,*q) will display 10 and 10. and also


printf(“%d %d”,a,b) will display 10 and 10.

Pointers can also be used to point arrays. We can have a declaration like,

int arr[5], *p;

p= &arr[0]; i.e. the address of first element is copied into the


pointer.

If the array is initialized as,

int arr[]={10,20,30,40,50}, *p;


p=&arr[0];

now the printf(“%d ”, *p); will display a value 10.

p++;
printf(“%d ”, *p); will display now the value 20.

The pointers arithmetic operation is different from normal arithmetic


operation. As the pointers work with addresses, the ++ is also performed on
address of the variable. If the variable/pointer is integer type, then the ++
increases the address value by 2 and if float, then by 4 (based on memory
allocated for that data type variable).

So, int memory can be allocated only to an int pointer and float
memory to a float pointer. Assigning float memory to int pointer
leads wrong execution because the variables are at an address
difference of 4 bytes and the int pointer moves only by 2 bytes at
a time., so the RE raises a warning “suspicious pointer
conversion”.
So the ++ increased address stored in p by 2.

So, the printf(“%d ”,*p+2) will display what ? Is your expectation 30! Then
it is no. Here comes into picture a topic called operator priority.

Even in simple math, we use “BODMAS RULE” for simple arithmetic


operation (Brackets, Of, Division, Multiplication, Addition and then
Subtraction), which specifies which operation must be given with higher
priority (Importance).

In C language, the pointer operator has higher priority than arithmetic


operators.

So in the statement,
printf(“%d ”,*p+2) first *p is evaluated, (value 10) and then added
with 2 will display 12.

We can use parenthesis to change priority of operators in C, then to


display a value 30 we can write the statement printf(“%d ”,*(p+2) );

Now p+2 is performed first, as p is a pointer and pointer operation is


on number of bytes, the pointer moves by 4 bytes first and then the value at
that location i.e. 30 is displayed.

Now If you sincerely observe, to display a value 30 from above array,


we can use the array syntax printf(“%d”,arr[2]); and similarly, with pointer
syntax printf(“%d”,*(p+2));

So 50 can be displayed either as

printf(“%d ”, arr [4] ) OR as


printf(“%d ”, * ( p+4 ) )

You could find similarity between arrays and pointers here. i.e. when
using arrays, we use [] and when using pointer we use *(). We can come to a
conclusion here as pointers and arrays both are same, but differ in their
syntaxes.

The code, for(i=0;i<5;i++) scanf(“%d”, & a[i]) can also be written


as for(i=0;i<5;i++) scanf(“%d”, p+i); observe, when using array syntax, we
used & operator with variable and when using pointer syntax, as pointer
itself is address, we don’t specify &.

Similarly,

for(i=0;i<5;i++)
printf(“%d”, a[i]) is similar to

for(i=0;i<5;i++)
printf(“%d”, *(p+i) );

So again, the pointer and arrays both are same but differ in their syntaxes.
Remember, when we declare an array in C, the C Runtime Environment
automatically creates a pointer with the same of array and stores base
address of the array into that built in pointer.

Realize again, when using a pointer we don’t specify & while taking
input, and when taking input of a name, where name is a char[], we
write code as “scanf(“%s”,name)”, and we are informed, when using %s
with in scanf(), & is optional. Identify it is not optional. As we
declared char name[20], the C RE declares a pointer with same name
“name” and stores the address of first element of the array name. so
we could use scanf() with out using & for taking input of char [].

It is again a proof that when we declare an array, the RE creates a


pointer.
Keeping above points in mind observe the following code.

When int a[5]; declared the C RE declares a pointer with same name “a”
and stored with address of first element of array.

So instead of using the code for taking input as

scanf(“%d”, &a[i] ) we can also write code as scanf(“%d”, a+i) where,


here we are using the pointer syntax.

Similarly, for printf(“%d”,a[i]) we can also use printf(“%d”,*(a+i));

We get correct output for any of the statements. Once the above code
runs, you can come to a conclusion that arrays and pointers both are same for
manipulation but differ in their syntaxes.

Now observe the concept with cool brains:

int + int results int, and


float + int results float as float is largest data type.

Similarly, pointer + int performs only pointer arithmetic operation


(i.e. on number of bytes based on data type of pointer).

Once int + float gives float and float+int also gives float, pointer +
int results pointer arithmetic operation and similarly, the int+pointer also
results pointer arithmetic operation.

So printf(“%d ”, *(a+i) ) results similar to printf(“%d ”, *(i+a) ).

Write code once on system and realize.

Now think, a[i] can be written as *(a+i).


*(a+i) can also be written as *(i+a), then
Can *(i+a) be written as i[a]?

Think, write code once and observe

a[i]= *(a+i) = *(i+a) = i[a] all are same. So when declared with array
for data storage, we can use any of the above syntaxes. And also with
pointers, when working with pointers, we can also use any of the above
syntaxes.

So,
printf(“%d”,a[i]) is equal to
printf(“%d”,*(a+i) ) is equal to
printf(“%d”,*(i+a) ) is equal to
printf(“%d”, i[a] )

The actual concept of pointers is not “declare variable, assign its address
to the pointer and work”. The actual concept of pointers is dynamic memory
management.

Memory Management: The memory allocation is of two types, viz. Static memory
allocation and Dynamic memory allocation.
Static memory: The memory once assigned, that can not be changed with its
size is called static memory. The static memory is managed using variables
and arrays.
If we declare an array as int a[5], the a will have 10 bytes memory
from the time of declaration till end of execution of program. The memory
size can not be modified either to 8 or to 12.

The static memory is allocated at the beginning of program and it is


released at the time of termination of program.

Dynamic memory: The memory that can be assigned whenever required (during
running of program) is called dynamic memory.

The dynamic memory is managed with the help of pointers. When a pointer
is declared, it occupies 2 bytes memory irrespective of its data type. i.e.
int pointer occupies 2 bytes and also char, float pointers occupy 2 bytes.
But the memories they manage are based on their data type.

During program development, being a programmer, we can declare a


pointer at beginning of program. This pointer occupies only 2 bytes of
memory. We can write program such that, when the code requires memory to
store data, we can assign memory for the pointer in just before line.

The memory is allocated with the function malloc().

Ex:
int *p,n;

printf(“Enter number of elements”);


scanf(“%d”,&n);

p=malloc(n*2);

Now the p holds only 2 bytes memory at first line. It is allocated with
memory for number of elements when the line in which malloc() is executed.
Observe following (wrong practiced) code

#define max 100

int arr[max],n;

printf(.....
scanf(“%d”,&n);

for(i=0;i<n;i++)
-------
is a wrong practice. Once we are declaring a macro max as 100
and allocated memory for the array for 100 elements, it becomes static
memory. If we specify n as 5 we are wasting 95 integers memory i.e.
190 bytes memory and if we need to work with 101 integers, we can not
work with.

So, it is not at all a good practice of working so. In this case, we


prefer pointers as mentioned in above example.

sizeof() : is called sizeof operator used to retrieve size of a


variable or specified data type or number of bytes occupied by the
variable/data type.

Ex :int a; printf(“%d ”, sizeof(a)) will display 2 as a occupied 2


bytes of memory OR also we can write printf(“%d”, sizeof(float))
will display 4.
Dynamic memory once assigned to a pointer must be released explicitly.

Observe the situation, you are moving in a bus, a seat is reserved for
you. On the way, you got down from the bus to have a cup of tea. Before
getting down, you always put a bag or a kerchief on the seat as it is an
indication to others that it is reserved for somebody and nobody will sit in
that seat.

Similarly, once some memory is allocated with malloc() for a pointer,


the operating system reserves it for that pointer. Even if the program is
terminated, it is kept reserved, and will not be used by OS for any other
purpose. So it is a good practice of releasing memory that is allocated with
malloc().

Now a days, as the main memory size is in Mega bytes and giga bytes, it
doesn’t make much affect on program execution. But in olden days, it was a
mandatory practice.

Functions used for dynamic memory management:

malloc() : used to allocate memory dynamically for pointer. This function is


argumented with number of bytes to be allocated.

Think on a simple concept, if we write a code malloc(12), the malloc


allocates 12 bytes of memory. But how to treat it, As 12 characters or as 6
integers or as 3 floats?

Here we must typecast the memory how it is to be treated.

Ex:
int *p= (int*) malloc(12) will allocate 12 bytes memory and assigns its
base address to the pointer “p” and treats it as int memory i.e. each of 2
byte elements. Similarly,

float *f=(float*)malloc(12) makes 12 bytes as 3 float variables.

realloc() : this is similar to malloc(). But differs in purpose. When


programmer needs some memory to be manipulated first, and in between he need
to increase / decrease the size of the array being processed by the pointer,
then he can prefer realloc(). It is much same as malloc(). The malloc() can
also be used for subsequent allocations of memories. But it decreases
readability for programmer. The programmer can use realloc() instead of
malloc() for subsequent allocates, to identify that the memory allocated is
not first allocation. Remember it is for the convenience of the programmer,
otherwise it has no affect on program.

calloc() : this is similar to malloc() but, it allocates memory and


initializes the values of all elements to ZEROs.

free() : this is used to release the memory allocated for a pointer.

Ex : free(p);

Programs to practice : You can do all the programs you did with arrays.

Structures:

If you would have developed the project specified with 2 dimensional


arrays, then you can understand the problem with them.

Think you have to exchange your bicycle with your friend’s, then if you
exchange handles first, then seat, then tires, then bells and so on, you need
to exchange for number of times, but if you exchange total cycle at once, you
need to exchange only once.

Think on the variable declaration for managing student’s data,

int no[60],marks[60][6],total[60];
char name[60][20];

When using above variables for displaying sorted data, we need to


interchange data for number of times, and we need to develop at least 30
lines of code for sorting on each type like, 30 lines of code for sorting on
1st subject marks, another 30 LOC for 2nd subject marks and so on.

Think, in practical life will you work with 60 numbers once, 60 names
again and 60 english marks once and so on? No, In practical life, we work
with one student’s details at once.

So as to work with one student’s details, the above variables


declaration will not permit, because, it is something like, 60 handles, 60
seats, 60 tires, 60 peddles etc. but it is not like 60 cycles.

In above declaration, the 60 numbers are grouped together, 60 names are


grouped together and so on. but what we need to have for easy logic
development is variables required for 1 student’s details should be grouped
together. For which we take help of structures.

The structures are defined as “user defined data type, used to group
number of elements of different data types with different names”.

So we have variables, no,name and marks[6], group them using braces


first.

{
int no,marks[6];
char name[20];
}

Now the above variables declared for storing data of one student are
grouped using braces. Now this group can be given/ identified with a name
with the help of the keyword “struct”.

Struct stud
{
int no,marks[6];
char name[20];
} ;
The structure declaration must be terminated with a ;.
As the structure declared above is a data type, we need to crate a
variable for the above data type to work with. It is similar to normal
variable declaration.

Data type variable name;

Think, int is a data type designed by Dennis Ritchie and the stud is a
data type designed by you.

Can you initialize values with in structure like,


Struct emp
{
int sal=5000;
};

NO. because, the structure is a data type specification we can not store data
with out creating variable for data type. The above initialization is
something similar to int=5; can 5 be stored into int? The ultimate answer is
NO, the int need to be declared with a variable and stored with data, the
same with structures also.

When we declare a variable for the structure, it is called structure


variable and the variables we declared with in the definition of structure
are called member variables.

The member variables of a structure are accessed through the structure


variable, using an operator (.) called period operator.

The term period we used in our childhood to refer a session in time


table, which has a meaning “a part of”. The same is the meaning here.

The declaration of stud structure when declared with a variable “s”


then it looks in memory as follows:

no name 0 1 2 3 4 5

marks

The members are referred with . as s.no, s.name, s.marks[i].

The structures can be declared either global or with in a function


definition. If they are declared global, they can be created with variables
any where. But when they are declared with in a function definition, as the
declaration becomes local to that function, we can not create variables for
such structure in other functions.

We can also create arrays of structure variables, like


struct stud s[10];

in such a case, the input code looks as :


for(i=0;i<10;i++)
{
printf(“Enter number and name”);
scanf(“%d%s”,&s[i].no,&s[i].name);
printf(“Enter six subject marks”);
Wefor(j=0;j<6;j++)
can also declare pointers to structures. But when using pointers to
structures, thescanf(“%d”,&s[i].marks[j]);
structure must be allocated with memory dynamically similar
to} normal data type pointer as,

struct stud *s;

s=(struct stud*) malloc( sizeof(struct stud) );

Here we have to go for sizeof operator that is discussed earlier, instead of


calculating number of bytes of memory to be assigned.

When we work with float member variable of a structure and declare an


array of structure variables, like:

struct emp
{
int no;
char name[20];
float sal;
};

struct emp e[5];

when we write scanf() for taking input like,

scanf(“%f”,&e[i].sal); the scanf terminates the program abnormally, as


the scanf() is defined to work with int by default when specific float
variable is not referred. Now the float can not be referred directly as it is
a member of structure variable.

In scanf() we are using the format specifier %f and producing address


of a structure variable, there the scanf() terminates abnormally.

We need to write a simple code, which is an indication to RE, that when


it interacts with %f format specifier, it searches for float memory and
stores data into that.

Place following code prior to scanf() that take input of float member :

float *fp,f;
fp=&f; this is indication to RE that whenever it interacts with float
value, it assigns the value to a float pointer/variable.

Unions : the unions are similar to structures, these are defined as “user
defined data types, used to group number of elements of different data types
with different names, amongest with we can use only one”.

The unions provide better memory management. When a structure declared


as

struct abc
{
int x;
float y;
};
And a variable declared struct abc a; the memory looks as

x y

But when a union declared as

union abc
{
int x;
float y;
}; and declared with a variable “a”, then the memory looks like:

a
When a variable is declared for a union, the largest member element of
the union gets allocated with memory and shared by all other member elements.

As in above union, “y” the float variable occupies large memory of 4


bytes, so 4 bytes memory is allocated, in which first two bytes is referred
as x (the int variable) and all the four bytes together is called y (the
float variable).

So the unions provide better memory management. But when using unions,
we can use only one variable at a time. If we are using “x” from the above
union variable “a”, we can not user “y”, and when using “y”, we can not use
“x”.

Now the question is, if we can not use both at a time, then why to
prefer the unions?

Think on the below situation:

We, the programmers are developing a project for an auto mobile show
room.

The show room sells TVS Mopeds, Bajaj Scooters and Yamaha Bikes. To
store and manage data we declare three structures, viz.

struct TVS
{
Modal no;
Price;
};

Struct Bajaj
{
Modal no;
Price;
No_of_gears;
};

Struct Yamaha
{
Modal no;
Proce;
No_of_gears;
CC Cubic Centimeters;
};

Void main()
{
Struct tvs t;
Struct Bajaj b;
Struct Yamaha y;
---
---
---
}
In above code, we are using memory 4 bytes for t, 6 bytes for b and 8 bytes
for y (assuming all the member variables are integers), total of 18 bytes of
memory.

Think on a practical issue, no user will purchase more than a bike at a


time and even if purchases, each bike will have its own bill, receipt and RC.

In above case, the following code looks better:

struct TVS
{
Modal no;
Price;
};

Struct Bajaj
{
Modal no;
Price;
No_of_gears;
};

Struct Yamaha
{
Modal no;
Proce;
No_of_gears;
CC Cubic Centimeters;
};

Union Vehicle
{
Struct tvs t;
Struct Bajaj b;
Struct Yamaha y; };
Void main()
{
Union vehicle v;

Now the v will have only 8 bytes memory allocated. Based on user
choice, either we can use, v.t.price OR v.y.cc.

Here, we prefer using unions.

When we need number of variables be grouped and we need only one to be


used amongst them, we prefer using unions.

Another example :

Union emp
{
int emp_id, pensioner_id;
}

Now any employee will use either his employee id or pensioner id at a


time, he can not use both at a time, as pensioner_id is given to one who is
retired, and he is no more an employee.

File Handling:

Again recollect the basics of programming, when we develop a program we


concentrate on three things User interface, Process and Data storage.
For data storage we use variables, arrays, pointers, structures and
unions. But when we use any of the above things, all of them are allocated
with memory in Main memory i.e. RAM. And the RAM is volatile in nature, i.e.
it stores data temporarily. If we get a requirement of keeping data for
future reference, we need to store it onto a storage media, like hard disk,
or floppy etc.

When the data is stored on any storage device, it is called a file. The
basic storage media of computer is hard disk. When we store data on hard
disk, it is called a file. Using a C program, we can write data to the hard
disk into a file and also we can read data from file (hard disk).

Process :
Take input from user and store into variables, write data stored in
variables to the hard disk. The other way, read data from hard disk and store
into variables in the program. Display the data stored in variables. This is
called file handling.

When the file is situated on hard disk, and our program runs in RAM, we
need to use a pointer in our program to point to the specific file.

The pointer is created for the built in structure "FILE".

FILE *f; is a pointer that is capable of pointing to a file on hard


disk/ any storage media.

Operations on file:

We can open file.


We can read data from file
We can write data to the file
We can close the file.

Modes of operations:

Files can be opened in different modes. That can be either read mode,
write mode or append mode. A file opened in specific mode can be used for
that purpose only. When a file is opened in read mode, we can only read data
from the file (i.e. we can not write). When the file is opened in write
mode, the program creates a new file, with specified name. If a file exists
with same name, then the old file is deleted and a new file is created.

When we need data to be added to the file that already exists, we need
to open the file in append mode.

Mode Specification

read "r"
write "w"
append "a"

Functions used:

fopen() : this function is used to open a file in specific mode.


syntax :
fopen("file name","mode"); the file name should have total path
specified, as
ex :
FILE *f=fopen("c:/myfolder/file.txt","r");

We do not use \ as in C it is representation of ESCAPE sequence.

fprintf() : is used to give output to a file, i.e. it is used to write data


to the file. its syntax is similar to normal printf().
syntax :
fprintf(fptr,"format specifiers", source variables)

fscanf() : is used to read data from file into the variables of program.

syntax :
fscanf(fptr,"format_sp",&dest_variables);

fclose() : when a file is opened in a specific mode, it must be closed before


opening in other modes. Unless which the data of file may be corrupted. A
file opened must be closed.
syntax:
fclose(fptr)

feof() :
NOTE : when a file is closed, the C RE places a NULL character at the
end of file, as identification.

The feof() function is used to identify end of file. This can be used to
develop loops to read data from file till end of file.

syntax : feof(fptr);

but this function returns true when it reaches end of file. to make
loop running we need to change the result of this function from true to false
and false to true, using logical !.

A simple program to write employee’s data to a file is:

#include<stdio.h>
Void main()
{
char name[20];
int no,sal;
FILE * f;
Clrscr();
printf(“Enter number name and sal”);
scanf(“%d%s%d”,&no,name,&sal);
f=fopen(“c:/data.txt”, “a”);
fprintf(f,“%d %s %d\n”,no,name,sal);
fclose(f);
}

A simple program to read employee’s data from the file, remember the file has
multiple records and if we do fscanf() once, only one record gets read. So we
develop a logic with loops to read till end of file.

#include<stdio.h>
Void main()
{
char name[20];
int no,sal;
FILE * f;
Clrscr();
f=fopen(“c:/data.txt”, “r”);
fscanf(“%d%s%d”,no,name,sal);
while(! feof(f) )
{
printf(“%d %s %d\n”,no,name,sal);
fscanf(“%d%s%d”,no,name,sal);
}
fclose(f);
}
Along with fprintf() and fscanf(), we can also use the functions fgetc() and
fputc() for reading single characters from/to file and also we can use
fwrite() and fread() to read/write data with a structure variable.

Other Built in structures:

The C has a built in structure TIME for which we can create a variable
and get system time into that variable with the function gettime(&st_var).
the structure TIME has member variables ti_hour, ti_min,ti_sec.

And similarly the C has struct DATE which can be used to get system
date with the method getdata(&d), where d is a struct DATE variable. It has
member variables da_day, da_mon,da_year.

You might also like