cp lab ii manual -

108
Computer Practice Laboratory – II L ist of E x e r c i s e s a) B a sic sh e ll c om m a n d s 1. Display commands 2. File manipulation commands 3. Directory manipulation commands 4. Process commands 5. Grouping commands b) S h e ll P r o g ra ms 1. 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 numbers 5. Conversion of temperature 6. Checking the number prime or not 7. Raising a number to its power 8. Armstrong number 9. Fibonacci series 10. Factorial of a given number 11. Employee details 12. Multiplication table 13. Menu driven calculator c) Unix – C p r o g r ams 1. Function with no arguments & no return values 2. Function with arguments & return values 3. Dynamic memory allocation 4. Dynamic allocation of a string & print it backwards 5. Binary search using function 6. Factorial in finding ncr using function 7. Cosine values using function 8. Product of matrix using arrays 9. Creation & reading the content of a file 10. Appending content to the file

Upload: baskaranchandran

Post on 28-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

yuy

TRANSCRIPT

Page 1: CP Lab II Manual -

Computer Practice Laboratory – II

List of Ex ercis es

a) Basic shell comm and s

1. Display commands2. File manipulation commands3. Directory manipulation commands4. Process commands5. Grouping commands

b) S hell P rograms

1. 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 calculator

c) 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

Page 2: CP Lab II Manual -

UNIXCOMMANDS

Page 3: CP Lab II Manual -

INTRODUCTION TO UNIX

UNIX: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 UNIX

commands works in Linux also and it is available free of cost. The main feature of

Linux is coexisting with other OS.

STRUCTURE OF A LINUX SYSTEM:It consists of three parts.

a) UNIX kernel

b) Shells

c) Tools and Applications

Page 4: CP Lab II Manual -

UNIX SYSTEM

USERS

TOOLS AND APPLICATIONS

SHELLS

THE UNIX KERNEL

COMPUTER HARDWARE

UNIX KERNEL:Kernel is the core of the UNIX OS. It controls all tasks, schedule all

processes 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 command

from the user and analyses and interprets them.

Page 5: CP Lab II Manual -

1. DISPLAY COMMANDS

a) date – used to check the date and time syn: $ date

Format 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 calendar syn: $ 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‟

Page 6: CP Lab II Manual -

e) lp – used to take printouts syn: $ 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 to the 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 last reboot 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 name syn: $ hostname

k) bc – stands for „best calcualtor‟

$ bc $ bc $ bc $ bc10/2*3 scale =1 ibase = 2 sqrt(196)15 2.25+1 obase = 16 14 quit 3.35 11010011

quit 892751010ĀQuit

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

Result:Thus the display commands were executed successfully

Page 7: CP Lab II Manual -

.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 from the file.Syn: $ grep searchword filenameEg: $ grep anu student

c) rm – deletes a file from the file system syn: $ 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 file eg: $ cp student stud

f) mv – to rename the file or directory syn: $ 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

.

Page 8: CP Lab II Manual -

$ 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 student

To display the top two lines:$ head -2 student

i) tail – displays last 10 lines of the file syn: $ tail filenameeg: $ tail student

To 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 permission

Category Operation Permissionu – users g –groupo – othersa - all

+ assign- remove= assign absolutely

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

and execute permissions

.

Page 9: CP Lab II Manual -

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

$wc –w filename$wc –c filename

Result:Thus the file manipulating commands were executed successfully

.

Page 10: CP Lab II Manual -

.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

.

Page 11: CP Lab II Manual -

4. PROCESS COMMANDS

a) exit – terminates a process

syn: $ exit

b) kill – terminates or send a signal to process

syn: $ kill

c) passwd – create or change a password

syn: $ passwd

d) telnet – connect to remote machine using the telnet

protocol syn: $ telnet

Result:Thus the process commands were executed successfully.

.

Page 12: CP Lab II Manual -

5. GROUPING COMMANDS

a) The semicolon (;) - used ot execute more than one command at a

time eg: $ who ; date ; ls

b) The && operator – signifies the logical AND operation. It means that only if first command is successfully executed, then the nest command will be executed.

