Computer Practice Laboratory 2

51
Computer Practice Laboratory – II By eee exclusive author

description

computer lab manual

Transcript of Computer Practice Laboratory 2

Computer Practice Laboratory – II

By eee exclusive author

List of exercises

a) Basic shell commands1. Display commands2. File manipulation commands3. Directory manipulation commands4. Process commands5. Grouping commands

b) Shell Programs1. Write shell script for simple shell programming.2. Write shell script for conditional statements.3. Write shell script testing and loops statements.4. Greatest of three numbers5. Conversion of temperature6. Checking the number prime or not7. Raising a number to its power8. Armstrong number9. Fibonacci series10. Factorial of a given number11. Employee details12. Multiplication table13. Menu driven calculatorc) Unix – C programs

1. Function with no arguments & no return values2. Function with arguments & return values3. Dynamic memory allocation4. Dynamic allocation of a string & print it backwards5. Binary search using function6. Factorial in finding ncr using function7. Cosine values using function8. Product of matrix using arrays9. Creation & reading the content of a file10. Appending content to the file

UNIXCOMMANDS

INTRODUCTION TO UNIXUNIX:It is a multi-user operating system. Developed at AT & T Bell Industries,USA in1969.Ken Thomson along with Dennis Ritchie developed it from MULTICS(Multiplexed Information and Computing Service) OS.By 1980, UNIX had been completely rewritten using C language.LINUX:It is similar to UNIX, which is created by Linus Torualds. All UNIXcommands works in Linux also and it is available free of cost. The main feature ofLinux is coexisting with other OS.

STRUCTURE OF A LINUX SYSTEM:

It consists of three parts.a) UNIX kernelb) Shellsc) Tools and Applications

USERS|

UNIX SYSTEM|

TOOLS AND APPLICATIONS|

SHELLS|

THE UNIX KERNEL|

COMPUTER HARDWARE

UNIX KERNEL:Kernel is the core of the UNIX OS. It controls all tasks, schedule allprocesses and carries out all the functions of OS.Decides when one program stops and another starts.

SHELL:Shell is the command interpreter in the UNIX OS. It accepts commandfrom the user and analyses and interprets them.

1. DISPLAY COMMANDa) date – used to check the date and timesyn: $ dateFormat Purpose Example Result+ % m To display only month $ date + % m 06+ % h To display month name $ date + % h June+ % d To display day of month $ date + % d O1+ % y To display last two digits of the year $ date + % y 09+ % H To display hours $ date + % H 10+ % M To display minutes $ date + % M 45+ % S To display seconds $ date + % S 55

b) cal – used to display the calendarsyn: $ cal 2 2009

c) echo – used to print the message on the screen.Syn: $ echo “text”

d) ls – used to list the files. Your files are kept in a directory.Syn: $ ls

ls – s All files (include files with . prefix)ls – l Long detail (provide file statistics)ls – t Order by creation timels – u Sort by access time (or show when last accessed together with –l)ls – s Order by sizels – r Reverse orderls – f Mark directories with / ,executable with * , symbolic links with @ , local sockets with = ,

named pipes (FIFOs) with |ls – s Show file sizels – h “Human Readable”, show file size in Kilo Bytes & Mega Bytes (h can be used together with –l or -s)ls [a-m]* List all the files whose name begin with alphabets From „a‟ to „m‟ls [a]* List all the files whose name begins with ‘a’ or ‘A’

Eg: $ ls > mylistOutput of ‘ls’ command is stored to disk file named ‘my list’

e) lp – used to take printoutssyn: $ lp filename

f) man – used to provide manual help on every UNIX commands.

Syn: $ man unixcommand$ man cat

g) who & who am i – it displays data about all users who have logged in tothe system currently. The next command displays about current user only.Syn: $ who$ who am i

h) uptime – tells you how long the computer has been running since its lastreboot or power-off.Syn: $ uptime

i) uname – it displays the system information such as hardware platform,system name and processor, OS type.Syn: $ uname –a

j) hostname – displays and set system host namesyn: $ hostnamek) bc – stands for „best calcualtor‟$ bc $ bc $ bc $ bc10/2*3 scale =1 ibase = 2 sqrt(196)15 2.25+1 obase = 16 14Quit 3.35 11010011 quit 89275 1010 Ā Quit

$ bc $ bc-lfor (i=1;i<3;i=i+1)I scale = 21 s(3.14)2 03Quit

