在 C 编程中,我可以在不使用循环的情况下打印 '1' n 次吗?

问题描述 投票:0回答:1

当我们使用Python时,我们可以使用print("1"*n)多次打印相同的字符串。这有助于减少执行时间。如果我们有一个用 C 语言实现这一点的方法,那将会很有帮助。

预期结果是O(n)的时间复杂度

c time syntax logic
1个回答
0
投票

是的,您可以使用递归来打印“1”n 次。

#include <stdio.h>

void printOne(int n) {
// Base case: if n is 0, stop recursion
if (n == 0)
    return;

// Print 1
printf("1 ");

// Recursively call printOne with n-1
printOne(n - 1);
}

int main() {
int n;

// Get input from the user
printf("Enter the number of times to print 1: ");
scanf("%d", &n);

// Call the recursive function
printOne(n);

return 0;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.