Eg: $ ls marks && date

c) The || operator – signifies the logical OR operation. It means the first command will happen to be unsuccessful, it will continue to execute next command.

Eg: $ ls marks || date

Result:Thus the grouping commands were executed successfully

.

Page 13: CP Lab II Manual -

UNIX EDITOR

A IM: To study the UNIX editor vi and EMACS

C O N C E P T : Editor is a program that allows user to see a portions a file on the

screen and modify characters and lines by simply typing at the current position. UNIX supports variety of Editors. They are:

ed ex viEMACS

vi - vi is stands for “visual”. vi is the most important and powerful editor. vi is a full screen editor that allows user to view and edit entire document at the same time. vi editor was written in the University of California, at Berkley by Bill Joy, who is one of the co-founder of Sun Microsystems.

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 mode insert modeEscape or ex mode

In 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

.

Page 14: CP Lab II Manual -

EMACS Editor

Motio n Co mmands :

M -> Move to end of fileM -< Move to beginning of fileC -v Move forward a screen M -v Move backward a screen C -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 characterC -b Move backward a characterM -f Move forward a wordM -b Move backward a word

EMACS h elp s yst em co mman d opt ion s

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

.

Page 15: CP Lab II Manual -

D e l e t i o n C o m m a nd s :

DEL delete the previous character C -d delete the current character M -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 Repl ace in EMACS:

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

Result :

Thus the basic commands of EMACS are studied.

.

Page 16: CP Lab II Manual -

SHELLPROGRAMMING

.

Page 17: CP Lab II Manual -

T: Thus a program to find reverse of a number is created.RESUL6. 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 the

greatest 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.

P r og r a m f o r Gr e at e s t o f 3 N u m ber echo greatest of 3 numbers

echo enter the numbers

read a

read b

read c

if test $a -gt $b -a $a -gt $c

then

echo $a is greater

elif test $b -gt $c

then

.

Page 18: CP Lab II Manual -

echo $b is greater

else

echo $c is greater

fi

O U T P UT

greast of 3 numbers

enter the numbers

25

65

80

c is greater

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

.

Page 19: CP Lab II Manual -

7. Conversion between different temperature scales

AIM:To Conversion between different temperature scales using shell program

ALGORITHM:

STEP 1: Start the program

STEP 2: Input the choice as 1 or 2

STEP 3: Is choice is 1 then goto step4 otherwise goto step 7

STEP 4: Input temperature in Celsius

STEP 5: Calculate Fahrenheit F =((9/5)*c) +32

STEP 6: Print Fahrenheit F and goto step 10

STEP 7: Input temperature in Fahrenheit

STEP 8: Calculate Celsius C=((5/9)*(f-32))

STEP 9: Print Celsius C

STEP 10: Stop the program

Prog ra m fo r Conver sion betw een different te mper atu re scales

echo Converting between different temperature scales

echo 1. Convert Celsius into Farenheit

echo 2. Convert Farenheit into Celsius

echo “Select your choice (1 or 2) :”

read choice

if [ $choice –eq 1 ]

then

echo Enter the Celsius temperature C :

.

Page 20: CP Lab II Manual -

read tc

tf=$( echo “scale=2; (( 9 / 5 ) * $tc ) + 32” | bc )

echo “$tc C = $tf F”

elif [ $choice –eq 2 ]

echo Enter the Farenheit temperature F :

read tf

tc=$( echo “scale=2; ( 5 / 9 ) * ( $tf – 32 )” | bc )

echo “$tf F = $tc C”

else

echo “Please select 1 or 2”

exit 1

fi

output:

Converting between different temperature scales

1. Convert Celsius into Farenheit

2. Convert Farenheit into Celsius

“Select your choice (1 or 2) :”

Enter the Celsius temperature C : 37

37 C=98.60F

Converting between different temperature scales

1. Convert Celsius into Farenheit

2. Convert Farenheit into Celsius

“Select your choice (1 or 2) :”

Enter the Farenheit temperature F : 100

100 F=37.40 C

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

.

Page 21: CP Lab II Manual -