Result:Thus the display commands were executed successfully.

2. FILE MANIPULATION COMMANDS

a) cat – this create, view and concatenate files.Creation:Syn: $ cat > filename

Viewing:Syn: $ cat filename

Add text to an existing file:Syn: $ cat >> filename

Concatenate:Syn: $ cat file1 file2 > file3$ cat file1 file2 >> file3 (no overwriting of file3)b) grep – used to search a particular word or pattern related to that word fromthe file.

Syn: $ grep searchword filenameEg: $ grep anu student

c) rm – deletes a file from the file systemsyn: $ rm filename

d) touch – used to create a blank file.Syn: $ touch file names

e) cp – copies the files or directoriessyn: $ cp source file destination fileeg: $ cp student stud

f) mv – to rename the file or directorysyn: $ mv old file new fileEg: $ mv –i student student list(-i prompt when overwrite)

g) cut – it cuts or pick up a given number of character or fields of the file.Syn: $ cut <option> <filename>Eg: $ cut –c filename$ cut –c 1 -10 emp$ cut –f 3,6 emp.$ cut –f 3-6 emp-c cutting columns-f cutting fields

h) head – displays 10 lines from the head (top) of a given file

syn: $ head filenameeg: $ head studentTo display the top two lines:$ head -2 student

i) tail – displays last 10 lines of the filesyn: $ tail filenameeg: $ tail studentTo display the bottom two lines;$ tail -2 student

j) chmod – used to change the permissions of a file or directory.Syn: $ chmod category operation permission file

Where, category – is the user typeOperation – is used to assign or remove permissionPermission – is the type of permissionFile – are used to assign or remove permissiona) Category------------- b) Operation-------------- c) Permission--------------a)u – usersg –groupo – othersa – all-------------------b)+ assign- remove= assign absolutely--------------------c)r – readw – writex- execute------------------------Examples:$ chmod u-wx studentremoves write and execute permission for users

$ chmod u+rw, g+rw studentassigns read and write permission for users and groups

$ chmod g=rwx studentassigns absolute permission for groups of all read, write andexecute permissions

k) wc – it counts the number of lines, words, character in a specified file(s)with the options as –l, -w, -csyn: $wc –l filename$wc –w filename$wc –c filename

Result:Thus the file manipulating commands were executed successfully

3. DIRECTORY COMMANDS

a) mkdir – used for creating a directory.Syn: $ mkdir <directory name>

b) rmdir – it is an utility for deleting empty directories.Syn: $ rmdir directory name

c) cd – changes the current directory of the shell.Syn: $ cd ~(stores the path to your home directory)$ cd..(changes to parent directory)$ cd

d) pwd – (Print Working Directory) shows the current directory.Syn: $ pwd

Result:Thus the directory commands were executed successfully

4. PROCESS COMMANDSa) exit – terminates a processsyn: $ exit

b) kill – terminates or send a signal to processsyn: $ kill

c) passwd – create or change a passwordsyn: $ passwd

d) telnet – connect to remote machine using the telnet protocolsyn: $ telnet

Result:Thus the process commands were executed successfully.

5. GROUPING COMMANDSa) The semicolon (;) - used ot execute more than one command at a timeeg: $ who ; date ; ls

b) The && operator – signifies the logical AND operation. It means that onlyif first command is successfully executed, then the nest command will beexecuted.Eg: $ ls marks && date

c) The || operator – signifies the logical OR operation. It means the firstcommand will happen to be unsuccessful, it will continue to execute nextcommand.Eg: $ ls marks || date

Result:Thus the grouping commands were executed successfully

UNIX EDITORAIM:To study the UNIX editor vi and EMACSCONCEPT:Editor is a program that allows user to see a portions a file on thescreen and modify characters and lines by simply typing at the currentposition. UNIX supports variety of Editors. They are:edexviEMACSvi - vi is stands for “visual”. vi is the most important and powerfuleditor. vi is a full screen editor that allows user to view and edit entiredocument at the same time. vi editor was written in the University ofCalifornia, at Berkley by Bill Joy, who is one of the co-founder of SunMicrosystems.

Features of vi:It is easy to learn and has more powerful features.It works in great speed and is case sensitive.vi has powerful undo functions and has 3 modes:command modeinsert modeEscape or ex modeIn command mode, no text is displayed on the screen.In Insert mode, it permits user to edit insert or replace text.In escape mode, it displays commands at command line.Moving the cursor with the help of h,l,k,j,I,etc

