如果我们仔细研究这个问题,我们会发现“循环”的概念是跟踪一些计数器值,例如“i=0”直到“i<=100”。因此,如果我们不允许使用循环,那么在C语言中还有什么可以跟踪的呢! 使用任何循环条件(如for()、while()、do-while())可以通过多种方式打印数字。但不使用循环(使用递归函数、goto语句)也可以做到这一点。
null
使用递归函数打印从1到100的数字已经在中讨论过 Set-1 .在本文中,还讨论了其他两种方法:
1.使用goto语句:
C++
#include <iostream> using namespace std; int main() { int i = 0; begin: i = i + 1; cout << i << " " ; if (i < 100) { goto begin; } return 0; } // This code is contributed by ShubhamCoder |
C
#include <stdio.h> int main() { int i = 0; begin: i = i + 1; printf ( "%d " , i); if (i < 100) goto begin; return 0; } |
C#
using System; class GFG{ static public void Main () { int i = 0; begin: i = i + 1; Console.Write( " " + i + " " ); if (i < 100) { goto begin; } } } // This code is contributed by ShubhamCoder |
输出:
1 2 3 4 . . . 97 98 99 100
2.使用递归主函数:
C++
// C++ program to count all pairs from both the // linked lists whose product is equal to // a given value #include <iostream> using namespace std; int main() { static int i = 1; if (i <= 100) { cout << i++ << " " ; main(); } return 0; } // This code is contributed by ShubhamCoder |
C
// C program to count all pairs from both the // linked lists whose product is equal to // a given value #include <stdio.h> int main() { static int i = 1; if (i <= 100) { printf ( "%d " , i++); main(); } return 0; } |
JAVA
// Java program to count all pairs from both the // linked lists whose product is equal to // a given value class GFG { static int i = 1 ; public static void main(String[] args) { if (i <= 100 ) { System.out.printf( "%d " , i++); main( null ); } } } // This code is contributed by Rajput-Ji |
Python3
# Python3 program to count all pairs from both # the linked lists whose product is equal to # a given value def main(i): if (i < = 100 ): print (i, end = " " ) i = i + 1 main(i) i = 1 main(i) # This code is contributed by SoumikMondal |
C#
// C# program to count all pairs from both the // linked lists whose product is equal to // a given value using System; class GFG { static int i = 1; public static void Main(String[] args) { if (i <= 100) { Console.Write( "{0} " , i++); Main( null ); } } } // This code is contributed by Rajput-Ji |
输出:
1 2 3 4 . . . 97 98 99 100
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END