8. CHECKING PRIME NUMBERS

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

ALGORITHM:

STEP 1: Start the program

STEP 2: Input number n

STEP 3: Assign i=2, j=o

STEP 4: Is i<n then r=n%i. otherwise go to step 8

STEP 5: Is r=0 then increment I and j value by i. otherwise go to step 6

STEP 6: Increment I value by one

STEP 7: Is j=0 then print number is prime and go to step 10

STEP 8: Is j!=0 then print number is not a prime number

STEP 9: Stop the program

P r og r a m f o r i d ent i f y nu m ber i s P r i m e o r n o t

echo Enter a number

read n

i=2

j=0

while test $i –le $n

do

r=$(( $n % $i ))

if test $r –eq 0

then

j=$(( $j + 1 ))

.

Page 22: CP Lab II Manual -

fi

i=$(( $i + 1 ))

done

if test $j –eq 0

then

echo Number is Prime

else

echo Number is Not Prime

fi

O U T P UT

Enter a number

10

Number is Not a prime

Enter a number

5

Number is a prime

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

.

Page 23: CP Lab II Manual -

9. Raising number to a power

AIM:To find the value of one number raised to the power of another using shell

program

ALGORITHM:

STEP 1: Start the program

STEP 2: Input number and power values

STEP 3: Assign i=1 and product=1

STEP 4: If i<power then calculate product=product* number and increment I

value by 1.

STEP 5: Repeat step 4

STEP 6: Print the result

STEP 7: Stop the program

Prog ra m fo r Raising nu mber t o a pow er

echo Enter the number

read n

echo Enter the power

read pow

i=1

prod=1

while test $i –le $pow

do

prod=$(( $prod * $n ))

i=$(( $i + 1 ))

done

echo $n is raised to $pow = $prod

.

Page 24: CP Lab II Manual -

Output

Enter the number

4

Enter the power

2

4 raised to 2=16

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

.

Page 25: CP Lab II Manual -

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

increment value 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, ams

equal to product of ams and cube of d. Then find n equal to n divided

by

10.

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.

Prog ra m fo r Arms tro ng Number Betw een 1 to 5 00

echo Armstrong numbers between 1 to 500

i=0

while test $i –le 500

do

i=$(( $i + 1 ))

temp=$i

n=$i

ams=0

.

Page 26: CP Lab II Manual -

while test $n -ne 0

do

d=$(( $n % 10 ))

ams=$(( $ams + $d * $d * $d ))

n=$(( $n / 10 ))

done

if test $temp -eq $ams

then

echo $ams

fi

done

O U T P UT

ARMSTRONG NUMBERS BETWEEN 1 TO 500

1

153

370

371

407

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

.

Page 27: CP Lab II Manual -

11. FIBONACCI SERIES

AIM:To generate Fibonacci series.

ALGORITHM:

STEP 1: Start

STEP 2: Get the value s from the user

STEP 3: Assign a=0,b=1 and print a,b values

STEP 4: Assign i=2

STEP 5: If i<n then goto step 6 otherwise goto step 9

STEP 6: Calculate c=a+b,i=i+1 and assign a=b, b=c

STEP 7: Print the value of c

STEP 8: Repeat the value of c.

STEP 9: Stop the program

P r og r a m f o r F i b n a c ci Se r i e s

echo Program to generate Fibonacci series

echo Enter the range to be displayed

read n

a=0

b=1

echo Fibonacci series

echo $a

echo $b

i=2

while test $i -lt $n

.

Page 28: CP Lab II Manual -

do

c=$(( $a + $b ))

echo $c

i=$(( $i + 1 ))

a=$b

b=$c

done

O U T P UT

Program to generate Fibonacci series

Enter the range to be displayed:3

0

1

1

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

.

Page 29: CP Lab II Manual -

12. Factorial of a given number

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

ALGORITHM:

STEP 1: Start the program

STEP 2: Input number n

STEP 3: Initialize the value of I and factorial f to 1

STEP 4: Is the value of I less than the number find the value of factorial

by multiplying i and f.

STEP 5: Increment the value of i by 1

