Im using awk script programming in the END state if i set the for loop i in name it would print out the values of the name array but not the sales array, If i set the for loop i in sales it would print out the values in the sales array but not the name array i need to know how to print out both the name & sales array at the same time.

# Write an awk script that produces
# a report from an input file

BEGIN {
# printing header
print "Lazy Acres, Inc."
print "2010 Sales Associates Ranking"
print "Name          Position        Sales Amount"
print "=========================================="
# setting field separator to :
FS = ":"
}

# Product lines
# $1 = Product ID.
# $2 = Product Caregory
# $3 = Description
# $4 = Price
NF == 4 {
    product[$1] = $4;
}

# Associates lines
# $1 = Associate ID.
# $2 = Name
# $3 = Position.
NF == 3 {
    name[$1] = $2  ":" $3;
}

# Sales lines.
# $1 = Transaction ID
# $2 = Product ID
# $3 = Quantity
# $4 = Date
# $5 = Assoiciate ID
NF == 5 && $4 ~ /2010/ {
    if ($2 in product) { sales[$5] += $3 * product[$2]  }

}



END{
#for loop to print
for (i in name) {
   printf("%15s %21.2f\n", name[i], sales[i]) | "sort -nr"
 }
}
for (i in name) {
   printf("%15s %21.2f\n", name[i], sales[i]) | "sort -nr"
}

In this i is set to each "value" of the array element and not the index.

There is no simple way to find the array size in awk. Some newer versions of gawk, nawk support it. So either you can use that or find it yourself.
Here is how you do it yourself:

END{
   arrlen = 0;
   for (nn in name) arrlen++
   # assumes that the array lengths of name and sales are same.
   # if not then could be trouble.
   for (i = 0; i < arrlen; i++) {
      printf("%15s %21.2f\n", name[i], sales[i])
}

PS:
awk supports associative arrays (i.e. non int index). So if you know that name and sales are always associated, you can use a single array. See some description here.

NF == xxx {
   name=$1
        names_arr[$1]=name
   sales=$2
   # increment the sales against this name.
   name_sales_map[name] = name_sales_map[name] + sales
}
END{
   #for loop to print
   for (name in names_arr) {
      printf("%15s %21.2f\n", name_sales_map[name])
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.