EMACS EditorMotion Commands:M -> Move to end of fileM -< Move to beginning of fileC -v Move forward a screenM -v Move backward a screenC -n Move to next lineC -p Move to previous lineC -a Move to the beginning of the lineC -e Move to the end of the lineC -f Move forward a character

C -b Move backward a characterM -f Move forward a wordM -b Move backward a word

EMACS help system command options

A List all commands matching the specified word.B List all key mappings.C Describe any key sequence pressed.F Describe the specified functionI Start up the info browserK Fully describe the result of a particular key sequenceL Show the last 100 characters you typedM Describe the current mode you are inS List a command syntax table.T Start a EMACS tutorialV Define and describe the specified variableW Indicate what keystroke invokes a particular functionC -c EMACS copyright and distribution informationC -d EMACS ordering informationC -n Recent EMACS changesC -w EMACS warranty

Deletion Commands:

DEL delete the previous characterC -d delete the current characterM -DEL delete the previous wordM -d delete the next wordC -x DEL delete the previous sentenceM -k delete the rest of the current sentenceC -k delete the rest of the current lineC-x u undo the last edit change

Search and Replace in EMACS:

y Change the occurence of the patternn Dont change the occurence, but look for the otherq Dont change. Leave query replace completely! Change this occurence and all others in the file

Result:Thus the basic commands of EMACS are studied.

SHELLPROGRAMMING

6. GREATEST OF 3 NUMBERS

AIM:To write a program to find the greatest of three numbers.

ALGORITHM:STEP 1: Start the program.STEP 2: Enter any three numbers.STEP 3: Read the values as a, b and c.STEP 4: If a greater than b and greater than c, print the value of a as thegreatest number.STEP 5: Else if b is greater than c, print the value of b as greatest number.STEP 6: Else print the value of c as the greatest number.STEP 7: Stop the program.

Program for Greatest of 3 Numberecho greatest of 3 numbersecho enter the numbersread aread bread cif test $a -gt $b -a $a -gt $cthenecho $a is greaterelif test $b -gt $cthenecho $b is greaterelseecho $c is greaterfi

OUTPUTgreast of 3 numbersenter the numbers256580c is greater

RESULT:Thus Shell program is executed and output is verified successfully.

7. Conversion between different temperature scales

AIM:To Conversion between different temperature scales using shell program

ALGORITHM:STEP 1: Start the programSTEP 2: Input the choice as 1 or 2STEP 3: Is choice is 1 then goto step4 otherwise goto step 7STEP 4: Input temperature in CelsiusSTEP 5: Calculate Fahrenheit F =((9/5)*c) +32STEP 6: Print Fahrenheit F and goto step 10STEP 7: Input temperature in FahrenheitSTEP 8: Calculate Celsius C=((5/9)*(f-32))STEP 9: Print Celsius CSTEP 10: Stop the program

Program for Conversion between different temperature scalesecho Converting between different temperature scalesecho 1. Convert Celsius into Farenheitecho 2. Convert Farenheit into Celsiusecho “Select your choice (1 or 2) :”read choiceif [ $choice –eq 1 ]thenecho Enter the Celsius temperature C :read tctf=$( echo “scale=2; (( 9 / 5 ) * $tc ) + 32” | bc )echo “$tc C = $tf F”elif [ $choice –eq 2 ]echo Enter the Farenheit temperature F :read tftc=$( echo “scale=2; ( 5 / 9 ) * ( $tf – 32 )” | bc )echo “$tf F = $tc C”elseecho “Please select 1 or 2”exit 1fi

output:Converting between different temperature scales1. Convert Celsius into Farenheit2. Convert Farenheit into Celsius“Select your choice (1 or 2) :”Enter the Celsius temperature C : 3737 C=98.60FConverting between different temperature scales1. Convert Celsius into Farenheit2. Convert Farenheit into Celsius“Select your choice (1 or 2) :”Enter the Farenheit temperature F : 100100 F=37.40 C

RESULT:Thus Shell program is executed and output is verified successfully.

8. CHECKING PRIME NUMBERS

AIM:To write a program to find number is prime or not.

