Page 2 :
CERTIFICATE, This is to certify that Mr./Ms.__________________________________, Seat Number ___________ of S.Y.B.B.A. (C.A) Sem-III has, successfully completed Laboratory course (Data structure, Angular, JS/PHP, Big Data/ Block Chain) in the year ____________________ ., He/She has scored _____mark out of 10 (For Lab Book)., , Subject Teacher, , Internal Examiner, , H.O.D./Coordinator, , External Examiner
Page 4 :
Introduction, 1. About the work book:, This workbook is intended to be used by S.Y.B.B.A. (C.A.) Semester-III students for, Data structure, Angular JS, PHP, Big data, Block chain Practical assignments. This, workbook is designed by considering all the practical topics mentioned in syllabus., 2. The objectives of this workbook are:, •, •, •, •, •, •, , Defining the scope of the course., To bring the uniformity in the practical conduction and implementation in all colleges, affiliated to SPPU., To have continuous assessment of the course and students., Providing ready reference for the students during practical implementation., Provide more options to students so that they can have good practice before facing the, examination., Catering to the demand of slow and fast learners and accordingly providing the, practice assignments to them., , 3. How to use this workbook:, The workbook is divided into five sections. Section-I is related to Data Structure, assignments, Section-II is related to Angular JS assignments, Section-III is related to, PHP assignments, Section-IV is related to Big Data assignments and Section-V is, related to Block Chain assignments., Section-I: Data Structure is divided into nine assignments., Section-II: Angular JS is divided into assignments., Section-III: PHP is divided into assignments., Section-IV: Big Data divided into assignments, Section-V: Block Chain divided into assignments., Students have to perform practical assignment of selected elective subject both from, Section-II or Section-III and from Section IV or Section V., Each assignment of all sections has three SETs-A, B and C. It is mandatory for students, to complete SET A and SET B in lab. It also includes practice programs which are, expected to be solved by students as home assignments and to be evaluated by subject, teachers., 4. Instructions to the students, Please read the following instructions carefully and follow them during practical., • Students are expected to carry this workbook every time they come to the lab for, computer practical., • Students should prepare for the assignment by reading the relevant material which is
Page 5 :
•, , •, , mentioned in ready reference and the concepts taught in class., Instructor will specify which problems to solve in the lab during the allotted slot and, student should complete them and get verified by the instructor. However, student, should spend additional hours in Lab and at home to cover all workbook assignments, if needed., Students will be assessed for each exercise on a scale from 0 to 5., , Notdone, Incomplete, Late Complete, Needs improvement, Complete, WellDone, , 0, 1, 2, 3, 4, 5, , 5. Instruction to the Instructors, Make sure that students should follow above instructions., • Explain the assignment and related concepts in around ten minutes using, whiteboard if required or by demonstrating the software., • Evaluate each assignment carried out by a student on a scale of 5 as specified, above by ticking appropriate box., • The value should also be entered on assignment completion page of the, respective Lab course., 6. Instructions to the Lab administrator, You have to ensure appropriate hardware and software is made available to each, student., The operating system and software requirements on server side and also client side are, as given below:, • Operating System - Windows, • Turbo C, • Java script, • WampServer, • RStudio
Page 6 :
Assignment Completion Sheet, , Section-I: Data Structure, Sr., No., , Assignment Name, , 1, , Array, , 2, , Sorting Techniques (Non Recursive), , 3, , Sorting Techniques (Recursive), , 4, , Searching Techniques, , 5, , Linked List, , 6, , Stack, , 7, , Queue, , 8, , Trees, , 9, , Graph, , Total ( Out of 45 ), Total (Out of 4), , Instructor Signature:, , Marks, (out of 5), , Teacher’s, Sign
Page 7 :
Section-II: Angular JS, Sr., No., , Assignment Name, , 1, , Introduction to Angular JS, AngularJS Directives ,, Expressions, Events, , 2, , AngularJS Modules, Controller, View and Scope, , 3, , Filter, Forms Validation, , 4, , AngularJS Services, , Marks, (out of 5), , Teacher’s, Sign, , Marks, (out of 5), , Teacher’s, Sign, , Total ( Out of 20 ), Total (Out of 3), , ‘OR’, Section-III: PHP, Sr., No., , Assignment Name, , 1, , Basics in PHP, , 2, , Control Structures and Loops, , 3, , Arrays and Strings, , 4, , Functions, Class, and Object, , 5, , Working With Form and form element, , 6, , Session and Cookies, , 7, , Database, , Total ( Out of 35 ), Total (Out of 3), , Instructor Signature:
Page 8 :
Section-IV: Big Data, Sr. No., , Assignment Name, , 1, , Basic R Programming, , 2, , Decision making and loop control structures, , 3, , Sting and Function in R Programming, , 4, , Vector and List in R Programming, , 5, , Array and Matrices in R Programming, , 6, , Factor and Data Frame in R Programming, , 7, 8, , Marks, (out of 5), , Teacher’s, Sign, , Data Analysis, Data Visualization, , Total ( Out of 40 ), Total (Out of 3), , ‘OR’, Section-V: Block Chain, Sr. No., , 1, , Assignment Name, Working with Blockchain, Implementation of Smart Contracts and, , 2, , Hyperledger, , Total ( Out of 10 ), Total (Out of 3), , Instructor Signature:, , Marks, (out of 5), , Teacher’s, Sign
Page 9 :
Section-I, , Data Structure
Page 10 :
Assignment No 1: Array (One Dimensional Array), ARRAY, ➢ An array is a finite ordered collection of homogeneous data elements which provide, random access to the elements., Finite: - There are specific no. of elements in the array., Ordered: - The elements are arranged one by one i.e. first then second and so on., Homogeneous: - All the elements are of same type., WHAT IS POYNOMIAL, ➢ A polynomial p(x) is the expression in variable x which is in the form (axn + bxn-1 + …. +, jx+ k), where a, b, c …., k fall in the category of real numbers and 'n' is non negative, integer, which is called the degree of polynomial., ➢ An essential characteristic of the polynomial is that each term in the polynomial, expression consists of two parts:, • one is the coefficient, • other is the exponent, EXAMPLE:, ➢ 10x2 + 26x, here 10 and 26 are coefficients and 2, 1 is its exponential value., Practice Program:, 1) Write a menu driven C program to perform the following operation on an integer array:, a) Display the sum of elements at even subscript position of array, b) Display the sum of elements at odd subscript position of array, 2) Write a C Program to find the largest pair sum in an unsorted array.(hint: find 2 maximum, elements from array and then find the sum of both numbers.), 3) Write a C Program to calculate Median of two sorted arrays of different sizes., SET A:, 1) Write a C Program to Count number of occurrences (or frequency) in a given sorted array, Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 2, Output: 4 // x (or 2) occurs 4 times in arr[], 2) Write a C program to accept n elements, store those elements in array and store the square, of these numbers in another array and display both the array., 3) Write a C program to Copy one array into another array., SET B:, 1) Write a C program accept the polynomial and display it in format e.g. 6x^4+2x^2+5x^1+3, 2) Write a ‘C’ program to accept n elements store those elements in array and find and replace, a given number., 3) Write a ‘C’ program to accept two polynomials and find the addition of accepted, polynomials., , 1
Page 11 :
SET C:, 1) Write a ‘C’ program to accept two polynomials and find the Multiplication of accepted, polynomials., Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], , Signature of Instructor, , 2
Page 12 :
Assignment No 2: Sorting Techniques (Non Recursive), SORTING, ➢ Sorting means arranging a set of data in some given order or ordering a list of items., ‘Or’, Sorting is a process of ordering a list of elements in either ascending or descending, order., ➢ List is a collection of record each contains one or more fields. The field which contains, unique value for each record is called key field., ➢ Definition:Sorting is the operation of arranging the records of a table according to the key value of, each record, e.g. consider a telephone directory which consists of 4 field phone number, name,, address, pin code ., So a large data is maintained in the form of records. If we want to search a phone no, and name it should be alphabetically sorted then we can search easily. It would be very, difficult if records were unsorted., ➢ The sorting algorithm are divided into two categories, 1) Internal sortingSorting is done on data which is sorted in main memory., 2) External sorting –, Sorting is done on data which is stored on auxiliary storage device., e.g. hard disk, floppy, tape etc., •, , BUBBLE SORT, ➢ This is one of the simplest and most popular sorting methods. The basic idea is to pass, through the file sequentially several times., ➢ In each pass we compare successive pairs of elements(x[i] with x[i+1]) and interchange, the two if they are not in the required order., ➢ One element is placed in its correct position in each pass., ➢ In first pass, the largest element will sink to the bottom, second largest in the second, pass and so on. Thus a total of n-1 passes are required to sort n keys, ➢ Time Complexity: Base Case: O(n), Worst Case: O(n2 ), Average Case: O(n2 ), Algorithm for Bubble sort:, Step1: Start, Step2: Accept ‘n’ numbers in array ‘A’, Step3: set i=0, Step4: set j=0, Step5: if j<n-i-1 then go to next stepelse go to step 8, Step 6: if i A[j+1] then interchange A[j] and A[j+1], Step7: j=j+1 and goto step 5, Step8: i=i+1 and goto step 4, Step9:Stop, 3
Page 13 :
•, , INSERTION SORT, ➢ Insertion sort inserts each item into its proper place in the final list, ➢ In this the first iteration starts with comparison of 1st element with 0th, ➢ In second iteration 2nd element is compared with the 0th and 1st element and so on., ➢ In every iteration an element is compared with all elements, ➢ The basic idea of this method is to place an unsorted element into its correct position in, a growing sorted list of data. We select one element from the unsorted data at a time, and insert it into its correct position in the sorted set., ➢ E.g. in order to arrange playing cards we pick one card at a time and insert this card, hold in the hand., ➢ Time Complexity: Base Case: O(n) Worst Case: O(n2 ) Average Case: O(n2 ), Algorithm for Insertion Sort:, Step1: Start, Step2: Accept ‘n’ numbers and store all in array ‘A’, Step3: set i=1, Step4: if i<=n-1 then goto next step else goto step 10, Step5: set Temp=A[i] and j=i-1, Step6: if Temp < A[j] && j>=0 then goto next step else goto step 9, Step7: set A[j+1]=A[j], Step8: set j=j-1, Step9: set A[j+1]=Temp, Step10: Stop, , •, , SELECTION SORT, ➢ It is also called pushdown sort., ➢ In this the largest or smallest element is selected by placing it repeatedly till it reaches, its proper position., ➢ The 0th element is compared with all other elements, if the 0th is found to be greater, than the compared element then they are interchanged . In this way after first iteration, the smallest element is placed at 0th position. The Procedure is repeated for 1st element, and so on., ➢ It is Simple to implement., ➢ The main advantage is that data movement is very less, ➢ It is not stable so. It is an in-place sort, ➢ Time Complexity: Base Case: O(n2 ) Worst Case: O(n2 ) Average Case: O(n2 ), Algorithm for Selection Sort, Step1: Start, Step2: Accept ‘n’ numbers and store all in array ‘A’, Step3: set i=0, Step4: if i <n-1 then goto next step else goto step 11, Step5: set min=i and j=i+1, 4
Page 14 :
Step6: if j< n then goto next step else goto step 9, Step7: if A[j]< A[min] then min=j, Step8: set j=j+1 and goto step 7, Step9: if(min not equal to i) then interchange A[i] and A[min], Step10: i=i+1 and goto step 4, Step11: Stop, Practice Programs:, 1) Write a C program to create a integer array with elements {56,23,11,67,12,89,2} and sort, the given array using bubble sort., 2) Write a C program to sort a random array of n integers (value of n accepted from user) by, using Bubble Sort / Insertion Sort algorithm in ascending order., 3) Write a C program to create a string array with 5 elements which contains word starting, with vowel and sort them using Selection sort., SET A:, 1) Write a C program to accept and sort n elements in ascending order by using bubble sort., 2) Write a C program to accept and sort n elements in ascending order by using insertion sort., 3) Write a ‘C’ program to accept and sort n elements in ascending order using Selection sort, method., SET B:, 1) Write a C program to create a string array with day of week and sort them using Insertion, sort., 2) Write a ‘C’ program to accept names from the user and sort in alphabetical order using, bubble sort., 3) Write a C program to accept and sort n elements in ascending order by using bubble sort, and also count the number of swaps. Display the sorted list and total no of swap count., SET C:, 1) Write a C program to read the data from the file “employee.txt” which contains empno and, empname and sort the data on names alphabetically (use strcmp) using Bubble Sort., 2) Write a C program to read the data from the file “person.txt” which contains personno and, personage and sort the data on age in ascending order using insertion Sort / Selection Sort., 3) Modify the bubble sort, insertion sort and selection sort program of Set A to sort the, integers in descending order?, Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], , Signature of Instructor, , 5
Page 15 :
Assignment No 3: Sorting Techniques (Recursive), QUICK SORT, ➢ It is also called “partition Exchange sort. The strategy used here is “divide and, conquer” i.e we successively partition the list in smaller lists and apply the same, procedure to the sub-list. The procedure is as follows:Procedure –, ➢ We will consider one element at a time (pivot) and place it in its correct position., ➢ The pivot is placed in a position such that all elements to the left of the pivot are less, than the pivot and all elements to the right are greater., ➢ The array is partitioned into two parts:- left partition and right partition., ➢ The same method is applied for each of the partition., ➢ The process continues till no more partition can be made. We shall be considering the, first element of the partition as the pivot element., Algorithm:, Step 1: start., Step 2: A is an array of n element., Step 3: lb=0, lb = lower bound, ub = n-1, ub = upper bound., Step 4: if(lb<ub), i.e. if the array can be partitioned, j=partition(A,lb,ub) // j is the pivot position, quicksort(A,lb,j-1);, quicksort(A,j+1,ub);, ➢ Now, we must write the function to partition the array. There are many methods to do the, partitioning depending upon which element is chosen as the pivot., ➢ We will be selecting the first element as the pivot element and do the partitioning, accordingly., ➢ We shall choose the first element of the sub- array as the pivot and find its correct position, in the sub- array., ➢ We will be using two variables down and up for moving down and up array., Algorithm for partitioning, Step 1: down=lb+1, Step 2: up=ub, Step 3: pivot=A[lb], Step 4: perform step 5 to 7 as long as down<up else go to step 8., Step 5: while (A[down]<=pivot && down<ub), down++;, Step 6: while (A[up]>pivot), up--;, Step 7: if (down<up), interchange A[down] and A[up], Step 8: interchange A[up] and pivot,, j=up, i.e. pivot position=up, 6
Page 16 :
Step 9: return up, Step 10: stop., ➢, ➢, ➢, ➢, ➢, , In this algorithm we want to find the position of pivot i.e. A[lb]., We use two pointers up and down initialized to the first and last elements respectively., We repeatedly increase down as long as the element is < pivot., We repeatedly decrease up as long as the element is > pivot., If up and down cross each other i.e. up<=down, the correct position of the pivot is up and, A[up and pivot are interchanged., ➢ If up and down do not cross A[up] and A[down] are interchanged and process is repeated, till they do not cross or coincide., ➢ Efficiency of quick sort., Best case = average case = O(nlogn), Worst case = O(n2), MERGE SORT., ➢ Merging is the process of combining two or more sorted data lists into a third list such, that it is also sorted., ➢ Merge sort follows Divide and Conquer strategy., - Divide :- divide an n element sequence into n/2 subsequence., - Conquer :- sort the two sequences recursively., - Combine :- merge the two sorted sequence into a single sequence., ➢ In this two list are compared and the smallest element is stored in the third array., Algorithm:Step 1: start, Step 2: initially the data is considered as a single array of n element ., Step 3: divide the array into n/2 sub-array each of length 2i (I is 0 for 0th iteration). i.e. array is, divided into n sub-arrays each of 1 element., Step 4: merge two consecutive pairs of sub-arrays such that the resulting sub-array is also, sorted., Step 5: The sub-array having no pairs is carried a sit is, Step 6: step 3 and 4 are repeated till there is only one sub-array remaining of size n., Step 7: stop., Practice Programs:, 1) Write a C program to create a integer array with elements {888,111,666,444,222,999,333}, and sort the given array using Merge sort., 2) Write a C program to sort a random array of n integers (value of n is accepted from user), by using quick Sort algorithm in ascending order., 3) Write a C program to sort a random array of n integers (value of n accepted from user) by, using merge Sort algorithm in ascending order, , SET A:, 1) Write a C program to accept and sort n elements in ascending order by using merge sort., 2) Write a C program to accept and sort n elements in ascending order by using quick sort., 7
Page 17 :
3) Modify the Quick sort program of SET A to sort the integers in descending order?, , SET B:, 1) Write a C program to create a string array with months (accept atleast 6 month) and sort, them using Quick sort., 2) Write a C program to create a string array with atlaest 5 elements which contains word, ending with ‘at’ and ‘an’ sound and sort them using Merge sort., 3) Modify the Merge sort program of Set B to sort the integers in descending order?, SET C:, 1) Write a C program to read the data from the file “person.txt” which contains personno,, name and personage and sort the data on age in ascending order using merge Sort., 2) Write a C program to read the data from the file “student.txt” which contains rollno, name, and age and sort the data on age in ascending order using quick Sort., 3) Read the data from the file student.txt and sort on names in alphabetical order (use strcmp), using Merge sort / Quick sort. Write the sorted data to another file 'sortstudentname.txt'., Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], , Signature of Instructor, , 8
Page 18 :
Assignment No 4: Searching Techniques, Searching is the process of finding a value in a list of values. The commonly used searching, methods used are linear search and Binary search., LINEAR SEARCH, ➢ In Linear search, we search an element or value in a given array by traversing the array, from the starting, till the desired element or value is found., ➢ Time Complexity: Base Case: O(1) Worst Case: O(n) Average Case: O(n), Algorithm for Linear Search:, Step 1: Start, Step 2: Accept n numbers in an array num and a number to be searched, Step 3: set i=0 and flag=0, Step 4: if i< n the goto next step else goto, Step 5: Compare num[i] and number If equal then set flag=1 and goto step 7, Step 6: i=i+1 and goto step 4, Step 7: if (flag=1) then Print “Required number is found at location i+1” else Print “Require data, not found”, Step 8: Stop, BINARY SEARCH, ➢ Binary Search is used with sorted array or list. So a necessary condition for Binary search, to work is that the list/array should be sorted. It works by repeatedly dividing in half the, portion of the list that could contain the item., ➢ Time Complexity: Base Case: O(1) Worst Case: O(log n) Average Case: O(log n), Algorithm for Binary search:, Step 1: Start, Step 2: Accept n numbers in an array num and a number to be searched, Step 3: set low=0, high=n-1 and flag=0, Step 4: if low <= high then middle=(low+high)/2 else goto step 7., Step 5: if (num[middle]=number) position=middle, flag=1 goto step 7. else if (number<, num[middle]) high=middle-1 else low=middle+1, Step 6: goto step 4, Step 7: if flag=1 Print “Required number is found at location position+1” Else Print “Required, number is not found., Step 8: Stop, Practice Programs:, 1) Write a C program to linearly search an element in a given array. (Use Recursion)., 2) Read the data from file ‘employee.txt’ containing names of n employees, their qualification, and salary. Accept a name of the employee from the user and by using linear search, algorithm check whether the name of employee is present in the file or not if present, display salary of that employee, otherwise display “Employee not found”., , 9
Page 19 :
3) Read the data from file ‘player.txt’ containing names of n Player, their game_played and, age. Accept a name of the player from the user and by using binary search algorithm check, whether the name of player is present in the file or not if present display game_played and, age of that player, otherwise display “player not found”., SET A:, 1) Write a C program to accept n elements from user store it in an array. Accept a value from, the user and use linear/Sequential search method to check whether the value is present in, array or not. Display proper message., 2) Write a C program to accept n elements from user store it in an array. Accept a value from, the user and use binary search method to check whether the value is present in array or not., Display proper message. (Students should accept sorted array and use Recursive function)., 3) Write a ‘C’ program to create a random array of n integers. Accept a value of n from user, and use Binary search algorithm to check whether the number is present in array or not., (Students should accept sorted array and use Non-Recursive function also use random, function)., SET B:, 1) Write a ‘C’ program to accept the names of cities and store them in array. Accept the city, name from user and use linear search algorithm to check whether the city is present in array, or not., 2) Write a C program to accept n elements from user store it in an array. Accept a value from, the user and use recursive binary search method to check whether the value is present in, array or not. Display proper message. (use any sorting method to sort the array), 3) Read the data from file ‘sortedcities.txt’ containing sorted names of n cities and their STD, codes. Accept a name of the city from user and use linear search algorithm to check, whether the name is present in the file and output the STD code, otherwise output “city not, in the list”., SET C:, 1) Write a C program to read the data from file 'cities.txt' containing names of 10 cities and, their STD codes. Accept a name of the city from user and use Binary search algorithm to, check whether the name is present in the file and output the STD code, otherwise output, “city not in the list”., 2) Write a C program to read the data from file 'student.txt' containing names of 10 students, and their roll no. Accept a name of the student from user and use Binary search algorithm, to check whether the name is present in the file and output the roll no, otherwise output, “Student name not in the list”., Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], Signature of Instructor, , 10
Page 20 :
Assignment No 5: Linked List, • Linked list:A linked list is an ordered collection of items which is dynamic in nature i.e. its size varies and, each item is ‘linked” or connected to another item. It is a linear collection of data elements, called nodes., •, , LINKED LIST IMPLEMENTATION-:, A linked list may be implemented in two ways:, 1) Static representation, 2) Dynamic representation., , 1) Static representation:An array is used to store the elements of the list. The elements may not be stored in a, sequential order. The correct order can be stored in another array called “link”, The values in this array are pointers to elements in the disk array., Data array, 0, Blue, 1, Red, 2, 3, Violet, 4, Green, 5, 6, Orange, Data[3] = violet, Data[0] = Blue, Data[4] = Green, Data[6] = Orange, Data[1] = Red, , 0, 1, 2, 3, 4, 5, 6, , Link array, 4, -1, 0, 6, 1, , Link[3] = 0, Link[0] = 4, Link[4] = 6, Link[6] = 1, Link[1] = -1 list end, , 2) Dynamic Representation:➢ The static representation uses arrays which is a static data structure and has its own, limitations., ➢ A linked list is a dynamic data structure i.e. the size should increase and when elements are, deleted, its size should decrease., ➢ This cannot be possible using an array which uses static memory allocation i.e. memory is, allocated during compile time. Hence we have to use “dynamic memory allocation” where, memory can be allocated and de-allocated during run-time., ➢ Another way of storing a list in memory is by dynamically allocating memory for each, node and linking them by means of pointers since each node will be at random memory, location. We will need a pointer to store the address of the first node., , 11
Page 21 :
list=3, violet, , 0, , Blue, , 4, , Green, , 6, , orange, , red, , 1, , NULL, , List is an external pointer which stores the address of the first node of the list., •, , TYPES OF LINKED LIST, , 1), 2), 3), 4), , Singly Linked list, Circular linked list, Doubly linked list, Circular doubly linked list, Linked list, , Linear, Singly linked list, , Circular, , Doubly linked list, , Singly linked list, , Doubly linked list, , 1) Linear linked list, In this list the elements are organized in a linear fashion and list terminates at some point, i.e. the last node contains a NULL pointer., list, , Data, , next, , Data, , next, , node, , Data NULL, NULL, , node, , node, , ➢ Singly linked listEach node in this list contains only one pointer which points to the next node., Data, , next, , list, Data, , next, , Data, , next, , Data, , NULL, NULL, , ➢ Doubly linked list, Each node in this contains two pointers, one pointing to the previous node and the other, pointing to the next node. This list is used when traversing in both directions is required., Prev, data, next, 12
Page 22 :
Prev, NULL, , list, , data, 10, , next, , Prev, , 200, , 100, , data, , 20, , next, , 300, , Prev, 200, , 30, , data, , next, , NULL, , NULL, , 100, , 200, , 300, , 2) Circular list, In this list, the last node does not contain a NULL pointer but points back to the first node, i.e. it contains the address of the first node. Each of these lists can be either a singly linked or a, doubly list., Circular singly linked list, , Prev, , Data, , next, , data, , next, , Data, , next, , Data, , next, , List, , Circular doubly linked list, , •, , OPERATIONS ON A LIST, The following are some of the basic list operations:1) Traversing a list:Visiting each node of the list is called traversal, 2) Insertion:A node can be inserted at the beginning, end or in between two nodes of the list., 3) Deletion:Deletion from a list may be done either position-wise or element-wise, 4) Display:Display each element of the list., 5) Searching:This process searches for a specific element in the list., 6) Reversing or inversion:This process reverses the order of nodes in the list, 7) Concatenation:This process appends the nodes of the second list at the end of the first list i.e. it joins two, lists., 8) Computation of length:Count the total no. of nodes in the list, 9) Creating a linked list, 10) Intersection, union, difference., 13
Page 23 :
Practice Programs:, 1) Write a C Program to find largest element of doubly linked list., 2) Write a C Program to interchange the two adjacent nodes in given circular linked list., 3) Write C Program to find length of linked list without using recursion., 4) Write C Program to print alternative nodes in linked list using recursion., SET A:, 1) Write a C program to implement a singly linked list with Create and Display operation., 2) Write a C program to implement a Circular Singly linked list with Create and Display, operation., 3) Write a C program to implement a doubly linked list with Create and Display operation., 4) Write a C program to implement a Circular doubly linked list with Create and Display, operation, SET B:, 1) Implement the following programs by adding the functions one by one in SET A(Question1), i) To count total number of nodes and display the count., ii) To insert node at the start., iii) To reverse the Linked List and display both the list., 2) Write a Menu driven program in C to implement the following functions:, i), To search the number in the list. If the number is present display the Position of, node .If number not present print the message “Number not Found”, ii), To swap mth and nth element of linked list., iii), To delete node from specific position of linked list., 3) Write a ‘C’ program to sort elements of a singly linked list in ascending order and display, the sorted List., 4) Write a ‘C’ program to create doubly link list and display nodes having odd value., SET C:, 1) Write a C program to find intersection of two singly linked lists., 2) Write a C program to divide a singly linked list into two almost equal size lists., Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], Signature of Instructor, , 14
Page 24 :
Assignment No 6: Stack, A stack is an ordered collection of items into which items may be inserted and deleted from, one end called the top of the stack., The stack operates in a LIFO (last in first out) manner. i.e. the element which is put in last is the, first to come out. That means it is possible to remove elements from stack in reverse order from the, insertion of elements into the stack., The real life e.g. of the stack are stack of coins, stack of dishes etc. only the topmost plate can be, taken and any new plates has to be put at the top., • PRIMITIVE OPERATIONS ON A STACK., 1) Create, 2) Push, 3) Pop, 4) Isempty, 5) Isfull, 6) Peek, •, 1), ➢, ➢, ➢, ➢, ➢, , STACK IMPLEMENTATION:The stack implementation can be done in two ways:Static implementation:It can be achieved using arrays. Though it is very simple method it has few limitations., Once a size of an array is declared, its size cannot be modified during program execution., The vacant space of stack also occupies memory space., In both cases, if we store less argument than declared, memory is wasted and if we want to, store more elements than declared array cannot be expanded. It is suitable only when we, exactly know the number of elements to be stored., Operations on static stack:1) Declaring of a stack :A stack to be implemented using an array will require., - An array of a fixed size., - An integer called top which stored the index or position of the topmost element., We can use a structure for the above purpose., 2) Creating a stack:This declaration only specifies the template. The actual stack can be declared asSTACK s1;, 3) initialize a stack:When a stack variable is declared the integer top has to be initialized to indicate an empty, stack. Since we are using an array the first element will occupy position 0. Hence to, indicate an empty stack top has to be initialized to -1, 4) Checking whether stack is empty:An empty stack can be tested from the value contained in top. If top contains -1 it, indicates an empty stack., 5) Checking whether stack is full:If the value of top reaches the maximum array index i.e. MAX-1 no more elements can be, pushed into the stack., 6) The push operation:15
Page 25 :
2), ➢, ➢, ➢, ➢, ➢, ➢, ➢, ➢, ➢, , The element can be pushed into the stack only if it is not full. In such case the top has to be, incremented first and the element has to be put in this position., 7) The pop operation:, An element can be removed from the stack if it is not empty. The topmost element can be, removed after which top has to decremented, 8) The peek operation:, It displays the topmost element of the stack without decrementing the top., Dynamic implementation:Pointers are used for implementation of stack. The linked list is an e.g. of this, implementation., The limitations noticed in static implementation can be removed using dynamic, implementation. The dynamic implementation is achieved using pointers., Using pointer implementation at runtime there is no restriction on the no. of elements. The, stack may be expandable., The memory is efficiently utilized with pointers., Memory is allocated only after element is pushed to the stack, In static representation there is a limitation on the size of the array if less elements are, stored, memory will be wasted. To overcome the program the stack can be implemented, using linked list., In the linked organization, - The stack can grow to any size., - We need not have prior knowledge of the number of elements., When an element is popped the memory can be freed. Thus memory is not unnecessary, occupied., Since random access to any element is not required in a stack, the linked representation is, preferred over the sequential organization., , Applications of Stack, 1) Inter conversion between infix, postfix and prefix expression., 2) Evaluating the postfix expression., 3) Reversing a string., 4) Reversing each word of the string and many more, There are 3 notations for specifying the operands:1) Infix :- if the operator symbols are placed between the operands then the expression, is in the infix notation (a+b)*c, 2) Postfix :- if the operator symbols are placed after its operands, then the expression is, in postfix notation., ab+c*, 3) Prefix :- if the operator symbols are placed before its operands, then the expression is, in prefix notation. *+abc, , 16
Page 26 :
Associativity and Precedence rule, Operator, , Precedence, , Associativity, , {},[].(), , High, , L-R, , ^ exponent, , High, , R-L e.g. 3^2^2, =3^4=81, , Mul/div *,/, , Intermediate, , L-R, , +,-, , Low, , L-R, , EVALUATE POSTFIX EXPRESSION:, Algorithme, 1) Scan the string from Left to right, 2) If symbol = = digit then push symbol in the stack., 3) If symbol = = operator then pop 2 elements from stack, Put first pop element in operand2, Put second pop element in operand1, Evaluate the value (operand1 operator operand2) and put the evaluated answer, in result, 4) Push the result in the stack, 5) After all the symbol are finished from symbol column pop the last element from the stack, which will be the final result of the postfix expression, INFIX TO POSTFIX CONVERSION, Algorithm, 1) Scan the string from left to right, 2) If symbol = = opening bracket push in stack, 3) If symbol = = closing bracket pop all the elements from stack till we get opening bracket,, pop the opening bracket also and then put the pop elements in the postfixstring leaving, opening bracket., 4) If symbol = = alphabet/ digit then put the symbol in postfixstring, 5) If symbol = = operator check priority of top element in the stack., If priority( top element)>= priority(symbol operator) then pop top element and put it in, postfixstring, If priority( top element)< priority(symbol operator) then push the symbol in the stack, 6) Repeat steps 2-5 until infix expression is scanned., 7) Print the output i.e. postfixstring, INFIX TO PREFIX CONVERSION, Algorithm, 1) Scan the string from right to left, 2) If symbol = = Closing bracket push in stack, 17
Page 27 :
3) If symbol = = opening bracket pop all the elements from stack till we get opening bracket,, pop the closing bracket also and then put the pop elements in the Prefixstring leaving, closing bracket., 4) If symbol = = alphabet/ digit then put the symbol in Prefixstring, 5) If symbol = = operator check priority of top element in the stack., If priority( top element)> priority(symbol operator) then pop top element and put it in, Prefixstring, If priority( top element)<= priority(symbol operator) then push the symbol in the stack, 6) Repeat steps 2-5 until infix expression is scanned., 7) Print the output i.e. print Prefixstring in reverse, , STRING REVERSE AND CHECKING PALINDROME STRING:, A string of characters can be reversed by reading each character from a string starting from the, first index and pushing it on a stack. Once all the characters have been read, the characters can be, popped one at a time from the stack and then stored in the another string starting from the first, index., Algorithm to reverse the string:, 1) Read the string character by character., 2) Push every character into the stack of characters., 3) When string becomes empty pop every character from stack and attach to the new string., Algorithm to check palindrome of string:, 1) Read the string character by character., 2) Push every character into the stack of characters., 3) When string becomes empty pop every character from stack and attach to the new string., 4) Compare original and reversed string if it matches string is palindrome else it is not, palindrome, Practice Programs:, 1) Let stack_ptr be a pointer to stack of integers and item be an integer variable., Write function like Push, Pop, Initialize, Empty, and Full for doing the following tasks., [You may declare additional variable in your functions in needed]., a. Return the top element of stack and leave the top element unchanged. If the stack is, empty, return INT_MAX., b. Return the third element from the top of the stack, provided that the stack contains, at least three integers. If not, return INT_MAX. Leave the stack unchanged., c. Return the bottom element of stack (or INT_MAX if stack empty), and leave the, stack unchanged., 2) Given an expression string exp, write a C program to examine whether the pairs and the, orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp., Example:, Input: exp = “[()]{}{[() ()]()}”, Output: Balanced, , 18
Page 28 :
Input: exp = “[(])”, Output: Not Balanced, 3) Write a C Program to solve Tower Of Hanoi Problem (Use Recursion)., 4) Write a C Program to sort a stack using temporary stack., SET A:, 1) Write a C program to implement Static implementation of stack of integers with following, operation:, -Initialize(), push(), pop(), isempty(), isfull(), display(), 2) Write a C program to implement Dynamic implementation of stack of integers with, following operation:, -Initialize(), push(), pop(), isempty(), display()., 3) Write a C program to reverse each word of the string by using static and dynamic, implementation of stack., Example: Input - This is an input string, Output – sihT si na tupni gnirts, SET B :, 1) Write a ‘C’ program which accepts the string and check whether the string is Palindrome or, not using stack. (Use Static/Dynamic implementation of Stack)., 2) Write a ‘C’ program to read a postfix expression, evaluate it and display the result. (Use, Static/Dynamic implementation of Stack)., 3) Write a ‘C’ program to accept an infix expression, convert it into its equivalent postfix, expression and display the result. (Use Static/Dynamic implementation of Stack)., SET C:, 1) Write a program to check whether the contents of two stacks are identical., 2) Write a program that copies the contents of one stack into another. The order of two stacks, must be identical.(Hint: Use a temporary stack to preserve the order)., 3) Write a ‘C’ program to accept an infix expression, convert it into its equivalent prefix, expression and display the result. (Use Static/Dynamic implementation of Stack)., , Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], , Signature of Instructor, , 19
Page 29 :
Assignment No 7: Queue, A queue is an ordered collection of items from which items may be deleted from (or removed, from ) one end called the front and into which items may be inserted at the other end called rear., ➢ BASIC OPERATIONS ON QUEUE, 1) Create:, Create a new queue. This operation creates an empty queue., 2) Add or insert:, Add an element to the queue. A new element can be added to the queue at, the rear., 3) Delete:, Remove an element from the queue. This operation removes the elements,, which is at the front of the queue. This operation can only be performed if the queue is, not empty., The result of an illegal attempt to remove an element from an empty queue, is called underflow., 4) isempty:, Check whether a queue is empty. The operation return true if the queue, isempty and false otherwise, 5) isfull:, Check whether a queue is full. The operation return true if the queue isfull and, false otherwise, ➢ REPRESENTATION OF LINEAR QUEUES., There are two ways to represent a queue in memory., 1) Static (using an array), 2) Dynamic (using an linked list), 1) Static implementation of queue, Static implementation or array representation of queue requires three, entities- An array to hold queue elements., - A variable to hold the index of the front element., - A variable to hold the index of the rear element., The implementation of a queue using sequential representation is done by using, some size MAX and two integer variable front and rear. Initially front and rear is, set to -1. Whenever new element is added it is added from the rear and whenever an, element is to be removed from the front. The queue full condition is when rear, reaches to MAX - 1. Queue empty condition is when front is equal to rear., 2) Dynamic implementation of linear queue (using an linked list), A queue can be considered as a list in which all insertions are made at one end called the, rear and all deletions from the other end from front., , 20
Page 30 :
A queue can be easily represented using a linked list. The front and rear will be two, pointers pointing to the first and last node respectively., Practice Programs:, 1) Write a C program to Implement Static implementation of circular queue of integers which, includes operation as: a) Initialize() b) insert() c) delete() d) isempty() e) isfull() f) display(), g) peek(), 2) Write a C program to Implement Dynamic implementation of circular queue of integers, includes operation as : a)Initialize() b) insert() c)delete() d) isempty() e)display() f) peek(), 3) Write a C Program to implement Deque using doubly linked list, SET A:, 1) Write a C program to Implement Static implementation of Queue of integers with, following operation:, -Initialize(), insert(), delete(), isempty(), isfull(), display(), peek(), 2) Write a program to reverse the elements of a queue (Use Static implementation of Queue), SET B:, 1) Write a C program to Implement Dynamic implementation of Queue of integers with, following operation:, -Initialize(), insert(), delete(), isempty(), display(), peek(), 2) Write a program to reverse the elements of a queue (Use Dynamic implementation of, Queue), 3) Write a C program to Implement Static implementation of circular queue of integers with, following operation:, -Initialize(), insert(), delete(), isempty(), isfull(), display(), peek(), SET C:, 1) Write a c program to simulate waiting list operations of railway reservation system., 2) Implement a priority of integers using a static implementation of the queue and, implementing the below two operations. Write a menu driven program, a) Add an element with its priority into the queue., b) Delete an element from queue according to its priority., 3) A doubly ended queue allows additions and deletions from both the ends that is front and, rear. Initially additions from the front will not be possible. To avoid this situation, the array, can be treated as if it were circular. Implement a queue library (dstqueue.h) of integers, using a static implementation of the circular queue and implementing the nine operations :, 1)init(Q), 2) isempty(Q) 3) isFull(Q) 4)getFront(Q), 5)getRear(Q), 6)addFront(Q,x),, 7)deleteFront(Q) 8) addRear(Q,x) 9)deleteRear(Q), Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: Well Done [ ], Signature of Instructor, , 21
Page 31 :
Assignment No 8: Tree, Definition of tree:A tree is a finite set of one or more nodes such that:- there is a specially designated node, called the root. The remaining nodes are partitioned into n>=0 disjoint sets T1……Tn, where each of these sets is a tree. T1…..Tn are called as sub-trees of the root., Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties• The value of the key of the left sub-tree is less than the value of its parent (root) node's key., • The value of the key of the right sub-tree is greater than or equal to the value of its parent, (root) node's key., •, The left and right sub tree each must also be a binary search tree., Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and, can be defined as – left_subtree (keys) < node (key) ≤ right_subtree (keys), The operations on binary search tree are, init (T), – creates an empty Binary search tree by initializing T to NULL, insert (T, x) – inserts the value x in the proper position in the Binary search tree, search (T, x) – searches if the value x is present in the search tree, inOrder (T) – displays the node using inorder traversal of binary search tree, postOrder (T) – displays the node using postorder traversal of binary search tree, preOrder (T) – displays the node using preorder traversal of binary search tree, Practice Programs:, 1) Write a C program to find all the ancestors of a given node in a binary tree., 2) Write a C program to implement binary search tree so that it handles duplicate keys, properly. That is, if a key is already in the tree then the new value should replace the old, rather than adding another node with the same key., 3) Write a C program to create binary search tree of integers and perform following, operations using non- recursive functions, - Preorder traversal, - Inorder traversal, - Postorder traversal, SET A:, 1) Write C programs to implement create and display operation for binary tree., 2) Write C programs to implement create and display operation for binary search tree., 3) Write a C Program to find the product of all leaf nodes of a binary tree, SET B:, 1) Write a C Program to implement the following functions on Binary Search Tree, - To insert a new element in the tree., - To search an element in tree and give the proper message., 2) Write a C Program to implement the following functions on Binary Search Tree, - To create mirror image of the tree., 22
Page 32 :
- To count non-leaf nodes., 3) Write a C Program to implement the following functions on Binary Search Tree, - To count leaf nodes., - To count total number of nodes., SET C:, 1) Write C programs to create and display the elements using Inorder traversal., 2) Write a C program to create binary search tree of integers and perform following operations: - Preorder traversal, - Postorder traversal, Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: WellDone [ ], , Signature of Instructor, , 23
Page 33 :
Assignment No 9: Graph, A graph consists of a set of vertices and a set of edges. The two main ways of representing, graphs are adjacency matrix representation and adjacency list representation. In adjacency matrix, representation of a Graph with n vertices and e edges, a two dimensional nxn array , say a , is used, , with the property that a[i,j] equals 1 if there is an edge from i to j and a[i,j] equals 0 if there is no, edge from i to j., In adjacency list representation of a graph with n vertices and e edges, there are n linked, lists, one list for each vertex in the graph., The usual operations on graph are:, Indegree(i) – returns the indegree (the number of edges ending on) of the ith vertex, Outdegree(i) – returns the outdegree(the number of edges moving out) of the ith vertex, displayAdjMatrix – displays the adjacency matrix for the graph, Practice Programs:, 1) Write a C Program to count the number of edges in an undirected graph., 2) Write a C Program to trace all the paths of a directed graph from the given source node to, the destination node .Given the adjacency representation of a directed graph, find all the, paths of the graph from source to destination., 3) Write a c program to find whether cycle in present in graph (use Directed graph), SET A:, 1) Write a C program to read a graph as adjacency matrix and display the adjacency matrix., 2) Write a C program to display total degree of each vertex., 3) Write a C program to display Indegree and outdgree degree of each vertex., SET B:, 1) Write a C program to convert adjacency matrix into adjacency list. Display the adjacency, list., 2) Write a C program to traverse graph by using BFS., 3) Write a C program to traverse graph by using DFS., SET C:, 1) Implement a program to read a graph as adjacency matrix. Find the transpose of the matrix, for display accepted adjacency Matrix and Adjacency Matrix and List of transpose of the, matrix., Assignment Evaluation, 0: Not Done [ ], 3: Needs Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [ ], 5: WellDone [ ], , Signature of Instructor, 24
Page 35 :
Assignment 1: Introduction to Angular JS, AngularJS Directives ,Expressions,, Events, What is AngularJS?, • AngularJS is an Open Source efficient JavaScript framework that can create Rich Internet, Applications (RIA) and provides developers an options to write client side applications, using JavaScript in a clean Model View Controller (MVC) way., • It is perfect for Single Page Applications (SPA) and the applications written in AngularJS, are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for, each browser., • Famous websites using AngularJS, , ENVIRONMENT, ◼ Download angular js file from : https://angularjs.org/, ◼ Give File name: angular.min.js or any name as u wish., ◼ Save in your folder, ◼ Develop angularJS first application., <html>, First.html, <head>, <title>AngularJS First Application</title>, </head>, <body> <h1>Sample Application</h1>, <div ng-app = "">, <p>Enter your Name: <input type = "text" ng-model =, "name"></p>, <p>Hello <span ng-bind = "name"></span>!</p>, </div>, <script src = "D:\satish\AngularJS\angular.min.js">, </script>, </body>, </html>, Expressions: In AngularJS, expressions are used to bind application data to HTML. AngularJS, resolves the expression, and return the result exactly where the expression is written. Expressions, are written inside double braces {{expression}}.They can also be written inside a directive: ngbind="expression"., Example 1: Simple AngularJS Script to add two numbers., <html>, <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>, <body>, <div ng-app>, <p>A simple expression example: {{ 5 + 5 }}</p>, </div>, </body>, 1
Page 37 :
Example :, <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},, {locale:'en-GB',name:'United Kingdom'},, {locale:'en-FR',name:'France'}]">, </div>, ng-model directive, The ng-model directive defines the model/variable to be used in AngularJS Application. In the, following example, we define a model named name., <div ng-app = "">, <p>Enter your Name: <input type = "text" ng-model = "name"></p>, </div>, ng-repeat directive, The ng-repeat directive repeats HTML elements for each item in a collection, Example, The following example shows the use of all the above-mentioned directives., <html>, <head>, <title>AngularJS Directives</title>, </head>, <body>, <h1>Sample Application</h1>, <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},, {locale:'en-GB',name:'United Kingdom'},, {locale:'en-FR',name:'France'}]">, <p>Enter your Name: <input type = "text" ng-model = "name"></p>, <p>Hello <span ng-bind = "name"></span>!</p>, <p>List of Countries with locale:</p>, <ol>, <li ng-repeat = "country in countries">, {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}, </li>, </ol>, </div>, <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">, </script>, </body>, </html>, , 3
Page 38 :
AngularJS Directives List, Directive, Description, Directive, It defines the root element of an, ng-app, ng-readonly, application., It binds the content of an html, ng-bind, ng-required, element to application data., It specifies a behavior on blur, ng-blur, ng-selected, events., It specifies an expression to, ng-change evaluate when content is being, ng-show, changed by the user., ngIt specifies if an element is checked, ng-src, checked, or not., It specifies an expression to, ng-click, evaluate when an element is being, ng-submit, clicked., ngcontroller, ng-copy, ng-cut, ngdblclick, ng-focus, ng-hide, ng-href, ng-if, nginclude, ng-init, ngkeydown, ngkeypress, ng-keyup, , ng-switch, , It specifies a behavior on copy, events., It specifies a behavior on cut, events., It specifies a behavior on doubleclick events., It specifies a behavior on focus, events., It hides or shows html elements., It specifies a URL for the <a>, element., It removes the html element if a, condition is false., It includes html in an application., It defines initial values for an, application., It specifies a behavior on keydown, events., It specifies a behavior on keypress, events., It specifies a behavior on keyup, events., It converts text into a list (array)., , ng-open, , It specifies the open attribute of an, element., , It shows or hides html elements., It specifies the src attribute for, the <img> element., It specifies expressions to run on, onsubmit events., , It specifies a condition that will, be used to show/hide child, elements., It specifies the value of an input, ng-value, element., It specifies if an element is, ng-disabled, disabled or not., It specifies an html form to, ng-form, inherit controls from., It binds the value of html, ng-model, controls to application data., ngIt specifies a behavior on, mousedown, mousedown events., ngIt specifies a behavior on, mouseenter, mouseenter events., ngIt specifies a behavior on, mouseleave, mouseleave events., ngIt specifies a behavior on, mousemove, mousemove events., It specifies a behavior on, ng-mouseover, mouseover events., It specifies a behavior on, ng-mouseup, mouseup events., It defines a template for each, ng-repeat, data in a collection., It specifies <options> in a, ng-options, <select> list., It specifies a behavior on paste, ng-paste, events., , It defines the controller object for, an application., , ng-list, , Description, It specifies the readonly attribute, of an element., It specifies the required attribute, of an element., It specifies the selected attribute, of an element., , 4
Page 40 :
2) Write angular JS by using ng-click Directive to display an alert message after clicking the, element., 3) Using angular js display the 10 student details in Table format (using ng-repeat directive use, Array to store data ), SET C:, 1) Write a HTML code using Angular JS to generate the following output, Undergraduate Courses (hint : use ng-repeat, ng-init directive), i. BBA(CA), ii. BCA(Science), iii. B.Sc.(Computer Science), Post Graduate Courses, i. M.Sc.(Comp.Sci.), ii. M.Sc.(CA), iii. MCA, 2) Write an AngularJS script to print details of bank (bank name, MICR code, IFC code, address, etc.) in tabular form using ng-repeat., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 6
Page 41 :
Assignment 2: AngularJS Modules, Controller, View and Scope:, , 1., 2., 3., , 4., 5., 6., 7., 8., 9., , MVC Architecture, • MVC – (Model View Controller) is a Software design pattern, for developing web applications. It is very popular because it, isolates the application logic from the user interface layer and, supports separation of concerns., ◼ Model: It is responsible for managing application data. It, responds to the requests from view and to the instructions from controller to update itself., ◼ View: It is responsible for displaying all data or only a portion of data to the users. It also, specifies the data in a particular format triggered by the controller's decision to present the, data., ◼ Controller: It is responsible to control the relation between models and views. It responds, to user input and performs interactions on the data model objects. The controller receives, input, validates it, and then performs business operations that modify the state of the data, model., In AngularJS controllers are used to control the flow of data of AngularJS application. A, controller is defined using ng-controller directive. A controller is a JavaScript object containing, attributes/properties and functions. Each controller accepts $scope as a parameter which refers to, the application/module that controller is to control. The scope is the binding part between the, HTML (view) and the JavaScript (controller). The scope is an object with the available properties, and methods and is available for both the view and the controller., <html>, Here, the AngularJS application runs inside, <script, the <div> is defined by ng-app="myApp"., and the AngularJS directive is ngsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/ controller="myCtrl" attribute., angular.min.js">, </script>, The myCtrl function is a JavaScript function., <body>, AngularJS will invoke the controller with a, <div ng-app="myApp" ng-controller="myCtrl">, $scope object., First Name: <input type="text" ngmodel="firstName"><br>, The controller creates two properties, Last Name: <input type="text" ng(variables) in the scope (firstName and, model="lastName"><br>, lastName)., <br>, Full Name: {{fullName()}} <!—Function Calling -The ng-model directives bind the input fields, >, to the controller properties (firstName and, </div>, lastName)., <script> var app = angular.module('myApp', []);, app.controller('myCtrl', function($scope) {, 1) View, which is the HTML., $scope.firstName = "Satish";, 2) Model, which is the data available for, $scope.lastName = "Mulgi";, the current view., $scope.fullName = function() {, 3) Controller, which is the JavaScript, return $scope.firstName + " " + $scope.lastName;, function that, 7
Page 44 :
</body>, </html>, Practice Problems:, 1), Using angular js create a SPA to display the student information in well formatted, form(use CSS), 2), Create Simple AngularJS Script to Print Student Marks card with grade, 3), Using angular js create a SPA to display the Pune Univercity information in well, formatted., SET A:, 1. Using angular js create a SPA that to accept the details of Employee(5-6) having field’s, eno, ename, address, and salary number. Display those in table format. (use MVC.), 2. Using Angular JS Create a SPA to take the information of a customer for booking Ticket, consisting of fields such as name, address, contact no., gender, Date of booking, date of, journey, name of passengers etc. Display the e –Ticket., 3. Using angular js Create a SPA that show Syllabus content of all subjects of SY BBA, (CA)(use ng-view), SET B:, 1) Using Angular JS Create a SPA for Bus Ticket Reservation consisting of fields : Name,, Address, contact no, source station(Dropdown list), Destination station(Dropdown list),, Date of booking, date of journey, name of passenger, gender of passenger etc. Display the, e –Ticket., 2) Create an HTML form using Angular JS that contain the Employee Registration details, and validate DOB, Joining Date, and Salary and also create a simple arithmetic calculator, using radio buttons (use ng-switch, ng-switch-when), 3) Using angular js create a SPA that shows Teacher Profile who is teaching SY BBA (CA), with photo, SET C:, 1) Using angular js create a SPA to display the details of product (srNo,Name, Price,, quantity) available in the departmental stores., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 10
Page 45 :
Assignment 3: Filter, Forms Validation., AngularJS filters are used to format data, Following is a list of filters used for transforming data., currency: Format a number to a currency, lowercase : Format a string to lower case., format., number : Format a number to a string., date : Format a date to a specified format., orderBy : Orders an array by an expression., filter : Select a subset of items from an array. uppercase : Format a string to upper case., limitTo : Limits an array/string, into a, json: Format an object to a JSON string., specified number of elements/characters., Adding Filters to Expressions, Filters can be added to expressions by using the pipe character |, followed by a filter. case:, Example 1 : The uppercase filter format strings, to upper, < <div ng-app="myApp" ngcontroller="personCtrl">, <p>The name is {{ lastName |uppercase, }}</p>, </div>, <script>, var app = angular.module('myApp', []);, app.controller('personCtrl', function($scope) {, $scope.lastName ="Satish Mulgi";, });, </script>, , Example 2 : The lowercase filter format strings, to lower, <div ng-app="myApp" ngcontroller="personCtrl">, <p>The name is {{ lastName | lowercase, }}</p>, </div>, <script>, var app = angular.module('myApp', []);, app.controller('personCtrl', function($scope) {, $scope.lastName ="Satish Mulgi";, });, </script>, , Adding Filters to Directives, Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:, Example 3 : The orderBy filter sorts an Example 6: Date, array:, <html><script, <html>, src="https://ajax.googleapis.com/ajax/libs/angularjs, <script, /1.4.8/angular.min.js"></script> <body>, src="https://ajax.googleapis.com/ajax/libs/ <div ng-app="myApp" ng-controller="datCtrl">, angularjs/1.6.9/angular.min.js">, <p><strong>The following date format is the by, </script>, default date format.</strong> </p>, <body>, <p>Date = {{ today | date }}</p>, <div ng-app="myApp" ng<p><strong>You can write the date in many, controller="namesCtrl">, different formats.</strong></p>, <p>Looping with objects:</p>, <p>Date = {{ today | date : "dd.MM.y" }}</p>, <ul>, <p><strong>You can use predefinted formats, <li ng-repeat="x in names |, when displaying a date.</strong></p>, orderBy:'country'">, <p>Date = {{ today | date : "fullDate" }}</p>, {{ x.name + ', ' + x.country }}, <p><strong>This is another format.</strong></p>, </li>, <p>Date = {{ today | date : "'today is ' MMMM d,, </ul>, y" }}</p> </div>, </div>, <script>, var app = angular.module('myApp', []);, <script>, app.controller('datCtrl', function($scope) {, angular.module('myApp',, $scope.today = new Date();, []).controller('namesCtrl', function($scope) }); </script> </body> </html>, 11
Page 47 :
Form Validation, AngularJS offers client-side form validation. AngularJS monitors the state of the form and input, fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also, holds information about whether they have been touched, or modified, or not.we can use standard, HTML5 attributes to validate input, or you can make your own validation functions, Form State and Input State, Forms have the following states:, AngularJS is constantly updating the state of both • $pristine : No fields have been modified, the form and the input fields., yet, Input fields have the following states:, • $dirty : One or more have been modified, • $untouched :The field has not been touched yet • $invalid : The form content is not valid, • $touched : The field has been touched, • $valid : The form content is valid, • $pristine : The field has not been modified yet, • $submitted :The form is submitted, • $dirty : The field has been modified, They are all properties of the form, and are, • $invalid : The field content is not valid, either true or false., • $valid : The field content is valid, You can use these states to show meaningful, They are all properties of the input field, and are, messages to the user. Example, if a field is, either true or false., required, and the user leaves it blank, you, should give the user a warning:, Required, <html> <script, src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>, <body ng-app="">, <p>Try leaving the first input field blank:</p>, <form name="myForm">, <p>Name:, <input name="myName" ng-model="myName" required>, <span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is, required.</span>, </p> <p>Address:, <input name="myAddress" ng-model="myAddress" required>, </p> </form>, <p>We use the ng-show directive to only show the error message if the field has been touched, AND is empty.</p></body> </html>, , 13
Page 49 :
3) Write an AngularJS script to search student name according to the character typed and, display details (use array and filter)., SET B:, 1) Using angular js display the Employee details order by salary in Table format (using ngrepeat directive, use Array to store data, use filter), 2) Using angular js create a SPA that to accept the details such as name, mobile number, pincode and email address and make validation. Name should contain character only, mobile, number should contain only 10 digit, Pin code should contain only 6 digit, email id should, contain only one @, . Symbol, 3) Using AngularJS create a SPA for Login System., SET C:, 1) Using angular js create a SPA for eLearning System., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 15
Page 52 :
2), 3), , Create a angular JS Application that greet the User (Use $timeout Service), Using angular js create a SPA to carry out validation for a username entered in textbox. If, the textbox is blank, alert ‘Enter username’. If the number of characters is less than three,, alert ’ Username is too short’. If value entered is appropriate the print ‘Valid username’, and password should be minimum 8 characters, , SET B, 1), , 2), , 3), , Create an HTML form using Angular JS that contain the Student Registration details and, validate Student first and last name as it should not contain other than alphabets and age, should be between 18 to 50 and display greeting message depending on current time, using ng-show (e.g. Good Morning, Good Afternoon, etc.)(Use AJAX)., Using angular js create a SPA that to accept the details such as name, mobile number, pincode and email address and make validation. Name should contain character only, mobile, number should contain only 10 digit, Pin code should contain only 6 digit, email id should, contain only one @, . Symbol., Using angular js create a SPA that accept Voters details and check proper validation for, (name, age, and nationality) as Name should be in upper case letters, Age should not be, less than 18 yrs and Nationality should be Indian., , SET C:, 1) Using angular js create a SPA to fetch suggestions when is user is typing in a textbox. (eg, like google suggestions. Hint create array of suggestions and matching string will be, displayed)., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 18
Page 53 :
Section-III, , PHP
Page 54 :
Assignment 1:Basics in PHP, Basics of PHP, For learning PHP, we have to learn the following basic points:, PHP Delimiters:, PHP is an embedded application, for writing PHP code we have to use its delimiters, <? php => starting delimiter and, ?> => ending delimiter., Syntax:, <? php, ?>, , Data Types:, PHP supports the following data types:, • String, • Integer, • Float (floating-point numbers - also called double), • Boolean, • Array, • Object, • NULL, • Resource, Operators in PHP, Types of operators that can be used in PHP programs are, There are the following types of operators:, • Arithmetic operators:- + , - , * , / , % ,**, • Assignment operators :- =, • Comparison operators :- <, >, <=, ==, ===, !=, <>, !==, • Increment/Decrement operators :- ++,-• Logical operators: - &&, ||, !, • String operators:- .(concatenation), • Conditional assignment operators: - ?,:, , 1
Page 55 :
*Note: Students can design HTML form to accept input from the user as per the requiremet of, the program., Practice Programs:, 1. Write a PHP script to perform arithmetic operations on two numbers (Addition, Subtraction,, Multiplication Division )., 2. Write a PHP script to display a maximum of two numbers using a conditional operator., 3. Write a PHP script that will perform pre and post-increment of a number. (Example ++a,, a++)., , SET A:, 1. Write a PHP Script to display Quotient and Remainder of the division of two variables., 2. Write a PHP Script to swap the values of two variables., 3. Write a PHP Script which will convert temperatures from Celsius(C)to Fahrenheit (F). (Hint:, C=5.0/9(F-32), SET B:, 1. Write a PHP Script to display the surface area and volume of a cuboid., (Hint: surface area=2(lb+lh+bh ), volume = l*b*h ), 2. Write a PHP Script to calculate the area of Circle, Square, and Rectangle., 3. Write a PHP Script to display the total and percentage of Marks of Subjects (Out of 100), Data Structure, Digital Marketing, PHP, SE, and Bigdata., SET C:, 1. Write a PHP Script to calculate the total cost of AIR Ticket Reservation and display the, details for Name, Address, Contact No, Source, Destination, Date of journey, Gender of, passenger, No of Persons, Price per Ticket, etc., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 2
Page 56 :
Assignment 2:Control Structures and Loops, Conditional Statements, Conditional statements are used to check conditions and the programmer can accordingly, display the results. PHP supports the following conditional statements., 1. if Statement, 2. if else Statement, 3. elseif Statement, 4. switch Statement, Name/Use, if Statement:, It is used to check a condition., If the condition is true the, corresponding body of if, statement is executed., , Syntax, if(Condition), {, Statements;, }, , if else Statement:, It checks a condition and if the, condition is true the, corresponding body of the if, statement is executed, otherwise else part is, executed., , if(Condition), {, Statements;, }, else, {, Statements;, }, , elseif Statement:, if (condition), It checks more than one { Statements;}, condition., elseif (condition), { Statements;}, else, { Statements;}, , switch Statement, switch (expression), It checks the result of the {, expression, with, multiple, case value1:, conditions (cases). The case is Statements, 3, , Example, <?php, $n=10;, if ($n%2==0), {, echo “Number Is Even”;, }, ?>, Output:Number Is Even, <?php, $n=10;, if ($n%2==0), { echo “Number Is Even”;}, else, { echo “Number Is Odd”;}, ?>, Output:Number Is Even, <?php, $a=10;, $b=20;, if ($a==$b), { echo “a and b are same”;}, elseif ($a<$b), { echo “a is less than b”;}, else, { echo “a is greater than b”;}, ?>, Output:a is less than b, <?php, $num=2;, switch($num), {
Page 57 :
executed for which the match, is found., , break;, Case 1:, case value2:, echo “One”;, Statements, break;, break;......, Case 2:, default:, echo “two”;, Code to be executed if all, break;, cases are not matched;, Case 3:, }, echo “Three”, break;, Case 4:, echo “Four;, break;, Case 5:, echo “Five”;, break;, default:, echo “Invalid, Number”;, ?>, Output: Two, , Loops, Loops in php are used to execute a similar group of statements. PHP supports the following 4, types of loops., 1. for Loop, 2. while Loop, 3. do…while Loop, 4. foreach Loop, Name/Use, for Loop, It executes a block of code for, a specified number of times., , Syntax, for (initialization; condition;, increment), {, code to be executed;, }, , while Loop, It executes a block of code, until the condition specified is, true., , while(expression), {, Statements;, }, , 4, , Example, <?php, For($j=1; $j<=5; $j++), {, echo $j;, }, ?>, Output: 12345, <?php, $j=1;, while($j<=5), {, echo $j;, $j++;, }, ?>
Page 58 :
do…while Loop, It executes ablock of code, once and then repeats the loop, as long as a special condition, is true., , do, {, code to be executed;, }, while (condition);, , foreach Loop, foreach (array as value) {, It is used to traverse the array, code to be executed;, and the block of code is }, executed for each element of, the array., , Output: 12345, <?php, $j=1;, do{, echo $j;, $j++;, } while($j<=5);, ?>, Output: 12345, <?php, $array = array( 1, 2, 3, 4, 5);, foreach( $array as $value ), {, echo "Value is $value";, }, ?>, Output:, Value is 1Value is 2Value is, 3Value is 4Value is 5, , *Note: Students can design HTML form to accept input from the user as per the requirement of, the program., Practice Programs:, 1. Write a PHP Script to display a maximum of two numbers., 2. Write a PHP Script to check whether a number is positive or negative., 3. Write a PHP Script to display a Multiplication table of a number, SET A:, 1. Write a PHP Script to check whether a year is a leap or not., 2. Write a PHP Script which will perform the Addition, Subtraction, Multiplication, and, Division of two numbers as per the choice. (Use Switch Case), 3. Write a PHP Script to display the grade of the student according to percentage. Use the, following conditions:, Percentage <40 => Grade=”Fail”, Percentage >= 40 and Percentage <=50 => Grade= “Pass Class”, Percentage >=50 and Percentage <=60 => Grade= “Higher Second Class”, Percentage >60 and Percentage <=70 => Grade= “First Class”, Percentage >70 => Grade= “First Class with Distinction”, SET B:, 1. Write a PHP Script to display prime numbers between 1 to 50., 5
Page 59 :
2. Write a PHP Script to display a perfect numbers between 1 to100., 3. Write a PHP Script to display the reverse of a number. E.g. 607 =>706, 4. Write a PHP Script to display Armstrong numbers between 1 to 500., SET C:, 1. Write a PHP script to display a number in words (Use Switch case), e.g. 345–three four five, 2. Write a PHP script to change the background color of the browser using a switch, statement according to the day of the week., 3. Write a PHP script to count the total number of even and odd numbers between, 1 to 1000., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 6
Page 60 :
Assignment 3: Arrays and Strings, Strings in PHP, A string is a sequence of characters. There are two types of strings., 1. Single-Quoted String:In this type, characters are enclosed with a single quotation mark(‘’);, Examples:, ‘Hello World’, ‘Amar’, ‘Pune’, The limitation of a single-quoted string is that variables are not interpolated., Example:, <?php, $name=‘Amar’;, $str='Hello $name';, echo $str;, ?>, Output:, Hello $name, , 2. Double-Quoted String: In this type,characters are enclosed with double quotation marks (“, ”)., PHP interpreter interprets variables and special characters inside double-quotes., Example:, <?php, $name=‘Amar’;, $str=“Hello $name”;, echo $str;, ?>, Output:, Hello Amar, It expands the many PHP escape sequences. The escape sequences recognized by PHP in doublequoted strings are as follows:, , 7
Page 61 :
E Escape, Sequence, \n, \r, \t, \v, \e, \f, \\, \$, \", , Meaning, New Line, carriage return, horizontal tab, vertical tab, escape, form feed, Backslash, dollar sign, double-quote, , String Functions, PHP provides approximately one hundred functions for string manipulations. Some of the, functions that can be performed on strings are:, • Compare two strings, • Find a String In AnotherString, • Find Out How Many Instances of A String Occur In AnotherString, • Return Part of aString, • Replace Part of aString, • Trim Whitespace From The Ends of aString, • Make An Entire String Lowercase or uppercase, Name, strlen(), , Use, It is used get string length., , trim(), , It used to remove the, whitespaces and other, characters., , ltrim(), , It used to strip whitespace, or other characters from, the beginning of a string., , rtrim(), , It is used to remove the, , Example, <?php, $input = 'Sunayana';, echo strlen($input);, ?>, Output:8, <?php, $input = " Programming in PHP \n";, echo trim($input);, ?>, Output: Programming in PHP, <?php, $input = " Programming in PHP \n";, echo trim($input);, ?>, Output: Programming in PHP \n, <?php, 8
Page 63 :
string., , str_pad(), , explode(), , echo strrev("sairamkrishna");, ?>, Output:anhsirkmarias, It pads a string to a new <?php, length., //Pad to the right side of the string, to a new, length of 20 characters:, $str = "Hello World";, echo str_pad($str,15,"=");, ?>, Output: Hello World====, It is used to split a string <?php, by string, //Decomposing string, //Break a string into an array:, $str = "Hello world. It's a beautiful day.";, $arr=explode(" ",$str);, print_r ($arr);, echo"<br><br>";, $str = "one|two|three|four";, $arr=explode('|',$str);, print_r ($arr);, ?>, Output:, Array ( [0] => Hello [1] => world. [2] =>It's [3], => a [4] => beautiful [5] => day. ), Array ( [0] => one [1] => two [2] => three [3], => four ), , implode(), , strpos(), , It creates a string from an <?php, array of smaller string., $arr = array('Hello','World!','Beautiful','Day!');, echo implode(" ",$arr);, echo "<br><br>";, $arr = array('Hello','World!','Beautiful','Day!');, echo implode(",",$arr);, ?>, Output:, HelloWorld!, Beautiful, Day!, Hello,World!,Beautiful,Day!, It is used to find the <?php, position of first occurrence echostrpos("I love php,, of a string inside another too!","php")."<br>";, string., ?>, Output:, 7, 10, , I, , love, , php
Page 64 :
strstr(), , It is used to find the first, occurrence of a string and, returns from that small, string onwards., , <?php, echostrstr("Hello world!","world")."<br><br>";, echostrstr("w3resource.com",".");, ?>, Output:, world!, .com, , Arrays in PHP, An array is a collection of different data elements. Multiple elements can be stored using, an array under a single name., Declaration of an Array, An array can be defined/declared by using array () function., Syntax:, $a=array (10, 20, 30, 40);, $colors = array("Red", "Blue, "Yellow");, There are following types of an array:, 1. Indexed array., 2. Associative array., 3. Multidimensional array., An array is organized as an ordered collection of (key,value) pairs. In PHP there are three types, of arrays:, a) Indexed array:It is an array with a numeric index starting with 0. There are two ways to, create an Indexed array:, Example:, $num=array (10, 20);, OR, $num[0]=10;, $num[1]=20;, b) Associative array:Associative arrays are arrays that use named keys that you assign to them., There are two ways to create an associative array:, Example:, $age = array("Sagar"=>"35", "Abhijeet"=>"37", "Ishwar"=>"43");, OR, 11
Page 65 :
$age['Sagar'] = "35";, $age['Abhijeet'] = "37";, $age['Ishwar'] = "43";, c)Multidimensional array: A multidimensional array is an array containing one or more arrays., In this type of array, multiple arrays can be defined in a single array., Example:, $cars = array(, array(“Swift”,20,30),, array(“Dezire,40,50),, array(“Mercedez”,6,7),, array("Scoda",12,15), );, Array Functions, Name, array_chunk(), , Use, It is used to split an array, into chunks of a given, size, , Example, <?php, $a=array("10","20","30","40");, print_r(array_chunk($a,2);, ?>, Output:, Array( [0] => Array([0] =>10 [1] =>20 ), [1] => Array ([0] =>30 [1] =>40 )), , array_combine (), , It is used to combine two, arrays into one, values of, the first array are the, keys and values of the, second array are the, values in the combined, array., It is used to compare the, values of two arrays and, return the difference, , <? php, , array_diff ():, , array_intersect(), , It returns the common, elements of two arrays., , $X=array("a","b","c");, $Y=array("100","200","300");, $Z=array_combine($X,$Y);, print_r($Z);, ?>, Output :Array([a]=>100, [b]=>200, [c]=>300), <?php, echo "<font size=14>";, $a=array(1,2,3,4,5);, $b=array(4,2,6);, $c=array_diff($a,$b);, print_r($c);, ?>, Output: Array ( [0] => 1 [2] => 3 [4] => 5 ), <?php, $a=array(1,2,3,4);, $b=array(4,5,6,2);, $c=array_intersect($a,$b);, 12
Page 66 :
array_flip(), , Exchanges all keys with, their associated values in, an array., , array_splice(), , It removes and replaces, specified elements of an, array, , array_slice(), , It returns selected parts, of an array. It returns the, sequence of elements, from the array array as, specified by, the offset and length para, meters., , array_reverse(), , Returns an array in the, reverse order., , array_key_exists(, ), , This function is used to, check if an element exists, in thearray, , array_push(), , This function add the, , print_r($c);, ?>, Output: Array([1]=>2, [2]=>4);, <?php, $a = array("a"=>1, "b"=>2, "c"=>3, "d"=>4,, "e"=>5);, print_r(array_flip($a));, ?>, Output: Array ( [1] => a [2] => b [3] => c [4], => d [5] => e ), <?php, $a=array(10,20,30,40,50,60);, $b=array_splice($a,2,3);, print_r($a);, print_r($b);, ?>, Output:Array ( [0] => 10 [1] => 20 [2] => 60 ), Array ( [0] => 30 [1] => 40 [2] => 50 ), <?php, $a=array(1,2,3,4,5,6);, $b=array_slice($a,2,3);, print_r($a);, echo "<br>";, print_r($b);, ?>, Output:, Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4], => 5 [5] => 6 ), Array ( [0] => 3 [1] => 4 [2] => 5 ), <?php, $a=array(1,2,3);, $d=array_reverse($a);, print_r($d), ?>, Output: Array ( [0] => 3 [1] => 2 [2] => 1 ), <?php, $a=array("a"=>"ABC","p"=>"PQR","x"=>"XY, Z");, if(array_key_exists("p",$a)), echo "Key Exists";, else, echo "Key Does not Exists";, ?>, Output: Key Exists, <?php, 13
Page 67 :
new element at the end of, $a =, an array., array("a"=>"banana","b"=>"apple","c"=>"orang, e");, print_r(array_push($a, "Straberry"));, print_r($input );, ?>, Output: 4 Array ( [a] => banana [b] => apple, [c] => orange [0] =>Straberry ), array_pop(), , This functions remove, last element of an array., , array_shift(), , It removes the first, element from an array,, and returns the value of, the removed element, , array_unshift(), , <?php, $a=array("a"=>"banana","b"=>"apple","c"=>"or, ange");, print_r(array_pop($a));, ?>, Output: orange, <?php, $a =, array("a"=>"banana","b"=>"apple","c"=>"Mang, o");, , print_r(array_shift($a));, ?>, Output: banana, It adds one or more, <?php, elements to the beginning, $a = array("orange", "banana");, of an array, array_unshift($a, "apple");, print_r($a);, ?>, Output: Array ( [0] => apple [1] => orange [2], => banana ), , array_sum(), , It returns the addition of, array elements., , array_product(), , It returns the product of, array elements., , array_unique(), , It removes duplicate, values from an array, , <?php, $a=array(1,2,3);, $sum=array_sum($a);, echo "Sum=$sum";, ?>, Output: Sum=6, <?php, $a = array(5,6);, print_r(array_product($a));, ?>, Output:30, <?php, $a = array("a" => "green", "red", "b" =>, "green", "blue", "red");, $result = array_unique($a);, print_r($result);, ?>, 14
Page 68 :
Output:Array ( [a] => green [0] => red [1] =>, blue ), extract(), , It creates local variables, from an array., , compact(), , Create array containing, variables and their values, , in_array(), , Checks if a specified, value exists in an array, , count(), , It gives number of, elements in an array., , ?php, $a = "Original";, $my_array = array("a" => "Cat","b" => "Dog",, "c" => "Horse");, extract($my_array);, echo "\$a = $a; \$b = $b; \$c = $c";, ?>, Output:, $a = Cat; $b = Dog; $c = Horse, <?php, $city = "Pune";, $state = "Mumbai";, $result = compact("city", "state");, print_r($result);, ?>, Output:Array ( [city] => Pune [state] =>, Mumbai ), <?php, $a=array(10,20,30,40,50,60);, if(in_array(40,$a)), echo "Element Available in array";, else, echo "Element not available in array";, ?>, Output: Element Available in array, <?php, $a=array(10,20,30,40,50,60);, echocount($a);, ?>, Output: 6, , Array Sorting Functions, Name, sort(), , Use, It sorts array in ascending, order., , Syntax, <?php, $a=array("mh","ap","LM","za");, print_r($a);, echo "<br>";, sort($a);, echo "<br> After Sorting<br>";, print_r($a);, ?>, 15
Page 70 :
krsort(), , It sorts associative array in, descending order as per the, keys., , echo "<br> After Sorting<br>";, print_r($b);, ?>, Output:, Array ( [X] => XYZ [A] => ABC [L] => LMN ), After Sorting, Array ( [A] => ABC [L] => LMN [X] => XYZ ), <?php, $b=, array("X"=>"XYZ","A"=>"ABC","L"=>"LMN");, print_r($b);, krsort($b);, echo "<br> After Sorting<br>";, print_r($b);, ?>, Output:, Array ( [X] => XYZ [A] => ABC [L] => LMN ), After Sorting, Array ( [X] => XYZ [L] => LMN [A] => ABC ), , *Note: Students can design HTML form to accept input from the user as per the requirement of, the program., , Practice Programs:, 1. Write a PHP Script to define an array. Find the element from the array that matches the given, value using the appropriate search function., 2. Write a PHP script to count the total number of vowels (a,e, i,o,u) from the string. Show the, occurrences of each vowel from the string., 3. Write PHP program to perform the following operations on Indexed Array:, a) Check the array element is positive or negative, b) Calculate the average of array elements, c) Calculate the sum of array elements, , SET A:, 1. Write PHP program to perform the following operations on Indexed Array:, a) Union of two arrays, b) Traverse the array elements in random order, 2. Write a PHP program to perform the following operations on an associative array:, a) Display the elements of an array along with the keys., b) Display the size of an array, c) Delete an element from an array from the given index., d) Reverse the order of each element’s key-value pair, 17
Page 71 :
e) Traverse the elements in an array in random order., 3. Write a PHP Script for the following:, a) Declare and Display a multidimensional Array., b) Search and display a specific element from a Multidimensional array., , SET B:, 1. Write a PHP script to perform the following operations on string :, i) Compare string 2 with string3., ii) Convert all the strings to Upper case, iii) Convert all the strings to Lowercase, 2. Write a PHP script to perform the following operations on string :, i) Convert each word of a string to Lowercase and Uppercase., ii) Find the first and last occurrence of string2 in string1., 3. Write a menu-driven program in PHP to perform the following operations on associative, arrays:, i) Sort the array by values (changing the keys) in ascending, descending order., ii) Also, sort the array by values without changing the keys., iii) Find the intersection of two arrays., iv) Find the union of two arrays., SET C:, 1. Write a PHP script to perform the following operations on string :, i) Replace the string2 by string3 in string1., ii) Reverse and display the string., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 18
Page 72 :
Assignment 4:Functions, Class, and Object, Functions, A function is a block of code that performs a specific task. It can be called from, anywhere from the program. It takes zero or any number of parameters and does some, processing and returns a value., PHP Built-in Functions, Name, Use, echo, This construct is used to display many values, at once on the screen., print(), It prints data to the screen, print_r(), It prints the contents of arrays and objects., , Example, echo “Hello”;, echo (“Hello”);, print (“Hello”);, <?php, $array = array( 1, 2, 3);, print_r($array);, ?>, Output:, Array ( [0] => 1 [1] => 2 [2] => 3, ), var_dump() It returns the value and data type of a given <?php, $a=50;, variable., echo var_dump($a);, ?>, Output:Int(50);, isset(), It returns true value, if a given parameter is <?php, initialized with a value otherwise it returns $n = 0;, if (isset($n)), false value., {, echo "Variable 'a' is set.”;, }, Output:Variable 'a' is set., unset(), It unsets a variable., <?php, $a = 10;, echo "The value of variable 'a', before unset: " . $a . "<br>";, unset($a);, echo "The value of variable 'a', after unset: " . $a;, ?>, Output:, The value of variable 'a' before, unset:10, 19
Page 73 :
define(), , It is used to define constant., , date(), , The date() function formats a local date and, time, and returns the formatted date string., Syntax: date(format,timestamp), List of characters commonly used for date:, d - Represents the day of the month, m - Represents a month, Y - Represents a year, l - Represents the day of the week, , The value of variable 'a' after, unset:, <?php, define (“PI”,3.14);, echo PI, ?>, Output:3.14., <?php, echo "Today is " ., date("Y/m/d") . "<br>";, echo "Today is " ., date("Y.m.d") . "<br>";, echo "Today is " . date("l");, ?>, Output:, Today is 2021/01/19, Today is 2021.01.19, Today is Tuesday, , Defining a user-defined function, While creating a user-defined function its name should be preceded by with, keyword function and the function code should be put inside { and } braces., Syntax:, functionfunction_name([parameters]), {, Statements;, }, Example:, <?php, /* Defining a PHP Function */, functionHelloWorld(), {, echo "HelloWorld Good Morning!!";, }, /* Calling a PHP Function */, HelloWorld();, ?>, Output:HelloWorld Good Morning!!, , 20
Page 74 :
Passing Parameters to Functions, 1. Call By Value, When a PHP function is called by value then actual values of variables are not modified if it, is modified into the function., Example:, <?php, functionaddFun($num1, $num2), {, $sum = $num1 + $num2;, echo "Sum of the two numbers is : $sum";, }, addFun(15, 20);, ?>, 2. Call By Reference, When a PHP function is called by reference then the actual values of the parameters are modified, by the function., Example:, <?php, functionaddFun(&$num1, &$num2), {, $sum = $num1 + $num2;, echo "Sum of the two numbers is : $sum";, }, addFun(15, 20);, ?>, , Default Parameter, If we do not pass any value to the function then the function uses a default value, calleddefault parameter., Example:, <?php, functionsetHeight($maxheight=100), {, echo "The height is : $maxheight<br>";, }, setHeight(350);, setHeight(); // will use the default value of 100, ?>, Output:, 21
Page 75 :
The height is: 350, The height is:100, Classes and Objects:, PHP supports to the object oriented programming concepts., Class:, It is user defined data type. It is a collection of data members and functionsas a single, unit., A class can be defined as:, Example:, <?php, class Car, {, /* Member variables */, var $price;, /* Member functions */, functionsetPrice($par), {, $this->price = $par;, }, functiongetPrice(), {, echo $this->price ."<br/>";, }, }, ?>, , Object:, Any real or runtime entity is called an object. Objects are also known as instance., Creating Objects in PHP, After defining a class, an object of that class can be created. It can be done by using a new, operator as follow:, Example:, Object_name=new Class_Name;, $Car1=new Car;, For accessing data member and member functions of a class, an object is used., 22
Page 76 :
Example:, $Car1->setPrice(5);, Practice Programs:, 1. Write a PHP script to calculate the area and volume of a cylinder using a function., 2. Write a PHP Script to display the sum and average of array elements(Using predefined, functions), 3. Write a PHP script to calculate the factorial of a number using a function., , SET A:, 1. Write a PHP script to calculate xy using a function., 2. Write a PHP script to define a function EvenOdd, which will display even and odd numbers, between 1 to 50., 3. Write a PHP script to define a function Maximum, which will accept 3 numbers as, parameters and returns a maximum of 3 numbers., 4. Write a PHP script to swap two numbers using a function (Use Call by value and Call by, reference), SET B:, 1. Write a PHP Script to create a class Fruit that contains data members as Name, Color and, Price. Write a member function to accept and display details of Fruit., 2. Write a PHP Script to create a class Student that contains data members as Roll_Number,, Stud_Name, and Percentage. Write member functions to accept Student information., 3. Write a PHP Script to create a class Book (Book_id, Book_name, Publication, Author,, Book_price). Write a member function to accept and display Book details., SET C:, 1. Write a PHP script to define a function “DisplayDay”, which will display the day of the, current date., 2. Write a PHP script to perform arithmetic operations on two numbers. Write a PHP function, to display the result. (Use the concept of function and default parameters), Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 23
Page 77 :
Assignment 5: Working with forms, Processing a Form’s Data:, HTML forms are used to send the user information to the server and returns the result to, the browser. For example, if you want to get the details of visitors to your website, and send, them good thoughts, you can collect the user information employing form processing. Then,, the information can be validated either at the client-side or on the server-side. The final result, is sent to the client through the respective web browser. To create a HTML form, the following, form tag should be used., • Action, • Method, Form processing contains a set of controls through which the client and server can, communicate and share information. The controls used in forms are:, • Text, • Textarea, • Dropdown, • Radio, • Checkbox, • Buttons, PHP methods used in form processing are:, •, •, , $_GET[]: It is used the retrieve the information from the form control through the, parameters sent in the URL. It takes the attribute given in the URL as the parameter., $_POST[]: It is used the retrieve the information from the form control through the HTTP, POST method. It takes the name attribute of the corresponding form control as the, parameter., Example Using POST Method, stud.html, <html>, <body>, <form method=POST action=”stud.php”>, RollNo :, <input type=text name=rno><br>, Student Name : <input type=text name=sname><br>, Percentage :, <input type=text name=per><br>, <input type=submit value=submit name=submit>, </form>, </body>, </html>, , stud.php, <?php, 24
Page 80 :
{, echo $_GET[‘rno’];, echo $_GET[‘sname’];, echo $_GET[‘per’];, }, ?>, </body>, </html>, , Sticky Forms:, Form remembers the values that are entered in the input fields. For example Google, search box. In the sticky form, the results of a query are accompanied by a search form whose, default values are those of the previous query., To create the sticky form, we have to follow 2 steps:, •, •, , Step 1: Taking the data sent by the form by using the “GET” or “POST” method: $data=, $_GET[“data”];, Step 2: Settings that data as a value for text fields and selected or checked for other form, elements., , Example Sticky Forms, stud.php, <html>, <body>, <form method=GET action="<?php $_SERVER['PHP_SELF'];?>">, Your Name : <input type=text name=sname value=”<?phpecho$_POST[‘sname’] ?>”>, <br>, <input type=submit value=submit>, </form>, <?php, if(isset($_GET[‘sname’])), {, echo $_GET[‘sname’];, }, ?>, </body>, </html>, Dealing with Checkbox, <html>, <body>, <form method=GET action="<?php echo $_SERVER['PHP_SELF']; ?>">, Select ur Choice<br>, 27
Page 81 :
<input type=checkbox name=ch[] value="1" <?php if($_GET['ch']=="1") echo 'checked="checked"';, ?>>, Reading, <input type=checkbox name=ch[] value="2" <?php if($_GET['ch']=="2") echo 'checked="checked"';, ?>>, Dancing<br>, <input type=Submit name="S" value=Click>, </form>, <?php, if ((isset($_GET['S']))), {, $ch=$_GET['ch'];, if($ch=="1"), echo "Reading";, else, echo "Dancing";, }, ?>, </body>, </html>, Dealing with Radio button, <html>, <body>, <form method=GET action="<?php echo $_SERVER['PHP_SELF']; ?>">, Select ur Choice<br>, <input type=radio name="r" value="1" <?php if($_GET['r']=="1") echo 'checked="checked"';, ?>> Add, <input type=radio name="r" value="2" <?php if($_GET['r']=="2") echo 'checked="checked"';, ?>> Sub<br>, <input type=Submit name="S" value=Click>, </form>, <?php, if ((isset($_GET['S']))), {, $ch=$_GET['r'];, switch($ch), {, case 1:, 28
Page 82 :
$a=$t1+$t2;, echo "Addition=$a";, break;, case 2:, $a=$t1-$t2;, echo "Sub=$a";, break;, }, }, ?>, </body>, </html>, Retrieving values from List:, <html>, <body>, <form method=GET action="<?php echo $_SERVER['PHP_SELF']; ?>">, Select ur Choice<br>, <select name=m>, <option value="R" <?php if($_GET['m']=="R") echo 'selected="selected"'; ?>>Reading, <option value="D" <?php if($_GET['m']=="D") echo 'selected="selected"'; ?>>Dancing, </select>, <input type=submit name=S value=Click>, </form>, <?php, if ((isset($_GET['S']))), {, $ch=$_GET['m'];, echo $ch;, }, ?>, </body>, </html>, Validating and Restricting data:, Different strategies for validating form data are,, • Fields should not be empty, • Check the length of the data entered by the user., • Check the type of data entered by the user., • Check specific conditions for form fields, Functions for Validating and Restricting data are,, • Empty(varName): it is used to check whether a variable is empty or not., 29
Page 83 :
•, •, , isset(): This function is used to determine whether the variable or a form control is, having a value or not., filter_var() function filters a variable with the specified filter., Syntax:, filter_var(var, filtername, options), Parameters: This function accepts three parameters and is described below:, 1. var : It is the required field. It denotes the variable to filter., 2. filtername : It is used to specify the ID or name of the filter to use. Default is, FILTER_DEFAULT, which results in no filtering. It is an optional field., 3. options : It is used to specify one or more flags/options to use. Check each filter, for possible options and flags. It is also an optional field., Return Value: It returns the filtered data on success, or FALSE on failure., Filternames are,, • FILTER_VALIDATE_INT: to check if the variable is an integer or not, • FILTER_VALIDATE_IP: to check if the variable is a valid IP address or not., • FILTER_VALIDATE_EMAIL: to check if the variable is a valid email address, or not., • FILTER_VALIDATE_URL: to check if the variable is a valid URL or not., , Example using empty(), <html>, <body>, <form method=GET action="<?php echo $_SERVER['PHP_SELF']; ?>">, Search<input type=text name="t1" value="<?php if(isset($_GET['t1'])) echo $_GET['t1']; ?>">, <input type=Submit name="s" value=Click>, </form>, <?php, if ((isset($_GET['t1']))), {, $t1=$_GET['t1'];, if ((!empty($t1))), {, echo $t1;, }, else, {, echo "enter the value in textbox";, }, }, ?>, </body>, </html>, , 30
Page 85 :
{, echo("$url is a valid URL");, }, else, {, echo("$url is not a valid URL");, }, ?>, , Practice Programs:, 1. To design an application that works as a simple calculator using PHP. (use isset())., 2. Write a PHP script to check PAN number entered by the customer is valid or not and, display an appropriate message., 3. Write a PHP script to check mobile number entered by the user is valid or not and, display an appropriate message., SET A:, 1. Write a PHP script to accept font name, background color, and welcome message on 1st, page. Display the welcome message with the given font and background color on the next, page., 2. Write a PHP program to accept name, address, pincode, gender information. If any field, is blank display error messages “all fields are required”., 3. Write a PHP script to accept employee details (name, address) and earning details (basic,, DA, HRA). Display employee details and earning details in the proper format., SET B:, 1. Write a PHP script to accept customer name and the list of product and quantity on the, first page. On the next page display the name of the customer, name of the products, rate, of the product, quantity, and total price in table format., 2. Write HTML code to design multiple choice question paper for PHP subject. Display, question wise marks and total marks received by the student in table format., 3. Write a PHP script to accept student name and list of programming languages (using drop, down box) and display it on the next page in the proper format., 4. Write a PHP script to accept user name, email address and age. If data entered by the user, is valid then display it on the next page otherwise display the appropriate message(use, filter_var())., , 32
Page 86 :
SET C:, 1. A web application that takes name and age from an HTML page. If the age is less than, 18, it should send a page with “Hello <name>, you are not authorized to visit the site”, message, where <name> should be replaced with the entered name. Otherwise, it should, send a “Welcome <name> to this site” message., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 33
Page 87 :
Assignment 6: Session and Cookies, Cookies:, A cookie is often used to identify a user. A cookie is a small file that the server embeds, on the user's computer. Each time the same computer requests a page with a browser, it will send, the cookie too. With PHP, you can both create and retrieve cookie values., A cookie is created with the setcookie() function., setcookie(name[, value, expire, path, domain, secure, httponly]);, where,, • name: A unique name for a particular cookie. You can have multiple cookies with different, • names and attributes., • value : It is used to set the value of the cookie, • expire : The expiration date for this cookie. If no expiration date is specified, the browser, • saves the cookie in memory and not on disk. When the browser exits, the cookie disappears., • The expiration date is specified as the number of seconds., • path :It is used to specify the path on the server for which the cookie will be available., • domain :It is used to specify the domain for which the cookie is available., • secure : It is used to indicate that the cookie should be sent only if a secure HTTPS, connection exists., <?php, //Creating a cookie, $cookie_name = "user";, $cookie_value = "abc";, setcookie($cookie_name, $cookie_value, time() + (1* 24 * 60 * 60));, //Checking a Cookie is set or not, if(!isset($_COOKIE[$cookie_name])), {, echo "Cookie named '" . $cookie_name . "' is not set!";, }, else, {, echo "Cookie '" . $cookie_name . "' is set!<br>";, }, //Accessing Cookie value, echo "Value is: " . $_COOKIE[$cookie_name];, // set the expiration date to one hour ago, setcookie("user", "", time() - 3600);, echo "Cookie 'user' is deleted.";, //cookie expire after 1 day, setcookie($cookie_name, $cookie_value, time() + (1* 24 * 60 * 60));, ?>, 34
Page 88 :
Session:, A session is a way to store information (in variables) to be used across multiple pages. The, information is not stored on the user’s computer.By default, session variables last until the user, closes the browser.Session variables hold information about one single user and are available to, all pages in one application, • The first step is to start up a session. After a session is started, session variables can be, created to store information. The PHP session_start() function is used to begin a new, session. It also creates a new session ID for the user., • The second step is to set Session variables using PHP global variable: $_SESSION., <?php, // Start the session, session_start();, // Set session variables, $_SESSION["favcolor"] = "green";, $_SESSION["favanimal"] = "cat";, echo "Session variables are set.<br>";, // access session data, echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";, echo "Favorite animal is " . $_SESSION["favanimal"] . "<br>";, print_r($_SESSION);, // to change a session variable, just overwrite it, $_SESSION["favcolor"] = "yellow";, print_r($_SESSION);, // remove all session variables, session_unset();, if(($_SESSION["favcolor"]!=0) && ($_SESSION["favanimal"]!=0)), print_r($_SESSION);, else, echo "Session variables are unset.<br>";, // destroy the session, session_destroy();, print_r($_SESSION);, echo "Session variables are destroyed.<br>";, ?>, , Practice Programs:, 1. A web application that lists all cookies stored in the browser on clicking “list cookies”, button,add cookies if necessary., 35
Page 89 :
2. Write a PHP program to store the current date-time in a COOKIE and display the ‘Last, visited on’date-time on the web page upon reopening of the same page., 3. Write a script to keep track of a number of times the web page has been accessed using the, session., SET A:, 1. Write PHP program to store student information like Seat number, name, and class. On the, second page, accept marks of the subject PHP, DS, CPP, and RDBMS. Display Result in, table format on the third page (use cookies)., 2. Write a PHP script to accept username and password. If in the first three chances, username, and password entered is correct, then display the welcome message on the second form,, otherwise display an error message., 3. Write a PHP script to accept font style, font size, font color, background color using a cookie., Display selected values on the next second page and actual implementation on the third web, page., SET B:, 1. Create an online flight registration form. On the first page accept name, address, birthdate,, and mobile number. On the second page accept flight details (flight name, source,, destination, departure date-time and charges). If the user doesn’t enter information within a, specified time limit, expire his session and give a warning otherwise display details using, sessions on the third page., 2. Create a form to accept patient details like name, address birthdate, and mobile number., Once thePatient information is accepted, and then accepts health details like medicare, number, health fund and critical information. Display patient details and health details on the, next form., 3. Write a PHP script to create an inventory management system. On the first page accept the, highest sold product details like product name, total quantity and total sold. On the second, page accept the latest sales details like product name, date and total sale. Display highest sold, product details in one table and latest sales details in another table on the third page., SET C:, 1. Write a PHP script to create an online shopping form. On the first page accept customer, name, email address, shipping address, mode of payment. Design the Second page as given, below. And the third page should display a bill, which consists of customer details and, purchase details in the proper format., , 36
Page 90 :
Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 37
Page 91 :
Assignment 7: Database, Database :, It is a collection of inter-related data that helps in efficient retrieval, insertion, and, deletion of data from the database and organizes the data in the form of tables, views, schemas,, reports, etc. The basic functions used in PHP for database connection are,, Function, mysql_connect(server, user, pwd), , mysql_select_db(db name), , mysql_query(query);, , mysql_fetch_array(result,resultty, pe);, , mysql_close(connection);, , Description, It opens a database connection and, returns the connection on success,, or FALSE and an error on failure., It is used to change the default, database for the connection., , Example, $con=mysql_connect("lo, calhost","root","");, , It executes a query on a MySQL, database.This function returns the, query handle for SELECT queries,, TRUE/FALSE for other queries, or, FALSE on failure., function fetches a result row as an, associative array, a numeric array,, or both., , $sql=”Select * from, stud”, $r=mysql_query($sql);, , mysql_select_db("sybba, ");, , mysql_fetch_array($r,, MYSQL_ASSOC);, , result=Required., resulttype=Optional. Specifies what, type of array that should be, produced. Values are,, MYSQL_ASSOC, MYSQL_NUM,, MYSQL_BOTH, The mysql_close() function closes, mysql_close($con);, MySQL connection.This function, returns TRUE on success, or, FALSE on failure., , 1. The basic steps to create a MySQL database using PHP are:, •, •, •, •, , Establish a connection to the MySQL server from your PHP script., If the connection is successful, write a SQL query to create a database and store it in a, string variable., Execute the query., Close the connection, , <?php, $con=mysql_connect("localhost","root","");, 38
Page 92 :
if(!$con), {, die("unable to connect");, }, $sql="create database sybba";, $r=mysql_query($sql);, if(! $r), {, die("could not create database");, }, echo "Database created successfully";, mysql_close($con);, ?>, 2. The basic steps to create a MySQL table using PHP are:, •, •, •, •, •, , Establish a connection to the MySQL server from your PHP script., If the connection is successful, then select the database., Write a SQL query to create a table and store it in a string variable., Execute the query., Close the connection, , <?php, $con=mysql_connect("localhost","root","");, if(!$con), {, die("unable to connect");, }, mysql_select_db("sybba");, $sql="create table stud(rnoint, snamevarchar(20), per int)";, $r=mysql_query($sql);, if(! $r), {, die("could not create table");, }, echo "Table created successfully";, mysql_close($con);, ?>, , 3. The basic steps to manipulate MySQL table using PHP are:, •, •, •, •, , Establish a connection to the MySQL server from your PHP script., If the connection is successful, then select the database., Write aninsert/update/delete query to manipulate and store it in a string variable, Execute the query., 39
Page 93 :
•, , Close the connection, , <?php, $con=mysql_connect("localhost","root","");, if(!$con), {, die("unable to connect");, }, mysql_select_db("sybba");, $sql="insert into stud values(1,’Neeta’,84)";, $r=mysql_query($sql);, if(! $r), {, die("not inserted");, }, echo "record added successfully";, mysql_close($con);, ?>, , 4. The basic steps to fetchdata from MySQL table using PHP are:, •, •, •, •, •, •, , Establish a connection to the MySQL server from your PHP script., If the connection is successful, then select the database., Write a select query and store it in a string variable, Execute the query, Display data using a while loop., Close the connection, , <?php, $con=mysql_connect("localhost","root","");, if(!$con), {, die("unable to connect");, }, mysql_select_db("sybba");, $result=mysql_query("select * from stud");, while($col=mysql_fetch_array($result,MYSQL_NUM)), {, echo "Rollno=".$col[0]."<br>";, echo "Name=".$col[1]."<br>";, echo "Per =".$col[2]."<br>";, }, mysql_close($con);, ?>, 40
Page 94 :
Practice Programs:, 1. Consider the following entities and their relationships, Company (c_no, c_name, c_city, c_share_value), Person (p_no, p_name, p_city, p_ph_no), Relationship between Company and Person is many-to-many with descriptive attribute no_of_shares., , Using the above database, write a PHP script to display person wise share detailsin tabular, format., 2. Consider the following entities and their relationships, Customer (c_no, c_name, c_city, c_ph_no ), Ticket (t_no, booking_date, fare, traveling_date), The relationship between Customer and Ticket is one-to-many. Create a RDB in 3 NF for the, above., Using the above database, write a PHP script to accept date and display,, 1) The total fare collected from customers on a given date., 2) Ticket details booked by the customer., , SET A:, 1. Write a PHP script to create an employee table using attributes employee number, employee, name, address joining date and salary. If a table is created then display the appropriate, message otherwise end the PHP script., 2. Write a PHP script to accept account details (account number, account type and balance)., Store these details in the account table and display an appropriate message., 3. Write a PHP script to accept product number from the user. Update the price of the product, and display an appropriate message., SETB:, 1. Consider the following entities and their relationships., Employee (eno, ename, sal), Project (pno, pname,duration), Employee and Project are related with a many-many relationship. Create a RDB in 3 NF for, the above., Using the above database write a PHP script to accept the project name. Display the name of, the employees and the duration of the project., 2. Consider the following entities and their relationships., Train(t_no, t_name), Passenger (p_no, p_name, addr, age), The relationship between Train and Passenger is many-to-many with descriptive attribute, date,seat_no and amt. Create a RDB in 3 NF for the above., Using the above database write a PHP script to accept a date. Display train details having, maximum passenger for a given date., 3. Consider the following entities and their relationships., Crop (c_no, c_name, c_season, pesticides), 41
Page 95 :
Farmer (f_no, f_name, f_location), The relationship between Crop and Farmer is many-to-many with descriptive attribute year., Create a RDB in 3 NF for the above., Using the above database write a PHP script to accept crop name and year value. Display, total number of farmers harvesting given crop in a given year., SETC:, 1. Consider the following entities and their relationships., Client (c_no, c_name, c_addr, birth_date), Policy_info (p_no, p_name, maturity_amt, prem_amt, policy_term), The relationship between Client and Policy_info is many-to-many with descriptive attribute, date_of_purchase.Create a RDB in 3NF for the above., Using the above database write a PHP script to display policy details of a given client for a, given year in the following format., Client Name :, Policy Name, , Year:, Maturity Amount, , Premium Amount Policy Term, , Date of Purchase, , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 42
Page 96 :
Section-IV, , Big Data
Page 97 :
Assignment 1: Basic R Programming, , Introduction:, R is a programming language and software environment for statistical analysis, graphics, representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the, University of Auckland, New Zealand, and is currently developed by the R Development Core, Team., The core of R is an interpreted computer language which allows branching and looping, as well as modular programming using functions. R allows integration with the procedures, written in the C, C++, .Net, Python or FORTRAN languages for efficiency., , Installing R and RStudio:, To install R and RStudio on windows, go through the following steps:, Install R on windows, Step – 1: Go to CRAN R project website., , Step – 2: Click on the Download R for Windows link., Step – 3: Click on the base subdirectory link or install R for the first time link., Step – 4: Click Download R X.X.X for Windows (X.X.X stand for the latest version of R. eg:, 3.6.1) and save the executable .exe file., , 1
Page 98 :
Step – 5: Run the .exe file and follow the installation instructions., 5.a. Select the desired language and then click Next., , 5.b. Read the license agreement and click Next., , 2
Page 99 :
5.c. Select the components you wish to install (it is recommended to install all the components)., Click Next., , 5.d. Enter/browse the folder/path you wish to install R into and then confirm by clicking Next., , 5.e. Select additional tasks like creating desktop shortcuts etc. then click Next., , 3
Page 100 :
5.f. Wait for the installation process to complete., , 5.g. Click on Finish to complete the installation., , 4
Page 101 :
Install RStudio on Windows:, Step – 1: With R-base installed, let’s move on to installing RStudio. To begin, go to download, RStudio and click on the download button for RStudio desktop., Step – 2: Click on the link for the windows version of RStudio and save the .exe file., Step – 3: Run the .exe and follow the installation instructions., 3.a. Click Next on the welcome window., , 3.b. Enter/browse the path to the installation folder and click Next to proceed., , 5
Page 102 :
3.c. Select the folder for the start menu shortcut or click on do not create shortcuts and then, click Next., , 3.d. Wait for the installation process to complete., , 6
Page 103 :
3.e. Click Finish to end the installation., , Data Types:, , 1. Logical:, It is a special data type for data with only two possible values which can be construed, as true/false., Example:, True, False, , 2. Numeric:, Decimal value is called numeric in R, and it is the default computational data types., Example:, 12,32,112,5432, 7
Page 104 :
3. Integer:, Here, L tells R to store the value as an integer, Example:, 3L, 66L, 2346L, 4. Complex:, A complex value in R is defined as the pure imaginary value i., Example:, Z=1+2i, t=7+3i, , 5. Character, In R programming, a character is used to represent string values. We convert objects, into character values with the help ofas.character() function., Example:, 'a', '"good'", "TRUE", '35.4', Variables in R:, Variables are used to store the information to be manipulated and referenced in the R, program. The R variable can store an atomic vector, a group of atomic vectors, or a combination, of many R objects., A valid variable name consists of letters, numbers and the dot or underline characters., The variable name starts with a letter or the dot not followed by a number., Example:, Var.1 = c(0,1,2,3), , Operators in R programming:, Operators, Arithmetic Operators(), , +, *, /, %%, %/%, ^, , Description, Adds two vectors, Subtracts second vector from the first, Multiplies both vectors, Divide the first vector with the second, Give the remainder of the first vector with the, second, The result of division of first vector with second, (quotient), The first vector raised to the exponent of second, 8
Page 105 :
vector, Relational Operators, , >, , <, , ==, <=, , Logical Operators, , >=, , Checks if each element of the first vector is greater, than or equal to the corresponding element of the, second vector., , !=, , Checks if each element of the first vector is unequal, to the corresponding element of the second vector., , &&, , Called Logical AND operator. Takes first element, of both the vectors and gives the TRUE only if both, are TRUE., Called Logical OR operator. Takes first element of, both the vectors and gives the TRUE if one of them, is TRUE., Called Left Assignment, , ||, , Assignment Operators, , Miscellaneous Operators, , Checks if each element of the first vector is greater, than the corresponding element of the second, vector, Checks if each element of the first vector is less, than the corresponding element of the second, vector., Checks if each element of the first vector is equal to, the corresponding element of the second vector., Checks if each element of the first vector is less, than or equal to the corresponding element of the, second vector., , <− or =, or <<−, -> or >>, :, %in%, %*%, , Called Right Assignment, Colon operator. It creates the series of numbers in, sequence for a vector., This operator is used to identify if an element, belongs to a vector., This operator is used to multiply a matrix with its, transpose., , Practice Programs:, 1. Write a R program to take input from the user (name and age) and display the values., Also print the version of R installation., 2. Write a R program to get the details of the objects in memory., SET A:, 9
Page 106 :
1. Write a R program to accept dimensions of a cylinder and print the surface area and, volume., 2. Write a R program to accept temperatures in Fahrenheit (F) and print it in Celsius(C) and, Kelvin (K)., 3. Write a R program to accept two numbers and print arithmetic and harmonic mean of the, two number., 4. Accept three dimensions length (l), breadth(b) and height(h) of a cuboid and print surface, area and volume, SET B:, 1. Accept the x and y coordinates of two points and computes the distance between the two, points., 2. A cashier has currency notes of denomination 1, 5 and 10. Accept the amount to be, withdrawn from the user and print the total number of currency notes of each, denomination the cashier will have to give., SET C:, 1. Write a R program to create a sequence of numbers from 20 to 50 and find the mean of, numbers from 20 to 60 and sum of numbers from 51 to 91., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 10
Page 107 :
Assignment 2: Decision making and loop control structures, if Statement:, The if statement consists of the Boolean expressions followed by one or more statements., The if statement is the simplest decision-making statement which helps us to take a decision on, the basis of the condition., The if statement is a conditional programming statement which performs the function and, displays the information if it is proved true., The syntax of if statement in R is as follows:, if(boolean_expression) {, // If the boolean expression is true, then statement(s) will be executed., }, Flow Chart:, , Example:, x <- 5, if(x > 0){, print("Positive number"), 11
Page 108 :
}, Output, [1] "Positive number", If-else statement:, In the if statement, the inner code is executed when the condition is true. The code which, is outside the if block will be executed when the if condition is false., There is another type of decision-making statement known as the if-else statement. An ifelse statement is the if statement followed by an else statement. An if-else statement, else, statement will be executed when the boolean expression will false. In simple words, If a Boolean, expression will have true value, then the if block gets executed otherwise, the else block will get, executed., The basic syntax of If-else statement is as follows:, if(boolean_expression) {, // statement(s) will be executed if the boolean expression is true., } else {, // statement(s) will be executed if the boolean expression is false., }, , Flow Chart:, , 12
Page 109 :
Example:, x <- -5, if(x > 0){, print("Non-negative number"), } else {, print("Negative number"), }, Output:, [1] "Negative number", Switch Statement:, A switch statement is a selection control mechanism that allows the value of an, expression to change the control flow of program execution via map and search., The switch statement is used in place of long if statements which compare a variable with, several integral values. It is a multi-way branch statement which provides an easy way to, dispatch execution for different parts of code. This code is based on the value of the expression., The basic syntax of If-else statement is as follows:, switch(expression, case1, case2, case3....), , Flow Chart:, , 13
Page 110 :
next Statement:, The next statement is used to skip any remaining statements in the loop and continue, executing. In simple words, a next statement is a statement which skips the current iteration of a, loop without terminating it. When the next statement is encountered, the R parser skips further, evaluation and starts the next iteration of the loop., Syntax, next, Flowchart, , Example:, x <- 1:5, for (val in x) {, if (val == 3){, next, }, print(val), }, Output:, [1] 1, [1] 2, [1] 4, [1] 5, , 14
Page 111 :
Break Statement:, The break statement is used to break the execution and for an immediate exit from the, loop. In nested loops, break exits from the innermost loop only and control transfer to the outer, loop., It is useful to manage and control the program execution flow. We can use it to various, loops like: for, repeat, etc., Syntax:, Break, Flowchart:, , Example:, x <- 1:5, for (val in x) {, if (val == 3){, break, }, print(val), }, , 15
Page 112 :
Output:, [1] 1, [1] 2, Loops:, The function of a looping statement is to execute a block of code, several times and to, provide various control structures that allow for more complicated execution paths than a usual, sequential execution., Repeat Loop:, A repeat loop is one of the control statements in R programming that executes a set of, statements in a loop until the exit condition specified in the loop, evaluates to TRUE., Syntax, repeat{, Statements, if(exit_condition){, break, }, }, Example:, x <- 1, repeat {, print(x), x = x+1, if (x == 6){, break, }, }, Output:, [1] 1, [1] 2, [1] 3, [1] 4, [1] 5, While Loop:, A while loop is one of the control statements in R programming which executes a set of, statements in a loop until the condition (the Boolean expression) evaluates to TRUE., while(Boolean expression), {, Statement, }, Example:, 16
Page 113 :
i<- 1, while (i< 6) {, print(i), i = i+1, }, Output:, [1] 1, [1] 2, [1] 3, [1] 4, [1] 5, For Loop:, A for loop is the most popular control flow statement. A for loop is used to iterate a, vector. It is similar to the while loop. There is only one difference between for and while, i.e., in, while loop, the condition is checked before the execution of the body, but in for loop condition is, checked after the execution of the body., Syntax, for (value in vector) {, statements, }, Example:, x <- c(2,5,3,9,8,11,6), count<- 0, for (val in x) {, if(val %% 2 == 0) count = count+1, }, print(count), Output:, [1] 3, , Practice Programs:, 1. Write a R program to accept an integer and check if it is even or odd., 2. Write a R program, which accepts annual basic salary of an employee and calculates and, displays the Income tax as per the following rules., Basic: < 1,50,000 Tax = 0, Basic: 1,50,000 to 3,00,000 Tax = 20%, Basic: > 3,00,000 Tax = 30%, 3. Writet a R program to accept character from the user and check whether the character is a, vowel or consonant., 4. Write a R program accept any year as input and check whether the year is a leap year or, not., 17
Page 114 :
SET A:, 1., 2., 3., 4., 5., , Write a R program to display the first 10 Fibonacci numbers., Write a program to calculate sum of digits of a given input number., Write program to check whether a input number is Armstrong number or not., Write a program to check whether a input number is perfect number of not., Write a R script to display multiplication table of a given input number., , SET B:, 1. Write a R program to get all prime numbers up to a given number., 2. Accept the cost price and selling price from the keyboard. Find out if the seller has made, a profit or loss and display how much profit or loss has been made., 3. Accept the x and y coordinate of a point and find the quadrant in which the point lies., 4. Write a program to check whether a input number is palindrome or not., 5. Write a program to accept a number and count number of even, odd, zero digits within, that number., SET C:, 1. Use a while loop to simulate one stock price path starting at 100 and random normally, distributed percentage jumps with mean 0 and standard deviation of 0.01 each period., How long does it take to reach above 150 or below 50?, 2. Implement a multiplication game. A while loop that gives the user two random numbers, from 2 to 12 and asks the user to multiply them without using * operator., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 18
Page 115 :
Assignment 3: String and Function in R Programming, String:, Any value written within a pair of single quote or double quotes in R is treated as a, string. Internally R stores every string within double quotes, even when you create them with, single quote., Example:, string1 <- “This is a string”, R String Manipulation Functions, 1. grep(), It is used for pattern matching and replacement. grep, grepl, regexpr, gregexpr and, regexec search for matches with argument pattern within each element of a character vector., Here we subsitute the first and other matches with sub and gsub. sub and gsub perform, replacement of the first and all matches., Example:, g <- grep("iconHomicideShooting", homicides), length(g), 2. nchar(), With the help of this function, we can count the characters. This function consists of a, character vector as its argument which then returns a vector comprising of different sizes of the, elements of x. nchar is the fastest way to find out if elements of a character vector are non-empty, strings or not., Example, # Using nchar() function, nchar("hel'lo"), 3.substr():, It is the substrings of a character vector. The extractor replaces substrings in a character, vector., 4. str_length(), The length of strings indicate the number of characters present in the string.The, function str_length() belonging to the ‘stringr’ package or nchar() inbuilt function of R can, be used to determine the length of strings in R., Example, # Importing package, 19
Page 116 :
library(stringr), # Calculating length of string, str_length("hello"), 5. cat() function, Different types of strings can be concatenated together using the cat()) function in R,, where sep specifies the separator to give between the strings and file name, in case we wish to, write the contents onto a file., Syntax:, cat(..., sep=" ", file), Example:, # Concatenation using cat() function, str<- cat("learn", "code", "tech", sep = ":"), print (str), 6. Conversion to upper case, All the characters of the strings specified are converted to upper case., Example:, print(toupper(c("Learn Code", "hI"))), 7. Conversion to lower case, All the characters of the strings specified are converted to lower case., Example:, print(tolower(c("Learn Code", "hI"))), , 8. Character replacement, Characters can be translated using the chartr(oldchar, newchar, …) function in R, where, every instance of old character is replaced by the new character in the specified set of strings., Example:, 20
Page 117 :
chartr("a", "A", "An honest man gave that"), Output:, "An honest mAngAvethAt", 9. Splitting the string, A string can be split into corresponding individual strings using ” ” the default, separator., Example:, strsplit("Learn Code Teach !", " "), Output:, [1] "Learn" "Code" "Teach" "!", 10. Working with substrings, substr(…, start, end) or substring(…, start, end) function in R extracts substrings out of, a string beginning with the start index and ending with the end index. It also replaces the, specified substring with a new set of characters., Example:, substr("Learn Code Tech", 1, 4), Output:, "Lear", Function in R:, A function, in a programming environment, is a set of instructions. A programmer builds, a function to avoid repeating the same task, or reduce complexity., A function should be, •, •, •, •, , written to carry out a specified a tasks, may or may not include arguments, contain a body, may or may not return one or more values., , Syntax, , 21
Page 118 :
func_name<- function (argument) {, statement, }, Example:, Pow <- function(x,y){, # function to print x raised to the power y, Result <- x^y, Print(paste(x,”raised to the power”, y,”is”,result)), }, Output:, >pow(8,2), [1] “8 raised to the power 2 is 64”, 1. Default Values for Arguments, We can assign default values to arguments in a function in R., Example, pow<- function(x, y = 2) {, # function to print x raised to the power y, result<- x^y, print(paste(x,"raised to the power", y, "is", result)), }, Output:, >pow(3), [1] "3 raised to the power 2 is 9", 3. Return Value from Function, Many a times, we will require our functions to do some processing and return back the, result. This is accomplished with the return() function in R., Syntax, return(expression), , Example:, check<- function(x) {, if (x > 0) {, result<- "Positive", }, else if (x < 0) {, 22
Page 119 :
result<- "Negative", }, else {, result<- "Zero", }, return(result), }, Output:, >check(1), [1] "Positive", >check(-10), [1] "Negative", 3. Recursive Function:, A function that calls itself is called a recursive function and this technique is known as, recursion.This special programming technique can be used to solve problems by breaking them, into smaller and simpler sub-problems., Example:, # Recursive function to find factorial, recursive.factorial<- function(x) {, if (x == 0) return (1), else, return (x * recursive.factorial(x-1)), }, Output:, >recursive.factorial(0), [1] 1, >recursive.factorial(5), [1] 120, , 23
Page 120 :
In-built Functions:, These functions in R programming are provided by R environment for direct execution,, to make our work easier., Function Name, seq(), , sum(), , mean(), , paste(), , min(), , max(), , Description, Example, To create a sequence of print(seq(1,9)), numbers, O/P, [1] 1 2 3 4 5 6 7 8 9, To find the sum of numbers print(sum(25,50)), O/P, [1] 75, To find the mean of print(mean(41:68)), numbers, O/P, [1] 54.5, To combine vectors after paste(1,"sam",2,"rob",3,"max"), converting, them, to O/P, characters, [1] "1 sam 2 rob 3 max", To return the minimum x<-c(3,45,6,7,89,9)print(min(x)), value from a vector., O/P, [1] 3, To return the maximum x <- c(3,45,6,7,89,9), value from a vector, print(max(x)), O/P, [1] 89, , Practice Programs:, 1. Write a R program to accept a string from user and display the length of the string., 2. Write a R program to accept a string in lowercase and display it uppercase and vice versa, 3. Write a program to check whether a input number is prime number or not using user, defined function., SET A:, 1. Write a program to calculate factorial of a input number using user defined function., 2. Write R program to find the factors of a given number using user defined function, 3. Write a R Program to connect two different strings., , SET B:, 1. Write a program to calculate xy using user defined function (Use default parameters), 2. Write R program to accept a string and character from user and replace all occurrences of, that character from string with other character., 3. Write a recursive function in R to calculate multiplication of all digits of a given input, number., , 24
Page 121 :
4. Write a function which accepts one number. Function should return 1 if the number is, Perfect No, otherwise function should return 0., 5. Write a function isPrime, which accepts an integer as parameter and returns 1 if the, number is prime and 0 otherwise., SET C:, 1. Write a R program to print the numbers from 1 to 100 and print "Fizz" for multiples of 3,, print "Buzz" for multiples of 5, and print "FizzBuzz" for multiples of both., 2. Write a program to calculate sum of following series up to n terms using user defined, function, Sum=X+X2/2!+X3/3!+……, , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 25
Page 122 :
Assignment 4: Vector and List in R programming, Introduction:, The Vector is the most basic Data structure in R programming. R Vector can hold a collection of, elements of similar types. A vector supports logical, integer, numeric, character, complex, or raw, data type. The elements which are contained in vector known as components of the vector. We, can check the type of vector with the help of the typeof() function. The length is an important, property of a vector. A vector length is basically the number of elements in the vector, and it is, calculated with the help of the length () function. Vector is classified into two parts, i.e., Atomic, vectors and Lists., There is only one difference between atomic vectors and lists. In an atomic vector, all the, elements are of the same type, but in the list, the elements are of different data types., Creating vector in R:, In R, we use c () function to create a vector. This function returns a one-dimensional array or, simply vector. The c() function is a generic function which combines its argument. All, arguments are restricted with a common data type which is the type of the returned value., For Example:, 1. # Numeric Vector: a=c(1, 2, 3, 4), 2. # Character vector: b=c("India", "China", "Japan", "Russia“), 3. #Boolean vector: d=c(TRUE, FALSE, FALSE, TRUE, TRUE), 4. # Mixed Vector and its Type will be Character : e= c("India", 2, "China", 1, TRUE), 5. # Placing or Nesting One Vector inside the another : f = c("UK", "USA", TRUE, FALSE,, b) where b is another Vector, There are various other ways to create a vector in R, which are as follows:, 1. Create R Vector using Range: In R programming, there is a special operator called Range, or Colon, and this will help to create a vector. For example, 1., 2., 3., 4., , # Vector with Range : i =1 : 10, Vector with Decimal Range : j =1.5 : 5.5, # Vector with Decimal Range : n = -10 : -20, Letter Vector with Range: l =letters[1:6], , 2. Using the seq() function: In R, we can create a vector with the help of the seq() function. A, sequence function creates a sequence of elements as a vector. For example, 1. v1=seq(1,5), #v1 will be 1,2,3,4,5, 26
Page 123 :
2. v2=seq(1,10,by=2), #v2 will be 1,3,5,7,9, 3. v3=seq(1,4,length.out=6) #v3 will be 1.0,1.6,2.2,2.8,3.4,4.0, Atomic vectors in R:, Atomic vectors are created with the help of c() function. In R, there are four types of atomic, vectors. These atomic vectors are numeric vector, integer vector, character vector and logical, vector., 1. Numeric vector: The decimal values are known as numeric data types in R. If we assign a, decimal value to any variable d, then this d variable will become a numeric type. A vector, which contains numeric elements is known as a numeric vector. For example, > d=c(10.5, 24.5,7), >d, #prints 10.5 24.5 7.0 at console, >class(d), #prints “numeric”, 2. Integer Vector: A non-fraction numeric value is known as integer data. There is two way to, assign, an integer value to a variable, i.e., by using as.integer() function and appending of, L to the value. A vector which contains integer elements is known as an integer vector. For, example, >int_vec=as.interger(c(1,2,3,4,5) ), >int_vec1=c(1L,2L,3L,4L,5L), >d=as.integer(5), >e=5L, 3. Character Vector: In R, there are two different ways to create a character data type value,, i.e., using as.character() function and by typing string between double quotes("") or single, quotes(''). A vector which contains character elements is known as an character vector. For, example, >f=c("shubham","arpita","nishka","vaishali"), >g=as.character(c(123, 234)), >d='shubham', >e="Arpita", 4. Logical vector: The logical data types have only two values i.e., True or False. These values, are based on which condition is satisfied. A vector which contains Boolean values is known, as the logical vector. For example, > a=10, > b=4, > c=8, > log_vec=c(a>b, b<c, c>a, c<a), > log_vec, # it prints TRUE TRUE FALSE TRUE, , 27
Page 124 :
Accessing elements of vectors:, We can access the elements of a vector with the help of vector indexing. Indexing, denotes the position where the value in a vector is stored. Indexing will be performed with the, help of integer, character, or logic., 1. Indexing with integer vector: On integer vector, indexing is performed in the same way as, we have applied in C. There is only one difference, i.e., in C the indexing starts from 0, but in, R, the indexing starts from 1. we perform indexing by specifying an integer value in square, braces [] next to our vector. For example, > d=c(10,20,30,40,50), >d, #Prints 10 20 30 40 50, > d[2], # Prints 20, > d[3], # Prints 30, > d[2:4], #Prints 20 30 40, 2. Indexing with a character vector: In character vector indexing, we assign a unique key to, each element of the vector. These keys are uniquely defined as each element and can be, accessed very easily. For example, > Stud=c(“Rollno”=101, “Marks”=80.74), > Stud[“Rollno”], #prints 101, >Stud[“Marks”], #prints 80.74, >Stud[c(“Rollno”,”Marks”)], #prints 101 80.74, 3. Indexing with a logical vector: In logical indexing, it returns the values of those positions, whose corresponding position has a logical vector TRUE. For example, > vec=c(1,2,3,4,5,6), >vec[c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE)], #It, prints 1 2 5, 4. Access using Vector: In this example, we will show how to access the Vector elements using, another Vector in R. for example, >a =c("India", "China", "Japan", "UK", "USA", "Russia", "Sri Lanka"), > b =c(2, 4, 6), >print(a[b]), # It prints, China UK, Russia, >print(a[c(5, 7)]), # It prints USA, Sri Lanka, >print(a[c(7, 4, 1)]), # It prints Sri Lanka UK, India, 5. Using Negative Values in R: We can access the Vector elements using Negative values and, the Boolean values. In R Vectors, Negative index position is used to omit those values. For, example, >a=c("India", "China", "Japan", "UK", "USA", "Russia”), >print(a[-3]), #it prints India China UK, USA Russia, >b =c(-3, -6), >print(a[b]), #it prints India China UK, USA, 28
Page 125 :
>print(a[c(-4, -6)]), , #it prints "India" "China" "Japan" "USA", , Manipulate R Vector Elements:, In R Programming, we can manipulate the Vector elements in following ways:, >a <- c(10, 20, 30, -15, 40, -25, 60, -5), >a[7] =77, #it update the 7th element of vector to 77, >a[a < 0]=99 #it modifies all the elements of vector to 99 if the element is less than 99, >a= a[1:5], # it truncates all the elements of vector except elements 1 to 5, > a= NULL #it deletes the vector a, Vector Operation:, 1. Combining Vectors: The c() function is not only used to create a vector, but also it is, also used to combine two vectors. By combining one or more vectors, it forms a new, vector which contains all the elements of each vector., >a=c(1,2,3), >b=c("p","q","r"), >c=c(a,b), >c, #prints "1" "2" "3" "p" "q" "r“, >d=(b,a), >d, #prints "p" "q" "r" "1" "2" "3", 2. Arithmetic operations: We can perform all the arithmetic operation on vectors. The, arithmetic operations are performed member-by-member on vectors. We can add,, subtract, multiply, or divide two vectors. For example, > a=c(8,4,10), > b=c(2,6,5), > a+b, #10 10 15, > a-b, #6 -2 5, > a*b, #16 24 50, > a/b, #4.0000000 0.6666667 2.0000000, > a%%b, #0 4 0, > a%/%b, #402, Important Functions of Vector:, 1. typeof(Vector): This method tells you the data type of the vector., 2. Sort(Vector): This method helps us to sort the items in the Ascending order., 3. length(Vector): This method counts the number of elements in a vector., 4. head(Vector, limit): This method return the top six elements (if you Omit the limit). If, you specify the limit as 4 then, it returns the first 4 elements., 5. tail(Vector, limit): It returns the last six elements (if you Omit the limit). If you specify, the limit as 2, then it returns the last two elements., 29
Page 126 :
R List:, Lists are the objects of R which contain elements of different types such as number, vectors,, string and another list inside it. It can also contain a function or a matrix as its elements., A list is a data structure which has components of mixed data types. We can say, a list is a, generic vector which contains other objects., In R, the list is created with the help of list() function., > a_vec=c(1,2,3), > b_vec=c("Pune","Mumbai"), >list_var=list(2.3,45L,"R Programming", TRUE, a_vec,b_vec), > print(list_var), # Here print(list_var) will display the content of list on console as ouput, Giving a name to list elements:, R provides a very easy way for accessing elements, i.e., by giving the name to each element of a, list. After creating list we can assign a name to the list elements with the help of names(), function. For example, > list_var=list(101L,"Nilesh",80.45), > names(list_var)=c("Roll No","Name","Marks"), > print(list_var), $`Roll No`, [1] 101, $Name, [1] "Nilesh“, $Marks, [1] 80.45, Accessing List Elements:, R provides two ways through which we can access the elements of a list. First one is the, indexing method performed in the same way as a vector. In the second one, we can access the, elements of a list with the help of names. It will be possible only with the named list., > list1=list (10, 20, 30), > list1[1], # display 10, > list1[2], #display 20, > for(i in list1), + print(i), # display 10 20 30, > list2=list(101,"Nilesh",80.57), >names(list2)=c("Rollno", "Name", "Marks"), > list2["Rollno"], #display $Rllono 101, , 30
Page 127 :
Manipulation of list elements:, R allows us to add, delete or update elements in the list. We can update an element of a list from, anywhere, but elements can add only at the end of the list. To remove an element from a, specified index, we will assign it a NULL value., We can update the element of a list by overriding it from the new value., > list1=list (10, 20, 30), >list1, #display 10 20 30, >list1 [4] =40, >list1, #display 10 20 30 40, >list1[2]=200, >list1, #display 10 200 30 40, >list1[4]=NULL, >list1, #display 10 200 30, Converting list to vector:, There is a drawback with the list, i.e., we cannot perform all the arithmetic operations on list, elements. To remove this, drawback R provides unlist() function. This function converts the list, into vectors. In some cases, it is required to convert a list into a vector so that we can use the, elements of the vector for further manipulation.The unlist() function takes the list as a parameter, and change into a vector., > list1=list(2:5), #list1=(2,3,4,5), > list2=list(11:14), #list2=(11,12,13,14), > list1+list2, #Error, > v1=unlist(list1), #converting list1 to vector v1, > v2=unlist(list2), # converting list1 to vector v2, > v1+v2, #display 13 15 17 19, Merging List:, R allows us to merge one or more lists into one list. Merging is done with the help of the list (), function also. To merge the lists, we have to pass all the lists into list function as a parameter,, and it returns a list which contains all the elements which are present in the lists., >even=list (2, 4, 6), >odd=list (1, 3, 5), > mix=list(even, odd), > print (mix), #display 2 4 6 1 3 5, Sample R Scripts using Vector and List, Q.) Write an R program to find the maximum and the minimum value of a given vector., Solution:, n=as.integer(readline(prompt="How many nos do u want to strore in vector=")), 31
Page 128 :
vec=c(), a=1, while(a<=n), {, num=as.integer(readline(prompt="Enter Elemnt=")), vec[a]=num, a=a+1, }, cat("\n Original Vector="), print(vec), cat("\n Maximum elemennt of vector=",max(vec)), cat("\n Minimum elemennt of vector=",min(vec)), Q.) Write an R program to sort a list of 10 strings in ascending and descending order., n=as.integer(readline(prompt="How many strings u want to store in list=")), lst=list(), for(a in seq(1,n)), {, lst[a]=readline(prompt="Enter any String="), }, b=unlist(lst), b=sort(b), lst=list(b), cat("\n List in Ascending Order="), print(lst), b=sort(b,decreasing=TRUE), lst=list(b), cat("\n List in Descending Order="), print(lst), Practice Programs:, 1. Write a R program to create a vector of a specified type and length. Create vector of, numeric, complex, logical and character types of length 6., 2. Write a R program to add, multiply and divide two vectors of integers type and length 3., 3. Write a R program to create a list containing strings, numbers, vectors and a logical, values., , 32
Page 129 :
4. Write a R program to list containing a vector, a matrix and a list and give names to the, elements in the list. Access the first and second element of the list., SET A:, 1. Write an R program to sort a Vector in ascending and descending order., 2. Write an R program to find Sum, Mean and Product of a Vector., 3. Write a R program to sort a Vector in ascending and descending order., 4. Create a list containing a four vectors and give names to the elements in the list, 5. Write a R program to merge two given lists into one list., 6. Write a R program to convert a given list to vector., 7. Write a R program to create a list named s containing sequence of 15 capital letters,, starting from ‘E’., SET B:, 1. Write a R program to find all elements of a given list that are not in another given list., 2. Write a R program to extract all elements except the third element of the first vector of a, given list., 3. Write a script in R to create a list of cities and perform the following, a. Give names to the elements in the list., b. Add an element at the end of the list., c. Remove the last element., d. Update the 3rd Element, 4. Write a script in R to create a list of students and perform the following, a. Give names to the students in the list., b. Add a student at the end of the list., c. Remove the first Student., d. Update the second last student., 5. Write a script in R to create a vector of numbers and perform the following, a. Search for specific element, b. Count the occurrences of specific element, c. Access the last element of given vector, SET C:, 1. Write a R program to extract every nth element of a given vector., 2. Write a R program to select second element of a given nested list., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, 33
Page 130 :
Assignment 5: Arrays and Matrices in R programming, R Arrays:, In R, arrays are the data objects which allow us to store data in more than two dimensions. In R,, an array is created with the help of the array() function., Syntax: array_name <- array (data, dim = (row_size, column_size, matrices), dim_names)), Where,, 1. data: The data is the first argument in the array() function. It is an input vector which is, given to the array., 2. row_size: This parameter defines the number of row elements which an array can store., 3. column_size: This parameter defines the number of columns elements which an array, can store., 4. Matrices: This parameter defines number of arrays to create., 5. dim_names: This parameter is used to change the default names of rows and columns. It, is list of 3 vectors, where first vector correspond to row names, second vector represent, column names and third vector represent matrix name., Ex:, >d=array(c(1,2,3,4,5,6,7,8,9),dim=c(3,3,1),dimnames=list(c("r1","r2","r3"),c("c1","c2","c3"),c(", m1"))), >print(d), , , m1, c1, r1 1, r2 2, r3 3, , c2, 4, 5, 6, , c3, 7, 8, 9, , Accessing R Array Elements:, In R programming, we can use the index position to access the array elements. Using the index,, we can access or alter/change each and every individual element present in an array. Index value, starts at 1 and an end at n where n is the size of a matrix, row, or column., The syntax behind this R Array accessing is: Array_Name[row_position, Column_Position,, Matrix_Level]., For example, we declared an array of two matrices of size 6 rows * 4 columns., To access or alter 1st value use Array_name[1, 1, 1], to access or alter 2nd-row 3rd column value, at 1st Matrix level then use Array_name[2, 3, 1], Ex. >A[2,3,1]=10, , 34
Page 131 :
Accessing Subset of a Array Elements:, In our previous example, we show you how to access the single element from tan Array. In this, example, we will show how to access the subset of multiple items from the Array. To achieve the, same, we use the R array A as follows, >A =array(1: 24, dim = c(3, 4, 2)), # Access the elements of 1st, 3rd row and 2nd, 4th column in Matrix 1., >print(A[c(1, 3), c(2, 4), 1]), # Access all the element of 2nd and 3rd row in Matrix 2., >print(A[c(2, 3), , 2]), # Access all the element of 1st and 4th Column in Matrix 1., >print(A[ , c(1, 4), 1]), TIP: Negative index position is used to omit those values from an Array., # Access all the element except 2nd row and 3rd Columm in Matrix 2., >print(A[-2, -3, 2]), R Array Addition and Subtraction:, In this example, we show how to use Arithmetic Operators on Matrices to perform arithmetic, Operations on Array., # Adding and Subtracting Elements of Array in R, >vect1= c(10, 20, 40 ), >vect2=c(55, 67, 89, 96, 100), >A=array(c(vect1, vect2), dim = c(3, 4, 2)), >print(A), >mat.A=A[, , 1], >mat.B=A[, , 2], >print(mat.A + mat.B), >print(mat.B - mat.A), R Matrix:, The Matrix in R is the most two-dimensional Data structure. In R Matrix, data is stored in row, and columns, and we can access the matrix element using both the row index and column index., A matrix is created with the help of the vector input to the matrix function. On R matrices, we, can perform addition, subtraction, multiplication, and division operation. In the R matrix,, elements are arranged in a fixed number of rows and columns. In R, we use matrix function,, which can easily reproduce the memory representation of the matrix. In the R matrix, all the, elements must share a common basic type., R provides the matrix() function to create a matrix., Syntax of creating Matrix:, matrix(data, nrow, ncol, byrow, dim_name), Where,, 35
Page 132 :
1. Data: The first argument in matrix function is data. It is the input vector which is the data, elements of the matrix., 2. Nrow: It is the number of rows in the matrix., 3. Ncol: It is the number of columns in the matrix., 4. Byrow: If its value is true, then the input vector elements are arranged by row., 5. dim_name: The dim_name parameter is the name assigned to the rows and columns., For Example M1= matrix(c (11, 13, 15, 12, 14, 16), nrow =2, ncol =3, byrow = TRUE), R = matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_n, ames)), Different ways of creating Matrix in R:, 1. # R Create Matrix, >A=matrix(c(1:12), nrow = 3, ncol = 4), >print(A), 2. # Elements are arranged sequentially by column., >B=matrix(c(1:12), nrow = 3, ncol = 4, byrow = FALSE), >print(B), 3. # Elements are arranged sequentially by row., >D=matrix(c(1:12), nrow = 3, ncol = 4, byrow = TRUE), 4. # It will create a Matrix of 3 Rows and the remaining elements will be arranged, Accordingly, >A=matrix(c(1:12), nrow = 3), 5. # It will create a Matrix of 4 Columns and the remaining (row) elements will be arranged, Accordingly, >B=matrix(c(1:12), ncol = 4), 6. # It will create a Matrix of 3 rows and 4 Columns, > D=matrix(c(1:12), 3, 4), 7. # It will create a Matrix of 3 rows, >E=matrix(c(1:12), 3), 8. # It will create a Matrix of 4 Rows. To create 4 Columns you have to specify ncol = 4, explicitly, >G=matrix(c(1:12), ncol=4), Create R Matrix using cbind and rbind:, In this example, we will show you another way of creating a Matrix in R programming. cbind is, used for binding vectors in Columns wise, and the rbind is used for binding vectors in Row wise., , 36
Page 133 :
Define Row names and Column names for matrix in R:, , Accessing matrix elements in R:, There are three ways to access the elements from the matrix., 1. We can access the element which presents on nth row and mth column., 2. We can access all the elements of the matrix which are present on the nth row., 3. We can also access all the elements of the matrix which are present on the mth column., E.g. A=matrix(c(1:12), nrow = 3, ncol = 4, byrow = TRUE), I., # Access the element at 1st row and 2nd column., >print(A[1, 2]), II., # Access the element at 3rd row and 4th column., >print(A[3, 4]), III., # Access only the 2nd row., >print(A[2,]), IV., # Access only the 4th column., >print(A[, 4]), V. # Access Complete Matrix., >print(A[ , ]), Accessing Subset of a Matrix in R: Following are the examples of accessing subset of a, matrix, 1. A =matrix(c(1:12), nrow = 3, ncol = 4, byrow = TRUE), >print(A), 2. # Access the elements at 1st, 2rd row and 3nd, 4th column., 37
Page 134 :
3., 4., 5., 6., 7., , >print(A[c(1, 2), c(3, 4)]), # Access All the element at 2nd and 3rd row., >print(A[c(2, 3), ]), # Access All the element at 1st and 4th Column., >print(A[ , c(1, 4)]), # Access All the element except 2nd row., >print(A[-2, ]), # Access All the element except 2nd row and 3rd Columm., >print(A[-2, -3]), # Access All the element except 3rd and 4th Columm., >print(A[, c(-3, -4)]), , Accessing R Matrix Elements using Character Index:, By assigning the Row names and Columns Names can help us to extract the Matrix elements, using the Row names or column names as the Index values., > row.names=c("Row1", "Row2", "Row3"), #, >column.names=c("Col1", "Col2", "Col3", "Col4"), >B=matrix(c(1:12), nrow = 3, dimnames = list(row.names, column.names)), 1. # Access the elements at 1st row and 3rd Column., >print(B["Row1", "Col3"]), 2. # Access only the 2nd row., >print(B["Row2",]), 3. # Access only the 4th column., print(B[, "Col4"]), 4. # Access the elements at 2nd row and 2, 3, 4th Column., >print(B["Row2", 2:4]), 5. # Access the elements at 1st, 3rd row and 1, 2, 3rd Column., >print(B[c("Row1", "Row3"), 1:3]), Modify R Matrix Elements:, In R programming, We can use the index position to modify the elements in a Matrix. Using this, index value, we can access or alter/change each and every individual element present in the, vector. For example, if we declare a 3 * 4 matrix that stores 12 elements (3 rows and 4 columns)., To access or alter 1st value use Matrix.name[1, 1], to access or alter 2nd row 3rd column value use, Matrix.name[2, 3]., # Modifying Matrix in R Programming, >A= matrix(c(1:9), nrow = 3, ncol = 3), >A[2, 2] =100, #modify second row, second column element to 100, >A[A < 5] =222 # modifies all element to 222 if the element is less than 5, , 38
Page 135 :
Matrix Arithmetic in R:, R Arithmetic Operators are used on Matrices to perform arithmetic Operations., # Create 2x3 matrices., >a=matrix( c(15, 34, 38, 44, 75, 93), nrow = 2), >b=matrix( c(10, 20, 30, 40, 50, 60), nrow = 2), 1. # Addiing two Matrices, >print(a + b), 2. # Subtraction One Matrix from another, >print(a - b), 3. # R Matrix Multiplication, >print(a * b), 4. # Matrix Division, >print(a / b), Practice Programs:, 1. Write a R program to create an array of two 3x3 matrices each with 3 rows and 3, columns from two given two vectors., 2. Write a R program to create a blank matrix., 3. Write a R program to create a matrix taking a given vector of numbers as input. Display, the matrix., 4. Write a R program to create a two-dimensional 5x3 array of sequence of even integers, greater than 50., 5. Write a R program to convert a given matrix to a 1 dimensional array., SET A:, 1. Write a R program to create a matrix taking a given vector of numbers as input. Display, the matrix., 2. Write a R program to create a matrix taking a given vector of numbers as input and, define the column and row names. Display the matrix., 3. Write a R program to access the element at 3rd column and 2nd row, only the 3rd row, and only the 4th column of a given matrix., 4. Write an R program to create three vectors a,b,c with 3 integers. Combine the three, vectors to become a 3×3 matrix where each column represents a vector. Print the content, of the matrix., 5. Write an R program to create a list of elements using vectors, matrices and a functions., Print the content of the list., SET B:, 1. Write a R program to create an array of three 3x2 matrices each with 3 rows and 2, columns from two given two vectors of different length., , 39
Page 136 :
2. Write a R program to create an array of two 3x3 matrices each with 3 rows and 3, columns from two given two vectors. Print the second row of the second matrix of the, array and the element in the 3rd row and 3rd column of the 1st matrix., 3. Write a R program to access the element at 3rd column and 2nd row, only the 3rd row, and only the 4th column of a given matrix., 4. Write a R program to create two 2x3 matrices and add, subtract, multiply and divide the, matrix elements., 5. Write an R program to convert a given matrix to a list and print list in ascending order., SET C:, 1. Write a R program to combine three arrays so that the first row of the first array is, followed by the first row of the second array and then first row of the third array., 2. Write a R program to find row and column index of maximum and minimum value in a, given matrix., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 40
Page 137 :
Assignment 6: Factor and Data Frame in R language, R factors:, Factors are the data objects which are used to categorize the data and store it as levels. In order to, categorize the data and store it on multiple levels, we use the data object called R factor. They, are useful in the columns which have a limited number of unique values. Like "Male, "Female", and True, False etc. They are useful in data analysis for statistical modeling., By default, R always sorts levels in alphabetical order., The command used to create or modify a factor in R language is – factor() with a vector as input., The two steps to creating a factor are:, 1. Creating a vector, 2. Converting the vector created into a factor using function factor(), # Creating a vector:, >x=c("female", "male", "male", "female"), >print(x), #it prints "female" "male" "male" "female", # Converting the vector x into a factor named gender, >gender=factor(x), >print(gender), #it prints, [1] female male male female, Levels: female male, Levels can also be predefined by the programmer. For eample, # Creating a factor with levels defined by programmer:, >gender=factor(c("female", "male", "male", "female"), levels = c("female", "transgender",, "male"));, Further one can check the levels of a factor by using function levels(). Function is.factor() is used, to check whether the variable is a factor and returns “TRUE” if it is a factor., >gender=factor(c("female", "male", "male", "female"));, >print(is.factor(gender)), Function class() is also used to check whether the variable is a factor and if true returns “factor”., >gender=factor(c("female", "male", "male", "female"));, >class(gender), Accessing elements of a Factor:, Like we acess elements of a vector, same way we acess the elements of a factor. If gender is a, factor then gender[i] would mean acessing i th element in the factor., Example:, >gender =factor(c("female", "male", "male", "female")), >gender[4], #It prints [1] female, Levels: female male, >gender[c(2, 4)], #It prints [1] male female, Levels: female male, 41
Page 138 :
For selecting all the elements of the factor gender except ith element, gender[-i] should be used., >gender[-3], Modification of a Factor, After a factor is formed, its components can be modified but the new values which needs to be, assigned must be in the predefined level. For example, >gender[2]<-“female”, , Data Frame in R:, The Data Frame in R is a table or two-dimensional data structure. In R Data Frames, data is, stored in row and columns, and we can access the data frame elements using the row index and, column index. A data frame is a list of variables, and it must contain the same number of rows, with unique row names. The Column Names should not be Empty, The data frame’s data can be only of three types- factor, numeric and character type., Data frame in R is created as follows, >Id=c(1:5), >Name=c(“Nilesh”, “Suresh”, “Ramesh”, “Kamlesh”, “Rajesh”), >Salary=c(80000, 70000, 90000, 50000, 60000), >employee=data.frame(Id, Name,Salary), > print(employee), will print, Id Name Salary, 1, 1 Nilesh 80000, 2, 2 Suresh 70000, 3, 3 Ramesh 90000, 4, 4 Kamlesh 50000, 5, 5 Rajesh 60000, Create Named Data Frame in R:, # We are assigning new names to the Columns, >employee=data.frame("Empid" = Id, "Full_Name" = Name, "income" = Salary), >print(employee) will print, Empid Full_Name income, 1, 1, Nilesh, 80000, 2, 2, Suresh, 70000, 3, 3, Ramesh 90000, 4, 4, Kamlesh 50000, 5, 5, Rajesh, 60000, # Names function will display the Index Names of each Item >print(names(employee)), > print(names(employee)), 42
Page 139 :
[1] "Empid", , "Full_Name" "income", , Access R Data Frame Elements:, In R programming, We can access the Data Frame item in multiple ways. In this example, we, will show you how to access the data frame items using the index position. Using this index, value, we can access each and every item present in the Data Frame. Index value starts at 1 and, ends at n where n is the number of items in a data frame. For example, >Id=c(1:5), >Name=c(“Nilesh”, “Suresh”, “Ramesh”, “Kamlesh”, “Rajesh”), >Salary=c(80000, 70000, 90000, 50000, 60000)>, >employee=data.frame("Empid" = Id, "Full_Name" = Name, “Income" = Salary), 1. # Accessing all the Elements (Rows) Present in the Name Items (Column), >employee["Name"], 2. # Accessing all the Elements (Rows) Present in the 3rd Column (i.e., Occupation), >employee[3], 3. #Accessing Name column as vector, > employee[[“Full_Name"]] or, >employee[[2]], 4. # Accessing Element at 1st Row and 2nd Column, >employee[1, 2], 5. # Accessing Element at 4th Row and 3rd Column, >employee[4, 3], 6. # Accessing All Elements at 5th Row, >employee[5, ], 7. # Accessing All Item of the 4th Column, >employee[, 4], Accessing Multiple Values from R Data:, 1. # Accessing Item at 1st, 2nd Rows and 3rd, 4th Columns, >employee[c(1, 2), c(3, 4)], 2. # Accessing Item at 2nd, 3rd, 4th Rows and 2nd, 4th Columns, >employee[2:4, c(2, 4)], 3. # Accessing All Item at 2nd, 3rd, 4th, 5th Rows, >employee[2:5, ], 4. # Accessing All Item of 2nd and 4th Column, >employee[ ,c(2, 4)], 5. # Extract first three rows., >employee[(1:3), ], 6. #Adding column in data frame, 43
Page 140 :
> employee$dept=c(“Comp”, “Math”, “Ele”, “Stat”, “Eng.”), Access R Data Frame Elements using $:, In R Programming, We can also access the Data frame elements using the $ dollar symbol., Ex., >employee$Empid, >employee$Full_Name, 1. # Accessing Item at 2nd, 4th Rows of Full_Name Columns, >employee$Full_Name[c(2, 4)], 2. # Accessing Item at 2nd, 3rd, 4th, 5th Rows of income Column, >employee$income[2:5], 3. # Accessing Specific columns., >data.frame(employee$Full_Name, employee$income), Modifying R Data Frame Elements:, In R programming, We can access the data frame elements using the index position. Using this, index value, we can alter or change each and every individual element present in the data frame., For example, >Id=c(1:5), >Name=c(“Nilesh”, “Suresh”, “Ramesh”, “Kamlesh”, “Rajesh”), >Salary=c(80000, 70000, 90000, 50000, 60000)>, >employee=data.frame(Id, Name, Salary), 1. # Modifying Item at 2nd Row and 3rd Column, >employee[2, 3] =100000, 2. # Modifying All Item of 1st Column, >employee[, 1]=c(10:15), Adding Elements to Data Frame:, 1. cbind(Data Frame, Values): This method is used to add extra Columns with values. In, general, we prefer Vector as values parameter, Ex. # Adding Extra Column, >address=c(“Pimpri”, “Pune”, “Sangvi”, “Kalewadi”, “Nigdi”), >cbind(employee, address), where employee is a dataframe, 2. rbind(Data Frame, Values): This method is used to add extra Row with values., Ex. # Adding Extra Row, >rbind(employee, list(7, “Kamlesh", 8000)), Important Functions of Data Frame in R:, 1. typeof(Data Frame): This method will tell you the type of Data Frame. Since the data, frame is a kind of list, this function will return a list, 44
Page 141 :
2. class(Data Frame): This method will tell you the class of the Data Frame, 3. length(Data Frame): This method will count the number of items (columns) in a Data, Frame, 4. nrow(Data Frame): This method will return the total number of Rows present in the, Data Frame., 5. ncol(Data Frame): This method will return the total number of Columns available in the, Data Frame., 6. dim(Data Frame): This method will return the total number of Rows and Columns, present in the Data Frame., 7. str(Data Frame): This method returns the structure of the data present in the Data, Frame., 8. summary(Data Frame): This R Programming method returns the nature of the data and, the statistical summary such as Minimum, Median, Mean, Median, etc., Use of Head and Tail Functions in R Data Frame:, 1. head(Data Frame, limit): This method will return the top six elements (if you Omit the, limit). If you specify the limit as 2 then, it will return the first 2 records. It is something, like selecting the top 10 records., 2. tail(Data Frame, limit): This method will return the last six elements (if you Omit the, limit). If you specify the limit as 4, it will return the last four records., 1. # No limit - It means Displaying First Six Records, >head(emp), 2. # Limit is 4 - It means Displaying First Four Records, >head(emp, 4), 3. # Limit is 10 - It means Displaying First Four Records, >head(emp, 10), 4. # No limit - It means Displaying Last Six Records, >tail(emp), 5. # Limit is 4 - It means Displaying Last four Records, >tail(emp, 4), Practice Programs:, 1. Write a R program to find the levels of factor of a given vector., 2. Write a R program to create a data frame from four given vectors., 3. Write a R program to count the number of NA values in a data frame column., , SET A:, 1. Write a R program to change the first level of a factor with another level of a given, factor., 45
Page 142 :
2. Write a R program to create a data frame from four given vectors and display the, structure and statistical summary of a data frame., 3. Write a R program to display second row using row index and third column using, column name of a data frame., 4. Write a R program to create a data frame using two given vectors and display the, duplicated elements and unique rows of the said data frame., 5. Write a R program to call the (built-in) dataset airquality. Remove the variables 'Solar.R', and 'Wind' and display the data frame., SET B:, 1. Write an R program to concatenate two given factor in a single factor and display in, descending order., 2. Write a R program to extract the five of the levels of factor created from a random, sample from the LETTERS., 3. Write a R program to compare two data frames to find the row(s) in first data frame that, are not present in second data frame., 4. Write a R program to create a data frame from four given vectors and perform the, following, a. add a new column in a given data frame, b. add new row to data frame., c. drop specific column by name from a given data frame., d. drop row by number from a given data frame., 5. Write a R program to create a data frame from four given vectors and perform the, following, a. Extract 3rd and 5th rows with 1st and 3rd columns from a given data frame., b. Sort and display given data frame by specific column., SET C:, 1. Write a R program to create inner, outer, left, right join(merge) from given two data, frames., 2. Write a R program to save the information of a data frame in a file and display the, information of the file., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, 46
Page 143 :
Assignment 7: Data Analysis, R CSV Files:, A Comma-Separated Values (CSV) file is a plain text file which contains a list of data. These, files are often used for the exchange of data between different applications. These files can, sometimes be called character-separated values or comma-delimited files. They often use the, comma character to separate data. The idea is that we can export the complex data from one, application to a CSV file, and then importing the data in that CSV file to another application. R, allows us to read data from files which are stored outside the R environment. The file should be, present in the current working directory so that R can read it. We can also set our directory and, read file from there., Getting and setting the working directory:, In R, getwd() and setwd() are the two useful functions., ➢ The getwd() function is used to check on which directory the R workspace is pointing., ➢ And the setwd() function is used to set a new working directory to read and write files from, that directory., 1. # Getting and printing current working directory., >print(getwd()), 2. # Setting the current working directory., >setwd("C:/Users/ajeet"), Creating a CSV File:, A text file in which a comma separates the value in a column is known as a CSV file., Let's start by creating a CSV file with the help of the data from ms excel, which is mentioned, below and by saving the file (save as) with .csv extension, id,name,marks, 1,Nilesh,80.67, #student.csv file, 2,Shubham,90, 3,Rajesh,65, Reading a CSV file:, R provides read.csv() function, which allows us to read a CSV file available in our current, working directory., Syntax: data=read.csv(file, header = , sep = , quote = ), some of the most useful arguments in read csv function:, 1. file: You have to specify the file name, or Full path along with file name., 2. header: If the csv contains Columns names as the First Row then please specify TRUE, otherwise, FALSE, 3. sep: It is a short form of separator. You have to specify the character that is separating, the fields. ” , “ means data is separated by comma, , 47
Page 144 :
4. quote: If your character values (FirstName, Education column tc) are enclosed in quotes, then you have to specify the quote type. For double quotes we use: quote = “\”” in r, read.csv function, 5. nrows: It is an integer value. You can use this argument to restrict the number of rows to, read. For example, if you want top 5 records, use nrows = 5, 6. skip: Please specify the number of rows you want to skip from file before beginning the, csv read. For example, if you want to skip top 2 records, use skip = 2, , R Read csv File from Current Working Directory:, In this example, we will show you, How to read data from the csv (comma separated values) file, that is present in the current working directory in R Programming., >setwd(“E:\R”), >data <- read.csv("student.csv”), >print(data), Accessing csv file Data:, ➢ In R programming, read.csv function will automatically convert the data into Data Frame., ➢ So, all the functions that are supported by the Data Frame can be used on csv data., ➢ While we are working with csv files or read from csv files in R programming, the, following functions are the common functions used for data analysis., 1. max: This method will return the maximum value within the column, 2. min: This method will return the minimum value within the column, 3. subset(data, condition): This method will return the subset of data, and the data depends, on the condition., Examples:, 1. # Creating a data frame by reading csv file, >csv_data=read.csv("student.csv"), 2. #Accessing all the Elements (Rows) Present in the marks Column, >print(csv_data$marks), 3. # Getting the maximum marks from data frame., >Max_Marks=max(csv_data$marks), >print(Max_Marks), 4. # Accessing Element at 4th Row and 3rd Column, >print(csv_data[4, 3] ), 5. # Accessing Item at 1st, 2nd 4th Rows and 4th, 5th, 6th, 7th Columns, >csv_data [c(1, 2, 4), c(4:7)], 6. #Getting the details of the Student who score minimum marks, >Details=subset(csv_data, marks==min(marks)), >print(Details), 48
Page 145 :
7. #Getting the details of all the students whose name is Nilesh, >details=subset(csv_data,name==“Nilesh"), >print(details), 8. #Getting the details of all the student whose name is Nilesh and rollno is 5, >details=subset(csv_data,rollno==5 & name==“Nilesh”), 9. #Getting the details of all the students who score more than 60 marks, > details=subset(csv_data,marks>60), >print(details), 10. #using inbuilt dataset mtcars find the number of cars of each gear type, >data=mtcars, >f=factor(data$gear), >print(table(f)), 11. #using inbuilt dataset mtcars find the number of cars having 3 gear and 2 carburetor, >data=mtcars, >d=subset(data,gear==3 & carb==2), >print(nrow(d)), , Data Frame and dplyr package:, The data frame is a key data structure in statistics and in R. dplyr package is very very helpful for, managing data frames. The dplyr package was developed by Hadley Wickham of RStudio and is, an optimized and distilled version of his plyr package. The dplyr package does not provide any, “new” functionality to R, in the sense that everything dplyr does could already be done with base, R, but it greatly simplifies existing functionality in R. Filtering, re-ordering, and collapsing, can, often be tedious operations in R whose syntax is not very intuitive. The dplyr package is, designed to mitigate a lot of these problems and to provide a highly optimized set of routines, specifically for dealing with data frames., Installing the dplyr package:, >install.packages("dplyr"), After installing the package it is important that you load it into your R session with the library(), function., >library(dplyr), Some of the key functions provided by the dplyr package are:, 1. select: Select columns with select(). It returns a subset of the columns of a data frame., Ex., , df=iris, x<-select(df,c(Species,Sepal.Length)), head(x), 49
Page 146 :
2. filter: Filter rows with filter().It extracts a subset of rows from a data frame based on, logical conditions., Ex, , x<-filter(iris, Sepal.Length > 5.843), head(x), , 3. arrange: Arrange rows with arrange(). It helps to reorder rows of a data frame, Ex, x<-arrange(mtcars, cyl), Print(x), y<-arrange(mtcars, desc(cyl)), print(y), 4. group_by:, The group_by() function first sets up how you want to group your data., The general operation here is a combination of splitting a data frame into separate pieces, defined by a variable or group of variables (group_by()), and then applying a summary, function across those subsets (summarize())., Ex, cyl <- group_by(mtcars, cyl), summarise(cyl, mean(disp), mean(hp)), Practice Programs:, 1. Using inbuilt dataset women perform the following, a. display all rows of dataset having height greater than 120, b. display all rows of dataset in ascending order of weight, 2. Using the inbuilt mtcar dataset perform the following, a. Display all the cars having 4 gears, b. Display all the cars having 3 gears and 2 carburetor., 3. Using inbuilt PlantGrowth dataset perform the following, a. Find the flowers of each type of group, b. Display all rows of type “ctrl” having weight greater than 5.0, SET A:, 1. Using the inbuilt mtcar dataset perform the following, a. Display all the cars having mpg more than 20, b. Subset the dataset by mpg column for values greater than 15.0., 2. Using the inbuilt airquality dataset perform the following, a. Find the temperature of day 30 of month 8, b. Display the details of all the days if the temperature is greater than 90, 3. Using the inbuilt airquality dataset perform the following, a. Subset the dataset for the month July having Wind value greater than 10, b. Find the number of days having temperature less than 60, SET B:, 1. Using iris inbuilt dataset perform the following, a. Find the flowers of each type of species, 50
Page 147 :
b. Find the Sepal length and width of the flower of type setosa having maximum, petal length, 2. Using iris inbuilt dataset perform the following, a. Display details of all flowers of type virginica in ascending order of petal length., (use order function), b. Display details of first five flowers of type setosa having maximum petal length., 3. Using inbuilt PlantGrowth dataset perform the following, a. Display details of all plant having weigth greater than 5.80, b. Display details of all Plants of group trt1 in ascending order of their weight., SET C:, 1. Using inbuilt ToothGrowth dataset perform the following, a. Find supplement (supp) wise maximum and minimum length of tooth, b. Display details of first 3 tooth having minimum length for supplement OJ for dose, 1.0, Assignment Evaluation, 0: Not Done [ ], , 1: Incomplete [ ], , 2: Late Complete [, , 3: Need Improvement [ ], , 4: Complete [ ], , 5: Well Done [ ], , ], , Signature of Instructor, , 51
Page 148 :
Assignment 8: Data Visualization, Introduction:, Data visualization is an efficient technique for gaining insight about data through a visual, medium. With the help of visualization techniques, a human can easily obtain information about, hidden patterns in data that might be neglected., By using the data visualization technique, we can work with large datasets to efficiently obtain, key insights about it., In R, we can create visually appealing data visualizations by writing few lines of code., Advantages of Data Visualization in R:, 1. Understanding: It is easier to understand through graphics and charts than a written, document with text and numbers. Thus, it can attract a wider range of audiences. Also, it, promotes the widespread use of business insights that come to make better decisions., 2. Efficiency: Its applications allow us to display a lot of information in a small space., Although, the decision-making process in business is inherently complex and, multifunctional, displaying evaluation findings in a graph can allow companies to, organize a lot of interrelated information in useful ways., R Bar Charts:, A bar chart is a pictorial representation in which numerical values of variables are represented by, length or height of lines or rectangles of equal width. A bar chart is used for summarizing a set of, categorical data. In bar chart, the data is shown through rectangular bars having the length of the, bar proportional to the value of the variable.In R, we can create a bar chart to visualize the data, in an efficient manner., For this purpose, R provides the barplot() function, which has the following syntax:, Syntax: barplot(h, xlab, ylab, main, names.arg, col) where, 1. h: A vector or matrix which contains numeric values used in the bar chart., 2. xlab: A label for the x-axis., 3. ylab: A label for the y-axis., 4. main: A title of the bar chart., 5. names.arg: A vector of names that appear under each bar., 6. Col: It is used to give colors to the bars in the graph., Example: # Creating the data for Bar chart, > h=c(100,300,500,200,350,50), > barplot(h, xlab="Year", ylab="Strength", main="Bar Chart", names.arg = c (2000,, 2001, 2002,2003,2004,2005)), , 52
Page 149 :
Creating a barplot in R by reading data from CSV file:, >setwd("F:/SYBBA/R/"), >d=read.csv("SaleReport.csv", header=TRUE), , #setting the path where csv file is stored, #reading csv file data in data frame d, , SaleReport.csv File, >print(d), #printing data frame, >barplot(d$Sale.Amount, xlab="Month", ylab="Sale Amount", main="Sale Report", names.arg=, d$Month, col="red“, border="blue"), , Horizontal Bar Chart in R Programming:, In this example, we change the default vertical bar chart into a horizontal bar chart, using horiz argument in R., We also change the bar density using density argument in R barplot, >setwd("F:/Yogesh/R/"), >getwd(), >d=read.csv("SaleReport.csv",header=TRUE), >print(d), 53
Page 150 :
>barplot(d$Sale.Amount, xlab="Month", ylab="Sale Amount", main="Sale Report",, names.arg=d$Month, col="red", border="blue", horiz = TRUE, density=100), , Creating Stacked Bar Plot using Matrix:, We can create bar charts with groups of bars and stacks using matrices as input values in each, bar. One or more variables are represented as a matrix that is used to construct group bar charts, and stacked bar charts., >setwd("F:/Yogesh/R/"), >d=read.csv("class.csv",header=TRUE), >print(d), , Class.csv File, >fy=d$FY, >sy=d$SY, >ty=d$TY, >data=matrix(c(fy,sy,ty),ncol=3,byrow=TRUE), >barplot(data, xlab="class", ylab="Strength", main="Course Wise Student Strength",, names.arg=d$Class, col= c ("red", "blue", "green")), , R Scatterplots:, In a scatterplot, the data is represented as a collection of points. Each point on the scatterplot, defines the values of the two variables. One variable is selected for the vertical axis and other for, the horizontal axis., 54
Page 151 :
The scatter plots are used to compare variables. A comparison between variables is required, when we need to define how much one variable is affected by another variable., Scatterplot is created using plot() function. The syntax is as follows, Syntax:, plot(x, y, main, xlab, ylab, xlim, ylim, axes) where,, 1. X- It is the dataset whose values are the horizontal coordinates., 2. Y- It is the dataset whose values are the vertical coordinates., 3. Main- It is the title of the graph., 4. Xlab- It is the label on the horizontal axis., 5. Ylab- It is the label on the vertical axis., 6. Xlim- It is the limits of the x values which is used for plotting., 7. Ylim- It is the limits of the values of y, which is used for plotting., 8. axes- It indicates whether both axes should be drawn on the plot., Example:, Following scatterplot show the relationship between HP and MPG attribute of mtcars dataset, >plot(mtcars$hp, mtcars$mpg, xlab="HP", ylab="Milage", xlim=c(50,350), ylim=c(9,36), main=, "HP Vs Milage", col="red"), , R Histogram:, A histogram is a type of bar chart which shows the frequency of the number of values which are, compared with a set of values ranges. The histogram is used for the distribution, whereas a bar, chart is used for comparing different entities., In the histogram, each bar represents the height of the number of values present in the given, range., For creating a histogram, R provides hist() function, which takes a vector as an input and uses, more parameters to add more functionality., There is the following syntax of hist() function:, Syntax: hist(v, main, xlab, ylab, xlim, ylim, breaks, col, border) where, 1. V: It is a vector that contains numeric values., 2. Main: It indicates the title of the chart., 3. Col: It is used to set the color of the bars., 4. Border: It is used to set the border color of each bar., 5. Xlab: It is used to describe the x-axis., 6. Ylab: It is used to describe the y-axis., 7. Xlim: It is used to specify the range of values on the x-axis., 8. Ylim: It is used to specify the range of values on the y-axis., 9. Breaks: It is used to mention the width of each bar., 55
Page 152 :
Example: Consider Vector V which consists of weight of different students, > V=c(55,67,78,82,57,62,74,80,52,64,76,66), >hist(v, xlab = "Weight", ylab="Frequency", col = "green", border = "red"), , R Boxplot:, Boxplots are a measure of how well data is distributed across a data set. This divides the data set, into three quartiles. This graph represents the minimum, maximum, average, first quartile, and, the third quartile in the data set. Boxplot is also useful in comparing the distribution of data in a, data set by drawing a boxplot for each of them., R provides a boxplot() function to create a boxplot. There is the following syntax of boxplot(), function, Syntax: boxplot(data or formula, xlab, ylab, main, names, col) where,, 1. data: DataFrame, or List that contains the data to draw boxplot., 2. Xlab: It is used to describe the x-axis., 3. Ylab: It is used to describe the y-axis., 4. Main: It is used to give a title to the graph., 5. Names: It is the group of labels that will be printed under each boxplot., Creating a Boxplot in R Programming:, In this example, we create a Boxplot using the airquality data set, >a=airquality, > boxplot(a$Wind), , 56
Page 153 :
Use Formula to create a Boxplot in R:, In this example, we create a Boxplot using the formula argument, formula: It should be something like value~group, where value is the vector of numeric values,, and the group is the column you want to use as a group by., e.g., if you want to draw a boxplot for Monthwise wind speed, then value = Wind and group =, Month, >a=airquality, >boxplot(a$Wind~a$Month, xlab="Month", ylab="Wind Speed", main="Box Plot",, col="red"), , Practice Programs:, 1. Write an R program to draw an empty plot and an empty plot specifies the axes limits of, the graphic., 2. Using inbuilt airquality dataset make a scatter plot to compare Wind speed and, temperature., 3. Using inbuilt iris dataset create Histogram for Petal.length values, 4. Using iris dataset draw horizontal bar plot for Petal length values for species setosa, , SET A:, 1. Using inbuilt mtcars dataset, a) Create a bar plot for attribute mpg for all cars having 3 gears, b) Create a Histogram to show number of cars per carburetor type whose mpg is, greater than 20, 2. Using airquality dataset, a) Create a scatter plot to show the relationship between ozone and wind values by, giving appropriate value to color argument, b) Create a bar plot to show the ozone level for all the days having temperature, greater than 70, SET B:, 1. Using inbuilt mtcars dataset, a. Create a bar plot that shows the number of cars of each gear type., 57
Page 154 :
b. Draw a scatter plot showing the relationship between wt and mpg for all the cars, having 4 gears, 2. Using airquality dataset, a. Show the statistical summary using box plot for Temprature value of month June, b. Using histogram show the frequency of number of days for Temp values of month, August, SET C:, 1. Using inbuilt mtcars dataset show a stacked bar graph of the number of each gear type, and how they are further divided out by cyl, 2. Draw boxplot to show the distribution of mpg values per number of gears, Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 58
Page 155 :
Section-V, , Block Chain
Page 156 :
Assignment No 1: Working with Blockchain, Blocks are like ledger pages while the whole record-keeping book is the blockchain. A block is, a file that stores unalterable data related to the network. It hold all the records of valid, cryptocurrency transactions. They are hashed and encoded into a hash tree or Merkle tree. Every, block has the cryptographic hash of the block that precedes it in the blockchain., A block, plus all the blocks before and after it, form a block chain., The first block in a blockchain is the Genesis Block. It is the only one with no data on the, previous block because there is no block before it., Blockchain, A blockchain is a continuously growing list of records, called blocks, which are linked and, secured using cryptograph., For use as a distributed ledger a blockchain is typically managed by a peer-to-peer network, collectively adhering to a protocol for validating new blocks. The data recorded in any given, block cannot be altered without the alteration of all subsequent blocks and a collusion of the, network majority., , The structure of blockchain program:, Step1: Import SHA256 Hash Function, Step2: Create a Block class, {, //Consructor, //Hash function, }, Step 3:Create a Bslockchain Class, {, //Constructor, //function to create genesis block, //function to get latest block, //function to add block, }, Step 4:, Display blockchain information, , 1
Page 158 :
✓ Data: parameter can include any type of data that you want to associate with this, block. If you want to build a cryptocurrency you can store transaction details in here, like sender/receiver and the amount of money that was transferred., ✓ previousHash: is a string that contains the hash of the previous block. This is what, will create the chain of blocks and will be very important to ensure the integrity of, our blockchain later., ✓ Hashes: Each block points towards the previous block (that's why we have the, previousHash attribute). That means that each block needs a hash., 3: Calculating hash using function:, Now that we have our calculateHash() method, let's use it in the constructor of our Block:, calculateHash(), {, return, SHA256(this.index+this.previous+this.timestamp+JSON.stringify(this.data)).toString();, }, 4: Creating a Blockchain class:, This defines the structure of a Blockchain should look like. So let's create a new class for that:, class Blockchain, {, constructor(), {, this.chain = [this.createGenesisBlock()];, }, In this case, the blockchain is a very simple object that contains a property chain. This is an array, containing all the blocks on the chain. Before we can add new blocks, we have to add a "genesis, block". This is the first block on the chain and it's a bit special because it cannot point to a, previous block., 5: Function for creating Genesis Block:, The following method is used to create a Genesis Block, createGenesisBlock(), {, return new Block(0,"01/01/2017", "Genesis block", "0");, }, Back in the constructor of our Blockchain class, we can now add the genesis block, Whenever we create a new Blockchain instance:, 6: Function for getting latest block, getLatestBlock(){, 3
Page 159 :
return this.chain[this.chain.length - 1];, }, 7. Function for adding block: The addBlock method is a bit more complicated. Before we can, add a new block to our chain, we have to correctly set the previousHash property of that block., It has to be set to the hash of the latest block on our chain. And we also have to calculate the, hash of the new block:, addBlock(newBlock){, newBlock.previousHash=this.getLatestBlock().hash;, newBlock.hash=newBlock.calculateHash();, this.chain.push(newBlock);, }, 8. Display block information: In reality, adding blocks to a blockchain requires you to "mine", it., let savjeeCoin = new Blockchain();, And let's add a few blocks:, savjeeCoin.addBlock(new Block("20/07/2017", { amount: 4 }));, savjeeCoin.addBlock(new Block("22/07/2017", { amount: 10 }));, There — we have created two new blocks. Let's see what our blockchain now looks like., We will stringifySavjeeCoin and use four spaces to format it:, console.log(JSON.stringify(savjeeCoin, null, 4));, , Note: After combining all the above steps the final program will look like following:, Program name: main.js, const SHA256 = require("crypto-js/sha256");, class Block, {, constructor(index,timestamp, data, previousHash = ''), {, this.index=index;, this.timestamp = timestamp;, this.data = data;, this.previousHash = previousHash;, this.hash=this.calculateHash(), }, calculateHash(), {, 4
Page 160 :
return, SHA256(this.index+this.previous+this.timestamp+JSON.stringify(this.data)).toString();, }, }, class Blockchain, {, constructor(), {, this.chain = [this.createGenesisBlock()];, }, createGenesisBlock(), {, return new Block(0,"01/01/2017", "Genesis block", "0");, }, getLatestBlock(), {, return this.chain[this.chain.length - 1];, }, addBlock(newBlock), {, newBlock.previousHash=this.getLatestBlock().hash;, newBlock.hash=newBlock.calculateHash();, this.chain.push(newBlock);, }, }, let savjeeCoin = new Blockchain();, savjeeCoin.addBlock(new Block(1,"20/07/2017", { amount: 4 }));, savjeeCoin.addBlock(new Block(2,"22/07/2017", { amount: 10 }));, console.log(JSON.stringify(savjeeCoin, null, 4));, Building A Small Blockchain Application :, 1. Installation:, ➢ Download the Visual Studio Code installer for Windows., ➢ Install VS Code and install additional component latest version of Node.js, 2. Write a code for Building Blocks:, Step 1: Create a folder on any drive where you can save your blockchain program, Step 2: Open Visual Studio Code, Step 3: Select File → Open Folder ( Select your Blockchain program folder), , 5
Page 161 :
Step 4: In the EXPLORER section your folder is displayed. There are 4 icons, near to your Folder Name. Click on new file icon and give a file name with, “.js” extension, Step 5: Write your program in the “.js” file, Step 6: Select Run→Run without Debugging→Select Environment→Node.js, And you will get the output, OR, Step 6:, 1. Select Terminal→New Terminal, (a new terminal is open with our folder Eg: D:\Blockchain>), 2. Type following command, D:\Blockchain>npm install --save crypto-js, 3. Execute the program using following command, D:\Blockchain>node FileName.js (Press Enter), D:\Blockchain->node Demo.js, ➢ The output is what our blockchain looks like:, , 6, , Output of Blockchain
Page 168 :
},, "previousHash":, "1142e97a465daaa9e87342580091d451c048f8f1d3ca052f59e1d39744afd7b0",, "hash": "a28d562675aed283d100e9e64d67e91525147be376873c007be61d74100d8de7", }, ], }, C:\blockchain-js>, Practice Programs:, 1. Write a blockchain application in JavaScript to create bitcoin wallet., 2. Write a blockchain application in JavaScript for the simple transaction., 3. Write a blockchain application in JavaScript for the implementation of SHA256(), function., 4. Write a decentralized block chain application in JavaScript to calculate fine for the, students those have submitted books late., SET A:, 1. Write a blockchain application in JavaScript for the creation of Transaction block for, the account holder., 2. Write a blockchain application in JavaScript to calculate hash code for the, transaction., 3. Write a JavaScript code for the implementation of block chain technology.(At least, two block)., SET B:, 1. Write a blockchain application in JavaScript for the simple transaction., 2. Write a decentralized block chain application in JavaScript for the bank transaction, 3. Write a blockchain application in JavaScript to transfer cryptocurrency from one, account to another account., SET C:, 1. Write a decentralized block chain application in JavaScript for the bank transaction, system., 2. Write a blockchain application in JavaScript for the generation of bitcoin after, completion of transaction., Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 13
Page 169 :
Assignment No 2: Implementation of Smart Contracts and Hyperledger, Solidity:, , Solidity is an object-oriented programming language for writing smart contracts. It is used for, implementing smart contracts on various blockchain platforms, most notably, Ethereum., Smart Contract:, Smart contracts help you exchange money, property, shares, or anything of value in a, transparent, conflict-free way while avoiding the services of a middleman. They showed the, world how the blockchain can evolve from a simple payment mechanism to something far more, meaningful and powerful. Smart contracts are automated contracts. They are self-executing with, specific instructions written in its code which get executed when certain conditions are made., Smart contracts are how things get done in the Ethereum ecosystem. When someone wants to get, a particular task done in Ethereum they initiate a smart contract with one or more people. Every, single transaction that you are doing, the smart contracts will get recorded and updated by the, network. It keeps everyone involved with the contract responsible for their actions., Smart contracts are implemented by using SOLIDITY Programming Language., Solidity is a programming language , smart contracts are series of instructions that write in, ‘solidity’. Language is set of instruction if the first set of instructions are done then execute the, next instruction and after that the next and keep on repeating until you reach the end of the, contract. Each and every step that you take acts like a trigger for the next step to execute itself, like a vending machine., Some important point of solidity language., ✓ Solidity is a typed language; the type of each variable (state and local) needs to be, specified at compile-time. Solidity provides several elementary types which can be, combined to form complex types., ✓ Solidity is a contract-oriented, high-level language for implementing smart contracts. It, was partially by C++, Python and JavaScript and is designed to target the Ethereum, Virtual Machine (EVM)., ✓ Solidity supports inheritance, libraries and complex user-defined types among other, features., 1. Structure of solidity Program, A Solidity source files can contain any number of contract definitions, import directives and, pragma directives., pragma contract >=0.4.0<0.6.9, import “filename”, contract ContractName, {, 14
Page 170 :
<variable declaration>, <mappings>, <constructor>, <functions>, <modifiers>, }, ▪, , ▪, ▪, ▪, ▪, ▪, ▪, ▪, , Pragma: The first line is a pragma directive which tells that the source code is written, for Solidity version 0.4.0 or anything newer that does not break functionality up to, but, not including, version 0.6.9. You also write this but it specific compile, Pragma solidity ^0.4.0;, Contract: A Solidity contract is a collection of code like function and data that resides at, a specific address on the Ethereum blockchain., Importing Files: The following statement imports all global symbols from "filename"., import "filename";, Variable declaration: Variables are the names you give to computer memory locations, Mapping: Mapping is a reference type as arrays and structs., Constructor: is a special kind of function. It uses to initialize the variables, data., Function: Functions are the executable units of code within a contract., Function modifiers: can be used to amend the semantics of functions in a declarative, Function Modifiers are used to modify the behavior of a function., , 2. Comment: Any text before you write in solidity language // the end of a line and also In, between /* ….. */ and the end of a line is treated as a comment and is ignored by Solidity, Compiler., // This is a comment. It is similar to comments in C++, /*, * This is a multi-line comment in solidity, * It is very similar to comments in C Programming, */, 3. Reserved Keywords: Following are the reserved keywords in Solidity, abstract, , after, , alias, , apply, , auto, , case, , catch, , copyof, , default, , define, , final, , immutable, , implements, , in, , inline, , let, , macro, , match, , mutable, , null, , 15
Page 171 :
Of, , override, , partial, , promise, , reference, , relocatable, , sealed, , sizeof, , static, , supports, , switch, , try, , typedef, , typeof, , unchecked, , 4. Data Type: Based on the data type of a variable, the operating system allocates memory and, decides what can be stored in the reserved memory., Data Type used in Solidity:, bool, integer (int8-int256/uint8-uint256), address, bytes, string, hex, enum, 5. Variable: Variables are the names you give to computer memory locations which are used to, store values in a computer program., Solidity supports three types of variables., ✓, , State Variables − Variables whose values are permanently stored in a contract storage., That declared into contract., , ✓, , Local Variables − Variables whose values are present till function is executing. That, declared inside a function., , ✓, , Global Variables − Special variables exists in the global namespace used to get, information about the blockchain. This are specific variables that are exist in global, workplace., , Scope of local variables is limited to function in which they are defined but State variables can, have three types of scopes with names public ,private, internal., e.g. uint public x = 40;, 6. Operators:, Solidity supports the following types of operators., ✓, ✓, ✓, ✓, ✓, ✓, , Arithmetic Operators: +, -, *, / , %, ++, -Comparison Operators: ==, <, >, <=, >=,!=, Assignment Operators: =, += ,-=, *=, /=, %=, Logical (or Relational) Operators:&&, ||,!, Assignment Operators:&, | , << , >>, ~, ^, >>>, Conditional (or ternary) Operators:?:, , 7. Loops:, , 16
Page 172 :
➢ while loop is to execute a statement or code block repeatedly as long as an expression is, true. Once the expression becomes false, the loop terminates., Syntax:, while (conditional expression) {, Statement(s) to be executed if conditional expression is true, }, ➢ Do…while loop:The do...while loop is similar to the while loop except that the condition, check happens at the end of the loop, Sytax:, do {, Statement(s) to be executed;, } while (conditional expression);, ➢ For Loop :It is a iterative loop. Its contains initialization, condition, iteration statement, Syntax:, for (initialization; condition; iteration statement) {, Statement(s) to be executed if condition is true }, 8. Decision making statement: Decision making statements such as If statement, if else, statement & If else if statement same as c programming language., 9. String: String is nothing but a sequence of characters. String literal using both double quote, (") and single quote ('), eg:, string myname = "Rajashri";, In Solidity we can assign String literal to a byte32 type variable easily., byte32 myname = “Rajashri”;, We can convert byte to string following code, bytes memory bstr = new bytes(10);, string message = string(bstr);, 10. Array: Arrays can have a compile-time fixed size, or they can have a dynamic size. The type, of an array of fixed size k and element type T is written as T[k], and an array of dynamic size as, A[]., ▪ Bytes and Strings as Arrays Variables of type bytes and string are special arrays. A, bytes is similar to byte[], but it is packed tightly in call data and memory. String is equal, to bytes but does not allow length or index access., ▪ Allocating Memory Array: Memory arrays with dynamic length can be created using, the new operator. As opposed to storage arrays, it is not possible to resize memory arrays, (e.g. the .push member functions are not available). You either have to calculate the, required size in advance or create a new memory array or copy every element., pragma solidity >=0.4.16 <0.7.0;, 17
Page 173 :
contract C {, function f(uint len) public pure {, uint[] memory a = new uint[](7);, bytes memory b = new bytes(len);, assert(a.length == 7);, assert(b.length == len);, a[6] = 8;}, }, Array Members, 1. length: Arrays have a length member that contains their number of elements. The length, of memory arrays is fixed (but dynamic, i.e. it can depend on runtime parameters) once, they are created., 2. push(x): Dynamic storage arrays and bytes (not string) have a member function called, push(x) that you can use to append a given element at the end of the array. The function, returns nothing. Syntax: x.push().t = 2 or x.push() = b., 3. pop: Dynamic storage arrays and bytes (not string) have a member function called pop, that you can use to remove an element from the end of the array. This also implicitly calls, delete on the removed element., 11. Enum Types: Enum can be used to create custom types with a finite set of ‘constant values’, // SPDX-License-Identifier: GPL-3.0, pragma solidity >=0.4.0 <0.7.0;, contract Purchase {, enum State { Created, Locked, Inactive } // Enum, }, Struct Types: Structs are custom defined types that can group several variables, pragma solidity >=0.4.0 <0.7.0;, contract Ballot {, struct Voter { // Struct, uint weight;, bool voted;, address delegate;, uint vote;, }, }, 12. Function: Functions are the executable units of code within a contract. Function Calls can, happen internally or externally and have different levels of visibility towards other contracts., Functions accept parameters and return variables to pass parameters and values between them., Function syntax:, Function FunctionName(Arguments…) <visibility><state mutablitiy> returns (<return types>) {, 18
Page 174 :
// statement that write in, }, State mutablitiy:, view – not to modify the state, pure – not to read from or modify the state, payable- to receive ether, e.g. function hi() public pure returns (string memory) {, return ("Hello World");, }, , 13. Cryptographic Function: Solidity provides inbuilt cryptographic functions as well. Some, inbuilt function like, ✓ keccak256 (bytes memory) : this function is useful for to computes the Keccak-256 hash, of the input., ✓ ripemd160(bytes memory) returns (bytes20): this function computes compute, RIPEMD-160 hash of the input the SHA-256 hash of the input., ✓ sha256(bytes memory) : This function is useful to compute the SHA-256 hash of the, input., ✓ recrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) : This, function is useful for recover address associated with the public key from elliptic curve, signature or return zero on error., e.g. function callKeccak256() public pure returns(bytes32 result{, return keccak256("ABC");, }, 14. Function modifiers: can be used to amend the semantics of functions in a declarative, Function Modifiers are used to modify the behavior of a function. The function body is inserted, where the special symbol "_;" appears in the definition of a modifier., //SPDX-License-Identifier: MIT, pragma contract ^5.0.0, contract Purchase {, address public seller;, modifier onlySeller() { // Modifier, require(, msg.sender == seller,, 19
Page 175 :
"Only seller can call this.", );, _;, }, function abort() public view onlySeller { // Modifier usage, // ..., }, }, , 15. Events: Events are convenience interfaces with the EVM logging facilities.Event is an, inheritable member of a contract. An event is emitted, it stores the arguments passed in, transaction logs. These logs are stored on blockchain and are accessible using address of the, contract till the contract is present on the blockchain., //Declare an Event, event Deposit(address indexed _from, bytes32 indexed _id, uint _value);, //Emit an event, emit Deposit(msg.sender, _id, msg.value);, 16. Contract: Contract in Solidity is similar to a Class in C++. A Contract have following, properties., •, , Constructor − A special function declared with constructor keyword which will be, executed once per contract and is invoked when a contract is created., , •, , State Variables − Variables per Contract to store the state of the contract., , •, , Functions − Functions per Contract which can modify the state variables to alter the, state of a contract., , Visibility Quantifiers, Following are various visibility quantifiers for functions/state variables of a contract., •, , external − External functions are meant to be called by other contracts. They cannot be, used for internal call. To call external function within contract this.function_name() call, is required. State variables cannot be marked as external., , •, , public − Public functions/ Variables can be used both externally and internally. For, public state variable, Solidity automatically creates a getter function., , •, , internal − Internal functions/ Variables can only be used internally or by derived, contracts., , •, , private − Private functions/ Variables can only be used internally and not even by, derived contracts., 20
Page 176 :
E.g. public contract MyContract {, // Statements, }, Contracts support inheritance like using is keyword, Contract C is D {, //statements, }, 17. Mapping: Mapping is a reference type as arrays and structs. Mapping can only have type, of storage and are generally used for state variables.Mapping used as public modifier. Solidity, automatically creates getter for it., Syntax:, mapping(_KeyType => _ValueType), •, , KeyType − can be any built-in types plus bytes and string. No reference type or complex, objects are allowed., , •, , ValueType − can be any type., , 18. Address: The address type is to use for account address specially. comes in two flavors,, which are largely identical:, • address: Holds a 20 byte value (size of an Ethereum address)., • address payable: Same as address, but with the additional members transfer and send., The idea behind this distinction is that address payable is an address you can send Ether, to, while a plain address cannot be sent Ether, Members of Addresses, • balance and transfer:, It is possible to query the balance of an address using the property balance and to send Ether (in, units of wei) to a payable address using the transfer function., address payable x = address(0x123);, address myAddress = address(this);, if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);, • send: Send is the low-level counterpart of transfer. If the execution fails, the current contract, will not stop with an exception, but send will return false., recipient.send(1 ether);, • call, delegatecall and staticcall, In order to interface with contracts that do not adhere to the ABI, or to get more direct control, over the encoding, the functions call, delegatecall and staticcall are provided., bytes memory payload = abi.encodeWithSignature("register(string)", "MyName");, (bool success, bytes memory returnData) = address(nameReg).call(payload);, 21
Page 177 :
require(success);, , Truffle:, Truffle is a development environment, testing framework and asset pipeline for Ethereum,, aiming to make life as an Ethereum developer easier. With Truffle, we can Built-in smart, contract compilation, linking, deployment and binary management.With Truffle, you get:, ▪, ▪, ▪, ▪, ▪, ▪, ▪, ▪, , Built-in smart contract compilation, linking, deployment and binary management., Automated contract testing with Mocha and Chai., Configurable build pipeline with support for custom build processes., Scriptable deployment & migrations framework., Network management for deploying too many public & private networks., Interactive console for direct contract communication., Instant rebuilding of assets during development., External script runner that executes scripts within a Truffle environment., , Web3:, Web3 is a collection of libraries which allow you to interact with a local or remote Ethereum, node, using a HTTP or IPC connection. The web3 JavaScript library interacts with the Ethereum, blockchain. It can retrieve user accounts, send transactions, interact with smart contracts, and, more., Web3.js API Type:, ➢ eth: Ethereum blockchain related methods, ➢ net: Node’s network status, ➢ personal: Account functions and sending, ➢ db: Get/put for local LevelDB, ➢ shh: P2P messaging using Whisper, , Hyperledger, Hyperledger is an umbrella project, under the Linux Foundation. NodeJs, Alljoyn,, Dronecode are some example projects that have adopted the “Linux Way”, i.e. to interlace a, community of developers who work on open source projects thus maintaining a cycle where a, piece of code is constantly getting modified and redistributed., , Hyperledger Fabric:, 22
Page 178 :
Hyperledger Fabric is a popular Hyperledger project. It is used for developing solutions, and applications with a modular architecture. Some of its key features include plug-and-play, membership, consensus, and other features. This gives the industry a lot of options to work with, blockchain technology and can be used in a plethora of industry use-cases. Also, its focus is to, bring more scalability without the need to sacrifice privacy. It has two components, including, State data and transaction log. Hyperledger Fabric supports to world state data store in LevelDB, & CouchDB., Fabric is the first distributed ledger platform to support smart contracts authored in generalpurpose programming languages such as Java, Go and Node.js, rather than constrained domainspecific languages (DSL). This means that most enterprises already have the skill set needed to, develop smart contracts, and no additional training to learn a new language or DSL is needed., At the core, Hyperledger Fabric wants to provide a customized yet powerful and comprehensive, enterprise blockchain solution., , Steps of Installing Hyperledger fabric & build a Hyperledger on Ubuntu, Prerequisite:, Step 1: Installing cURL type on terminal: sudo apt install curl, , Step 2: Installing Docker type on terminal : sudo apt install docker, , 23
Page 179 :
After installation you check the version type on terminal : docker–version, Step 3: Installing Docker Compose type on terminal: sudo apt install docker-compose, , After installation you check thee version type on terminal: docker-compose --version, Step 4: Installing Go Language type on terminal : sudo apt install golang-go, , 24
Page 181 :
Step 7: Installing python type on terminal: sudo apt install python, , Step 8: After Installation these two command type on, gitconfig --global core.autocrlf false, gitconfig --global core.longpaths true, , 26
Page 182 :
For checking that command, gitconfig --global core.autocrlf, gitconfig --global core.longpaths, Step 9: Create your own directory type on terminal, mkdir <your directory name>, e.g., mkdir Rajshri, , Step 10: Go to your created directory. Type on terminal, cd<your directory name> e.g.cd Rajshri, Step 11: Download files of fabric sample using this command type on terminal, curl -sSLhttps://goo.gl/6wtTN5 | bash -s 1.1.0 1.1.0 0.4.6, Download for latest version files of fabric samples, curl –sSLhttp://bit.ly/2ysbOFE | bash -s, , 27
Page 183 :
Step 12: Go to your downloaded directory. Type on terminal, cd fabric-samples/first-network, , Step 13: check the files on that path Type on terminal: ls -l, , 28
Page 184 :
Step 14: Then generate a network using to run file type on terminal, ./byfn.sh generate, , Step 15: Then start a network using type on terminal: ./byfn.sh up, Step 16: Then end or stop a network using type on terminal: ./byfn.sh down, , 29
Page 186 :
> Network name: 'ganache', > Network id:, 5777, > Block gas limit: 6721975 (0x6691b7), deploy_SmartContarct1.js, =======================, Replacing 'SmartContarct1', ---------------------->transaction, hash: 0xce20f7cdc9439852e3a7c5c214d0224b776bb09ec115786b99ae6face03d1db3, > Blocks: 0, Seconds: 0, >contract address: 0x980B5f555278Da4f02baee2B506dF941169bf257, >block number:, 5, >block timestamp: 1593797676, >account:, 0xD5d153C889d668DF699225674f4d2d91bE16f5F8, >balance:, 99.99113358, >gas used:, 94683 (0x171db), >gas price:, 20 gwei, >value sent:, 0 ETH, >total cost:, 0.00189366 ETH, , > Saving migration to chain., > Saving artifacts, ------------------------------------> Total cost:, 0.00189366 ETH, , 2. Write an Ethereum application in JavaScript for HELLO World contract., Write Code in helloworld.sol, //SPDX-License-Identifier: MIT, pragma solidity >= 0.5.0 < 0.7.0;, contract helloworld {, constructor() public {, }, function hi() public pure returns (string memory) {, return ("Hello World");, }, }, Write Code in Deploy_helloworld.js, var HelloWorld=artifacts.require ("./helloworld.sol");, 31
Page 188 :
------------------------------------> Total cost:, 0.0067537 ETH, Summary, =======, > Total deployments: 4, > Final cost:, 0.01422648 ETH, 3. Write an Ethereum application in JavaScript to transfer currency from one account to, another account., Write a code under MySendEther.sol, // SPDX-License-Identifier: MIT, pragma solidity >=0.4.0 <0.7.0;, contract MySendEther {, address public minter;, mapping (address => uint) public balances;, event Sent(address from, address to, uint amount);, constructor() public {, minter = msg.sender;, }, function mint(address receiver, uint amount) public{, require(msg.sender == minter);, require(amount < 1e60);, balances[receiver] += amount;, }, function send(address receiver, uint amount) public {, require(amount <= balances[msg.sender], "Insufficient balance.");, balances[msg.sender] -= amount;, balances[receiver] += amount;, emit Sent(msg.sender, receiver, amount);, }, }, Write a code under Deploy_MySendEther.js, const MySendEther = artifacts.require("./MySendEther.sol");, module.exports = function(deployer) {, deployer.deploy(MySendEther);, };, truffle compile, Compiling your contracts..., ===========================, > Compiling .\contracts\ MySendEther.sol, >Artifacts written to D:\SmartContracts\HelloWorld\build\contracts, 33
Page 189 :
> Compiled successfully using:, - solc: 0.5.16+commit.9c3226ce.Emscripten.clang, truffle migrate, Compiling your contracts..., ===========================, > Compiling .\contracts\MySendEther.sol, >Artifacts written to D:\SmartContracts\HelloWorld\build\contracts, > Compiled successfully using:, - solc: 0.5.16+commit.9c3226ce.Emscripten.clang, Starting migrations..., ======================, > Network name: 'ganache', > Network id:, 5777, > Block gas limit: 6721975 (0x6691b7), deploy_MySendEther.js, =====================, Replacing 'MySendEther', --------------------->transaction, hash: 0x0baefe4d8587feef205173fd316734a5d38df66f6ef9865b2fd20ae45ca61b02, > Blocks: 0, Seconds: 0, >contract address: 0xf484673A0BafcB54Dc061e725479C21C0C2C5557, >block number:, 3, >block timestamp: 1593797675, >account:, 0xD5d153C889d668DF699225674f4d2d91bE16f5F8, >balance:, 99.99357406, >gas used:, 114781 (0x1c05d), >gas price:, 20 gwei, >value sent:, 0 ETH, >total cost:, 0.00229562 ETH, , > Saving migration to chain., > Saving artifacts, ------------------------------------> Total cost:, 0.00229562 ETH, Practice Programs:, 1. Write a solidity program for the implementation of scope of the veriables (local, state,, global )., 2. Write a solidity program to perform setter and getter operations on State veriable., 3. Write a solidity program for the implementation of looping statement., 4. Write a solidity program to implement compile-time fixed size or a dynamic size array., 5. Write an Ethereum application in JavaScript for smart contracts., , 34
Page 190 :
6. Write an Ethereum application in JavaScript to transfer currency from one account to, another account., 7. Write an Ethereum application in JavaScript for the implementation of blockchain, technology., 8. Write a blockchain application in JavaScript to create a block by using hyperledger, fabric., SET A:, 1. Write a solidity program to display “Hello Word”, 2. Write a solidity program to create simple contract that you can get, increment and, decrement the count store in this contract., 3. Write a solidity program for the implementation of primitive data types., SET B:, 1. Write a solidity program to convert Ether and Wei (Note: one dollar is equal to 100 cent,, one ether is equal to 1018 wei), 2. Write a solidity program to calculate how much ether do you need to pay for a, transaction?(Formula: gas spent * gas price amount of ether), Note:, • gas is a unit of computation, • gas spent is the total amount of gas used in a transaction, • gas price is how much ether you are willing to pay per gas, 3. Write a solidity program for the implementation of conditional statement., SET C:, 1. Write a solidity program to implement enumeration (enum)., 2. Write a solidity program to implement the function., 3. Write an Ethereum application in JavaScript for HELLO World contract., , Assignment Evaluation, 0: Not Done [ ], 3: Need Improvement [ ], , 1: Incomplete [ ], 4: Complete [ ], , 2: Late Complete [, 5: Well Done [ ], , ], , Signature of Instructor, , 35