[英]converting a FOR loop to a DO WHILE loop in C++
im trying to convert this into a do-while; 我正在尝试将其转换为使用时间; it is supposed to show a pyramid based on a number that you have entered:
它应该根据您输入的数字显示一个金字塔:
int size,a,b,c;
printf("Enter a Number: ");
scanf("%d",&size);
printf("\n");
// for loop starts here
for(a=1; a<=size; a++)
{
for(b=1; b<=size-a; b++)
{
printf(" ");
}
for(c=1; c<=(2*a)-1; c++)
{
printf("*");
}
printf("\n");
}
getch();
}
this is what i have done so far: 这是我到目前为止所做的:
int size;
int a=1;
int b=1;
int c=1;
do {
a++;
do {
c++;
printf("*");
} while(c<=((2*a)-1));
do {
printf(" ");
b++;
} while(b<=(size-a));
printf("\n");
} while(a<=size);
getch();
}
Aaaaand its not showing the same output, any suggestion guys? Aaaa和它没有显示相同的输出,有什么建议吗? TIA :)
TIA :)
A for loop 一个for循环
for (BEGIN; COND; INC)
{
WORK;
}
Is equivalent to the while loop 相当于while循环
{
BEGIN;
while (COND)
{
WORK;
INC;
}
}
… except for the effect of a continue
statement in the WORK
part (with a for
loop the continue
jumps to the INC
), and except that names declared in the for
loop's BEGIN
are in the same declarative region as those declared in the COND
. …除了
WORK
部分中的continue
语句的效果(带有for
循环, continue
跳至INC
),以及for
循环的BEGIN
中声明的名称与COND
声明的名称位于同一声明性区域外。
It doesn't make an elegant do-while loop, however. 但是,它并没有形成优雅的do-while循环。
{
BEGIN;
do
{
if (! COND) break;
WORK;
INC;
} while (true)
}
Alternatively (although it repeats code) 或者(尽管它重复代码)
{
BEGIN;
if (COND)
{
do
{
WORK;
INC;
} while (COND)
}
}
Compilers actually tend to convert for-loops to the code equivalent of do-while loops. 编译器实际上倾向于将for循环转换为等效于do-while循环的代码。 The result looks like this (using Neil Kirk's metavariables):
结果看起来像这样(使用尼尔·柯克的元变量):
BEGIN;
if(COND) {
do {
WORK;
INC;
} while(COND);
}
Note that COND
appears in two different places. 请注意,
COND
出现在两个不同的位置。 If you examine the generated assembly for a for-loop, you'll usually see that effect, unless the optimizer is clever enough to figure out (or told by the programmer using __assume
) that COND
will never be false the first time through. 如果检查生成的程序集是否存在for循环,通常会看到这种效果,除非优化器足够聪明地弄清楚(或由程序员使用
__assume
) COND
第一次不会__assume
。
#include <stdio.h>
void main()
{
int size;
int i=1;
int j;
int k;
printf("Enter the number:\n");
scanf("%d",&size);
do
{
j=i;
do
{
printf(" ");
j++;
}while(j<=size);
k=1;
do
{
printf("*");
k++;
}while(k<=(2*i)-1);
printf("\n");
i++;
}while(i<=size);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.