ALGORITHM:STEP 1: Start the programSTEP 2: Input number nSTEP 3: Assign i=2, j=oSTEP 4: Is i<n then r=n%i. otherwise go to step 8STEP 5: Is r=0 then increment I and j value by i. otherwise go to step 6STEP 6: Increment I value by oneSTEP 7: Is j=0 then print number is prime and go to step 10STEP 8: Is j!=0 then print number is not a prime numberSTEP 9: Stop the program

Program for identify number is Prime or notecho Enter a numberread ni=2j=0while test $i –le $ndor=$(( $n % $i ))if test $r –eq 0thenj=$(( $j + 1 ))fii=$(( $i + 1 ))doneif test $j –eq 0thenecho Number is Primeelseecho Number is Not Primefi

OUTPUTEnter a number10Number is Not a primeEnter a number5Number is a prime

RESULT:Thus Shell program is executed and output is verified successfully.

9. Raising number to a powerAIM:To find the value of one number raised to the power of another using shellProgram

ALGORITHM:STEP 1: Start the programSTEP 2: Input number and power valuesSTEP 3: Assign i=1 and product=1STEP 4: If i<power then calculate product=product* number and increment Ivalue by 1.STEP 5: Repeat step 4STEP 6: Print the resultSTEP 7: Stop the program

Program for Raising number to a powerecho Enter the numberread necho Enter the powerread powi=1prod=1while test $i –le $powdoprod=$(( $prod * $n ))i=$(( $i + 1 ))doneecho $n is raised to $pow = $prod

OutputEnter the number4Enter the power24 raised to 2=16

RESULT:Thus Shell program is executed and output is verified successfully.

10. ARMSTRONG NUMBERS BETWEEN 1 TO 500

AIM:To write a program to find the Armstrong numbers between 1 to 500.

ALGORITHM:STEP 1: Start the program.STEP 2: When I equal to 0 and less than or equal to 500, calculate incrementvalue of i.STEP 3: Assign value of I to temp and n.STEP 4: Assign value of ams equal to zero.STEP 5: When n not equal to zero calculate d equal to n modulus 10, amsequal to product of ams and cube of d. Then find n equal to n divided by10.STEP 6: If temp equal to ams then print the value of ams.STEP 7: Thus for each value of I, values of ams is printed.STEP 8: Stop the program.

Program for Armstrong Number Between 1 to 500echo Armstrong numbers between 1 to 500i=0while test $i –le 500doi=$(( $i + 1 ))temp=$in=$iams=0while test $n -ne 0dod=$(( $n % 10 ))ams=$(( $ams + $d * $d * $d ))n=$(( $n / 10 ))doneif test $temp -eq $amsthenecho $amsfidone

OUTPUTARMSTRONG NUMBERS BETWEEN 1 TO 5001153370371407RESULT:Thus Shell program is executed and output is verified successfully.

11. FIBONACCI SERIES

AIM:To generate Fibonacci series.

ALGORITHM:STEP 1: StartSTEP 2: Get the value s from the userSTEP 3: Assign a=0,b=1 and print a,b valuesSTEP 4: Assign i=2STEP 5: If i<n then goto step 6 otherwise goto step 9STEP 6: Calculate c=a+b,i=i+1 and assign a=b, b=cSTEP 7: Print the value of cSTEP 8: Repeat the value of c.STEP 9: Stop the program

Program for Fibnacci Seriesecho Program to generate Fibonacci seriesecho Enter the range to be displayedread na=0b=1echo Fibonacci seriesecho $aecho $bi=2while test $i -lt $ndoc=$(( $a + $b ))echo $ci=$(( $i + 1 ))a=$bb=$cdone

OUTPUTProgram to generate Fibonacci seriesEnter the range to be displayed:3011

RESULT:Thus Shell program is executed and output is verified successfully.

12. Factorial of a given number

AIM:To calculate factorial of a given number using shell program

ALGORITHM:STEP 1: Start the programSTEP 2: Input number nSTEP 3: Initialize the value of I and factorial f to 1STEP 4: Is the value of I less than the number find the value of factorial bymultiplying i and f.STEP 5: Increment the value of i by 1STEP 6: Print the resultSTEP 7: Stop the program

Program for Factorial of a given numberecho Enter a number to find its factorialread ni=1f=1if test $n –eq 0thenecho Factorial is 1while test $i –le $ndof=$(( $f * $i ))i=$(( $i + 1 ))doneecho Factorial is $ffi

OutputEnter a number to find its factorial5Factorial is 120

RESULT:Thus Shell program is executed and output is verified successfully.

13. EMPLOYEE DETAILS

