Using While and If statements

  1. The problem statement, all variables and given/known data:
    Two problems I need solving please. I created a script where the user types in 7 numbers as standard input and each one is then stored in an array. Now I need to perform the following calculations on those numbers:

1) Use a while loop to determine the largest number in the range.

2)Use an If statement to calculate the median within the range.

Please provide each suggestion with the simplest command structure possible.

Many thanks for your help!

  1. Relevant commands, code, scripts, algorithms:
    If statement for question 2
    While statement for question 1
    -gt option
    {arr[0]} array

  2. The attempts at a solution (include all code and scripts):
    1)

While [{arr[0]} -gt {arr[1-6]}
do
Done

2)

Sort {arr[0-6]}

#Absolutely stuck after sort

  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):

Canterbury Christ Church University
Canterbury, Kent
United Kingdom

Professor name: Richard Henson

Course name: Operating Systems Assignment 1

Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

  • When refererring to an array element, you need a $ sign: ${arr[0]}
  • Statements are case sensitive: while instead of While
  • A test statement needs space around the square brackets :
while [ 1 -eq 1 ] 
do
  • You cannot refer to a range of array elements like this ${arr[1-6]}

Find largest number:

declare -a num
num=("3" "4" "1" "8" "2" "9" "7")
limit="`echo ${#num[@]}`"
check=0
i=0
while [ $i -lt $limit ]
do 
if [ $check -lt ${num[$i]} ]; then 
check="`echo ${num[$i]}`"
fi 
let i=i+1 
done 
echo "Largest number is:$check"

Median:

declare -a num
num=("3" "4" "1" "7" "2" "9" "10" "5")
limit="`echo ${#num[@]}`"
check=`expr $limit % 2`
if [ $check -eq 1 ];then
#Number count is odd 
# median
declare -a tmp_num 
tmp_num=(`for ((i=0;i<$limit;i++));do echo "${num[$i]}"; done | sort -n`)
med_pos=`expr $limit - 1`
med_posf=`expr $med_pos / 2`
echo "Median is:${tmp_num[$med_posf]}"
elif [ $check -eq 0 ];then
#number count is even
#median
declare -a tmp_num 
tmp_num=(`for ((i=0;i<$limit;i++));do echo "${num[$i]}"; done | sort -n`)
med_posx=`expr $limit / 2`
med_pos1=`expr $med_posx - 1`
med_pos2=`expr $med_pos1 + 1`
med_tmp=`expr ${tmp_num[$med_pos1]} + ${tmp_num[$med_pos2]}`
medf=`echo "scale = 2; $med_tmp / 2"| bc`
echo "Median is:$medf"
fi

This was just a quick attempt. change math options as u like
:slight_smile:

@mtomar, don't do other people's homework. Besides, your solution is a perfect example of shoddy programming.

Hi man. Many thanks for writing that long script but I must refuse to use it. It is far too complex and I would greatly like understand what scripts im adding to my assignment. Please give me a more simplified answer so I may interpret, understand it and then implement it. Thanks for your help again :slight_smile:

@javahater / @jjb1989
I am not here to get marks on my scripting skills... they are doing fine for me.
As i already said this was just a quick draft .. so i just kept adding lines rather than trying make it a beautiful looking small script. In my days there was no internet for help .... ahaha
idea is to give u a direction and u choose ur own path / scripts.
:slight_smile:

no hard feelings !!

@jjb1989
What Shell do you use?

echo $SHELL

I use BASH :slight_smile:

I don't write pure bash and I don't think we have seen your code to populate the array. Might be worth posting that script.
Remember that array elements are numbered from zero. In your case zero to six (i.e. seven elements).
Here's a bit of test code to get you started on how to walk the array and how to refer to the elements in shell script. You will need to change variable names to match the rest of your script and maybe change "echo" to "printf" depending on what you have been taught.

The idea is to build your script in simple stages and test each stage.
Once you can read back you array of the seven numbers the user typed you are in a position to insert code to do more (like find the highest value). Finding the median will be interesting.

echo "Read back test array in the same order it was created"
counter=0
counter_max=6
while [ ${counter} -le ${counter_max} ]
do
        echo "Array element ${counter} = ${num_array[${counter}]}"
        counter=$((counter+1))
done

Clearer:

#!/bin/bash

# Array
declare -a numeros=(
	$(
		for i in $(seq 1 1 7)
		do 
			echo -e `expr ${RANDOM} % 100`
		done
	)
);
# Integer variable
declare -i i=0;
mayor=${numeros[0]}

while [ $i -lt $[ ${#numeros[*]} - 1] ]
do
	echo -e "numeros[$i] = ${numeros[$i]}"
	if [ ${numeros[$i]} -gt $mayor ]
	then
		mayor=${numeros[$i]}
	fi
	((i++));
done

echo -e "Mayor : ${mayor}";
#!/bin/bash
# fill array:
declare -a numeros=($(for i in $(seq 1 1 8); do echo -e `expr ${RANDOM} % 100`; done));
# Integer variable
declare -i i=0;

echo -e "Array : ${numeros[*]}";
if expr ${#numeros[@]} % 2 &> /dev/null
then
	# sort tmp array:
	tmp=(`echo -en "${numeros[*]}" | tr ' ' '\n' | sort -n`);
	echo -e "Sort Array : ${tmp[*]}";
	echo -e "Median : ${tmp[`expr ${#tmp[@]} / 2`]}";	
else
	tmp=(`echo -en "${numeros[*]}" | tr ' ' '\n' | sort -n`);
	echo -e "Sort Array : ${tmp[*]}";
	echo -en "Mediana : ";
	echo -e $(( ${tmp[ `expr \( ${#tmp[*]} / 2 \) - 1` ]} + ${tmp[ `expr ${#tmp[*]} / 2` ]} )) / 2 | bc -l
fi

Wow, some of the above examples defy simplicity to the nth+1 degree.

#!/bin/bash
let count=0
let largest=-999999
while read input; do
    let number[$count]=$input;
    if [ $input -gt $largest ] ; then
         let largest=$input;
    fi;
    let  sum=sum+number
    let count=count=+1
done

The trouble I have difficulty with is "finding median with an if statement". BASH doesn't deal with floating point, so I'm not sure how to accomplish this. We could use sort but that would obviate the need for an if clause. We could iteratively throw away the highest and lowest values, but that's a lot of work (computationally).

If we can assume that the seven numbers contain no duplicates, the median is the number with exactly 3 numbers larger than it. This entails a double while loop and at least 2 if's, but no floating point is needed.