1. 顺序结构

1.1 交换变量的值

#include<stdio.h>

int main() {
    int a=1, b=2;

    // 交换两个变量a,b的值: "第三人"交换法(借助中间变量temp)
    int temp;
    temp = a;
    a = b;
    b = temp;
    printf("a=%-6db=%-6d\n", a, b);    // - 左对齐; 域宽为 6

    // 交换两个变量a,b的值: "近距离"互换法
    a = a+b; // a = (initial_a + initial_b)
    b = a-b; // b = (initial_a + initial_b) - initial_b = initial_a
    a = a-b; // a = (initial_a + initial_b) - initial_a = initial_b
    printf("a=%-6db=%-6d\n", a, b);
    // Swap Numbers Without Using Temporary Variables
    a = a - b; // a = (initial_a - initial_b)
    b = a + b; // b = (initial_a - initial_b) + initial_b = initial_a
    a = b - a; // a = initial_a - (initial_a - initial_b) = initial_b
    printf("a=%-6db=%-6d\n", a, b);

    return 0;
}

2. 分支结构/选择结构 Decision-making Statement

  • if
  • if...else
  • if...else Ladder
  • Nested if...else
  • switch...case
    • If we do not use break, all statements after the matching label are executed.
    • The default clause inside the switch statement is optional.
    • default 标号可以出现在语句体中的任何标号位置.
    • case 后面的 常量表达式 仅起语句标号作用, 并不进行条件判断. 系统一旦找到入口标号, 就从此标号开始执行, 不再进行标号判断, 所以必须加上 break; 语句, 用来结束 switch 语句.(goto label)

C 语言语法规定: 当缺省 {} 时, else 总是与其之前最近的且尚未配对的 if 配对.

2.1 判断奇数 / 偶数

// Check whether an integer is odd or even
#include <stdio.h>
int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);

    // True if the remainder is 0
    if  (number%2 == 0) {
        printf("%d is an even integer.\n",number);
    }
    else {
        printf("%d is an odd integer.\n",number);
    }

    return 0;
}

2.2 判断元音 / 辅音

/* C Program to Check Whether a Character is a Vowel or Consonant
The five letters A, E, I, O and U are called vowels(元音).
All other alphabets except these 5 vowels are called consonants(辅音).
*/
#include <ctype.h>
#include <stdio.h>

int main() {
   char c;
   int lowercase_vowel, uppercase_vowel;
   printf("Enter an alphabet: ");
   scanf("%c", &c);

   // evaluates to 1 if variable c is a lowercase vowel
   lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

   // evaluates to 1 if variable c is a uppercase vowel
   uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

   // Show error message if c is not an alphabet


// Note: This program assumes that the user will enter an alphabet. If the user enters a non-alphabetic character, it displays the character is a consonant.

// To fix this, we can use the isalpha() function. The islapha() function checks whether a character is an alphabet or not.

   if (!isalpha(c))
      printf("Error! Non-alphabetic character.");
   else if (lowercase_vowel || uppercase_vowel)
      printf("%c is a vowel.", c);
   else
      printf("%c is a consonant.", c);

   return 0;
}

2.3 判断闰年

// C Program to Check Leap Year(闰年: year%400==0 || (year%4==0 && year%100!=0))
#include <stdio.h>
int main() {
   int year;
   printf("Enter a year: ");
   scanf("%d", &year);

   // leap year if perfectly visible by 400
   if (year % 400 == 0) {
      printf("%d is a leap year.", year);
   }
   // not a leap year if visible by 100
   // but not divisible by 400
   else if (year % 100 == 0) {
      printf("%d is not a leap year.", year);
   }
   // leap year if not divisible by 100
   // but divisible by 4
   else if (year % 4 == 0) {
      printf("%d is a leap year.", year);
   }
   // all other years are not leap year
   else {
      printf("%d is not a leap year.", year);
   }

   return 0;
}

2.4 计算阶乘

// C Program to Find Factorial(阶乘) of a Number
#include <stdio.h>

int main() {
    int n, i;
    unsigned long long fact = 1;
    printf("Enter an integer: ");
    scanf("%d", &n);

    // shows error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else {
        for (i = 1; i <= n; ++i) {
            fact *= i;
        }
        printf("Factorial of %d! = %llu", n, fact);
    }

    return 0;
}

3. 循环结构 Loop Statement

  • for loop
  • while loop
  • do...while loop

3.1 打印九九乘法表

// C Program to Generate Multiplication Table
#include<stdio.h>

int main() {
    for (int i=1; i<=9; i++) {
        for (int j=1; j<=i; j++) {
            printf("%d*%d=%2d\t", i, j, i*j);
        }
        putchar('\012');    // 输出换行, '\n' 对应的 ASCII 码的八进制数表示为 012
    }

    return 0;
}

3.2 非波那契数列

// C Program to Display Fibonacci Sequence
// 1. Fibonacci Series up to n terms
#include <stdio.h>
int main() {
    int i, n, t1 = 0, t2 = 1, nextTerm;
    printf("Enter the number of terms: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");

    for (i = 1; i <= n; ++i) {
        printf("%d, ", t1);
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }

    return 0;
}