AIM:To write a program to display the employee details.

ALGORITHM:STEP 1: Start the programSTEP 2: Read the number of employees.STEP 3: Using while loop get the employee details as empno, ename, bsal.STEP 4: For the given bsalary using ifelse statement get the hra, da, ta.STEP 5: Calculate the salarySTEP 6: Display the employee detailsSTEP 7: Stop the program.

Program for Employee Detailsecho Enter the number of employeesread ni=1while $i –le $ndoecho Enter the Employee ID Numberread enoecho Enter the Employee nameread enameecho Enter the employees basic salaryread bsalif test $bsal -ge 10000thenhra=1000da=700ta=500elif test $bsal -lt 10000 -a $bsal -ge 5000thenhra=750da=500ta=350elif test $bsal -lt 5000 -a $bsal -ge 3000thenhra=500da=300ta=200elsehra=300da=200ta=100finetsal=$(( $hra + $da + $ta + $bsal ))echo ------------------------------echo PAY SLIP OF $ename

echo ------------------------------echo Empname = $enameecho Empno = $enoecho basicpay = $bsalecho HRA = $hraecho TA = $taecho DA = $daecho Netpay = $netsaldone.

OUTPUTEnter the number of employees1Enter the Employee ID Number1234Enter the Employee nameMr.V.ArunKumarEnter the employees basic salary12000------------------------------PAY SLIP OF Mr.V.ArunKumar------------------------------Empname = Mr.V.ArunKumarEmpno = 1234basicpay = 12000HRA = 1000TA = 500DA = 700Netpay = 14200

RESULT:Thus Shell program is executed and output is verified successfully.

4. MULTIPLICATION TABLE

AIM:To generate multiplication table using shell programALGORITHM:

STEP 1: Start the programSTEP 2: Input number „n‟STEP 3: If i<10 then m=n*iSTEP 4: Print the value of I,n and m in multiplication table formatSTEP 5: Increment the value of i.STEP 6: Stop the program.

Program for Multiplication Tableecho Enter the numberread nfor i in 1 2 3 4 5 6 7 8 9 10dom=$(( $n * $i ))echo “ $i * $n ”= $mdone

OUTPUTEnter the number21*2=22*2=43*2=64*2=85*2=106*2=127*2=148*2=169*2=1810*2=20

RESULT:Thus Shell program is executed and output is verified successfully.

15. MENU DRIVEN CALCULATOR

AIM:To write a program to display the menu driven calculator.

ALGORITHM:STEP 1: Start the program.STEP 2: Read the option and operators a,bSTEP 3: Evaluate the expression based on the user optiona) If operator is „+‟ then result is a+bb) If operator is „-„ then result is a-bc) If operator is x or X then result is a*bd) If operator is „/‟ then result is a/bSTEP 4: Print the result.STEP 5: Stop the program

Program for Menu Driven Calculator(Arithmetic Operators)echo Menuecho 1. Addition echo2. Subtraction echo 3.Multiplication echo 4.Divisionecho 5. Exitecho Enter the choiceread ncase “$n” in1)echo Enter the two numbersread aread bc=$(( $a + $b ))echo Addition of $a and $b is $c;;2)echo Enter the two numbersread aread bc=$(( $a - $b ))echo Subtraction of $a and $b is $c;;3)echo Enter the two numbersread aread bc=$(( $a * $b ))echo Multiplication of $a and $b is $c;;4)echo Enter the two numbers

read aread bc=$(( $a / $b ))echo Division of $a and $b is $c;;*)echo Wrong Selection;;esac

OUTPUTMenu1. Addition2. Subtraction3. Multiplication4. Division5. ExitEnter the choice1Enter the two numbers2025Addition of 20 and 25 is 45

RESULT:Thus Shell program is executed and output is verified successfully..

CPROGRAMMING

.

16. FUNCTION WITH NO ARGUMENTS AND NO RETURNVALUES

Program:#include<stdio.h>int sum(void);main(){sum();}int sum(void){int num1, num2, num3;printf(“Enter two numbers: \n”);scanf(“%d%d”, &num1, &num2);num3=num1+num2;printf(“Summation of %d and %d is %d \n”, num1, num2, num3);}

OUTPUT FOR FUNCTION NO ARGUMENTS AND NO RETURNVALUESEnter two numbers:1020Summation of 10 and 20 is 30.

