For loops

INTRODUCTION:

The for loop is one of the fundamental constructs in C programming, enabling developers to execute a block of code repeatedly for a fixed number of times. In this blog post, we'll dive deep into the versatility of the for loop by exploring 10 fascinating pattern examples. Each pattern not only demonstrates the power of the for loop but also showcases its creative potential in generating various shapes and designs. Explanation of the for loop in C:

The for loop in C is used to execute a block of code repeatedly for a fixed number of times. It has the following syntax:

for (initialization  ; condition ;  increment/decrement)

{

// code to be executed 

 }

Initialization: This part is executed only once at the beginning of the loop. It typically initializes the loop control variable.

Condition: It's the condition for executing the loop. If the condition evaluates to true, the loop continues; otherwise, it terminates.

Increment/Decrement: It's an expression that updates the loop control variable. It's executed after each iteration of the loop.

code examples

  • Pattern 1: Right Triangle Pattern
output 
* *
* * * 
* * * *
* * * * *

code:

#include <stdio.h> int main()

{

int rows = 5; for (int i = 1; i <= rows; i++)

{

for (int j = 1; j <= i; j++)

{ printf("* "); } printf("\n"); } return 0; }

  • Pattern 2: Inverted Right Triangle Pattern

output:

* * * * * * * * * * * * * * * code:

#include <stdio.h> int main()

{ int rows = 5; for (int i = rows; i >= 1; i--)

{

for (int j = 1; j <= i; j++)

{ printf("* "); } printf("\n"); } return 0; }

  • Pattern 3: Pyramid Pattern

output:

* * * * * * * * * * * * * * * * * * * * * * * * * code: #include <stdio.h> int main()

{ int rows = 5; int spaces = rows - 1; for (int i = 1; i <= rows; i++, spaces--)

{ for (int j = 1; j <= spaces; j++)

{ printf(" "); } for (int j = 1; j <= 2 * i - 1; j++)

{ printf("* "); } printf("\n"); } return 0; }


Comments

Post a Comment