STEP 6: Print the result

STEP 7: Stop the program

Prog ra m fo r Factori al of a g ive n nu mber

echo Enter a number to find its factorial

read n

i=1

f=1

if test $n –eq 0

then

echo Factorial is 1

while test $i –le $n

do

f=$(( $f * $i ))

.

Page 30: CP Lab II Manual -

i=$(( $i + 1 ))

done

echo Factorial is $f

fi

Output

Enter a number to find its factorial

5

Factorial is 120

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

.

Page 31: CP Lab II Manual -

13. EMPLOYEE DETAILS

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

ALGORITHM:

STEP 1: Start the program

STEP 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 salary

STEP 6: Display the employee details

STEP 7: Stop the program.

P r og r a m f o r E m p l o y ee D e t a i l s

echo Enter the number of employees

read n

i=1

while $i –le $n

do

echo Enter the Employee ID Number

read eno

echo Enter the Employee name

read ename

echo Enter the employees basic salary

read bsal

if test $bsal -ge 10000

then

.

Page 32: CP Lab II Manual -

hra=1000

da=700

ta=500

elif test $bsal -lt 10000 -a $bsal -ge 5000

then

hra=750

da=500

ta=350

elif test $bsal -lt 5000 -a $bsal -ge 3000

then

hra=500

da=300

ta=200

else

hra=300

da=200

ta=100

fi

netsal=$(( $hra + $da + $ta + $bsal ))

echo ------------------------------

echo PAY SLIP OF $ename

echo ------------------------------

echo Empname = $ename

echo Empno = $eno

echo basicpay = $bsal

echo HRA = $hra

echo TA = $ta

echo DA = $da

echo Netpay = $netsal

done

.

Page 33: CP Lab II Manual -

O U T P UT

Enter the number of employees

1

Enter the Employee ID Number

1234

Enter the Employee name

Mr.V.ArunKumar

Enter the employees basic salary

12000

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

PAY SLIP OF Mr.V.ArunKumar

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

Empname = Mr.V.ArunKumar

Empno = 1234

basicpay = 12000

HRA = 1000

TA = 500

DA = 700

Netpay = 14200

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

.

Page 34: CP Lab II Manual -

14. MULTIPLICATION TABLE

AIM:To generate multiplication table using shell program

ALGORITHM:

STEP 1: Start the program

STEP 2: Input number „n‟

STEP 3: If i<10 then m=n*i

STEP 4: Print the value of I,n and m in multiplication table format

STEP 5: Increment the value of i.

STEP 6: Stop the program.

Prog ra m fo r Mul ti pli ca tio n Ta ble

echo Enter the number

read n

for i in 1 2 3 4 5 6 7 8 9 10

do

m=$(( $n * $i ))

echo “ $i * $n ”= $m

done

.

Page 35: CP Lab II Manual -

OUT PUT

Enter the number

2

1*2=2

2*2=4

3*2=6

4*2=8

5*2=10

6*2=12

7*2=14

8*2=16

9*2=18

10*2=20

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

.

Page 36: CP Lab II Manual -

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,b

STEP 3: Evaluate the expression based on the user option

a) If operator is „+‟ then result is a+b

b) If operator is „-„ then result is a-b

c) If operator is x or X then result is a*b

d) If operator is „/‟ then result is a/b

STEP 4: Print the result.

STEP 5: Stop the program

Prog r a m f or M en u Driven Calcu lator(Ari th me ti c Op erato rs)

echo Menu

echo 1. Addition echo

2. Subtraction echo 3.

Multiplication echo 4.

Division

echo 5. Exit

echo Enter the choice

read n

case “$n” in

1)

.

Page 37: CP Lab II Manual -

echo Enter the two numbers

read a

read b

c=$(( $a + $b ))

echo Addition of $a and $b is $c

;;

2)

echo Enter the two numbers

read a

read b

c=$(( $a - $b ))

echo Subtraction of $a and $b is $c

;;

3)

echo Enter the two numbers

read a

read b

c=$(( $a * $b ))

echo Multiplication of $a and $b is $c

