By Andrew Pereira &-Jharna Sinha (M.Sc Computer Science)
AWK is considered to be a data-driven scripting language can take its input either from files or from input streams. The language used by awk makes extensive use of the string data type, associative arrays and regular expressions.
The essential organization of an AWK program follows the form:
pattern { action }
The pattern specifies when the action is performed
Some examples using AWK are as follows :
HCF of 2 numbers :
#An awk program to calculate HCF of 2 numbers.
BEGIN{
system("clear")
system("tput cup 13 10")
printf "Enter the 1st number : "
getline a < "/dev/tty"
system("tput cup 14 10")
printf "Enter the 2nd number : "
getline b < "/dev/tty"
if(a > b){
x=a
y=b
}
else{
x=b
y=a
}
while((r=x%y)!=0){
x=y
y=r
}
system("clear")
printf "\nHCF of %d & %d = %d",a,b,y
printf"\n"
}
Perfect Numbers :
#An awk program to calculate compute all perfect numbers within a given limit
BEGIN{
system("clear")
printf "\nEnter the limit : "
getline n < "/dev/tty"
i=2
j=1
sum=0
printf "\nPerfect numbers :-\n"
while(i <= n){
while(j <= i){
rem=i % j
res=i / j
if(rem == 0){
sum=sum + res
}
j=j + 1
}
if(sum == i){
printf "%d\n",i
}
i=i + 1
j=2
sum=0
}
}
Insertion Sort :
#A programme to sort numbers using insertion sort.
BEGIN{
system("clear")
system("tput cup 13 10")
printf "Enter the size of your list : "
getline n <"/dev/tty"
system("clear")
printf "\n Enter %d elements one by one ------------------>\n",n
for(i=1;i<=n;i++){
printf "a[%d] : ",i
getline a[i] < "/dev/tty"
ind[i]=i
}
printf "Press any key to see the unsorted list ------------>\n"
getline ch < "/dev/tty"
system("clear")
printf "\n<====Unsorted list====>\n"
printf "Number Index\n"
for(i=1;i<=n;i++){
printf "%4d %4d\n",a[i],ind[i]
}
#Insertion Sort routine starts
for(i=1;i<=n;i++){
t1=a[i]
t2=ind[i]
j=i-1
while(j>=1 && t1\n"
getline ch < "/dev/tty"
system("clear")
printf "\n<=====Sorted list=====>\n"
printf "Number Index\n"
for(i=1;i<=n;i++){
printf "%4d %4d\n",a[i],ind[i]
}
}
No comments:
Post a Comment