PPS Unit 1 &2 by BMK
PPS Unit 1 &2 by BMK
B.TECH
(I YEAR – I SEM)
DEPARTMENT OF CSE
UNIT - I
Introduction to Computing:
Computer Systems:
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions)
that allow the hardware to do its job.
Computer
System
Hardware Software
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the
computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or
an audio input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations,comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on
the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard
copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer,
or programs and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between
the hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
Software
System Application
software software
System Software:
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access
to the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category ,system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to
ensure that the programs are error free and computer –assisted software engineering(CASE)
systems.
Application software
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software. They can
be used only for the task for which they were designed they cannot be used for other
generalized tasks.
The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the out
layer. To work with the system,the typical user uses some form of application software. The
application software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
Computer Languages:
To write a program for a computer, we must use a computer language. Over the years
computer languages have evolved from machine languages to natural languages.
Machine Languages
In the earliest days of computers, the only programming languages available were machine
languages. Each computer has its own machine language, which is made of streams of 0’s and
1’s.
Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits
of a computer are made of switches transistors and other electronic devices that can be in one
of two states: off or on. The off state is represented by 0 , the on state is represented by 1.
Symbolic Languages:
In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the
concept of a special computer program that would convert programs into machine language.
The early programming languages simply mirror to the machine languages using symbols of
mnemonics to represent the various machine language instructions because they used symbols,
these languages were known as symbolic languages.
Computer does not understand symbolic language it must be translated to the machine
language. A special program called assembler translates symbolic code into machine language.
Because symbolic languages had to be assembled into machine language they soon became
known as assembly languages.
Symbolic language uses symbols or mnemonics to represent the various ,machine language
instructions.
Symbolic languages greatly improved programming effificiency; they still required programmers
to concentrate on the hardware that they were using. Working with symbolic languages was
also very tedious because each machine instruction has to be individually coded. The desire to
improve programmer efficiency and to change the focus from the computer to the problem
being solved led to the development of high-level language.
High level languages are portable to many different computers, allowing the programmer to
concentrate on the application problem at hand rather than the intricacies of the computer.
High-level languages are designed to relieve the programmer from the details of the assembly
language. High level languages share one thing with symbolic languages, They must be
converted into machine language. The process of converting them is known as compilation.
The first widely used high-level languages, FORTRAN (FORmula TRANslation)was created by
John Backus and an IBM team in 1957;it is still widely used today in scientific and engineering
applications. After FORTRAN was COBOL(Common Business-Oriented Language). Admiral
Hopper was played a key role in the development of the COBOL Business language.
C is a high-level language used for system software and new application code.
ALGORITHM:
Step 1: Start
Step 2:Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.
FLOW CHART :
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm. Flow
charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and
small circles. These symbols are connected by arrows called flow lines.
The diagrammatic representation of way to solve the given problem is called flow chart.
The following are the most common symbols used in Drawing flowcharts:
For processing(input) or
recording of the process
information(output)
type of operations.
1. Documentation section
2. Linking section
3. Definition section
Declaration section
Executable section
2. LINKING SECTION : This section tells the compiler to link the certain occurrences of keywords
or functions in your program to the header files specified in this section.
3. DEFINITION SECTION : It is used to declare some constants and assign them some value.
Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables which are used through out the program
(including main and other functions) are declared so as to make them global(i.e accessible to all
parts of program)
5. MAIN FUNCTION SECTION : It tells the compiler where to start the execution from
main()
1. declaration section : In this the variables and their data types are declared.
2. Executable section : This has the part of program which actually performs the task we
need.
6. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the functions
which our program needs.
SIMPLE ‘C’ PROGRAM:
/* simple program in c */
#include<stdio.h>
main()
printf(“welcome to c programming”);
} /* End of main */
KEYWORDS :
There are certain words, called keywords (reserved words) that have a predefined
meaning in ‘C’ language. These keywords are only to be used for their intended purpose and not
as identifiers.
Volatile While
IDENTIFIERS :
Names of the variables and other program elements such as functions, array,etc,are
known as identifiers.
There are few rules that govern the way variable are named(identifiers).
1. Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).
Eg: name,ptr,sum
where data type could be float, int, char or any of the data types.
id1, id2, id3 are the names of variable we use. In case of single variable no commas are
required.
eg float a, b, c;
char present_or_absent;
ASSIGNING VALUES :
When we name and declare variables we need to assign value to the variable. In some
cases we assign value to the variable directly like
a=10;
in our program.
In some cases we need to assign values to variable after the user has given input for
that.
#include<stdio.h>
main()
int a;
float b;
b=190.5;
scanf("%d",&a);
CONSTANTS :
A quantity that does not vary during the execution of a program is known as a constant
supports two types of constants namely Numeric constants and character constants.
NUMERIC CONSTANTS:
2. Long constant is written with a terminal ‘l’or ‘L’,for example 1234567899L is a Long
constant.
3. Unsigned constants are written with a terminal ‘u’ or ‘U’,and the suffix ‘ul’ and ‘UL’
CHARACTER CONSTANTS:
A character constant is written as one character with in single quotes such as ‘a’. The value
of a character constant is the numerical value of the character in the machines character set.
certain character constants can be represented by escape sequences like ‘\n’. These sequences
look like two characters but represent only one.
\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return
\t Horizontal Tab
\v Vertical Tab
To distinguish between a character constant and a string that contains a single character
ex: ‘a’ is not same as “a”. ‘a’ is an integer used to produce the numeric value of letter a in the
machine character set, while “a” is an array of characters containing one character and a ‘\0’ as
a string in C is an array of characters terminated by NULL.
There is one another kind of constant i.e Enumeration constant , it is a list of constant
integer values.
The first name in the enum has the value 0 and the next 1 and so on unless explicit values
are specified.
If not all values specified , unspecified values continue the progression from the last
specified value. For example
VARIABLES :
A quantity that can vary during the execution of a program is known as a variable. To
identify a quantity we name the variable for example if we are calculating a sum of two numbers
we will name the variable that will hold the value of sum of two numbers as 'sum'.
DATA TYPES :
To represent different types of data in C program we need different data types. A data type
is essential to identify the storage representation and the type of operations that can be
performed on that data. C supports four different classes of data types namely
All arithmetic operations such as Addition , subtraction etc are possible on basic data
types.
Char c;
The following table shows the Storage size and Range of basic data types:
Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.
Char name[20];
makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts,etc,like,
Integer num1,num2;
Which will be treated by the C compiler as the declaration of num1,num2as int variables.
varname=getchar();
The simplest of output operator is putchar to output a single character on the output
device.
putchar(varname)
The getchar() is used only for one input and is not formatted. Formatted input refers to an input
data that has been arranged in a particular format, for that we have scanf.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
%f floats
%l long
%c character
#include<stdio.h>
main()
int a,b;
float c;
a=getchar();
putchar(a);
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
OPERATORS :
An operator is a symbol that tells the compiler to perform certain mathematical or
logical manipulations. They form expressions.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
8. Special operators
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
An arithmetic operation involving only real operands(or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.
operator meaning
== is equal to
!= is not equal to
It is the form of
3. LOGICAL OPERATORS : An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The
operators and truth values are
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
op-1 !op-1
non-zero zero
zero non-zero
5. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a variable.
The assignment operator is '='.
v op=exp
v is variable
op binary operator
exp expression
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
++ and == are called increment and decrement operators used to add or subtract.
++m or m++
--m or m--
It work as
8. BIT WISE OPERATORS : C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
^ Bitwise exclusive OR
~ one's complement
9. SPECIAL OPERATORS : These operators which do not fit in any of the above classification are
,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->). The
comma operator is used to link related expressions together.
#include<stdio.h>
main()
int i,j;
float l, m;
scanf("%d%d",&i,&j);
scanf("%f%f",&l,&m);
sum=i+j;
mul=i*j;
modu=i%j;
sub=l-m;
divi=l/m;
}
/* program to implement relational and logical */
#include<stdio.h>
main()
int i, j, k;
if((i<j)&&(j<k))
printf("k is largest");
printf("j is largest");
else
#include<stdio.h>
main()
int i;
printf("Enter a number");
scanf("%d", &i);
i++;
i--;
#include<stdio.h>
main()
int i,j,large;
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
The if statement is a two way decision statement and is used in conjunction with an
expression. It takes the following form
If(test expression)
If the test expression is true then the statement block after if is executed otherwise it is not
executed
if (test expression)
statement block;
statement–x ;
/* program for if */
#include<stdio.h>
main()
int a,b;
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
If your have another set of statement to be executed if condition is false then if-else is
used
if (test expression)
statement block1;
else
statement block2;
statement –x ;
#include<stdio.h>
main()
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”)
else
printf(“b is greater”);
if(text cond1)
if (test expression2
statement block1;
else
statement block 2;
else
statement block2;
}
statement-x ;
if else ladder
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.
switch(expression)
{.
case value-1
block-1
break;
case value-2
block-2
break;
default:
default block;
break;
statement–x
In case of
if(cond1)
statement-1
if (cond2)
statement 2
#include<stdio.h>
main()
int marks,index;
char grade[10];
scanf(“%d”,&marks);
index=marks/10;
switch(index)
case 10 :
case 9:
case 8:
case 7:
case 6: grade=”first”;
break;
case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
break;
printf(“%s”,grade);
LOOPING :
Some times we require a set of statements to be executed repeatedly until a
condition is met.
We have two types of looping structures. One in which condition is tested before
entering the statement block called entry control.
The other in which condition is checked at exit called exit controlled loop.
WHILE STATEMENT :
While(test condition)
It is an entry controlled loop. The condition is evaluated and if it is true then body of
loop is executed. After execution of body the condition is once again evaluated and if is true body
is executed once again. This goes on until test condition becomes false.
#include<stdio.h>
main()
int count,n;
float x,y;
scanf(“%f%d”,&x,&n);
y=1.0;
count=1;
while(count<=n)
y=y*x;
count++;
}
DO WHILE STATEMENT :
The while loop does not allow body to be executed if test condition is false. The do while
is an exit controlled loop and its body is executed at least once.
do
body
}while(test condition);
#include<stdio.h>
#define COL 10
#define ROW 12
main()
int row,col,y;
row=1;
do
col=1;
do
y=row*col;
printf(“%d”,y);
col=col+1;
}while(col<=COL);
printf(“\n”);
row=row+1;
}while(row<=ROW);
body of loop
#include<stdio.h>
main()
long int p;
int n;
double q;
p=1;
for(n=0;n<21;++n)
if(n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
printf(“%101d%10d”,p,n);
UNCONDITIONAL STATEMENTS:
BREAK STATEMENT:
This is a simple statement. It only makes sense if it occurs in the body of a switch, do,
while or for statement. When it is executed the control of flow jumps to the statement
immediately following the body of the statement containing the break. Its use is widespread in
The use of the break within loops is of dubious legitimacy. It has its moments, but is really
only justifiable when exceptional circumstances have happened and the loop has to be abandoned.
It would be nice if more than one loop could be abandoned with a single break but that isn't how
it works. Here is an example.
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
It reads a single character from the program's input before printing the next in a sequence of
numbers. If an „s‟ is typed, the break causes an exit from the loop.
If you want to exit from more than one level of loop, the break is the wrong thing to use.
CONTINUE STATEMENT:
This statement has only a limited number of uses. The rules for its use are the same as for
break, with the exception that it doesn't apply to switch statements. Executing a continue starts
the next iteration of the smallest enclosing do, while or for statement immediately. The use of
continue is largely restricted to the top of loops, where a decision has to be made whether or not
to execute the rest of the body of the loop. In this example it ensures that division by zero (which
gives undefined behaviour) doesn't happen.
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
The continue can be used in other parts of a loop, too, where it may occasionally help to
simplify the logic of the code and improve readability. continue has no special meaning to a
switch statement, where break does have. Inside a switch, continue is only valid if there is a
loop that encloses the switch, in which case the next iteration of the loop will be started.
There is an important difference between loops written with while and for. In a while, a
continue will go immediately to the test of the controlling expression. The same thing in a for
will do two things: first the update expression is evaluated, then the controlling expression is
evaluated.
goto L1;
/* whatever you like here */
L1: /* anything else */
A label is an identifier followed by a colon. Labels have their own „name space‟ so they
can't clash with the names of variables or functions. The name space only exists for the function
containing the label, so label names can be re-used in different functions. The label can be used
before it is declared, too, simply by mentioning it in a goto statement.
Labels must be part of a full statement, even if it's an empty one. This usually only matters
when you're trying to put a label at the end of a compound statement—like this.
The goto works in an obvious way, jumping to the labelled statements. Because the name of
the label is only visible inside its own function, you can't jump from one function to another one.
It's hard to give rigid rules about the use of gotos but, as with the do, continue and the
break (except in switch statements), over-use should be avoided. More than one goto every 3–5
functions is a symptom that should be viewed with deep suspicion.
UNIT-II
ARRAYS :
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students are represented using an array name students. A particular
value is indicated by writing a number called index number or subscript in brackets after array
name. The complete set of value is referred to as an array, the individual values are called
elements.
A list of items can be given one variable index is called single subscripted variable or a
one-dimensional array.
The subscript value starts from 0. If we want 5 elements the declaration will be
int number[5];
This array is of type float. Its name is avg. and it can contains 50 elements only. The
range starting from 0 – 49 elements.
Initialization of Arrays :
Initialization of elements of arrays can be done in same way as ordinary variables are
done when they are declared.
If the number of values in the list is less than number of elements then only that elements will
be initialized. The remaining elements will be set to zero automatically.
The size may be omitted. In such cases, Compiler allocates enough space for all initialized
elements.
#include<stdio.h>
main()
int i;
float x[10],value,total;
for(i=0;i<10;i++)
scanf(“%f”,&value);
x[i]=value;
total=0;
for(i=0;i<10;i++)
total=total+x[i]
for(i=0;i<10;i++)
printf(“x*%2d+=%5.2f\n”,I+1,x*I+);
printf(“total=%0.2f”,total);
}
TWO – DIMENSIONAL ARRAYS:
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
int row,cols,prod[ROWS][COLS];
int i,j;
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
row = i+1;
printf(“%2d|”,row);
COLS=j;
printf(“%4d”,prod*i+*j+);
}
}
They can be initialized by following their declaration with a list of initial values enclosed
in braces.
Initializes the elements of first row to zero and second row to one. The initialization is done by
row by row. The above statement can be written as
When all elements are to be initialized to zero, following short-cut method may be used.
STRINGS(CHARACTER ARRAYS) :
A String is an array of characters. Any group of characters (except double quote sign
)defined between double quotes is a constant string.
A string variable is any valid C variable name and is always declared as an array.
size determines number of characters in the string name. When the compiler assigns a character
string to a character array, it automatically supplies a null character (‘\0’) at end of String.
Therefore, size should be equal to maximum number of character in String plus one.
char address[15];
scanf(“%s”,address);
The problem with scanf function is that it terminates its input on first white space it finds. So
scanf works fine as long as there are no spaces in between the text.
If we are required to read a line of text we use getchar(). which reads a singlecharacters.
Repeatedly to read successive single characters from input and place in character array.
#include<stdio.h>
main()
{
char line[80],ano_line[80],character;
int c;
c=0;
scanf(“%s”, line);
do
character = getchar();
ano_line[c] = character;
c++;
- while(character !=’\n’);
c=c-1;
ano_line*c+=’\0’;
The ..scanf functions provide a means to input formatted information from a stream
These functions take input in a manner that is specified by the format argument and store each
input field into the following arguments in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which specifies how
the input is to be stored in the appropriate variable. Other characters in the format string
specify characters that must be matched from the input, but are not stored in any of the
following arguments. If the input does not match then the function stops scanning and returns.
A whitespace character may match with any whitespace character (space, tab, carriage return,
new line, vertical tab, or formfeed) or the next incompatible character.
Declarations:
These functions take the format string specified by the format argument and apply each
following argument to the format specifiers in the string in a left to right fashion. Each
character in the format string is copied to the stream except for conversion characters which
specify a format specifier.
String Input/Output
In addition to the Formatted string functions,C has two sets of string functions that read and
write strings without reformatting any data.These functions convert text file lines to strings and
strings to text file lines.
gets():
Declaration:
Reads a line from stdin and stores it into the string pointed to by str. It stops when either the
newline character is read or when the end-of-file is reached, whichever comes first. The
newline character is not copied to the string. A null character is appended to the end of the
string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file
occurs before any characters have been read, the string remains unchanged.
puts:
Declaration:
Writes a string to stdout up to but not including the null character. A newline character is
appended to the output.
strcat() function:
strcat(string1,string2);
string1 = VERY
string2 = FOOLISH
strcat(string1,string2);
string1=VERY FOOLISH
string2 = FOOLISH
strcmp() function :
This function compares two strings identified by arguments and has a value 0 if they are
equal. If they are not, it has the numeric difference between the first non-matching characters in
the Strings.
strcmp(string1,string2);
Ex:- strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“ROM”,”Ram”);
strcpy() function :
strcpy(string1,string2);
strlen() function :
Counts and returns the number of characters in a string.
n= strlen(string);
/* Illustration of string-handling */
#include<stdio.h>
#include<string.h>
main()
char s1[20],s2[20],s3[20];
int X,L1,L2,L3;
scanf(“%s %s”,s1,s2);
X=strcmp(s1,s2);
if (X!=0)
strcat(s1,s2);
else
strcpy(s3,s1);
L1=strlen(s1);
L2=strlen(s2);
L3=strlen(s3);
POINTERS:
One of the powerful features of C is ability to access the memory variables by their memory
address. This can be done by using Pointers. The real power of C lies in the proper use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a
pointer points to a variable that is stored at that address. A pointer itself usually occupies 4 bytes
of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
The operator & returns the memory address of variable on which it is operated, this is
called Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to
display the contents of the Pointer Variable.
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following
printf statements is :
Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
When an array is declared, elements of array are stored in contiguous locations. The
address of the first element of an array is called its base address.
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we can
make the pointer P to point to the array a by following assignment
P = a;
We can access every value of array a by moving P from one element to another.
i.e., P points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd element
P +4 points to 4th element
main() {
int *a,i;
printf(“Enter five elements:”);
for (i=0;i<5;i++)
}
scanf(“%d”,a+i);
printf(“The array elements are:”);
for (i=0;i<5;i++)
printf(“%d”, *(a+i));
STRUCTURES :
A Structure is a collection of elements of dissimilar data types. Structures provide the
ability to create user defined data types and also to represent real world data.
Suppose if we want to store the information about a book, we need to store its name
(String), its price (float) and number of pages in it(int). We have to store the above three items as
a group then we can use a structure variable which collectively store the information as a book.
Structures can be used to store the real world data like employee, student, person etc.
Declaration :
The declaration of the Structure starts with a Key Word called Struct and ends with ; .
The Structure elements can be any built in types.
Initialization :
Structure elements are stored in contiguous memory locations as shown below. The
above Structure occupies totally 26 bytes.
main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;
printf (“ Enter Employee number: \n”);
scanf(“%d”,&e.empno);
/* Program to read Student Details and Calculate total and average using structures */
#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s;
int tot;
float avg;
#include<stdio.h>
main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
struct item i;
float tot_amt;
ARRAY OF STRUCTURES :
To store more number of Structures, we can use array of Structures. In array of
Structures all elements of the array are stored in adjacent memory location.
main()
{
struct book
{
char name[20];
float price;
int pages;
};
UNIONS :
Union, similar to Structures, are collection of elements of different data types. However,
the members within a union all share the same storage area within the computer‟s memory,
whereas each member within a Structure is assigned its own unique Storage area.
Unions are used to conserve memory. Unions are useful for applications involving
multiple members, where values need not be assigned to all of the members at any given time.
An attempt to access the wrong type of information will produce meaningless results.
The union elements are accessed exactly the same way in which the structure elements
are accessed using dot(.) operator.
The difference between the structure and union in the memory representation is as
follows.
struct cx
int i;
char ch[2];
};
struct cx s1;
union ex
int i;
char ch[2];
union ex u;
u.i →
u.ch[0]→ u.ch[0]→
main()
{
union example
int i;
char ch[2];
};
union exaple u;
u.i = 412;
Output :
u.i = 512
u.ch[0] = 0
u.ch[1] =2
u.i = 562
u.ch[0] = 50
u.ch[1] =2
A union may be a member of a structure, and a structure may be a member of a union. And
also structures and unions may be freely mixed with arrays.
main()
{
union id
char color;
int size;
};
struct {
char supplier[20];
float cost;
union id desc;
}pant, shirt;
shirt.desc.color = ‘w’;
shirt.desc.size = 12;