;;

4)

echo Enter the two numbers

read a

read b

c=$(( $a / $b ))

echo Division of $a and $b is $c

;;

*)

echo Wrong Selection

;;

esac

.

Page 38: CP Lab II Manual -

O U T P UT

Menu

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Exit

Enter the choice

1

Enter the two numbers

20

25

Addition of 20 and 25 is 45

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

.

Page 39: CP Lab II Manual -

CPROGRAMMING

.

Page 40: CP Lab II Manual -

16. FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES

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 RETURN VALUES

Enter two numbers:1020Summation of 10 and 20 is 30

.

Page 41: CP Lab II Manual -

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 VALUES

Enter two numbers1525Largest Element = 25

.

Page 42: CP Lab II Manual -

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 MEMORY

Value of P = 5Address of P =134518200

.

Page 43: CP Lab II Manual -

19. ALLOCATE SPACE FOR A STRING DYNAMICALLY AND PRINT 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 DYNAMICALLY AND

PRINT THE STRING BACKWARDS

Hai iaH

.

Page 44: CP Lab II Manual -

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;else if(x[mid]<s)

start = mid+1;else

}flag=1;

return(flag); }

.

Page 45: CP Lab II Manual -

OUTPUT FOR BINARY SEARCH

How many numbers? 10

Enter all the numbers in the list

8

15

23

25

36

45

50

62

65

78

Enter the number to be searched: 36

The number 36 is present in the list

Enter the number to be searched: 42

The number 42 is not present in the list

.

Page 46: CP Lab II Manual -

21. FACTORIAL IN FINDING ncr USING FUNCTION

Program:

#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);

}

.

Page 47: CP Lab II Manual -

OUTPUT FOR FACTORIAL IN FINDING ncr

Enter the values of n and r: 5 3

Value of ncr = 10

Enter the values of n and r: 10 5

Value of ncr = 252

.

Page 48: CP Lab II Manual -

22. COSINE SERIES USING FUNCTION

Program:

#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);

}

.

Page 49: CP Lab II Manual -

OUTPUT FOR COSINE SERIES

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

x in degrees cos(x)

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

0 1.0

30 0.87

60 0.50

90 0.00

120 -0.50

150 -0.87

180 -1.00

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

.

Page 50: CP Lab II Manual -

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");

.

Page 51: CP Lab II Manual -

for(i=0;i<m;i++){

for(j=0;j<l;j++) printf("%6d", *(*(c+i)+j)); printf("\n");

}return 0;

}

.

Page 52: CP Lab II Manual -

OUTPUT FOR PRODUCT OF A MATRIX

For A matrix

How many rows and columns ? 3 3

Enter A matrix values

3 2 1

-2 0 4

3 2 -1

For B matrix

How many rows and columns? 3 3

Enter B matrix values

6 4 -1

2 1 2

4 -5 4

Resultant Matrix is

26 9 5

4 -28 18

18 19 -3

.

Page 53: CP Lab II Manual -

24. CREATION & READING THE CONTENT OF 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);

.

Page 54: CP Lab II Manual -

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;

}

.

Page 55: CP Lab II Manual -

OUTPUT FOR CREATION OF A FILE

Enter the number of Employees: 2

Enter the 1 employee details :

Enter the Employee number: 101

Employee name: xxxx

Basic Pay: 65433.4

Enter the 2 employee details :

Enter the Employee number: 102

Employee name: yyyy

Basic Pay: 7000

After adding content to the file

-----------------------------------------------------------Emp.no Employee name Basic Pay----------------------------------------------------------

101 xxxx 65433.4

102 yyyy 7000.0

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

Page 56: CP Lab II Manual -

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;

}

.

Page 57: CP Lab II Manual -

OUTPUT FOR APPENDING A RECORD TO THE FILE

Enter the Employee number: 103

Employee name: zzzz

Basic Pay: 12000

After Appending the content of file

-----------------------------------------------------------Emp.no Employee name Basic Pay----------------------------------------------------------

101 xxxx 65433.4

102 yyyy 7000.0

103 zzzz 12000.0

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

.