17. FUNCTION WITH ARGUMENTS AND RETURN VALUES

Program:#include<stdio.h>#include<conio.h>int largest(int, int);void main(){int a,b,big;printf(“Enter two numbers : \n”);scanf(“%d%d”, &a, &b);big=largest(a,b);printf(“Largest Element = %d”, big);

}int largest(int a1, int b1){if(a1>b1)return a1;elsereturn b1;}

OUTPUT FOR FUNCTION ARGUMENTS AND RETURN VALUESEnter two numbers1525Largest Element = 25

18. DYNAMIC ALLOCATION OF MEMORY

Program:#include<stdio.h>main(){int *p;p=(int *)malloc(sizeof(int));if(p==0){printf(“ ERROR : Out of Memory \n”);return 1;}*p=5;printf(“Value of P = %d \n”, *p);printf(“Address of P = %d \n”, p);free(p);return 0;}OUTPUT FOR DYNAMIC ALLOCATION OF MEMORYValue of P = 5Address of P =134518200.

19. ALLOCATE SPACE FOR A STRING DYNAMICALLY ANDPRINT THE STRING BACKWARDS

Program:#include<stdio.h>#include<string.h>int main(){char *s;register int i;s=malloc(80);if(!s){printf(“Memory request failed................. \n”);exit(1);}gets(s);for(i=strlen(s)-1; i>=0; i--)putchar(s[i]);free(s);return 0;}

OUTPUT FOR ALLOCATE SPACE FOR A STRING DYNAMICALLYANDPRINT THE STRING BACKWARDSHaiiaH

20. BINARY SEARCH USING FUNCTION

Program:#include<stdio.h>#include<math.h>int main(){int bsearch(int x[],int n,int s);int x[20],i,n,s;printf("How many numbers?");

scanf("%d",&n);printf("Enter all numbers in the list");for(i=0;i<n;i++)scanf("%d",&x[i]);printf("Enter the number to be searched:");scanf("%d",&s);if(bsearch(x,n,s))printf("The number %d is present in the list",s);elseprintf("The number %d is not present in the list",s);return 0;}int bsearch(int x[],int n, int s){int i,j,flag=0,start,mid,end;start=0;end=n;while(start < end && flag==0){mid = (start + end)/2;if(x[mid] >s)end = mid;elseif(x[mid]<s)start = mid+1;else}flag=1;return(flag); }

OUTPUT FOR BINARY SEARCHHow many numbers? 10Enter all the numbers in the list81523253645506265

78Enter the number to be searched: 36The number 36 is present in the listEnter the number to be searched: 42The number 42 is not present in the list.

21. FACTORIAL IN FINDING ncr USINGFUNCTIONProgram:#include<stdio.h>#include<stdlib.h>int main(){int fact(int k);int n,r,ncr;printf("\n Enter value to n and r:");scanf("%d %d", &n,&r);ncr=fact(n)/(fact(r)*fact(n-r));printf("\n Value of ncr = %d",ncr);}int fact(int k){int i, p=1;for(i=1;i<=k;i++)p=p*i;return(p);}

OUTPUT FOR FACTORIAL IN FINDING ncrEnter the values of n and r: 5 3Value of ncr = 10Enter the values of n and r: 10 5Value of ncr = 252.

22. COSINE SERIES USING FUNCTIONProgram:#include<stdio.h>#include<math.h>int main()

{float cosine(float x);float x=0;printf("\n x in degrees cos(x) ");while (x<=180){printf("\n \t %6.0f %6.2f", x,cosine(x));x=x+30;}return 0;}float cosine(float x){float s, term;int i,k;x=x*3.14/180;s=0;term=1; i=0;for(k=1;k<=15;k++){s=s+term;term=term*x*x*(-1) / ((i+1) * (i+2));i=i+2;}return(s);}.

OUTPUT FOR COSINE SERIES----------------------------------------------------------------------x in degrees cos(x)----------------------------------------------------------------------0 1.030 0.8760 0.5090 0.00120 -0.50150 -0.87180 -1.00-------------------------------------------------------------------.

23. PRODUCT OF MATRIX USING ARRAYS

