How to calculate the sum of digits of a number n entered by user

 

Linux Bash Script

echo "Enter number: whose set bits are to be counted"
read num

while [[ $num -gt 0 ]]
do
        let temp=$num%2
        if [[ $temp -eq 1 ]]
        then
                let count=$count+1
        fi
        let num=$num/2
done

echo "Number of set bits are: $count"

 

 

Execute the Linux Script

./7_count_set_bits.sh

 

Output of Linux Script

Enter number: whose set bits are to be counted
15
Number of set bits are: 4