700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > c语言while与until的用法 while和until循环

c语言while与until的用法 while和until循环

时间:2023-03-13 05:38:11

相关推荐

c语言while与until的用法 while和until循环

while循环和until :循环次数不定。

一、while循环

1、格式:

while 条件测试;do

循环体;

done

例:用while求05月19日0内的所有正整数的和。

#!/bin/bash

declare -i sum=0,i=1

while [ $i -le 100 ];do

let sum+=$i

let i++

done

echo $sum

例:用while求05月19日0内的所有偶数的和。

#!/bin/bash

declare -i sum=0,i=2

while [ $i -le 100 ];do

let sum+=$i

let i+=2

done

echo $sum

例:通过键盘提示用户输入字符,将用户输入的小写字母转换为大写,

转换一次之后,再次提醒用户输入,再次转换,直到输入quit,

quit表示退出。

#!/bin/bash

read -p "Enter a word:" word

while [[ "$word" != "quit" ]];do

echo $word |tr 'a-z' 'A-Z'

read -p "Enter a word again:" word

done

例:提示用户输入一个用户名,如果存在,显示用户UID和SHELL信息,否则,则显示无此用户;

显示完成后,提示用户再次输入;如果是quit则退出。

#!/bin/bash

read -p "Enter a username:" userName

while [[ "$userName" != "quit" ]];do

if id $userName &> /dev/null;then

grep "^$userName>" /etc/passwd |cut -d : -f3,7

else

echo "$userName is not exist."

fi

read -p "Enter a username again:" userName

done

例:提示用户输入一个用户名,

如果不存在,提示用户再次输入。

如果存在,则判定用户是否登录,

如果未登录,提示“$userName is not here.”,

则停止5秒钟,再次判断用户是否登录,

直到用户登录系统,显示“$userName is on”。

#!/bin/bash

read -p "Enter a user name:" userName

while ! id $userName &>/dev/null;do

read -p "Enter a user name again:" userName

done

while ! who | grep "^$userName" &>/dev/null ;do

echo "$userName is not here."

sleep 5

done

echo "$userName is on."

二、until循环:条件不满足,则循环,否则退出(可见于while相反)。

例:用untile循环,求100以内所有正整数之和。

#!/bin/bash

declare -i sum=0

declare -i i=1

untile [ $i -gt 100 ];do

let sum+=$i

let i++

done

echo $sum

三、组合条件测试:

1、逻辑与:

[ condition1 ] && [ condition2 ]

[ condition1 -a condition2 ]

[[ condition1 && condition2 ]]

注意:&&只能用于双括号 ` `中.

2、逻辑或:

[ condition1 ] || [ condition2 ]

[ condition1 -o condition2 ]

[[ condition1 || condition2 ]]

注意:||只能用于双括号 ` `中.

3、使用while循环一次读取文件的一行,直到文件尾部;

while read line ;do

循环体

done

例:取出当前系统上,默认shell为bash的用户

#!/bin/bash

while read line;do

[[ `echo $line |cut -d: -f7` == "/bin/bash" ]] && echo $line |cut -d: -f1

done

五、循环控制continue和break:

1、continue提前结束本次循环而开始下一轮循环。

如:求100之内所有偶数之和。

#!/bin/bash

declare -i evenSum=0

declare -i i=1

while [ $i -le 100 ] ;do

if [ [$i%2] -eq 1 ];then

let i++

continue

else

let evenSum+=$i

let i++

fi

done

2、break [n]:跳出当前循环,n跳出基层循环(循环嵌套时)。

本文转自lzf0530377451CTO博客,原文链接:/8757505月19日41025,如需转载请自行联系原作者

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。