feat: add c codes for iteration (#735)

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
MwumLi 2023-09-13 03:13:55 +08:00 committed by GitHub
parent 9b8625d741
commit 01732cc14f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 5 deletions

View File

@ -1,3 +1,4 @@
add_executable(iteration iteration.c)
add_executable(time_complexity time_complexity.c) add_executable(time_complexity time_complexity.c)
add_executable(worst_best_time_complexity worst_best_time_complexity.c) add_executable(worst_best_time_complexity worst_best_time_complexity.c)
add_executable(space_complexity space_complexity.c) add_executable(space_complexity space_complexity.c)

View File

@ -1,7 +1,7 @@
/** /**
* File: iteration.c * File: iteration.c
* Created Time: 2023-09-09 * Created Time: 2023-09-09
* Author: Gonglja (glj0@outlook.com) * Author: Gonglja (glj0@outlook.com), MwumLi (mwumli@hotmail.com)
*/ */
#include "../utils/common.h" #include "../utils/common.h"
@ -10,7 +10,7 @@
int forLoop(int n) { int forLoop(int n) {
int res = 0; int res = 0;
// 循环求和 1, 2, ..., n-1, n // 循环求和 1, 2, ..., n-1, n
for (int i = 1; i <= n; ++i) { for (int i = 1; i <= n; i++) {
res += i; res += i;
} }
return res; return res;
@ -47,11 +47,10 @@ char *nestedForLoop(int n) {
// n * n 为对应点数量,"(i, j), " 对应字符串长最大为 6+10*2加上最后一个空字符 \0 的额外空间 // n * n 为对应点数量,"(i, j), " 对应字符串长最大为 6+10*2加上最后一个空字符 \0 的额外空间
int size = n * n * 26 + 1; int size = n * n * 26 + 1;
char *res = malloc(size * sizeof(char)); char *res = malloc(size * sizeof(char));
// 循环 i = 1, 2, ..., n-1, n // 循环 i = 1, 2, ..., n-1, n
for (int i = 1; i <= n; ++i) { for (int i = 1; i <= n; i++) {
// 循环 j = 1, 2, ..., n-1, n // 循环 j = 1, 2, ..., n-1, n
for (int j = 1; j <= n; ++j) { for (int j = 1; j <= n; j++) {
char tmp[26]; char tmp[26];
snprintf(tmp, sizeof(tmp), "(%d, %d), ", i, j); snprintf(tmp, sizeof(tmp), "(%d, %d), ", i, j);
strncat(res, tmp, size - strlen(res) - 1); strncat(res, tmp, size - strlen(res) - 1);