Professional Documents
Culture Documents
Untitled
Untitled
Untitled
If you could answer these questions you need not prefer this.
Can you answer these questions? If not, come across from first page with a
great patience. You will become a good professional.
Between the keyboard and monitor there is a box called CPU (Central
Processing Unit) to which all the devices are connected.
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.
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.
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
Computer
cache
ALU
Main Memory
Input
Devices
Hard Disk
OS
Devices Purpose
Comparing :
as in kitchen the fridge is used to store vegetables, in the system the
hard disk is used to store data.
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.
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 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.
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.
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.
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.
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 :
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.
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.
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.
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.
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.
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?
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.
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.
Ex : Assembly Language.
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.
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.
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
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.
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”.
Special Symbols:
~ : Tilde @ : atte...available at
# : Hash ^ : caret
& : ampersand * : Asterisk
() : parenthesis []: brackets
{} : Braces <>: Angled Brackets
_ : underscore | : pipe line
Tokens of C:
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.
The variable (reserved memory) is managed by naming them. The rules for
naming variables are as follows :
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.
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 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.
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.
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
9. Directives: The Directives are used to direct the RE about the kind of
process to be performed in pre-processor.
Ex : #include<stdio.h>
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
Program development:
Programming is nothing but giving instructions to the computer to
fulfill the requirement of the users.
IO Functions:
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;
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.
Ex: int a;
scanf(“%d”, &a);
main()
{
Declaration of variables
Instructions to computer
to fulfill the requirement of user
}
Points to remember :
Think! a function has a definition and not called, then 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.
main()
{
Coding;
}
And the above is a definition
The definition executes when the function is called. Then who calls the
main()?
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.
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.
The second compiler that is activated with the short cut key Ctrl+F9
has following parts:
main()
{
int a,b,c;
clrscr();
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.
Questions to practice:
Operators :
Binary Operators :
The operators that take two operands are called binary operators. These
are further classified into five types based on their purpose, viz.
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.
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.
For example, int a =5; is a correct statement. But int a; 5=a; is wrong.
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.
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.
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.
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.
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
Similarly,
int a=5;
Ex : for displaying user about biggest of two numbers, the code would look
like,
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:
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.
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
Syntax :
if(condition)
Statement 1;
else
statement 2;
Ex :
if( a>b )
printf(“a is big”);
else
printf(“b is big”);
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.
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 ;.
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”);
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.
Conclusion: So, leap year comes after every four years but skipped
after every hundred years but comes after every four hundred years
again.
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:
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.
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(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 :
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 :
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 :
char ch;
ch=getchar();
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”);
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.
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.
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.
So, for working with loops, one should have knowledge of three thing.
The loops are supported with keywords while, for and do-while.
While Loop:
initialization;
while( Condition )
false/true
{
statements to be executed;
Counter;
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.
int i;
i=0;
while(i < 5)
{
printf(“%d ”,i);
i++;
}
-5 -4 -3 -2 -1 0 1 2 3 4
int i=0;
while(i< 32768 )
{
printf(“hi”);
i++;
}
For loop :
initialization;
for ( ;Condition; )
false/true
{
statements to be executed;
Counter;
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;
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.
initialization;
do
{
statements to exceute;
counter;
while(condition ); true
false
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.
i=0;
while(i<5)
{
printf(“%d “,i);
i++;
}
can be coded as
for(i=0;i<5;i++)
printf(“%d “,i);
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.
i=5;
while(i<0)
{
printf(“%d “,i);
i++;
}
will give no results, as the first time itself the condition is false.
i=5;
do
{
printf(”%d “,i);
i++;
}while(i<0);
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.
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:
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):
}
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.
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.
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.
for(i=0;i<5;i++)
{
printf(“%d “,i);
sleep(1);
}
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)
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
? 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).
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.
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.
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.
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.
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.
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.
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
}
The term calling function is used for the function definition in which
the other function is being called.
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.
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.
Syntaxes:
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.
void main()
{
int a,b;
clrscr();
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
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;
}
Ex :
Void disp(int,int);
Void main()
{
int n;
printf(“Enter a number for which multiplication table required”);
scanf(“%d”,&n);
disp(n,1);
}
Static Variables :
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.
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”.
if(a>b)
printf(“a is big”);
else
printf(“b is big”);
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.
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.
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
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.
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.
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’.
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 [].
Ex : strcpy(name,”arc”);
printf(“%d”, strlen(name));
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.
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.
0 1 2 0 1 2
0 1
arr
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.
arr
We logically understand the memory as rows and columns but actually the
memory is allocated contiguously.
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.
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:
40
20 21
a
* 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.
20 21
a
Remember the above diagram of memory allocated for variable “a”, and
identify the output for following lines of code.
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
20
a
20
b
When we display now,
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.
For working with memory by naming, we use variables and arrays. But for
working with memory with its addresses, we must use pointers.
int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;
5 10
20 30
a b
20 30
p q
So,
int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;
and p=q;
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,
Pointers can also be used to point arrays. We can have a declaration like,
p++;
printf(“%d ”, *p); will display now the value 20.
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.
So in the statement,
printf(“%d ”,*p+2) first *p is evaluated, (value 10) and then added
with 2 will display 12.
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.
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 [].
When int a[5]; declared the C RE declares a pointer with same name “a”
and stored with address of first element of array.
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.
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.
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.
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.
Ex:
int *p,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
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.
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.
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.
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,
Ex : free(p);
Programs to practice : You can do all the programs you did with arrays.
Structures:
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.
int no[60],marks[60][6],total[60];
char name[60][20];
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.
The structures are defined as “user defined data type, used to group
number of elements of different data types with different names”.
{
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.
Think, int is a data type designed by Dennis Ritchie and the stud is a
data type designed by you.
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.
no name 0 1 2 3 4 5
marks
struct emp
{
int no;
char name[20];
float sal;
};
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”.
struct abc
{
int x;
float y;
};
And a variable declared struct abc a; the memory looks as
x y
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.
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?
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.
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.
Another example :
Union emp
{
int emp_id, pensioner_id;
}
File Handling:
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.
Operations on 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:
fscanf() : is used to read data from file into the variables of program.
syntax :
fscanf(fptr,"format_sp",&dest_variables);
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 !.
#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.
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.