while语句与for语句之间的互换

1.for 语句形式为
for ( init_expression; loop_condition; loop_expression )
program statement

2.while 语句的等价形式为
init_expression;
while ( loop_condition )
{
program statement
loop_expression ;
}

3.示例
//生成三角数的程序

import

int main(int argc, char *argv[])
{
@autoreleasepool {
int n, t, number=0, triangularNumber=0, counter ;

    NSLog(@"What count times do you want?") ;
    scanf("%i", &t) ;

// counter=1 ;
// while (counter<=t) {
// NSLog(@"What triangular number do you want?") ;
// scanf("%i", &number) ;
//
// triangularNumber = 0 ;
//
// n=1;
// while (n<=number) {
// triangularNumber += n ;
// ++n;
// }
// ++counter ;
// NSLog(@"Triangular number %i is %i", number, triangularNumber) ;
//
// }
// return 0 ;
// }
//}
for (counter=1; counter<=t; ++counter) {
NSLog(@"What triangular number do you want?") ;
scanf("%i", &number) ;

        triangularNumber = 0 ;

        for (n=1; n<=number; ++n)
        {
          triangularNumber += n ;
        }
        NSLog(@"Triangular number %i is %i", number, triangularNumber) ;
    
}
return 0 ;
}

}

4.注意:需要对变量做初始化。

你可能感兴趣的:(while语句与for语句之间的互换)