[学习笔记—Objective-C]《Objective-C 程序设计 第6版》第五章 循环结构 部分例题&课后题讲解

本章相对比较简单,知识点就不在赘述。主要就书中的例题和课后题进行说明。

for 结构

for 基本结构

for ( int_expression; loop_condition; loop_expression )

    program statement

end

for 结构变体

for (i = 0, j = 0; i < 10; ++i)
for (i = 0, j = 100; i < 10; ++i, j -= 10)
for (; j !=100; j++) //省略init_expression
for (i = 0, j = 0; ; ++i) //省略loop_condition无限循环 
for (counter =1 ; counter <= 5; counter++)//定义一个变量作为初始表达式的一部分

while 结构体

int_expression
while ( loop_condition )
{ program statement loop_expression }

do 语句

do
 program statement
while (expression)

break & continue 语句

  • break;跳出循环
  • continue;跳出此次循环

例题 5-5

题目:
输入5次正数,并计算相应的三角数。

代码:


#import <Foundation/Foundation.h>

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

        for (counter =1 ; counter <= 5; 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;
}

例题 5-8

题目:颠倒显示数字的位数

代码:


#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        int number, right_digit;

        NSLog(@"Enter your number");
        scanf("%i", &number);

        while (number != 0)
        {
            right_digit = number % 10; //整数除以10的余数
            NSLog(@"%i", right_digit);
            number /= 10; //每次循环结束后本整数除以10;
        }
    }
    return 0;
}

课后题 5-3

题目:打印前10个整数的阶乘表

代码:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        int i,number,counter;

        for (counter = 1; counter <= 10; counter++)
        {
             number = 1; //初始化阶乘结果

             for (i = 1 ; i <= counter; i++)
             {
                 number *= i;
             }

            NSLog(@"n is %i", number);

        }    
    }
    return 0;
}

课后题 5-8

题目:计算整数各位上数字的和

代码:


#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {
    @autoreleasepool
    {

        int number, right_digit, sum;

        NSLog(@"Enter your number:");
        scanf("%i", &number);

        sum = 0;

        do
        {
            right_digit = number % 10;
            NSLog(@"%i", right_digit);
            number /= 10;
            sum += right_digit; //和的累加

        }

        while (number != 0);

        NSLog(@"The sum is %i", sum);
    }

    return 0;
}

你可能感兴趣的:(ios,Objective-C)