C语言程序设计基础


If For Array

计算机学院    杨已彪

yangyibiao@nju.edu.cn


Review

Variables (变量)   Data Types (数据类型)


Operators (运算符)   Expressions (表达式)

Assignment Statements (赋值语句)


I/O (Input/Output; 输入输出)


Overview


If Statement (if 语句)

For Statement (for 语句)

Logical Expressions (逻辑表达式)


Array (数组)

代码任务

min.c   leap.c   min-array.c

Min

Min of Two



Given two integers aa and bb, to compute their minimum.


min=min{a,b}min = \min\{a, b\}


Min of Two


min = a >= b ? b : a;

(条件表达式; 三目运算符)


Do Not Use it Too Much!

Do Not Be Too Clever!

Min of Three



Given three integers aa, bb, and cc, to compute their minimum.


min=min{a,b,c}\mathit{min} = \min\{a, b, c\}

Min of a Set of Numbers


Given a set AA of integers, to compute their minimum.

min=minA\mathit{min} = \min A


Leap Year


Leap Year (1): Nested if/else (YES)


Leap Year (2): Nested if/else (NO)


Leap Year (3): else if


Leap Year (4): The Ultimate Version

A year is a leap year if


  • it is divisible by 44 but not by 100100,
  • except that years divisible by 400400 are leap years.

Short-circuit Evaluation (短路求值)

Min of a Set of Numbers


Given a set AA of integers, to compute their minimum.


min=miniAi\mathit{min} = \min_{i} A_{i}

min{3,5,2,7}=min(min(min(3,5),2),7)\min\{3, 5, 2, 7\} = \min(\min(\min(3, 5), 2), 7)


For Statement



Increment/Decrement Operators (++, --)





i = 2;
j = i * i++;

-->


#define NUM 5



Symbolic Constants (符号常量)


int numbers[NUM] = {0}; has a fixed size.


Array Initializer

  • int numbers[NUM] = {1};

  • int numbers[] = {0};

  • int numbers[NUM] = {[2] = 1};


Array Initializer (DON’T)

int numbers[NUM] = {};

Forbidden in C99 (Unfortunately!)

Allowed by GCC by default (Unfortunately!!)

Allowed in C23 (Fortunately or not???)


Array Initializer (DON’T)

int numbers[NUM];

numbers may contain garbage values;

always initialize it


Array Initializer (DON’T)

int numbers[];

You must specify the size so that the compiler/runtime can allocate memory for it.


Min of a Set of Input Numbers



Input a set AA of n1n \ge 1 integers, to compute their minimum.


min=miniAi\mathit{min} = \min_{i} A_{i}