Program:#include<stdio.h>#include<stdlib.h>int main(){int *a[10],*b[10], *c[10], m,n,l,i,k,j;for(i=0;i<10;i++){a[i] = (int *) calloc (10,sizeof(int));b[i] = (int *) calloc (10,sizeof(int));c[i] = (int *) calloc (10,sizeof(int));}printf("\nFor A matrix");printf("\nHow many rows and columns ?");scanf("%d %d", &m,&n);printf("\nEnter A matrix values");for(i=0; i<m; i++){for(j=0; j<n; j++)scanf("%d",(*(a+i)+j));}printf("\nFor B matrix");printf("\nHow many rows and columns ?");scanf("%d %d", &n,&l);printf("\nEnter B matrix values");for(i=0;i<n;i++)for(j=0;j<l;j++)scanf("%d", (*(b+i)+j));for(i=0;i<m;i++)for(j=0;j<l;j++){*(*(c+i)+j)=0;for(k=0;k<n;k++)*(*(c+i)+j) = *(*(c+i)+j) + *(*(a+i)+k) * * (*(b+k)+j);}printf("\n Resultant matrix is\n");for(i=0;i<m;i++){for(j=0;j<l;j++)printf("%6d", *(*(c+i)+j));printf("\n");}return 0;}

.

OUTPUT FOR PRODUCT OF A MATRIX

For A matrixHow many rows and columns ? 3 3Enter A matrix values3 2 1-2 0 43 2 -1For B matrixHow many rows and columns? 3 3Enter B matrix values6 4 -12 1 24 -5 4Resultant Matrix is26 9 54 -28 1818 19 -3.

24. CREATION & READING THE CONTENTOF A FILE

Program:#include<stdio.h>#include<ctype.h>struct emp{int eno;char ename[20];float bpay;};FILE *efile;int main(){struct emp erec;int n,i;efile = fopen("EMPLOY.DAT", "w");printf("\nEnter the number of employees:");scanf("%d",&n);for(i=1;i<=n;i++)

{printf("\nEnter the %d employee details",i);printf("\nEnter the employee number");scanf("%d",&erec.eno);printf("Employee Name");scanf("%s",erec.ename);printf("Basicpay");scanf("%f",&erec.bpay);fwrite(&erec,sizeof(erec),1,efile);}fclose(efile);printf("\nAfter adding content to the file");efile=fopen("EMPLOY.DAT","r");printf("\n--------------------------------------------------");printf("\n Emp.no Employee name Basic Pay");printf("\n --------------------------------------------------\n");fread(&erec,sizeof(erec),1,efile);while (!feof(efile)){printf("\n %d \t %-20s %0.2f",erec.eno,erec.ename,erec.bpay);fread(&erec, sizeof(erec),1,efile);}printf("\n --------------------------------------------------");fclose(efile);return 0;}.

OUTPUT FOR CREATION OF A FILEEnter the number of Employees: 2Enter the 1 employee details :Enter the Employee number: 101Employee name: xxxxBasic Pay: 65433.4Enter the 2 employee details :Enter the Employee number: 102Employee name: yyyyBasic Pay: 7000After adding content to the file-----------------------------------------------------------Emp.no Employee name Basic Pay----------------------------------------------------------101 xxxx 65433.4102 yyyy 7000.0

----------------------------------------------------------

25.APPENDING A RECORD TO THE FILE

Program:#include<stdio.h>#include<ctype.h>struct emp{int eno;char ename[20];float bpay;};FILE *efile;int main(){struct emp erec;efile = fopen("EMPLOY.DAT", "a");printf("\nEnter the Employee number");scanf("%d",&erec.eno);printf("Employee Name");scanf("%s",erec.ename);printf("Basicpay");scanf("%f",&erec.bpay);fwrite(&erec,sizeof(erec),1,efile);fclose(efile);printf(" After Appending the content of file");efile=fopen("EMPLOY.DAT","r");printf("\n--------------------------------------------------");printf("\n Emp.no Employee name Basic Pay");printf("\n --------------------------------------------------");fread(&erec,sizeof(erec),1,efile);while (!feof(efile)){printf("\n %d \t %-20s %0.2f",erec.eno,erec.ename,erec.bpay);fread(&erec, sizeof(erec),1,efile);}printf("\n --------------------------------------------------\n");fclose(efile);return 0;}

OUTPUT FOR APPENDING A RECORD TO THE FILEEnter the Employee number: 103Employee name: zzzzBasic Pay: 12000After Appending the content of file-----------------------------------------------------------Emp.no Employee name Basic Pay----------------------------------------------------------101 xxxx 65433.4102 yyyy 7000.0103 zzzz 12000.0---------------------------------------------------------