while循环

简介:

while循环

while condition; do

循环体

done

condition:循环控制条件:进入循环之前,先做一次判断;每一次循环之后会再次做判断;

条件为true,则执行一次循环;直到条件测试状态为false终止循环;

因此:condition中一般有循环控制变量;而此变量的值会在循环中不断的被修正;

实例:求100以内的正整数和;

#!/bin/bash

#

declare -i sum

declare -i i=1

while [ $i -le 100 ];do

let sum+=$i

let i++

done

echo "$sum

ping命令探测172.16.6.0-254在线的主机

#!/bin/bash

#

declare -i ip=1

declare -i up=0

declare -i down=0

while [ $ip -le 254  ];do

 ping -w 1 172.16.6.$ip &>/dev/null 

if [ $? -eq 0 ];then

echo "172.16.6.$ip is online"

let up++ 

else

echo "172.16.6.$ip is down" 

let down++

fi

let ip++

done

echo "online is $up"

echo "down is $down" 

打印九九乘法表

#!/bin/bash

#

for x in {1..9};do

for y in `seq 1 $x`;

do 

echo -e -n "$[x]X$[y]=$[$x*$y]\t"

done

echo

done

#!/bin/bash

#

declare -i x=1

declare -i y=1

while [ $x -le 9 ];do

while [ $y -le $x ];do

echo -e -n "$y*$x=$[$y*$x]\t"

let y++

done

let y=1

let x++

done

利用random生成10个随机数,输出这10个数,并显示其中最大的和最小的;

#!/bin/bash

#

declare -i max=0

declare -i min=0

declare -i i=1

rand=$RANDOM

echo $rand

max=$rand

min=$rand

while [ $i -le 9 ];do

rand=$RANDOM

echo $rand

if [ $rand -gt $max ];then

max=$rand

fi

if [ $rand -lt $min ];then

min=$rand

fi

let i++

done

echo "max=$max"

echo "min=$min"

#!/bin/bash

#

declare -i max=0

declare -i min=0

declare -i i=1

while [ $i -le 10 ];do

rand=$RANDOM

echo $rand

if [ $i -eq 1 ];then

   max=$rand

   min=$rand

fi


if [ $rand -gt $max ];then

max=$rand

fi


if [ $rand -lt $min ];then

min=$rand

fi

let i++

done

echo "max=$max"

echo "min=$min"



     本文转自阿伦艾弗森 51CTO博客,原文链接:http://blog.51cto.com/perper/1954274,如需转载请自行联系原作者





相关文章
|
24天前
|
机器人 Python
while`循环
`Python`的`while`循环在条件为真时重复执行代码块。常见用法包括:固定次数循环、无限循环(可由外部条件退出)、使用`break`和`continue`控制流程,以及等待条件满足。经典应用案例有模拟登录尝试、读取文件至末尾和实现简单聊天机器人。`while`循环适用于处理不确定次数迭代和条件触发场景。
17 2
|
1月前
|
Python
phython中while循环
phython中while循环
|
3月前
|
Shell 开发工具
while do done, until do done(不定循环)
【1月更文挑战第7天】。
18 0
|
5月前
while循环和do-while循环?
while循环和do-while循环?
|
6月前
|
C语言
C 循环
C 循环。
24 1
|
7月前
dowhile循环
do { // 循环体 } while (condition);
39 0
|
8月前
三个循环(C)
while语句:while(表达式){},先判断表达式,若符合,则执行循环内容,一个循环后再次判断表达式。
41 0
|
9月前
|
C语言
C 中的循环
C 中的循环
|
11月前
5 二重循环
5 二重循环
67 0
|
JavaScript 前端开发
For Of 循环
For Of 循环
47 0