2 Unix Programs
2 Unix Programs
1 Date:
AIM
To study the concept of operating systems and particularly about open source UNIX operating system.
OPERATING SYSTEM
An Operating System is a set of programs that functions as a virtual machine by presenting an interface that is easier to program than the underlying hardware. It acts as resource management through orderly and controlled allocation of the processors, memories, and I/O devices among the programs competing for it.
OS TYPES
1. Single User: The system will have its own hard disk, memory, CPU and other resources all dedicated to a single user.
Ex: MS-DOS
2. Multi User: The users having access to a multi-user system will have just a terminal and a keyboard. The other resources such as hard disk, printers are centrally located. The user is expected to simply hook onto his account, perform the work, disconnect and leave quietly.
Ex: UNIX
UNIX HISTORY
The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson and Dennis Ritchie. The OS was initially known as UNICS. In 1970 UNICS finally became UNIX. In 1973, UNIX was re-written in 1973 in C principally authored by Ritchie.
UNIX FEATURES
1. Multi-user system: Multi-user capability of UNIX allows several users to use the same computer to perform their tasks. Several terminals [Keyboards and Monitors] are connected to a single powerful computer [UNIX server] and each user can work with their terminals.
2. Multi-tasking system: Multitasking is the capability of the operating system to perform various task simultaneously, i.e. a user can run multiple tasks concurrently.
3. Programming Facility: UNIX is highly programmable, the UNIX shell has all the necessary ingredients like conditional and control structures, etc.
4. Security: UNIX allows sharing of data; every user must have a single login name and password. So, accessing another users data is impossible without his permission.
5. Portability: UNIX is portable because it is written in a high level language. So, UNIX can be run on different computers.
6. Communication: UNIX supports communication between different terminals of the same server as well as between terminals on different servers. Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and Libraries and enhanced GUI (X Window).
ORGANIZATION OF UNIX
2. Shell, which connects and interprets users' commands, calls programs from memory, and executes them;
The kernel is the heart of the system, a collection of programs written in C that directly communicate with the hardware. There is only one kernel for any system. It's that part of UNIX system that is loaded into memory when the system is booted. It manages the system resources,
allocates time between users and processes, decides process priorities, and performs all other tasks. The kernel, in traditional parlance, is often called the Operating system.
The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interface between the user and the kernel. The shell is the agency which takes care of the features of redirection and has a programming capability of its own.
The Tools and Applications consist of Application Software, Compilers, Database Package, Internet tools, UNIX commands, etc.
FILE SYSTEM
A file in UNIX is nothing but a storehouse of information and everything is treated as a file by UNIX. The files can be broadly classified as follows:
Ordinary files: Contains stream of data. All data, text, source programs, object and executable code, commands fall into this category.
Directory files: Contains no external data. It contains an entry, name of the file and its inode (identification number) for each file and subdirectory under that directory. Directory files are not created by the user but by the UNIX system itself.
Device files: Even physical devices are treated as files. These are special in the sense that any output directed to it will be reflected onto the respective device.
All files in UNIX are related to one another. The file system of UNIX resembles a tree that grows from top to bottom as shown in the figure. The file system begins with a directory called root (at the top). The root directory is denoted by a slash (\). Branching from root there are several directories such as bin, lib, etc, tmp, dev. Each of these directories contains several subdirectories and files.
RESULT
Thus the study of UNIX Operating System has been completed successfully.
BASIC COMMANDS
AIM
UNIX is security conscious, and can be used only by those persons who have an account. Telnet (Telephone Network) is a Terminal emulator program for TCP/IP networks that enables users to log on to remote servers. Otherwise, static login system can be used to authenticate the users. General commands Command date date +%D date +%T date +% Y date +% H cal cal year cal month year who who am i tty uname uname r uname n echo "txt" echo $HOME Function Used to display the current system date and time. Displays date only Displays time only Displays the year part of date Displays the hour part of time Calendar of the current month Displays calendar for all months of the specified year Displays calendar for the specified month of the year Login details of all users such as their IP, Terminal and User name Used to display the login details of the user Used to display the terminal name Displays the Operating System Shows version number of the OS (kernel). Displays domain name of the server Displays the given text on the screen Displays the user's home directory
Directory commands Command pwd mkdir dir mkdir dir1 dir2 cd subdir Function Path of the present working directory A directory is created in the given name under the current directory A number of sub-directories can be created under one stroke Change Directory. If the subdir starts with / then path starts from root (absolute) otherwise from current working directory. cd cd / To switch to the home directory. To switch to the root directory.
File commands
Function To create a file with some contents. The > symbol means redirecting output to a file. (< for input)
cat filename cat >> filename cp src des mv old new rm file rm * rm r * ls ls name
Displays the file contents. Used to append contents to a file Copy files to given location. If already exists, it will be overwritten To rename an existing file or directory. Used to delete a file or group of files. i option can also be used To delete all the files in the directory. Deletes all files and sub-directories Lists all files and subdirectories (blue colored) in sorted manner. To check whether a file or directory exists.
OUTPUT
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
[dmi@localhost dmi]$ cal 1800 1800 January February March Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 123411 5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8 12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15 19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22 26 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29 30 31 October November December Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 12341123456 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27 26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31 30
[dmi@localhost dmi]$ who root :0 Apr 9 08:41 dmi pts/0 Apr 9 13:00 (scl-64)
[dmi@localhost dmi]$ mkdir filter [dmi@localhost dmi]$ ls filter list.sh regexpr shellscripts
[dmi@localhost dmi]$ cat > greet hi students wishing u the best [Press Ctrl+D]
[dmi@localhost dmi]$ cat greet hi students wishing u the best [dmi@localhost dmi]$ cat >> greet bye [Press Ctrl+D]
[dmi@localhost dmi]$ ls -a . .bash_logout .canna .gtkrc regexpr .viminfo.tmp .. .bash_profile .emacs .kde shellscripts .xemacs .bash_history .bashrc greet list.sh .viminfo
[dmi@localhost dmi]$ ls -l total 16 -rw-rw-r-- 1 dmi dmi 32 Apr 11 14:52 greet -rw-rw-r-- 1 dmi dmi 30 Apr 4 13:58 list.sh drwxrwxr-x 2 dmi dmi 4096 Apr 9 14:30 regexpr drwxrwxr-x 7 dmi dmi 4096 Apr 4 14:57 shellscripts
[dmi@localhost dmi]$ cp greet ./regexpr/ [dmi@localhost dmi]$ ls greet list.sh regexpr shellscripts
[dmi@localhost dmi]$ mv greet greet.txt [dmi@localhost dmi]$ ls greet.txt list.sh regexpr shellscripts
RESULT
Thus the study and execution of basic UNIX commands has been completed successfully.
SIMPLE PROGRAMS
AIM
The activities of a shell are not restricted to command interpretation alone. The shell also has rudimentary programming features. When a group of commands has to be executed regularly, they are stored in a file (with extension .sh). All such files are called shell scripts or shell programs. Shell programs run in interpretive mode.
The original UNIX came with the Bourne shell (sh) and it is universal even today. Then came a plethora of shells offering new features. Two of them, C shell (csh) and Korn shell (ksh) has been well accepted by the UNIX fraternity. Linux offers Bash shell (bash) as a superior alternative to Bourne shell.
PRELIMINARIES
1. Comments in shell script start with #. It can be placed anywhere in a line; the shell ignores contents to its right. Comments are recommended but not mandatory.
2. Shell variables are loosely typed i.e. not declared. Their type depends on the value assigned. Variables when used in an expression or output must be prefixed by $.
3. The read statement is shell's internal tool for making scripts interactive.
4. Output is displayed using echo statement. Any text should be within quotes. Escape sequence should be used with e option.
6. Expressions are computed using the expr command. Arithmetic operators are + - * / %. Meta characters * ( ) should be escaped with a \.
8. The shell scripts are executed using the sh command (sh filename).
RESULT
Thus using programming basics, simple shell scripts were studied and executed.
CONDITIONAL STATEMENTS
AIM
Shell supports decision-making using if statement. The if statement like its counterpart in programming languages has the following formats. The first construct executes the statements when the condition is true. The second construct adds an optional else to the first one that has different set of statements to be executed depending on whether the condition is true or false. The last one is an elif ladder, in which conditions are tested in sequence, but only one set of statements is executed.
Type-1 // simple - if
Type-2 // if - else
The set of relational and logical operators used in conditional expression is given below. The numeric comparison in the shell is confined to integer values only.
Operator
Description
Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to Logical AND Logical OR Logical NOT
Algorithm
Step 1 : Start Step 2 : Read number Step 3 : If number divisible by 2 then Print "Number is Even" Step 3.1 : else Print "Number is Odd" Step 4 : Stop
Program (oddeven.sh)
# Odd or even using if-else echo -n "Enter a non-zero number : " read num rem=`expr $num % 2` if [ $rem -eq 0 ] then echo "$num is Even" else echo "$num is Odd" fi
2.2.BBiggest of 3 numbers
Algorithm
Step 1 : Start Step 2 : Read values of a, b and c Step 3 : If a > b and a > c then Print "A is the biggest" Step 3.1 : else if b > c then Print "B is the biggest " Step 3.2 : else Print "C is the biggest" Step 4 : Stop
Program (big3.sh)
# Biggest using logical expression echo -n "Give value for A B and C: " read a b c if [ $a -gt $b -a $a -gt $c ] then echo "A is the Biggest number" elif [ $b -gt $c ] then echo "B is the Biggest number" else echo "C is the Biggest number" fi
Output [dmi@localhost decision]$ sh big3.sh Give value for A B and C: 4 3 4 C is the Biggest number
2.2.CLeap year
Algorithm Step 1 : Start Step 2 : Read the value of year Step 3 : If year divisible by 400 then Print "Leap year" Step 3.1 : else if year divisible by 4 and not divisible by 100 then Print "Leap year" Step 3.2 : else Print "Not a leap year" Step 4 : Stop
Program (leap.sh)
# Leap year echo -n "Enter a year : " read year rem1=`expr $year % 4` rem2=`expr $year % 100` rem3=`expr $year % 400` if [ $rem3 -eq 0 ] then echo "$year is a Leap Year" elif [ $rem2 -ne 0 -a $rem1 -eq 0 ] then
echo "$year is a Leap Year" else echo "$year is Not a leap year" fi
Output
[dmi@localhost decision]$ sh leap.sh Enter a year : 1900 1900 is Not a leap year
2.2.DGrade Determination
Algorithm Step 1 : Start Step 2 : Read mark Step 3 : If mark > 90 then Print "S grade" Step 3.1 : else if mark > 80 then Print "A grade" Step 3.2 : else if mark > 70 then Print "B grade" Step 3.3 : else if mark > 60 then Print "C grade" Step 3.4 : else if mark > 55 then Print "D grade" Step 3.5 : else if mark Print "E grade" Step 3.6 : else Print "U grade" Step 4 : Stop 50 then
Program (grade.sh)
echo -n "Enter the mark : " read mark if [ $mark -gt 90 ] then echo "S Grade" elif [ $mark -gt 80 ] then echo "A Grade" elif [ $mark -gt 70 ] then echo "B Grade" elif [ $mark -gt 60 ] then echo "C Grade" elif [ $mark -gt 55 ] then echo "D Grade" elif [ $mark -ge 50 ] then echo "E Grade" else echo "U Grade" fi
Output
2.2.EString comparison
Algorithm
Step 1 : Start Step 2 : Read strings str1 and str2 Step 3 : If str1 = str2 then Print "Strings are the same" Step 3.1 : else Print "Strings are distinct" Step 4 : Stop
Program (strcomp.sh)
echo -n "Enter the first string : " read s1 echo -n "Enter the second string : " read s2 if [ $s1 == $s2 ] then echo "Strings are the same" else echo "Strings are distinct" fi
Output
[dmi@localhost decision]$ sh strcomp.sh Enter the first string : ece-a Enter the second string : ECE-A Strings are distinct
Algorithm
Step 1 : Start Step 2 : Read basic Step 3 : If basic > 30000 then hra is 5% of basic da is 5% of basic tax is 10% of basic Step 3.1 : else if basic > 20000 then hra is 4% of basic da is 3% of basic tax is 8% of basic Step 3.2 : else hra is 3% of basic da is 2% of basic tax is 5% of basic Step 4 : Stop
Program (emppay.sh)
echo -n "Enter employee basic pay : " read basic if [ $basic -gt 30000 ] then hra=`expr 5 \* $basic / 100` da=`expr 5 \* $basic / 100` tax=`expr 10 \* $basic / 100` elif [ $basic -gt 20000 ] then
hra=`expr 4 \* $basic / 100` da=`expr 3 \* $basic / 100` tax=`expr 8 \* $basic / 100` else hra=`expr 3 \* $basic / 100` da=`expr 2 \* $basic / 100` tax=`expr 5 \* $basic / 100` fi gross=`expr $basic + $da + $hra` netpay=`expr $gross - $tax` echo "Gross Pay : $gross" echo "Net Pay : $netpay"
Output
[dmi@localhost decision]$ sh emppay.sh Enter employee basic pay : 12000 Gross Pay : 12600 Net Pay : 12000
RESULT
MULTI-WAY BRANCHING
AIM
The case statement is used to compare a variables value against a set of constants (integer, character, string, range). If it matches a constant, then the set of statements followed after ) is executed till a ;; is encountered. The optional default block is indicated by *. Multiple constants can be specified in a single pattern separated by |.
case variable in constant1) statements ;; constant2) statements ;; ... constantN) statements ;; *) statements esac
2.3.AVowel or Consonant
Algorithm
Step 1 : Start Step 2 : Read char Step 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then Print "It's a vowel" Step 3.1 : else Print "It's a consonant" Step 4 : Stop
Program (vowel.sh)
# Vowel with multiple values in a pattern echo -n "Key in a lower case character : " read choice case $choice in a|e|i|o|u) echo "It's a Vowel";; *) echo "It's a Consonant" esac
Output
2.3.BSimple Calculator
Algorithm
Step 1 : Start Step 2 : Read operands a and b Step 3 : Display operation menu Step 4 : Read option Step 5 : If option = 1 then Calculate c = a + b Step 5.1 : else if option = 2 then Calculate c = a b Step 5.2 : else if option = 3 then Calculate c = a * b Step 5.3 : else if option = 4 then Calculate c = a / b Step 5.4 : else if option = 5 then Calculate c = a % b Step 5.5 : else Print "Invalid option" Step 6 : Print c Step 7 : Stop
Program (calc.sh)
# Arithmetic operations--multiple statements in a block echo -n "Enter the two numbers : " read a b echo " 1. Addition" echo " 2. Subtraction" echo " 3. Multiplication"
echo " 4. Division" echo " 5. Modulo Division" echo -n "Enter the option : " read option case $option in 1) c=`expr $a + $b` echo "$a + $b = $c";; 2) c=`expr $a - $b` echo "$a - $b = $c";; 3) c=`expr $a \* $b` echo "$a * $b = $c";; 4) c=`expr $a / $b` echo "$a / $b = $c";; 5) c=`expr $a % $b` echo "$a % $b = $c";; *) echo "Invalid Option" esac
Output
[dmi@localhost multway]$ sh calc.sh Enter the two numbers : 2 4 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Modulo Division Enter the option : 1 2+4=6
2.3.CRental Options
Algorithm
Step 1 : Start Step 2 : Read vehicle Step 3 : If vehicle = "car" then Print "Rental is Rs. 20/km" Step 3.1 : else if vehicle = "van" then Print "Rental is Rs. 10/km" Step 3.2 : else if vehicle = "jeep" then Print "Rental is Rs. 5/km" Step 3.3 : else if vehicle = "bicycle" then Print "Rental is Rs. 0.2/km" Step 3.4 : else Print "Vehicle not available" Step 4 : Stop
Program (rental.sh)
# String matching echo "Two/Four wheeler rental" echo -n "Enter the required vehicle : " read vehicle case $vehicle in "car") echo "For $vehicle Rs.20 per km";; "van") echo "For $vehicle Rs.10 per km";; "jeep") echo "For $vehicle Rs.5 per km";; "bicycle") echo "For $vehicle 20 paisa per km";; *) echo "Sorry, I cannot get a $vehicle for you";; esac
Output
[dmi@localhost multway]$ sh rental.sh Two/Four wheeler rental Enter the required vehicle : bicycle For bicycle 20 paisa per km
Algorithm
Print "Not eligible to vote" Step 3.1 : else Print "Eligible to vote" Step 4 : Stop
Program (vote.sh)
# Vote--range matching echo -n "Enter your age : " read age case $age in [0-9]|1[0-7])echo "You are not eligible to vote";; *)echo "Eligible to vote" Esac
Output
[dmi@localhost multway]$ sh vote.sh Enter your age : 12 You are not eligible to vote
RESULT
LOOPS
Shell supports a set of loops such as for, while and until to execute a set of statements repeatedly. The body of the loop is contained between do and done statement. The for loop doesn't test a condition, but uses a list instead.
The while loop executes the statements as long as the condition remains true.
The until loop complements the while construct in the sense that the statements are executed as long as the condition remains false.
2.4.AMultiplication Table
Algorithm
Step 1 : Start Step 2 : Read the value of n Step 3 : Initialize 1 to i Step 4 : Print n, i, ni Step 5 : Increment i by 1 Step 6 : Repeat steps 4 and 5 until i >=10 Step 7 : Stop
Program (multable.sh)
# Multiplication table using for loop clear echo -n "Which multiplication table? : " read n for x in 1 2 3 4 5 6 7 8 9 10 do p=`expr $x \* $n` echo -n "$n X $x = $p" sleep 1 done
Output
2.4.BArmstrong Number
Algorithm
Step 1 : Start Step 2 : Read number Step 3 : Initialize 0 to sum and number to num Step 4 : Extract lastdigit by computing number modulo 10 Step 5 : Cube the lastdigit and add it to sum Step 6 : Divide number by 10 Step 7: Repeat steps 46 until number > 0 Step 8 : If sum = number then Print Armstrong number Step 8.1 : else Print Not an Armstrong number Step 9 : Stop
Program (armstrong.sh)
# Armstrong number using while loop echo -n "Enter a number : " read n a=$n s=0 while [ $n -gt 0 ] do r=`expr $n % 10` s=`expr $s + \( $r \* $r \* $r \)` n=`expr $n / 10` done if [ $a -eq $s ] then echo "Armstrong Number" else echo -n "Not an Armstrong number" fi
Output
2.4.CNumber Reverse
Algorithm
Step 1 : Start Step 2 : Read number Step 3 : Initialize 0 to reverse Step 4 : Extract lastdigit by computing number modulo 10 Step 5 : Compute reverse = reverse10 + lastdigit Step 6 : Divide number by 10 Step 7: Repeat steps 46 until number > 0 Step 8 : Print reverse Step 9 : Stop
Program (reverse.sh)
# To reverse a number using while loop echo -n "Enter a number : " read n rd=0 while [ $n -gt 0 ] do rem=`expr $n % 10` rd=`expr $rd \* 10 + $rem` n=`expr $n / 10` done echo "Reversed number is $rd"
Output
2.4.DFibonacci Series
Algorithm
Step 1 : Start Step 2 : Read number of terms as n Step 3 : Initialize 0 to f1, 1 to f2 and 2 to i Step 4 : Print initial fibonacci terms f1, f2 Step 5 : Generate next term using the formula f3 = f1 + f2 Step 6 : Print f3 Step 7 : Increment i by 1 Step 8 : Assign f2 to f1 Step 9 : Assign f3 to f2 Step 10 : Repeat steps 59 until i Step 11 : Stop n
Program (fibo.sh)
# Fibonacci series using while loop echo -n "Enter number of terms : " read n echo "Fibonacci Series" f1=0 f2=1 echo -n "$f1 "
echo -n " $f2 " i=2 while [ $i -lt $n ] do f3=`expr $f1 + $f2` echo -n " $f3 " f1=$f2 f2=$f3 i=`expr $i + 1` done echo
Output
2.4.EPrime Number
Algorithm
Step 1 : Start Step 2 : Read the value of n Step 3 : Initialize i to 2 Step 4 : If n is divisible by i then Print Not Prime and Stop Step 5 : Increment i by 1 Step 6 : Repeat steps 4 and 5 until i Step 7 : Print "Prime" n/2
Step 8 : Stop
Program (prime.sh)
echo -n "Enter the number : " read n i=2 m=`expr $n / 2` until [ $i -gt $m ] do q=`expr $n % $i` if [ $q -eq 0 ] then echo "Not a Prime number" exit fi i=`expr $i + 1` done echo "Prime number"
Output
2.4.FFactorial Value
Algorithm
Step 1 : Start Step 2 : Read number Step 3 : Initialize 1 to fact and number to i Step 4 : fact = fact * i Step 5 : Decrement i by 1 Step 6: Repeat steps 46 until i > 0 Step 7 : Print fact Step 8 : Stop
Program (fact.sh)
# Factorial value using until echo -n "Enter a positive number : " read n f=1 until [ $n -lt 1 ] do f=`expr $f \* $n` n=`expr $n - 1` done echo "Factorial value : $f"
Output
Algorithm
Step 1 : Start Step 2 : Read n Step 3 : Initialize 0 to sum and 1 to i Step 4 : Add i to sum Step 5 : Increment i by 1 Step 6: Repeat steps 46 until i>= n Step 7 : Print sum Step 8 : Stop
Program (sum1ton.sh)
echo -n "Enter N value : " read n sum=0 i=1 until [ $i -gt $n ] do sum=`expr $sum + $i` i=`expr $i + 1` done echo "The sum of n numbers is $sum"
Output
RESULT
Introduction to Pointers
AIM
To learn the concept of pointers in C programs. Data for a variable is stored at some memory location. Address and Data are two sides an variable. For instance x = 10 is represented as
Variable x
Data 10
Address 3221216948
The address of a variable can be obtained using & operator known as reference operator. The variable's value can be obtained using the dereference operator *.
Pointer Variable
A Pointer variable or a pointer is a special variable that holds the address of another variable Pointer variable are distinguished from other variables by having an asterik (*) prefixed in the declaration statement.
int x, *iptr;
A pointer variable is a derived data type based on either standard, derived or user-defined data type. A pointer variable can be made to point any variable of its base type by assigning the variable's address to the pointer. For instance, an integer pointer can point to an integer variable only. A pointer variable is allocated 2 bytes irrespective of the data type it points.
Value of the variable pointed to can be accessed by applying the dereference operator
A pointer of type void is referred to as generic pointer i.e. it can point to any data type. Since pointer variables hold address, integers could be added or subtracted to yield another address. A pointer that holds the address of another pointer variable is known as pointer-topointer.
Algorithm
Step 1 : Start Step 2 : Initialize x to 10 Step 3 : Print the value of x Step 4 : Print the address of x using address operator Step 5 : Print the value of x by dereferencing the address operator Step 6 : Stop
Program (refderef.c)
#include <stdio.h> main() { int x; x=10; printf("Value of x is %d",x); printf("\nAddress of x is %u",&x); printf("\nValue of x is %d\n",*(&x)); }
Output
[dmi@localhost pointer]$ cc refderef.c [dmi@localhost pointer]$ ./a.out Value of x is 10 Address of x is 3221216948 Value of x is 10
3.1.BPointertoPointer
Algorithm
Step 1 : Demonstrate void pointer by making it to point to variables of different type Step 2 : Declare a pointer variable p1 and assign a variable's address of its type Step 3 : Declare a double pointer p2 and assign it the address of p1 Step 4 : Display the address stored in p1, data accessed using p1 and p1's address Step 5 : Display the address stored in p2, data accessed using p2 and p2's address Step 6 : Stop
Program (ptrtoptr.c)
# include<stdio.h> main() { int x=12, *p1, **p2; float z=8.5; void *ptr; /* Generic pointer */ ptr = &x ; /* ptr points to x (int) */ ptr = &z; /* ptr points to y (float) */ p1 = &x;
p2 = &p1; /* Pointer to pointer */ printf("X value is %d and stored at %u\n", x, &x); printf("\nPointer holds the address %u\n", p1); printf("Aceesing value thru pointer : %d\n", *p1); printf("Pointer is stored at location : %u\n",&p1); printf("\nPointer-to-pointer holds the address %u\n", p2); printf("Accessing value thru ptr-to-ptr : %d\n", **p2); printf("\nSize of ptr-to-ptr: %d bytes\n", sizeof(ptr)); }
Output
[dmi@localhost pointer]$ cc ptrtoptr.c [dmi@localhost pointer]$ ./a.out X value is 12 and stored at 3221220804 Pointer holds the address 3221220804 Aceesing value thru pointer : 12 Pointer is stored at location : 3221220800 Pointer-to-pointer holds the address 3221220800 Accessing value thru ptr-to-ptr : 12 Size of ptr-to-ptr: 4 bytes
Step 1 : Start Step 2 : Read the values of a and b Step 3 : Assign the address of a and b to x and y Step 4 : Sum the values at locations pointed by x and y and store in c Step 5 : Print c Step 6 : Stop
Program (ptradd.c)
#include<stdio.h> main() { int a,b,c; int *pa,*pb; pa=&a; pb=&b; printf("Enter values for A and B : "); scanf("%d%d",&a,&b); c = *pa + *pb; printf("Sum = %d\n",c); }
Output
[dmi@localhost pointer]$ cc ptradd.c [dmi@localhost pointer]$ ./a.out Enter values for A and B : 4 6 Sum = 10
RESULT
Pointer Programming
AIM
Arguments passed to functions are pass by value i.e., a copy of value of the actual arguments are passed. Therefore changes made to formal arguments are not reflected to actual arguments. However, to have the actual arguments modified during process by another function, then addresses of the arguments are passed, instead of values through pointers. This is known as pass by reference. Another use of pointers in function is that an address could be returned, known as return by reference.
Pointers can be used for efficient traversal of a given array. An array name by itself is a pointer to the first element in the array. The address of first element of array X can be expressed as either &X[0] or X. The i+1th element is termed as &X[i] or X+i. The value of i is referred to as offset. Thus a pointer can be assigned an array variable and array elements can be accessed by altering the offset. Similarly for two-dimensional array, Xi+1,j+1 element could be accessed as * (* (X + i) + j).
A string variable alternatively can be declared as a character pointer type since string is represented as an array of characters. The advantage is that length of the string need not be known in advance. Strings could be processed using character pointer.
A pointer variable can be assigned a structure as any other type. The members of a structure are accessed using the indirect selection operator (->). Self-referential structure is a structure where one of its members is a pointer to the structure itself. Such structures are used to implement data structures such as list and trees.
Algorithm
Step 1 : Define function swapval with parameters of type integer that swaps two variables using a temporary variable. Step 2 : Define function swapref with parameters of type integer pointer that swaps two variables using a temporary variable and pointer notation Step 3 : In main function get values of two variables, say a and b Step 4 : Call function swapval with a and b as arguments (Call by value) Step 5 : Print the values of a and b after function call. Step 6 : Call function swapref with address of a and b as arguments (Call by reference) Step 7 : Print the values of a and b after function call. Step 8 : Stop
Program (passbyref.c)
/* Pass by value and reference */ #include <stdio.h> main() { int a, b; void swapval(int, int); /* Pass by reference */
void swapref(int *, int *); /* Pass by value */ printf("Enter the values of A and B : "); scanf("%d%d",&a,&b); swapval(a,b); /* Call by value */ printf("\nValues after Pass by Value\n"); printf("Value of A is %d\n",a); printf("Value of B is %d\n",b); swapref(&a, &b); /* Call by reference */ printf("\nValues after Pass by Reference\n"); printf("Value of A is %d\n",a); printf("Value of B is %d\n",b); } void swapref(int *x, int *y) { int t; t = *x; *x = *y; *y = t; } void swapval(int a, int b) { int t; t = a; a = b; b = t; }
Output
[dmi@localhost pointer]$ cc passbyref.c [dmi@localhost pointer]$ ./a.out Enter the values of A and B : 12 23 Values after Pass by Value Value of A is 12 Value of B is 23 Values after Pass by Reference Value of A is 23 Value of B is 12
3.2.BReturn by reference
Algorithm
Step 1 : Define function big with parameters of type integer pointer that returns the address of the biggest number using pointers (Return by reference) Step 2 : In main function get values of two variables, say a and b Step 3 : Call function big with address of a and b as arguments (Call by reference) Step 4 : Print value stored at the address returned
Program (retbyref.c)
/*Return by reference*/ #include <stdio.h> int* big(int* x, int* y) { if (*x > *y) return x;
else return y; } main() { int a, b; int *p; printf("Enter two values : "); scanf("%d%d",&a,&b); p = big(&a, &b); printf("Biggest is %d\n",*p); }
Output
[dmi@localhost pointer]$ cc retbyref.c [dmi@localhost pointer]$ ./a.out Enter two values : 3 7 Biggest is 7
3.2.CStudent Detail
Algorithm
Step 1 : Declare a student structure with members rollno, name and mark Step 2 : Create a variable s1, and a pointer ptr of type student Step 3 : Populate s1 with inputs from the user Step 4 : Assign address of s1 to ptr Step 5 : Display the values of structure members using pointer-to-member operator Step 6 : Stop
Program (studdetail.c)
#include<stdio.h> struct student { long rollno; char name[10]; float mark; }; main() { struct student *ptr; struct student s1; printf("\nEnter students rollno, name, mark : "); scanf("%ld%s%f",&s1.rollno,s1.name,&s1.mark); ptr=&s1; printf("\n\tSTUDENT DETAIL"); printf("\nRollno\tName\t\tMark\n"); printf("%ld\t%s\t%.2f\n",ptr->rollno,ptr->name,ptr->mark); }
Output
[dmi@localhost pointer]$ cc studdetail.c [dmi@localhost pointer]$ ./a.out Enter students rollno, name, mark : 1032957 Adhithan 10 STUDENT DETAILS Rollno Name Mark 1032957 Adhithan 10.00
RESULT
Thus C programs using pointers were executed and its efficiency realized.
AIM
Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. In C, main function can accept two arguments: one argument is number of command line arguments, and the other argument is a list of all of the command line arguments.
The first one integer, (conventionally called argc) is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program. The second is a pointer to an array of character strings (conventionally called argv), for argument vector that contains the arguments, one per string. argv[0] is the name of the program. After that, every element number less than argc is a command line argument. argv[argc] is a null pointer. C's model of command line arguments adheres to the following:
Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument. A double quotation mark preceded by a backslash, \", is interpreted as ". Two back slash (\\) is replaced by a single backslash (\).
argc = 3
Command line arguments are typically used to pass the name of a data file to an application. Programs containing command line parameters are generally used to imitate OS commands.
Program (cmdline.c)
/* Command line arguments */ #include <stdio.h> main(int argc, int *argv[]) { int i; printf("Number of arguments : %d\n", argc); for(i=0; i<argc; i++) printf("Argument [%d] = %s\n",i, argv[i]); }
Output
[dmi@localhost files]$ gcc cmdline.c -o cmdline [dmi@localhost files]$ ./cmdline "C:\\Program Files\\Adobe" readme.txt Number of arguments : 3 Argument [0] = ./cmdline Argument [1] = C:\Program Files\Adobe Argument [2] = readme.txt
RESULT