《2.2.6循环结构程序设计---循环结构程序设计2.2(1).ppt》由会员分享,可在线阅读,更多相关《2.2.6循环结构程序设计---循环结构程序设计2.2(1).ppt(8页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Loops-While and Forwhile:while(expression)statementForfor(expr1;expr2;expr3)statementexpr1;while(expr2)statementexpr3;for(;)inifinte loop:processing the first n element of an arrayfor(i=0;in;i+)zeroexpression?non-zerostatement第一页,编辑于星期六:点 四分。Loops-While and ForExample 1:#include/*atoi:convey s to in
2、teger;version 2*/int atoi(char s)int i,n,sign;for(i=0;isspace(si);i+);/*skip white space*/sign=(si=-)?-1:1;if(si=+|si=-)/*skip sign*/i+;for(n=0;isdigit(si);i+)n=10*n+(si-0);return sign*n;第二页,编辑于星期六:点 四分。Loops-While and ForExample 2:/*shellshort:sort v0vn-1 into increasing order*/void shellshort(int
3、v,int n)int gap,i,j,temp;for(gap=n/2;gap0;gap/=2)for(i=gap;i=0&vjvj+gap;j-=gap)temp=vj;vj=vj+gap;vj+jap=temp;for(i=1;i=0&vjvj+1;j-=1)temp=vj;vj=vj+1;vj+1=temp;第三页,编辑于星期六:点 四分。Loops-While and ForExample 3:#include/*reverse:reverse string s in place*/void reverse(char s)int c,i,j;for(i=0,j=strlen(s)-1
4、;ij;i+,j-)c=si;si=sj;sj=c;第四页,编辑于星期六:点 四分。Loops-Do-whilesyntax:do statementwhile(expression);Example:/*itoa:convert n to characters in s*/void itoa(int n,char s)int i,sign;if(sign=n)0);/*delete it*/if(sign=0;n-)if(sn!=&sn!=t&sn!=n)break;sn+1=0;return n;continue:cause the next iteration to beginfor(i
5、=0;in;i+)if(ai0)/*skip negative element*/continue;/*do positive elements*/第六页,编辑于星期六:点 四分。Goto and Labelssyntax:goto label_namelabel_name:statementsExample 1:for()for()if(disaster)goto error;error:clean up the mess第七页,编辑于星期六:点 四分。Goto and Labelswith goto:for(i=0;in;i+)for(j=0;jm;j+)if(ai=bj)goto found;/*didnt find any common element*/found:/*got one:ai=bj*/without goto:found=0;for(i=0;in&!found;i+)for(j=0;jm&!found;j+)if(ai=bj)found=1;if(found)/*got one:ai=bj*/else /*didnt find any common element*/第八页,编辑于星期六:点 四分。