Home > OS >  I need to output all numbers between 0 and 10 and print "buzz" on odd numbers
I need to output all numbers between 0 and 10 and print "buzz" on odd numbers

Time:06-22

Provide a simple script (language of your choice) that outputs all numbers between 0 and 10 and prints "buzz" on odd numbers.

CodePudding user response:

StackOverflow is not a homework or interview problem solving service. But here is something that meets all the criteria of the specification.

Provide a simple script (language of your choice) that outputs all numbers between 0 and 10 and prints "buzz" on odd numbers.

  • ☑ This is a script.
  • ☑ Chosen language is POSIX-shell.
  • ☑ Outputs all numbers between 0 and 10 and prints "buzz" on odd numbers.
#!/bin/sh

cat <<EOF
0
1 buzz
2
3 buzz
4
5 buzz
6
7 buzz
8
9 buzz
10
EOF

CodePudding user response:

Using awk

awk 'BEGIN{for(i=0;i<=10;i  ){print(i%2==0?i:i" buzz")}}'
awk '{$1%2==0?$0:$0=$0" buzz"}1' <(seq 0 10)
awk '{$1%2==0?$0:$0=$0" buzz"}1' <(echo {0..10}|tr ' ' '\n')
awk -v s="0" -v e="10" -v b="buzz" 'BEGIN{while(s<=e){print(s%2==0?s:s" "b);s  }}'

Using bash

for i in {0..10}; do [[ "$i"%2 -eq 0 ]] && echo "$i" || echo "$i buzz"; done
for ((i=0;i<=10;i  )); do [[ "$i"%2 -eq 0 ]] && echo $i || echo "$i buzz"; done
i=0; while [ "$i" -le 10 ]; do [[ "$i"%2 -eq 0 ]] && echo "$i" || echo "$i buzz"; ((i  )); done
i=0; until [ "$i" -gt 10 ]; do [[ "$i"%2 -eq 0 ]] && echo "$i" || echo "$i buzz"; ((i  )); done
xargs -i bash -c '[[ "{}"%2 -eq 0 ]] && echo "{}" || echo "{} buzz"' < <(seq 0 10)

CodePudding user response:

You could try using a loop:

Using Bash:

$ for x in {0..10}; do [[ $((x % 2)) -eq 1 ]] && echo "$x buzz" || echo "$x"; done
0
1 buzz
2
3 buzz
4
5 buzz
6
7 buzz
8
9 buzz
10

Using Python:

$ python3 -c "for x in range(11): print(x, 'buzz') if x % 2 else print(x)"
0
1 buzz
2
3 buzz
4
5 buzz
6
7 buzz
8
9 buzz
10

CodePudding user response:

function oddBuzz(){
    for (let i = 0; i < 11; i  ){
        if (i % 2 === 0){ // even
            console.log(i)
        }else{
            console.log("buzz")
        }
    }
}
  • Related