Wednesday, March 15, 2023

Iteration in Programming

 

📌 Iteration in Programming

Iteration refers to the process of executing a set of instructions repeatedly until a certain condition is met. It is commonly implemented using loops.


1️⃣ Types of Iteration (Loops)

(a) Entry-Controlled Loops (Condition checked first)

🔹 For Loop → Used when the number of iterations is known.
🔹 While Loop → Used when the number of iterations is not known in advance.

(b) Exit-Controlled Loop (Condition checked after execution)

🔹 Do-While Loop → Executes at least once before checking the condition.


2️⃣ Iteration Using Loops in C

📌 (a) For Loop (Definite Iteration)


#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("Iteration %d\n", i); } return 0; }

🔹 Output:

nginx

Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5

📌 (b) While Loop (Indefinite Iteration)


#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("Iteration %d\n", i); i++; } return 0; }

🔹 Used when the number of repetitions is unknown beforehand.


📌 (c) Do-While Loop (Execute at Least Once)


#include <stdio.h> int main() { int i = 1; do { printf("Iteration %d\n", i); i++; } while (i <= 5); return 0; }

🔹 Executes at least once, even if the condition is false.


3️⃣ Iteration in Arrays (Traversing Elements)


#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; int size = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < size; i++) { printf("Element %d: %d\n", i, arr[i]); } return 0; }

🔹 Iterates through an array using a loop.


4️⃣ Infinite Loops (Use with Caution!)


while (1) { printf("This is an infinite loop!\n"); }

🔹 Use break to exit an infinite loop.

No comments:

Post a Comment

Complete Binary Tree in Data Structures

  Complete Binary Tree in Data Structures 🌳 A Complete Binary Tree (CBT) is a type of Binary Tree where: ✔ All levels except possibly t...