BCA 3rd Practical File
BCA 3rd Practical File
ANDREWS INSTITUTEOF
TECHNOLOGY & MANAGEMENT
Approved by AICTE, Govt. of India, New Delhi & Affiliated to Maharshi Dayanand University ‘A’ Grade
State University, accredited by NAAC
Experiment No: 1
Title: Implementation of DDL commands of SQL with suitable examples
● Create table
● Altertable
● DropTable
Objective:
✓ To understand the different issues involved in the design and implementation of a databasesystem.
✓ To understand and use data definition language to write query for adatabase.
Theory:
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer, Oracle Graphics etc.
➢ SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. Theseare
❖ Interactive SQL: Interactive SQL is designed for create, access and manipulate data structures like
tables andindexes.
❖ PL/SQL: PL/SQL can be used to developed programs for differentapplications.
➢ Oracle Forms: This tool allows you to create a data entry screen along with the suitable menu objects. Thus
it is the oracle forms tool that handles data gathering and data validation in a commercialapplication.
➢ Report Writer: Report writer allows programmers to prepare innovative reports using data from the oracle
structures like tables, views etc. It is the report writer tool that handles the reporting section of
commercialapplication.
➢ Oracle Graphics: Some of the data can be better represented in the form of pictures. The oracle graphics
tool allows programmers to prepare graphs using data from oracle structures like tables, viewsetc.
➢ SQL (Structured Query Language):
Structured Query Language is a database computer language designed for managing data in relational
database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification,
and data accesscontrol.
● SQL was one of the first languages for Edgar F. Codd's relational model and became
the most widely used language for relationaldatabases.
▪ IBM developed SQL in mid of1970’s.
▪ Oracle incorporated in the year1979.
▪ SQL used by IBM/DB2 and DS DatabaseSystems.
▪ SQL adopted as standard language for RDBS by ASNI in1989.
➢ DATATYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length. The
size in brackets determines the number of characters the cell can hold. The maximum number
of character is 255characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.
124
Number as large as 9.99 * 10 . The precision (p) determines the number of places to the
right of the decimal. If scale is omitted then the default is zero. If precision is omitted, values
are stored with their original precision up to the maximum of 38digits.
4. DATE: This data type is used to represent date and time. The standard format is DD-MM-
YY as in 17-SEP-2009. To enter dates other than the standard format, use the appropriate
functions. Date time stores date in the 24-Hours format. By default the time in a date field is
12:00:00 am, if no time portion is specified. The default date for a date field is the first day
the currentmonth.
5. LONG: This data type is used to store variable length character strings containing up to
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot beapplied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image.
Data loaded into columns of these data types are stored without any further conversion.RAW
data type can have a maximum length of 255 bytes. LONG RAW data type can contain
up to 2GB.
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)
Syntax: CREATE TABLE
<relation_name/table_name > (field_1
data_type(size),field_2 data_type(size), .. . );
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR (5));
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation. Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD
field_name) to (NEW field_name);
Example: SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;
3. DROP TABLE: This is used to delete the structure of a relation. It permanently
deletes the records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;
4. RENAME: It is used to modify the name of the existing database
object. Syntax: RENAME TABLE old_relation_name TO
new_relation_name; Example: SQL>RENAME TABLE std TOstd1;
Experiment No:2
1. INSERT INTO: This is used to add records into a relation. These are three type of
INSERT INTO queries which areas
a) Inserting a singlerecord
Syntax: INSERT INTO < relation/table name>(field_1,field_2……
field_n)VALUES (data_1,data_2,. data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);
b) Inserting a singlerecord
Syntax: INSERT INTO < relation/tablename>VALUES(data_1,data_2,.........data_n);
Example: SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’);
c) Inserting all records from anotherrelation
Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n FROM
relation_name_2 WHERE field_x=data;
Example: SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name =
‘Ramu‘;
d) Inserting multiplerecords
Syntax: INSERT INTOrelation_namefield_1,field_2,......field_n)
VALUES(&data_1,&data_2,........&data_n);
Example: SQL>INSERT INTO student (sno, sname,
class,address) VALUES (&sno,’&sname’,’&class’,’&address’);
Enter value for sno: 101
Enter value for name:
Ravi Enter value for
class: M.Tech Enter value
for name:Palakol
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of thatrelation.
a) DELETE-FROM: This is used to delete all the records ofrelation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
b) DELETE -FROM-WHERE: This is used to delete a selected record from arelation.
Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;
5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.
Difference between Truncate & Delete:-
✓ By using truncate command data will be removed permanently & will not get back
where as by using delete command data will be removed temporally & get back by using
roll back command.
✓ By using delete command data will be removed based on the condition where as by
using truncate command there is nocondition.
✓ Truncate is a DDL command & delete is a DMLcommand.
Syntax: TRUNCATE TABLE <Table name>
Example TRUNCATE TABLE student;
● To Retrieve data from one or moretables.
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of arelation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Experiment No: 3
NUMBER FUNCTION:
Abs(n) :Select abs(-15) from dual;
Exp(n): Select exp(4) from dual;
Power(m,n): Select power(4,2) from
dual; Mod(m,n): Select mod(10,3)
from dual;
Round(m,n): Select round(100.256,2) from dual;
Trunc(m,n): ;Select trunc(100.256,2) from dual;
Sqrt(m,n);Select sqrt(16) from dual;
Develop aggregate plan strategies to assist with summarization of several data entries.
Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now
consider a powerful class of constructs for computing aggregate values such as MIN
andSUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the column.
Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all
the tuples of thecolumn.
Syntax: COUNT (Column
name) 20
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in thatcolumn.
Syntax: SUM (Column name)
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that columnvalues.
Syntax: AVG (n1, n2...)
Example: Select AVG (10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of thatcolumn.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno, max(sal) from emp group
bydeptno; DEPTNO MAX (SAL)
------ --------
10 5000
20 3000
30 2850
SQL> select deptno, max (sal) from emp group by deptno
havingmax(sal)<3000; DEPTNO MAX(SAL)
----- --------
30 2850
5. MIN: MIN followed by column name returns the minimum value of thatcolumn.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
SQL>select deptno,min(sal) from emp group by deptno
havingmin(sal)>1000; DEPTNO MIN (SAL)
----- --------
10 1300
CHARACTER FUNCTION:
initcap(char) : select initcap(“hello”) from
dual; lower (char): select lower (‘HELLO’)
from dual; upper (char) :select upper (‘hello’)
from dual;
ltrim (char,[set]): select ltrim (‘cseit’, ‘cse’) from
dual; rtrim (char,[set]): select rtrim (‘cseit’, ‘it’) from
dual;
replace (char,search ): select replace(‘jack and jue’,‘j’,‘bl’) from dual;
CONVERSION FUNCTIONS:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the
optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or
BINARY_DOUBLE.
SQL>select to_char(65,'RN')from dual;
LXV
To_number : TO_NUMBER converts expr to a value of NUMBER data type.
SQL>Select to_number ('1234.64') from Dual;
1234.64
To_date:TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type to a value of DATE data type.
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;
TO_DATE
---------
15-JAN-89
STRING FUNCTIONS:
Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any
of the datatypes
SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the
sequence of characters in expr2.
SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;
*********ORACLE
Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated as
many times as necessary.
SQL>SELECT RPAD (‘ORACLE’,15,’*’)FROM DUAL;
ORACLE*********
Ltrim: Returns a character expression after removing leading blanks.
SQL>SELECT LTRIM(‘SSMITHSS’,’S’)FROM DUAL;
MITHSS
Rtrim: Returns a character string after truncating all
trailingblanks SQL>SELECT
RTRIM(‘SSMITHSS’,’S’)FROM DUAL; SSMITH
Lower: Returns a character expression after converting uppercase character data to
lowercase.
SQL>SELECT LOWER(‘DBMS’)FROM DUAL;
dbms
Upper: Returns a character expression with lowercase character data converted to uppercase
SQL>SELECT UPPER(‘dbms’)FROM DUAL;
DBMS
Length: Returns the number of characters, rather than the number of bytes, of the
given string expression, excluding trailing blanks.
SQL>SELECT LENGTH(‘DATABASE’)FROM
DUAL; 8
23
Substr: Returns part of a character, binary, text, or image expression.
SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;
CDEF
Instr: The INSTR functions search string for substring. The function returns an integer
indicating the position of the character in string that is the first character of this
occurrence. SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;
14
DATE FUNCTIONS:
Sysdate:
SQL>SELECT SYSDATE FROM
DUAL; 29-DEC-08
next_day:
SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM
DUAL; 05-JAN-09
add_months:
SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM
DUAL; 28-FEB-09
last_day:
SQL>SELECT LAST_DAY(SYSDATE)FROM
DUAL; 31-DEC-08
months_between:
SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM
EMP; 4
Least:
SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM
DUAL; 10-JAN-07
Greatest:
SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM
DUAL; 10-JAN-07
Trunc:
24
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM
DUAL; 28-DEC-08
Round:
SQL>SELECT ROUND(SYSDATE,'DAY')FROM
DUAL; 28-DEC-08
to_char:
SQL> select to_char(sysdate, "dd\mm\yy") from
dual; 24-mar-05.
to_date:
SQL> select to date (sysdate, "dd\mm\yy") from
dual; 24-mar-05.
1. .
Experiment4
Title :Implementation of different types of operators in
SQL. Arithmetic Operator
Logical Operator
Comparision Operator
Special Operator
Set Operator
Objective:
To learn different types of operator.
Theory:
ARIHMETIC OPERATORS:
(+) : Addition - Adds values on either side of the operator .
(-):Subtraction - Subtracts right hand operand from left hand
operand . (*):Multiplication - Multiplies values on either side of
the operator . (/):Division - Divides left hand operand by right
hand operand . (^):Power- raise to power of .
(%):Modulus - Divides left hand operand by right hand operand and returns remainder.
LOGICAL OPERATORS:
AND : The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.
OR: The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
26
NOT: The NOT operator reverses the meaning of the logical operator with which it is
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
COMPARISION OPERATORS:
(=):Checks if the values of two operands are equal or not, if yes then condition becomes
true. (!=):Checks if the values of two operands are equal or not, if values are not equal
then condition becomestrue.
(<>):Checks if the values of two operands are equal or not, if values are not equal
then condition becomestrue.
(>):Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true
(<):Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(>=):Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true.
(<=):Checks if the value of left operand is less than or equal to the value of right operand,
if yes then condition becomes true.
SPECIAL OPERATOR:
BETWEEN: The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
IS NULL: The NULL operator is used to compare a value with a NULL attribute
value. ALL: The ALL operator is used to compare a value to all values in another
value set ANY: The ANY operator is used to compare a value to any applicable value
in the list according to the condition.
LIKE: The LIKE operator is used to compare a value to similar values using wildcard
operators.It allows to use percent sign(%) and underscore ( _ ) to match a given string
pattern.
IN: The IN operator is used to compare a value to a list of literal values that have
been specified.
EXIST: The EXISTS operator is used to search for the presence of a row in a specified
table that meets certain criteria.
SET OPERATORS:
The Set operator combines the result of 2 queries into a single result. The
following are the operators:
Union
Union all
Intersect
Minus
Union: Returns all distinct rows selected by both the queries
Union all: Returns all rows selected by either query including the duplicates.
Intersect: Returns rows selected that are common to both queries.
Minus: Returns all distinct rows selected by the first query and are not by the second
Experiment No: 5
Objective:
To implement different types of joins
Theory :
The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values
common to each.The join is actually performed by the ‘where’ clause which combines
specifiedrows oftables.
Syntax:
SELECT column 1, column 2, column
3... FROM table_name1, table_name2
WHERE table_name1.column name = table_name2.columnname;
Types of Joins :
1. SimpleJoin
2. SelfJoin
3. OuterJoin
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a
common column and is further classified into
Equi-join :
A join, which is based on equalities, is called equi-
join. Example:
Select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where
clause. Since the where clause uses the comparison operator (=) to perform a join, it is
said to be equijoin. It combines the matched rows of tables. It can be used as follows
To insert records in the target table.
To create tables and insert records in this
table. To update records in the target table.
To create views.
Non Equi-join:
It specifies the relationship between columns belonging to different tables by
making use of relational operators other than’=’.
Example:
Select * from item, cust where
item.id<cust.id; Table Aliases
Table aliases are used to make multiple table queries shorted and more readable.
Wegive an alias name to the table in the ‘from’ clause and use it instead of the name
throughout thequery.
Selfjoin:
Joining of a table to itself is known as self-join. It joins one row in a table to another.
It can compare each row of the table to itself and also with other rows of the same table.
Example:
select * from emp x ,emp y where x.salary >= (select avg(salary) from
x.emp where x. deptno =y.deptno);
Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by
simple join as well as those rows from one table that do not match any row from the
table. The symbol(+) represents outer join.
– Left outerjoin
– Right outerjoin
– Full outerjoin
Experiment No: 6
Title :Study &
Implementationof Group by
& Having Clause Order
byClause
Indexing
Objective:
To learn the concept of group functions
Theory:
GROUP BY: This query is used to group to all the records in a relation together for
each and every value of a specific key(s) and then display them for a selected set of
fields the relation.
Syntax: SELECT <set of fields> FROM
<relation_name> GROUP BY <field_name>;
Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP
BY EMPNO;
GROUP BY-HAVING : The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. The HAVING clause must follow
the GROUP BY clause in a query and must also precede the ORDER BY clause if used.
Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator
value; 32
Example : SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
JOIN using GROUP BY: This query is used to display a set of fields from two relations
by matching a common field in them and also group the corresponding records for each
and every value of a specified key(s) while displaying.
Syntax:SELECT <set of fields (from both relations)> FROM relation_1,relation_2
WHERE relation_1.field_x=relation_2.field_y GROUP BY field_z;
Example:
SQL> SELECT empno,SUM(SALARY) FROM emp,dept
WHERE emp.deptno =20 GROUP BY empno;
ORDER BY: This query is used to display a selected set of fields from a relation in an
ordered manner base on some field.
Syntax: SELECT <set of fields> FROM
<relation_name> ORDER BY <field_name>;
Example: SQL> SELECT empno, ename, job FROM emp ORDER BY job;
JOIN using ORDER BY:This query is used to display a set of fields from two relations
by matching a common field in them in an ordered manner based on some fields.
Syntax: SELECT <set of fields (from both relations)> FROM relation_1, relation_2
WHERE relation_1.field_x = relation_2.field_y ORDER BY field_z;
Example: SQL> SELECT empno,ename,job,dname FROM
emp,dept WHERE emp.deptno = 20 ORDER BY job;
33
Objective:
To perform nested Queries and joining Queries using DML
command To understand the implementation of views.
Theory:
SUBQUERIES: The query within another is known as a sub query. A
statement containing sub query is called parent statement. The rows returned by
sub query are
used by the parent statement or in other words A subquery is a SELECT statement that is
embedded in a clause of another SELECT statement
You can place the subquery in a number of SQL clauses:
WHERE
clause
HAVING
clause FROM
clause
OPERATORS( IN.ANY,ALL,<,>,>=,<= etc..)
Types
1. Sub queries that return severalvalues
Sub queries can also return more than one value. Such results should be made use
along with the operators in and any.
2. Multiplequeries
Here more than one sub query is used. These multiple sub queries are combined
by means of ‘and’ & ‘or’ keywords.
3. Correlated subquery
A sub query is evaluated once for the entire parent statement whereas a
correlated Sub query is evaluated once per row processed by the parent
statement.
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more tables.
It is similar to a table but it does not store in the database. View is a query stored as
an object. Syntax: CREATE VIEW <view_name> AS SELECT <set of fields>
FROM relation_name WHERE (Condition)
Example:
SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM EMP
WHERE job = ‘clerk’;
SQL> View created.
Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID, ProductName
FROM Products
WHERE Discontinued=No;
UPDATING A VIEW : A view can updated by using the following syntax :
Syntax : CREATE OR REPLACE VIEW view_name
AS SELECT column_name(s)
FROM table_name
WHERE condition
DROPPING A VIEW: A view can deleted with the DROP VIEW command.
Syntax: DROP VIEW <view_name> ;
Index
Sr No List of Practical
4 Queue ADT.
5 Creation and display binary tree
Program 1
I. Create an array?
Algorithm:
1. Start
2. Select data-type of array
3. Create a variable of k size of data-type you want to create array
4. Store the elements in {} separated by ,
5. After your array is created print the array
6. Stop
Expected Output:
Show all the array
12245
Program:
Output:
II. Find address of an array?
Algorithm :
1. Start
2. Input an array from user
3. Take variable i=1
4. Check if i is less than size of array
5. Print value of array and use %p to print address of array
6. Set i to i+1 ,go to step 5
7. Stop
Expected Output:
Address of all elements of Array in hexadecimal value
Program:
Output:
III. Retrieve elements from array?
Algorithm:
To retrieve all elements from array:
1. Start
2. Input an array from user
3. Take variable i=0
4. Check if i is less than size of array
5. Print the array separated by a space
6. Update i to i+1, go to step 5
7. Stop
Expected Output:
All the elements of an array
Program:
Output:
Program 2: Linked list implementation of list ADT
Algorithm:
• Create a new node
• Stop
Expected Output:
First I should get my list without any data inserted and then, any number
which I will enter should be at the beginning of my new list.
Program:
• //This Program is copyrighted by Shreya_199129
• #include<stdio.h>
• #include<stdlib.h>
• struct node{
• int data;
• };
•
• ptr -> link = start;
start = ptr;
• return start;
• }
• if(start == NULL){
• printf("List is empty");
• }
• ptr = start;
• while(ptr != NULL){
• }
• }
• int main(){
•
• start -> data =30;
•
• struct node *current =(struct node*)(malloc(sizeof(s truct node*)));
•
• current -> data =45;
•
• struct node *now =(struct node*)(malloc(sizeof(struc t node*)));
•
• now -> data =60;
•
• display(start);
•
int data;
•
•
printf("\nEnter the new node: ");
•
• scanf("%d",&data);
•
start = join(start, data);
•
• current = start;
•
display(start);
•
•
return0;
•
• }
•
Output:
Algorithm:
1. Create a new node
2. Take the position and the value they want to insert
3. Traverse to the n-1th position and connect new node with n+ 1th
4. Now at last connect the n-1th node with the new node
5. Stop
Expected Output:
First I should get my list without any data inserted and then, any number which I
will enter should be at the given position of my new list.
Program
• //This Program is copyrighted by Shreya_199129
•
• #include<stdio.h>
• #include<stdlib.h>
•
• struct node{
• int data;
• struct node *next;
• };
• int display(struct node* p){
• while(p != NULL){
• printf("%d\n", p -> data);
• p = p -> next;
• }
• return0;
• }
• void add(struct node* head,int data,int pos){
• struct node *ptr = head;
• struct node *ptr2 = malloc(sizeof(struct node));
•
• ptr2 -> data = data;•
• ptr2 -> next = NULL;
•
• pos--;
•
• while(pos !=1){
•
• ptr = ptr-> next;
•
• pos--;
• }
•
• ptr2 -> next = ptr -> next;
•
• ptr -> next = ptr2;
•
• }
• int main(){
•
• struct node *a = NULL;•
• struct node *b = NULL;•
• struct node *c = NULL;
•
• a =(struct node*)(malloc(sizeof(struct node*)));•
• b =(struct node*)(malloc(sizeof(struct node*)));•
• c =(struct node*)(malloc(sizeof(struct node*)));
•
• a -> data =10;
• a -> next = b;
•
• b -> data =30;
• b -> next = c;
•
• c -> data =40;
• c -> next = NULL;
•
• printf("Linked List before insertion: \n");
• display(a);
•
• int data,placement;
• printf("\nHello this is @Shreya_In output \nEnter Data: ") ;
• scanf("%d",&data);
• printf("\nEnter Position(Keep it less than 5): ");
• scanf("%d",&placement);
• printf("\n");
• add(a, data, placement);
• struct node *ptr = a;
• printf("Linked List after insertion: \n");
• display(a);
• return0;
• }•
Output:
Program:
• //This Program is copyrighted by Shreya_199129
•
• #include<stdio.h>
• #include<stdlib.h>
• struct xyz{
• int data;
struct xyz*next;
• int display(struct xyz* p){
• while(p != NULL){
• printf("%d\n", p -> data);
• p = p -> next;
• }
• return0;
• }
•
• void delete_end(struct xyz* head){
• struct xyz *p1,*p2;
• if(head == NULL){
• printf("\nlist is empty");•}
• elseif(head -> next == NULL){
• head = NULL;
• free(head);
• }
• else{
• p1 = head;
• while(p1 -> next != NULL){
• p2 = p1;
• p1 = p1 -> next;
• }
• p2 -> next = NULL;
• free(p1);
• }
• p1 = NULL;
• }
•
• int main(){
• struct xyz *a = NULL;•struct xyz *b = NULL;•struct xyz *c = NULL;•struct xyz
*d = NULL;
• struct xyz *e = NULL;
•
• a =(struct xyz*)(malloc(sizeof(struct xyz*)));• b =(struct xyz*)
(malloc(sizeof(struct xyz*)));• c =(struct xyz*)(malloc(sizeof(struct xyz*)));• d
=(struct xyz*)(malloc(sizeof(struct xyz*)));
• e =(struct xyz*)(malloc(sizeof(struct xyz*)));
•
Output:
IV. Traversal
Algorithm:
1. Create a temporary variable for traversing. 2.
Starting node to is to say temp = start
3. Repeat below step till temp!= NULL.
4. temp->data contains the current node data
5. Print it
6. Once done, move to next node using temp = temp->agla;
7. Go to step 2nd
8. Stop
Expected Output:
Print whole new List with address.
Program:
• //This Program is copyrighted by Shreya_199129
• #include<stdio.h>
• #include<stdlib.h>
• struct xyz{
• int data;
• struct xyz *agla;
• };
• int show(struct xyz* p){
• while(p != NULL){
• printf("%d\t", p -> data);
• printf("%p\n", p -> agla);
• p = p -> agla;
• }
• return0;
• }
• int main(){
• struct xyz *a = NULL;•struct xyz *b = NULL;•struct xyz *c = NULL;
• struct xyz *d = NULL;
•
• a =(struct xyz*)(malloc(sizeof(struct xyz*)));• b =(struct xyz*)
(malloc(sizeof(struct xyz*)));• c =(struct xyz*)(malloc(sizeof(struct xyz*)));
• d =(struct xyz*)(malloc(sizeof(struct xyz*)));
•
• a -> data =5;
• a -> agla = b;
•
• b -> data =10;
• b -> agla = c;
•
• c -> data =15;
• c -> agla = d;
•
• d -> data =20;
• d -> agla = NULL;
•
• printf("Hello this is @Shreya_In output\n");
• show(a);
• return0;
• }
•
Output:
Program 3:
Algorithm:
Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the stack.
Step 3 - If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with
top. Display stack[i] value and decrement i value by one (i--).
Expected Output:
First I will display the elements using stack. After which I would pop the
elements using pop() function. Hence display the output.
Program:
//This Program is copyrighted by Shreya Srivastava_199129
#include<stdio.h>
#include<stdlib.h> int
n=10, top = -1, *storage;
void push(int x)
{ if(top==n) return;
storage[++top]=x;
} int
pop(){
Algorithm:
Step 1: Take two pointers Front and Rear.
Step 2: Initially set value of Front and Rear to -1.
enqueue() Operation:
dequeue() Operation:
Expected Output:
First inserted all the elements in the queue unless full. Now display all the elements of
Queue. After this delete an element from the Queue, and finally display the elements again.
Program:
//This Program is copyrighted by Shreya Srivastava_199129 include
<stdio.h> #define SIZE 7 void enqueue(int); void dequeue(); void
display();
int items[SIZE], front = -1, rear = -1; void
enqueue(int value) { if (rear == SIZE - 1)
printf("\nQueue is Full!!"); else { if
(front == -1) front = 0; rear++;
items[rear] = value;
printf("\nInserted value is -> %d", value);
}
} void dequeue() { if (front == -1)
printf("Queue is Empty!!"); else {
printf("\nFront will be Deleted i.e. %d", items[front]); front++; if (front > rear)
front = rear = -1;
}
}
void display() {
printf("\n\nHi this output is of Shreya Srivastava -"); if (rear ==
-1) printf("\nQueue is Empty!!!"); else { int i;
printf("\nQueue elements are:\n"); for
(i = front; i <= rear; i++) printf("%d ",
items[i]);
} printf("\n");
}
int main() { dequeue();
enqueue(13);
enqueue(26);
enqueue(39);
enqueue(52);
enqueue(65);
enqueue(78);
enqueue(91);
enqueue(104); display();
dequeue();
display(); return
0;
}
Output:
Program 5:
Algorithm:
Step1: Read a data in x.
Step 2: Allocate memory for a new node and store the address in pointer p.
Step 3: Store the data x in the node p.
Step 4: Recursively create the left subtree of p and make it the left child of p.
Step 5: Recursively create the right subtree of p and make it the right child of p.
Expected Output:
All the nodes created will be printed.
Program:
//This Program is copyrighted by Shreya Srivastava_199129
#include <stdio.h>
#include <stdlib.h>
struct node { int item;
struct node* left;
struct node* right;
}; void order(struct node* root) { if
(root == NULL) return; order(root-
>left); printf("%d ->", root->item);
order(root->right);
}
// Create a new Node
struct node* createNode(int value) {
// Create a new Node
struct node* createNode(int value) {
struct node* newNode = (struct node*)malloc(sizeof(struct node)); newNode-
>item = value; newNode->left = NULL; newNode->right = NULL; return
newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) { root->left = createNode(value);
return root->left;
}
// Insert on the right of the node
struct node* insertRight(struct node* root, int value) { root->right = createNode(value);
return root->right;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 2); insertRight(root, 3);
insertLeft(root->left, 4); insertLeft(root-
>right, 5);
printf("\nHi this output is of Shreya Srivastava - \n"); printf("Nodes are as follows \n");
order(root);
Output: