YouTip LogoYouTip

C Nested Loops

# C Nested Loops [![Image 6: C Loops](#) C Loops](#) The C language allows the use of one loop inside another loop. The following section demonstrates a few examples to illustrate the concept. ## Syntax The syntax for a **nested for loop** statement in C is: for (initialization; condition; increment/decrement){ statement(s); for (initialization; condition; increment/decrement) { statement(s); ... ... ... } ... ... ...} Flow Diagram: !(https://static.jyshare.com/wp-content/uploads/c/c-nested-loops-20200922-1.svg) The syntax for a **nested while loop** statement in C is: while (condition1){ statement(s); while (condition2) { statement(s); ... ... ... } ... ... ...} Flow Diagram: !(https://static.jyshare.com/wp-content/uploads/c/c-nested-loops-20200922-2.svg) The syntax for a **nested do...while loop** statement in C is: do{ statement(s); do { statement(s); ... ... ... }while (condition2); ... ... ...}while (condition1); Flow Diagram: !(https://static.jyshare.com/wp-content/uploads/c/c-nested-loops-20200922-3.svg) One thing worth noting about nested loops is that you can put any type of loop inside any other type of loop. For example, a for loop can be inside a while loop, or vice versa. ## Examples The following program uses a nested for loop to find the prime numbers between 2 and 100: ## Nested for Loop Example #includeint main(){/* local variable definition */int i, j; for(i=2; i<100; i++){for(j=2; j(i/j))printf("%d is a prime numbern", i); }return 0; } When the above code is compiled and executed, it produces the following result: 2 is a prime number3 is a prime number5 is a prime number7 is a prime number11 is a prime number13 is a prime number17 is a prime number19 is a prime number23 is a prime number29 is a prime number31 is a prime number37 is a prime number41 is a prime number43 is a prime number47 is a prime number53 is a prime number59 is a prime number61 is a prime number67 is a prime number71 is a prime number73 is a prime number79 is a prime number83 is a prime number89 is a prime number97 is a prime number ## Nested while Loop Example #includeint main(){int i=1,j; while(i<= 5){j=1; while(j<= i){printf("%d ",j); j++; }printf("n"); i++; }return 0; } When the above code is compiled and executed, it produces the following result: 11 21 2 31 2 3 41 2 3 4 5 ## Nested do-while Loop Example #includeint main(){int i=1,j; do{j=1; do{printf("*"); j++; }while(j<= i); i++; printf("n"); }while(i<= 5); return 0; } When the above code is compiled and executed, it produces the following result: ****** **** ****C Loops](#) AI is thinking... [](#)(#) (#)[](#) [Byte Ark Coding Plan supports mainstream large models like Doubao, GLM, DeepSeek, Kimi, MiniMax, etc. Official direct supply, stable and reliable. Configuration Guide Β₯9.9/month Subscribe Now](https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E)
← Python3 Basic OperatorsC Do While Loop β†’