// 2. Fibonacci Sequence Up to a Certain Number
#include <stdio.h>
int main() {
    int t1 = 0, t2 = 1, nextTerm = 0, n;
    printf("Enter a positive number: ");
    scanf("%d", &n);

    // displays the first two terms which is always 0 and 1
    printf("Fibonacci Series: %d, %d, ", t1, t2);
    nextTerm = t1 + t2;

    while (nextTerm <= n) {
        printf("%d, ", nextTerm);
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1 + t2;
    }

    return 0;
}

3.3 素数/质数

// C Program to Check Whether a Number is Prime or Not
// 1. A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17
#include <stdio.h>
int main() {
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 2; i <= n / 2; ++i) {
        // condition for non-prime
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }

    if (n == 1) {
        printf("1 is neither prime nor composite.");
    }
    else {
        if (flag == 0)
            printf("%d is a prime number.", n);
        else
            printf("%d is not a prime number.", n);
    }

    return 0;
}


// 2. Display Prime Numbers when Larger Number is Entered first
#include <stdio.h>

int main() {
   int low, high, i, flag, temp;
   printf("Enter two numbers(intervals): ");
   scanf("%d %d", &low, &high);

   // swap numbers if low is greather than high
   if (low > high) {
      temp = low;
      low = high;
      high = temp;
   }

   printf("Prime numbers between %d and %d are: ", low, high);
   while (low < high) {
      flag = 0;

      // ignore numbers less than 2
      if (low <= 1) {
         ++low;
         continue;
      }

      for (i = 2; i <= low / 2; ++i) {
         if (low % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
         printf("%d ", low);
      ++low;
   }

   return 0;
}

3.4 水仙花数

/* C Program to Check Armstrong Number
A positive integer is called an Armstrong number (of order n) if
     abcd... = an + bn + cn + dn + ...
    abc    = a3 + b3 + c3
*/
#include <stdio.h>

int main() {
    int num, originalNum, remainder, result = 0;
    printf("Enter a three-digit integer: ");
    scanf("%d", &num);
    originalNum = num;

    while (originalNum != 0) {
       // remainder contains the last digit
       remainder = originalNum % 10;

       result += remainder * remainder * remainder;

       // removing last digit from the orignal number
       originalNum /= 10;
    }

    if (result == num)
        printf("%d is an Armstrong number.", num);
    else
        printf("%d is not an Armstrong number.", num);

    return 0;
}

3.5 杨辉三角

// Pascal's Triangle(杨辉三角)
#include <stdio.h>
int main() {
   int rows, coef = 1, space, i, j;
   printf("Enter the number of rows: ");
   scanf("%d", &rows);
   for (i = 0; i < rows; i++) {
      for (space = 1; space <= rows - i; space++)
         printf("  ");
      for (j = 0; j <= i; j++) {
         if (j == 0 || i == 0)
            coef = 1;
         else
            coef = coef * (i - j + 1) / j;
         printf("%4d", coef);
      }
      printf("\n");
   }
   return 0;
}

Others

break & continue statements

  • break;
    The break statement ends the current loop immediately when it is encountered.
    • 跳出 switch 语句;
    • 跳出所在循环体.
  • continue;
    The continue statement skips the current iteration of the loop and continues with the next iteration.

语句标号 和 无条件转向语句 goto statement

  • The goto statement allows us to transfer control of the program to the specified label. (goto 语句的作用是把程序的执行转向语句标号所在的位置, 这个 语句标号必须与此 goto 语句在同一个函数中.)

  • The label is an identifier. (语句标号必须是标识符.)

  • When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.

  • Reasons to avoid goto

    • The use of goto statement may lead to code that is buggy and hard to follow.
    • The goto statement allows you to do bad stuff such as jump out of the scope.
  • Goto can be useful sometimes

    • To break from nested loops.
    • If you think the use of goto statement simplifies your program, you can use it.

其他程序

翻转数字

// Reverse an Integer
#include <stdio.h>
int main() {
    int n, rev = 0, remainder;
    printf("Enter an integer: ");
    scanf("%d", &n);
    while (n != 0) {
        remainder = n % 10;
        rev = rev * 10 + remainder;
        n /= 10;
    }
    printf("Reversed number = %d", rev);
    return 0;
}

回文数判断

// C Program to Check Whether a Number is Palindrome(回文) or Not
#include <stdio.h>
int main() {
    int n, reversedN = 0, remainder, originalN;
    printf("Enter an integer: ");
    scanf("%d", &n);
    originalN = n;

    // reversed integer is stored in reversedN
    while (n != 0) {
        remainder = n % 10;
        reversedN = reversedN * 10 + remainder;
        n /= 10;
    }

    // palindrome if orignalN and reversedN are equal
    if (originalN == reversedN)
        printf("%d is a palindrome.", originalN);
    else
        printf("%d is not a palindrome.", originalN);

    return 0;
}