<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Loops - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Loops - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 11:07:04 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/loops/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Loops in C# ]]>
                </title>
                <description>
                    <![CDATA[ Writing the same code repeatedly is poor practice in C# and doesn’t follow the Don’t Repeat Yourself (DRY) principle. But, there are many times in programming where you need to repeat commands, operations, or computations multiple times — perhaps cha... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-loops-in-c/</link>
                <guid isPermaLink="false">68caa6382769a3737407de1b</guid>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Wed, 17 Sep 2025 12:14:48 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757595108095/f7bd2673-3da5-4f34-8541-64cc8129fe96.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Writing the same code repeatedly is poor practice in C# and doesn’t follow the Don’t Repeat Yourself (DRY) principle. But, there are many times in programming where you need to repeat commands, operations, or computations multiple times — perhaps changing one small thing each iteration.</p>
<p>This is where loops come in. In this article, you’ll learn:</p>
<ul>
<li><p>How to create your first loop</p>
</li>
<li><p>Benefits and caveats of using loops</p>
</li>
<li><p>The different types of loops in C# and how to use them</p>
</li>
<li><p>When it’s best to use each one</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-a-for-loop-in-c">How to Use a For Loop in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-a-foreach-loop-in-c">How to Use a ForEach Loop in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-a-dowhile-loop-in-c">How to Use a Do..While Loop in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-a-while-loop-in-c">How to Use a While Loop in C</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts-choosing-the-right-loop">Final Thoughts: Choosing the Right Loop</a></p>
</li>
</ul>
<p>Let’s get started. Open your preferred IDE or coding editor and create a new Console Application in .Net 8+.</p>
<h2 id="heading-how-to-use-a-for-loop-in-c">How to Use a For Loop in C</h2>
<p>A for loop repeats a block of code a set number of times by:</p>
<ul>
<li><p>Initialising a loop variable.</p>
</li>
<li><p>Checking a condition before each iteration.</p>
</li>
<li><p>Updating the loop variable after each iteration.</p>
</li>
</ul>
<p>You can create a <code>for</code> loop with the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// number of iterations</span>
<span class="hljs-keyword">var</span> totalIterations = <span class="hljs-number">5</span>

<span class="hljs-comment">// the loop</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= totalIterations; i++){
   Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{i}</span>,"</span>);
}

<span class="hljs-comment">// Output</span>
<span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,
</code></pre>
<p><strong>Breaking it down:</strong></p>
<ul>
<li><p><code>for</code> — declares the loop</p>
</li>
<li><p><code>int i = 0;</code> — sets the starting point for the loop variable <code>i</code></p>
</li>
<li><p><code>i &lt;= totalIterations;</code> — the condition to keep looping. The code inside the loop runs only if this is true.</p>
</li>
<li><p><code>i++</code> — shorthand for “increase <code>i</code> by 1” after each iteration</p>
</li>
</ul>
<h3 id="heading-iterations-and-zero">Iterations and Zero</h3>
<p>Why does the example print six numbers when <code>totalIterations</code> is 5? C# uses zero-based indexing. Counting from 0 → 5 includes six numbers: 0,1,2,3,4,5.</p>
<p>If you want to print 1 → 5 instead, start <code>i</code> at 1:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> totalIterations = <span class="hljs-number">5</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= totalIterations; i++)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{i}</span>,"</span>);
}
<span class="hljs-comment">// Output: 1,2,3,4,5</span>
</code></pre>
<p><strong>Tip:</strong><br>In general, <code>for</code> loops are used for indexing/accessing elements in collections, so it’s common practice to start your loop variable at 0 and use <code>&lt;</code> (less than) a given number or length of the collection.</p>
<h3 id="heading-reversal-of-direction">Reversal of Direction</h3>
<p>You can reverse a <code>for</code> loop by starting at the end and decrementing <code>i</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">5</span>; i &gt; <span class="hljs-number">0</span>; i--)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{i}</span>,"</span>);
}
<span class="hljs-comment">// Output: 5,4,3,2,1</span>
</code></pre>
<p>The loop checks if <code>i &gt; 0</code>. After each iteration, <code>i</code> decreases by 1, printing numbers in descending order.</p>
<h3 id="heading-other-uses-of-for-loops">Other Uses of For Loops</h3>
<p>Let’s say you want to access every other item in a list. This is where the power of <code>for</code> loops come in, and we can maximise our <code>loop variable</code>, using it as an index accessor.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Address</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> AddressLineOne { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> HouseNumber { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">default</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> PostCode { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Telephone { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;
}

<span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> addressBook = <span class="hljs-keyword">new</span> List&lt;Address&gt;
        {
            <span class="hljs-keyword">new</span> Address
            {
                Name = <span class="hljs-string">"Grant"</span>, AddressLineOne = <span class="hljs-string">"Developer Avenue"</span>, HouseNumber = <span class="hljs-number">1</span>, PostCode = <span class="hljs-string">"DV19 8EP"</span>,
                Telephone = <span class="hljs-string">"0102919 93020-92019"</span>
            },
            <span class="hljs-keyword">new</span> Address
            {
                Name = <span class="hljs-string">"Bill"</span>, AddressLineOne = <span class="hljs-string">"Developer Avenue"</span>, HouseNumber = <span class="hljs-number">19</span>, PostCode = <span class="hljs-string">"DV19 8EP"</span>,
                Telephone = <span class="hljs-string">"0102919 93020-92019"</span>
            },
            <span class="hljs-keyword">new</span> Address
            {
                Name = <span class="hljs-string">"Rebecca"</span>, AddressLineOne = <span class="hljs-string">"Developer Avenue"</span>, HouseNumber = <span class="hljs-number">4</span>, PostCode = <span class="hljs-string">"DV19 8EP"</span>,
                Telephone = <span class="hljs-string">"0102919 93020-92019"</span>
            },
            <span class="hljs-keyword">new</span> Address
            {
                Name = <span class="hljs-string">"Amy"</span>, AddressLineOne = <span class="hljs-string">"Rower Avenue"</span>, HouseNumber = <span class="hljs-number">1</span>, PostCode = <span class="hljs-string">"DV19 8EP"</span>,
                Telephone = <span class="hljs-string">"0102919 93020-92019"</span>
            },
            <span class="hljs-keyword">new</span> Address
            {
                Name = <span class="hljs-string">"Joe"</span>, AddressLineOne = <span class="hljs-string">"Olympic Drive"</span>, HouseNumber = <span class="hljs-number">1</span>, PostCode = <span class="hljs-string">"DV19 10E"</span>,
                Telephone = <span class="hljs-string">"0102919 93020-92019"</span>
            }
        };

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; addressBook.Count; i += <span class="hljs-number">2</span>)
        {
            Console.WriteLine(<span class="hljs-string">$"Name: <span class="hljs-subst">{addressBook[i].Name}</span>, PostCode: <span class="hljs-subst">{addressBook[i].PostCode}</span>"</span>);
        }
    }
}

<span class="hljs-comment">/* Ouput:
Name: Grant, PostCode: DV19 8EP
Name: Rebecca, PostCode: DV19 8EP
Name: Joe, PostCode: DV19 10E
*/</span>
</code></pre>
<h3 id="heading-whats-happening"><strong>What’s Happening:</strong></h3>
<ul>
<li><p><code>i</code> starts at 0 and increases by 2 (<code>i += 2</code>) each iteration</p>
</li>
<li><p><code>addressBook[i]</code> now accesses every other item</p>
</li>
<li><p>This shows the power of using <code>i</code> as an index</p>
</li>
</ul>
<p>So far we’ve seen how <code>for</code> loops give control over indexes and step sizes.</p>
<p>But sometimes you just want to loop through every item in a collection, without worrying about indexes. That’s where the foreach loop shines.</p>
<h2 id="heading-how-to-use-a-foreach-loop-in-c">How to Use a ForEach Loop in C</h2>
<p>A <code>foreach</code> loop iterates over any object that inherits from <code>IEnumerable</code> (lists, arrays, collections). It automatically accesses each item in order, so you don’t need an index.</p>
<h3 id="heading-how-to-write-a-foreach-loop">How To Write a ForEach Loop</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> characters = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;{<span class="hljs-string">"Batman"</span>, <span class="hljs-string">"CatWoman"</span>, <span class="hljs-string">"The Joker"</span>,<span class="hljs-string">"Harley Quinn"</span>};

<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> character <span class="hljs-keyword">in</span> characters){
    Console.WriteLine(character);
}

<span class="hljs-comment">/* Output:
Batman
CatWoman
The Joker
Harley Quinn
*/</span>
</code></pre>
<p><strong>Key points:</strong></p>
<ul>
<li><p>No need for indexes</p>
</li>
<li><p>Works with any enumerable collection</p>
</li>
<li><p>Cleaner, more expressive code</p>
</li>
</ul>
<h3 id="heading-caveats-of-foreach-loop">Caveats of ForEach Loop</h3>
<h4 id="heading-no-indexing">No Indexing</h4>
<p>You can’t directly access items with <code>addressBook[i]</code> inside a foreach. That’s because <code>foreach</code> works on <code>IEnumerable</code>, which doesn’t expose indexes.</p>
<h4 id="heading-performance">Performance</h4>
<p>A <code>foreach</code> loop has a small overhead compared to a <code>for</code> loop. In most cases this won’t matter, but in performance-critical code, a <code>for</code> loop may be faster.</p>
<h4 id="heading-modifying-items">Modifying Items</h4>
<p><code>foreach</code> gives you a copy of the current item, not a direct reference. That means you can’t reassign values to the list items inside the loop.</p>
<ul>
<li><p>You can read properties.</p>
</li>
<li><p>You can’t update the items themselves (use a for loop for that).</p>
</li>
</ul>
<p><code>foreach</code> is ideal when you want to visit every item, but not control the number of iterations.</p>
<h2 id="heading-how-to-use-a-dowhile-loop-in-c">How to Use a Do..While Loop in C</h2>
<p><code>do..while</code> loops run code at least once, then repeat while a condition is true:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> num;
<span class="hljs-keyword">do</span> {
    Console.Write(<span class="hljs-string">"Enter a positive number: "</span>);
    num = <span class="hljs-keyword">int</span>.Parse(Console.ReadLine());
} <span class="hljs-keyword">while</span> (num &lt;= <span class="hljs-number">0</span>);

Console.WriteLine(num);
</code></pre>
<p>The above code requests a number to be entered within the console application if the condition is met. That is, if a positive number is provided, the code will not ask for another, exiting the loop.</p>
<p>Should the user enter a negative number, it would continue to loop, requesting a positive number to be entered.</p>
<p>What if you didn’t want the code to run at least once, and only if a condition is met? This where you can use a <code>while</code> loop.</p>
<h2 id="heading-how-to-use-a-while-loop-in-c">How to Use a While Loop in C</h2>
<p><code>while</code> loops repeat code as long as a condition is true, but the body may never run if the condition is initially false:</p>
<p>We can use an example of a darts score board:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> sum = <span class="hljs-number">0</span>;
<span class="hljs-keyword">var</span> dartsThrown = <span class="hljs-number">0</span>;
<span class="hljs-keyword">var</span> random = <span class="hljs-keyword">new</span> Random();

<span class="hljs-keyword">while</span> (sum &lt; <span class="hljs-number">180</span> &amp;&amp; dartsThrown &lt; <span class="hljs-number">3</span>)
{
    <span class="hljs-keyword">var</span> dartScore = random.Next(<span class="hljs-number">61</span>); <span class="hljs-comment">// 0–60</span>
    sum += dartScore;
    dartsThrown++;
}

Console.WriteLine(<span class="hljs-string">"Your score is "</span> + sum);
</code></pre>
<p>While the player has darts to throw, the code will pick a number at random and increase their score.</p>
<p><strong>Tip:</strong> Always include code that changes the condition, or you risk creating an infinite loop. An infinite loop, is a loop which never stops, and causes your application to break.</p>
<p>You’ve seen four different ways to repeat code in C#: <code>for</code>, <code>foreach</code>, <code>do..while</code>, and <code>while</code>. Let’s summarise when to use each one.</p>
<h2 id="heading-final-thoughts-choosing-the-right-loop">Final Thoughts: Choosing the Right Loop</h2>
<p>C# gives us several types of loops. Choosing the right one makes your code readable, efficient, and intentional.</p>
<ul>
<li><p><strong>For Loop:</strong> Use when you know how many times to run something, or when you need an index, like using arrays, skipping items. Use a <code>for</code> loop when you need more control over the iterative nature of the loop.</p>
</li>
<li><p><strong>ForEach Loop:</strong> Use when you want to iterate through every item in a collection without worrying about indexes.</p>
</li>
<li><p><strong>While Loop:</strong> Use when you don’t know in advance how many times to run the code, but a condition drives the loop.</p>
</li>
<li><p><strong>Do..While Loop:</strong> Use when the loop body must run at least once, such as for user input or retry logic.</p>
</li>
</ul>
<p>By matching the loop type to your intent, your code will be correct, readable, and maintainable.</p>
<p>I hope this tutorial was useful, and as always I’d love to hear your thoughts and discuss further on social media. You can find me on <a target="_blank" href="https://x.com/grantdotdev">twitter/x</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Infinite Loops Work in C++ ]]>
                </title>
                <description>
                    <![CDATA[ In C++, a loop is a part of code that is executed repetitively until the given condition is satisfied. An infinite loop is a loop that runs indefinitely, without any condition to exit the loop. In this article, we will learn about infinite loops in C... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-infinite-loops-work-in-c/</link>
                <guid isPermaLink="false">688d43422c35fedc5be4fa94</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ while loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Do while loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ for loop ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ AYUSH MISHRA ]]>
                </dc:creator>
                <pubDate>Fri, 01 Aug 2025 22:44:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754065314765/5c8e45f0-6a43-4f1f-b254-2603b7d37e0c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In C++, a loop is a part of code that is executed repetitively until the given condition is satisfied. An infinite loop is a loop that runs indefinitely, without any condition to exit the loop.</p>
<p>In this article, we will learn about infinite loops in C++, their types and causes, and their applications.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-infinte-loop-in-c">What is an Infinite Loop in C++?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-infinte-loops-in-c">Types of Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-cause-of-accidental-infinte-loops-in-c">Common Causes of Accidental Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-application-of-infinte-loops-in-c">Applications of Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-infinite-loops-to-take-user-input-in-c">Using Infinite Loops To Take User Input in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-is-an-infinite-loop-in-c">What is an Infinite Loop in C++?</h2>
<p>An infinite loop is any loop in which the loop condition is always true, leading to the given block of code being executed an infinite number of times. They can also be called endless or non-terminating loops, which will run until the end of the program’s life.</p>
<p>Infinite loops are generally accidental and occur due to some mistake by the programmer. But they are pretty useful, too, in different kinds of applications, such as creating a program that does not terminate until a specific command is given.</p>
<h2 id="heading-types-of-infinite-loops-in-c">Types of Infinite Loops in C++</h2>
<p>There are several ways to create an infinite loop in C++, using different loop constructs such as while, for, and do-while loops. Here, we will explore each method and provide examples.</p>
<ul>
<li><p>Infinite While Loops</p>
</li>
<li><p>Infinite For Loops</p>
</li>
<li><p>Infinite do-while Loops</p>
</li>
</ul>
<h3 id="heading-1-infinite-loop-using-while-loop">1. Infinite Loop using While Loop</h3>
<p>This is the most popular type of while loop due to its simplicity. You just pass the value that will result in true as the condition of the while loop.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">while(1)
    or
while(true)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Example of Infinite loop in C++ using for loop</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Infinite loop using while</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>………………….</p>
<h3 id="heading-infinite-loop-using-for-loop">Infinite Loop using For Loop</h3>
<p>In a for loop, if we remove the initialization, comparison, and update conditions, then it will result in an infinite loop.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">for(;;)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">//Example of Infinite loop in C++ using for loop</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Infinite loop using for loop</span>
    <span class="hljs-keyword">for</span> (;;) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<h3 id="heading-infinite-loop-using-do-while-loop">Infinite Loop using do-while Loop</h3>
<p>Just like the other two loops discussed above, we can also create an infinite loop using a do-while loop. Although this loop is not preferred much due to its longer syntax.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">do{
}while(1)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop in C++ using do-while loop</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
   <span class="hljs-comment">// infinite do-while loop</span>
    <span class="hljs-keyword">do</span> {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    } <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<h2 id="heading-common-causes-of-accidental-infinite-loops-in-c">Common Causes of Accidental Infinite Loops in C++</h2>
<p>Infinite loops can be both intentional and accidental. Accidental infinite loops are those which were not intended by the programmer but are caused due to some error in the program.</p>
<p>Following are some of the errors that may cause infinite loops in your programs unintentionally:</p>
<h3 id="heading-1-missing-update-statements">1. Missing Update Statements</h3>
<p>Infinite loops are caused when you forget to add an update condition inside the loop, which will terminate the loop in the future. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop caused due to missing update statement</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">5</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; i &lt;&lt;<span class="hljs-built_in">endl</span>;
        <span class="hljs-comment">// Missing update: i++;</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>……………………</p>
<p>To fix the above code, we can add an update condition inside the loop like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// fixed code</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span> ;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>;
<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">5</span>) {
    <span class="hljs-built_in">cout</span> &lt;&lt; i &lt;&lt; <span class="hljs-built_in">endl</span>;
    i++; <span class="hljs-comment">// add the condition</span>
}

<span class="hljs-keyword">return</span> <span class="hljs-number">0</span> ; 

}
</code></pre>
<p>Output:</p>
<p>3</p>
<p>4</p>
<h3 id="heading-incorrect-loop-conditions">Incorrect Loop Conditions</h3>
<p>The conditions mentioned inside the loop body are crucial to terminate a loop. An incorrect loop condition can result in an infinite loop. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop caused due to incorrect loop conditions</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">while</span> (i &gt;= <span class="hljs-number">0</span>) {  
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello AnshuAyush "</span> &lt;&lt; <span class="hljs-built_in">endl</span>;

    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>……………………..</p>
<p>To fix the above code, we can update <code>i</code> inside the loop to eventually make the condition false:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// fixed code </span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span> ;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
<span class="hljs-keyword">while</span> (i &gt;= <span class="hljs-number">0</span>) {  
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello AnshuAyush"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    i--; <span class="hljs-comment">// loop will stop</span>
}

<span class="hljs-keyword">return</span> <span class="hljs-number">0</span> ; 

}
</code></pre>
<p>Ouptut:</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<h3 id="heading-logical-errors-in-the-loop">Logical Errors in the Loop</h3>
<p>In many scenarios, infinite loops are caused by small logical errors in the code. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &gt;<span class="hljs-number">2</span>; i += <span class="hljs-number">2</span>) {  
        <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"This is an infinite loop"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<p>To fix the above code, we can either use a decreasing condition or use an incrementing loop condition.</p>
<p>Decreasing condition:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &gt; <span class="hljs-number">0</span>; i--) {
    <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"This is NOT an infinite loop"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Increasing condition:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &lt; <span class="hljs-number">10</span>; i += <span class="hljs-number">2</span>) {
    <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"Loop will end when i reaches 10"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<h2 id="heading-applications-of-infinite-loops-in-c">Applications of Infinite Loops in C++</h2>
<p>Infinite loops do not only occur by accident, as I mentioned above. You can also create them on purpose for different use cases. The following are some of the common applications where you might use infinite loops intentionally:</p>
<ul>
<li><p><strong>Event loops:</strong> Many Graphical User Interfaces (GUIs) use infinite loops to keep the program running and responsive to user actions.</p>
</li>
<li><p><strong>Server applications:</strong> Web servers use infinite loops to continuously listen to client connections or requests.</p>
</li>
<li><p><strong>Embedded systems:</strong> Embedded systems, such as microcontrollers, frequently use infinite loops as their main program loops to continuously respond to external events.</p>
</li>
<li><p><strong>User inputs:</strong> Infinite loops are also used to wait for valid user inputs. The loop keeps running until a valid input is provided by the user. We’ll look at an example of this one.</p>
</li>
</ul>
<h3 id="heading-using-infinite-loops-to-take-user-input-in-c">Using Infinite Loops to Take User Input in C++</h3>
<p>Infinite loops are commonly used in scenarios where a program needs to continuously take user input until a specific condition is met, such as exiting the program or getting a valid user input. The following program demonstrates how we can take user input from the user until a specific condition is met:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ Program to take user input from users using infinite loops</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">string</span> input;

    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter a command (type 'exit' to quit): "</span>;
        getline(<span class="hljs-built_in">cin</span>, input);

        <span class="hljs-keyword">if</span> (input == <span class="hljs-string">"exit"</span>) {
        <span class="hljs-comment">// Exit the loop if the user types 'exit'</span>
            <span class="hljs-keyword">break</span>; 
        }

        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"You entered: "</span> &lt;&lt; input &lt;&lt; <span class="hljs-built_in">endl</span>;
        <span class="hljs-comment">// Process the input</span>
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Program exited."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>Enter a command (type 'exit' to quit): Anshu</p>
<p>You entered: Anshu</p>
<p>Enter a command (type 'exit' to quit): Ayush</p>
<p>You entered: Ayush</p>
<p>Enter a command (type 'exit' to quit): exit</p>
<p>Program exited.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Infinite loops aren’t always dangerous. They can be very useful when used with proper control, like break statements or condition checks. But if you use them carelessly, they can crash your program.</p>
<p>So just make sure you check your loop conditions and test your code using print statements between the programs to discover any unexpected behavior. In sum, infinite loops can be very powerful when handled carefully but can be very risky if left unchecked.</p>
<p>And if you'd like to support me and my work directly so I can keep creating these tutorials, <a target="_blank" href="https://paypal.me/ayushM010">you can do so here</a>. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Does Python's For-Else Loop Construct Work? ]]>
                </title>
                <description>
                    <![CDATA[ Python supports the for-else loop construct that is lesser known but super helpful. If you’ve programmed in Python, you may have used the for loop to iterate over items in iterables such as lists. But for some use cases, using the for loop in conjunc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/for-else-loop-in-python/</link>
                <guid isPermaLink="false">66bb8b2bc332a9c775d15b6a</guid>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 19 Jun 2024 13:52:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/fimg-1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python supports the for-else loop construct that is lesser known but super helpful.</p>
<p>If you’ve programmed in Python, you may have used the <code>for</code> loop to iterate over items in iterables such as lists. But for some use cases, using the for loop in conjunction with the <code>else</code> clause can be helpful.</p>
<p>In this tutorial, we’ll learn how to use for-else loops by coding a couple of examples to understand how they work.</p>
<h2 id="heading-syntax-of-the-for-else-loop-in-python">Syntax of the <code>for-else</code> Loop in Python</h2>
<p>In Python, the <code>for-else</code> loop is a construct that combines a <code>for</code> loop with an <code>else</code> clause.</p>
<p>The loop body typically checks for a condition. If the condition is <code>True</code>, the control breaks out of the loop. The <code>else</code> block will execute only when the <code>for</code> loop completes normally without encountering a <code>break</code> statement.</p>
<p>Let's look at a generic <code>for-else</code> loop construct:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> iterable:
    <span class="hljs-comment"># loop body</span>
    <span class="hljs-keyword">if</span> condition:
        <span class="hljs-keyword">break</span>
<span class="hljs-keyword">else</span>:
    <span class="hljs-comment"># else body</span>
</code></pre>
<p>Here's a breakdown of how this works:</p>
<ul>
<li>The <code>for</code> loop iterates over each item in the <code>iterable</code>.</li>
<li>If the <code>condition</code> is <code>True</code> and the control breaks out of the loop, the <code>else</code> block is skipped.</li>
<li>If the <code>for</code> loop iterates over all items in the <code>iterable</code>—without meeting the condition to break out of the loop—the <code>else</code> block is executed.</li>
</ul>
<p>Now let's code a couple of examples.</p>
<h2 id="heading-example-1-finding-a-prime-number">Example 1: Finding a Prime Number</h2>
<p>Let's use the <code>for-else</code> loop to check if a number is prime. As you may recall, a number is prime if it is divisible only by 1 and itself and has no other factors.</p>
<p>Look at the code snippet below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> math

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, int(math.sqrt(n))+ <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> n % i == <span class="hljs-number">0</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{n}</span> is divisible by <span class="hljs-subst">{i}</span>. Not a prime number."</span>)
            <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-comment"># This block executes if the loop did not encounter a break statement</span>
        print(<span class="hljs-string">f"<span class="hljs-subst">{n}</span> is a prime number."</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<p>Here, the <code>is_prime()</code> function first checks if the input number <code>n</code> is less than or equal to 1. If so, it returns <code>False</code> since prime numbers are greater than 1. Remember, the smallest prime number is 2.</p>
<p>We use the <code>for</code> loop to iterate over the range of numbers from 2 to the square root of <code>n</code> (inclusive). </p>
<ul>
<li>If <code>n</code> is divisible by any <code>i</code> in this range (2, <code>√n</code>), it means <code>n</code> is not a prime number, as we've found a factor. The function prints a message and breaks out of the loop. And the <code>else</code> block is skipped.</li>
<li>If the loop completes without finding any factors—without hitting a <code>break</code> statement—the <code>else</code> block executes. The function prints that <code>n</code> is a prime number and returns <code>True</code>.</li>
</ul>
<p>You can verify that the <code>is_prime()</code> function works as expected with a few function calls:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Test with a non-prime number</span>
is_prime(<span class="hljs-number">10</span>) 
<span class="hljs-comment"># Output: 10 is divisible by 2. Not a prime number.</span>


<span class="hljs-comment"># Test with a prime number</span>
is_prime(<span class="hljs-number">13</span>) 
<span class="hljs-comment"># Output: 13 is a prime number.</span>
</code></pre>
<h3 id="heading-a-note-on-checking-for-prime-numbers">📑 A Note on Checking for Prime Numbers</h3>
<p>You’d probably run the loop over all the numbers from 2 to <code>n</code> to check if there’s a factor. But it actually suffices to iterate up to the <strong>square root of <code>n</code></strong>. Why?</p>
<p>Recall that if <code>p</code> is a factor, you can always find a <code>q</code> such that <code>p x q = n</code>:</p>
<ul>
<li>If <code>n</code> is a perfect square, then <code>p = q</code>. </li>
<li>If <code>n</code> is not a perfect square, you have the following. If <code>p</code> is less than <code>√n</code>, <code>q</code> is greater than <code>√n</code>. And if <code>q</code> is greater than <code>√n</code>, <code>p</code> is less than <code>√n</code>.</li>
</ul>
<p>💡 So if you don't find a factor up to <code>√n</code>, you cannot find one beyond <code>√n</code> either.</p>
<h2 id="heading-example-2-searching-for-an-item-in-a-list">Example 2: Searching for an Item in a List</h2>
<p>Let's take another example where the <code>for-else</code> loop is helpful.</p>
<p>The following <code>search item()</code> function takes in a list and an item. The goal is to loop over the items in the list and check if the item exists. For this problem you can use the for-else loop construct like so:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search_item</span>(<span class="hljs-params">lst, item</span>):</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> lst:
        <span class="hljs-keyword">if</span> i == item:
            print(<span class="hljs-string">f"Found <span class="hljs-subst">{item}</span> in the list."</span>)
            <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{item}</span> is not in the list."</span>)
</code></pre>
<p>If the <code>item</code> is found the control breaks out of the loop. The <code>else</code> block is triggered only if the item is not found in the list.</p>
<p>Let’s verify with a few calls to the function:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Test with a list containing the item</span>
search_item([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], <span class="hljs-number">3</span>)  
<span class="hljs-comment"># Output: Found 3 in the list.</span>

<span class="hljs-comment"># Test with a list not containing the item</span>
search_item([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], <span class="hljs-number">6</span>)  
<span class="hljs-comment"># Output: 6 is not in the list.</span>
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>I hope you found this tutorial on the <code>for-else</code> loop construct in Python helpful. </p>
<p>This can come in handy especially when exiting the loop after iterating over all items—without breaking out of the loop earlier—is of interest. That said, if you don't need to conditionally break out of the loop, you don't need a <code>for-else</code> loop, and a simple <code>for</code> loop will suffice.</p>
<p>Keep coding. Until the next tutorial!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Break Statement – How to Break Out of a For Loop in Python ]]>
                </title>
                <description>
                    <![CDATA[ You can use loops in Python to execute code logic repeatedly until a specified condition is met. Python provides some built-in control statements that let you change the behavior of a loop. Some of these control statements include continue, break, pa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-break-statement-tutorial/</link>
                <guid isPermaLink="false">6616c3899fd7ac3907ca544c</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 10 Apr 2024 16:51:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ieic5Tq8YMk/upload/1e00a0a8acc5c22dea9a4910bffecbb1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use loops in Python to execute code logic repeatedly until a specified condition is met.</p>
<p>Python provides some built-in control statements that let you change the behavior of a loop. Some of these control statements include <code>continue</code>, <code>break</code>, <code>pass</code>, and <code>else</code>.</p>
<p>In this article, you'll learn how to terminate the current loop or a switch statement using the <code>break</code> statement.</p>
<h2 id="heading-how-to-use-the-break-statement-in-a-python-for-loop">How to Use the <code>break</code> Statement in a Python <code>for</code> Loop</h2>
<p>Consider the Python list below:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]
</code></pre>
<p>You can use a <code>for</code> loop to iterate through and print the elements of the <code>usernames</code> list:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> usernames:
    print(i)
<span class="hljs-comment"># Jade</span>
<span class="hljs-comment"># John</span>
<span class="hljs-comment"># Jane</span>
<span class="hljs-comment"># Doe</span>
</code></pre>
<p>But what if you want to stop the loop when a particular username is found? You can do this using the <code>break</code> statement.</p>
<p>Here's an example:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> usernames:
    print(i)
    <span class="hljs-keyword">if</span> i == <span class="hljs-string">"John"</span>:
        <span class="hljs-keyword">break</span>
<span class="hljs-comment"># Jade</span>
<span class="hljs-comment"># John</span>
</code></pre>
<p>In the code above, we created an <code>if</code> statement that checks whether the current value of <code>i</code> is "John": <code>if i == "John"</code>.</p>
<p>In the body of the <code>if</code> statement, we used the <code>break</code> statement. So the loop will stop when it finds an element in the list with the value of "John".</p>
<p>So instead of printing the whole list ("Jade", "John", "Jane", "Doe"), "Jade" and "John" were printed because the loop stopped immediately after it found "John".</p>
<h2 id="heading-how-to-use-the-break-statement-in-a-python-while-loop">How to Use the <code>break</code> Statement in a Python <code>while</code> Loop</h2>
<p>You can terminate a <code>while</code> loop using the <code>break</code> statement:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

i = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> i &lt; len(usernames):
    print(usernames[i])
    <span class="hljs-keyword">if</span> usernames[i] == <span class="hljs-string">"John"</span>:
        <span class="hljs-keyword">break</span>
    i += <span class="hljs-number">1</span>
</code></pre>
<p>Just like we did in the <code>for</code> loop example, we created a <code>usernames</code> list with four elements: <code>["Jade", "John", "Jane", "Doe"]</code>.</p>
<p>Using an <code>if</code> statement in the <code>while</code> loop, we checked when the current loop was at the index with a value "John". When that happens, the loop is terminated.</p>
<p>Once again, "Jade" and "John" were printed because the loop stops when "John" is found.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned to use the <code>break</code> statement in Python. You can use it to terminate the current loop when a condition is met.</p>
<p>From the above examples, you learned how to use the <code>break</code> statement to terminate <code>for</code> and <code>while</code> loops in Python.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Prevent Infinite Loops When Using useEffect() in ReactJS ]]>
                </title>
                <description>
                    <![CDATA[ By Roy Chng The useEffect hook in React has become a common tool for managing side effects in functional components. But there's a common pitfall when using it: the potential for infinite loops. These can cause performance issues and disrupt the inte... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prevent-infinite-loops-when-using-useeffect-in-reactjs/</link>
                <guid isPermaLink="false">66d460c7c7632f8bfbf1e491</guid>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 26 Apr 2023 14:07:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/preventing-infinite-loops-react.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Roy Chng</p>
<p>The <code>useEffect</code> hook in React has become a common tool for managing side effects in functional components. But there's a common pitfall when using it: the potential for infinite loops. These can cause performance issues and disrupt the intended behavior of components. </p>
<p>In this tutorial, we will explore how to prevent infinite loops when using <code>useEffect</code> in React.</p>
<p>You use the <code>useEffect</code> hook in functional components in React to manage side effects, such as fetching data from an API, updating the DOM, or subscribing to events that are external to React. </p>
<h1 id="heading-situations-that-cause-infinite-loops">Situations that Cause Infinite Loops</h1>
<h2 id="heading-missing-dependencies">Missing Dependencies</h2>
<p>One common mistake that can cause infinite loops is not specifying a dependency array. <code>useEffect</code> checks if the dependencies have changed after every render of the component. </p>
<p>So, when no dependencies are provided, the effect will run after every single render, which can lead to a continuous loop of updates if state is being updated.</p>
<p> For example, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
    });
}
</code></pre>
<p>In this example, the following occurs:</p>
<ul>
<li>When the component initially renders, the effect will run.</li>
<li>When the effect is run, it updates a count state, resulting in the component being re-rendered.</li>
<li>Since the component is re-rendered, it causes the <code>useEffect</code> to run again.</li>
<li>This causes the <code>count</code> state to update again, and goes on forever.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/useEffect-code-1-6.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Animation showing process of an infinite loop caused by useEffect</em></p>
<p>This happened because there isn't any dependency array specified, indicating that the effect should be run every time after the component re-renders.</p>
<p>To avoid this, add an empty dependency array:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
    }, []);
}
</code></pre>
<p>This will ensure that the effect is only executed after the initial rendering of the component.</p>
<p>Alternatively, if your effect depends on a certain state, remember to add it as a dependency:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [isLoggedIn, setIsLoggedIn] = useState(<span class="hljs-literal">false</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    }), [isLoggedIn];
}
</code></pre>
<p>That way, the effect is only run initially and when the dependency has changed after the component has re-rendered.</p>
<h2 id="heading-using-references-as-dependencies">Using References as Dependencies</h2>
<p>In JavaScript, data types can be categorized as being reference values or primitive values.</p>
<p>Primitive values are basic data types such as Strings, Booleans, Numbers, Null and Undefined.</p>
<p>On the other hand, reference values are more complex data types such as Arrays and Objects.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/primitive-vs-reference-values.png" alt="Image" width="600" height="400" loading="lazy">
<em>Types of primitive and reference values in JavaScript</em></p>
<p>When a reference value is assigned to a variable, the value and location to that value is stored and the variable will only point to that location.</p>
<p>Whereas with a primitive value, the variable is directly assigned to the primitive's value. The value is stored on a stack, a data structure used to store static data.</p>
<p>With reference values such as Functions and Objects, they are stored in a heap, a data structure used for dynamic memory allocation, which is useful when storing complex data types. </p>
<p>The variable is then assigned to the location in the stack, which points to the reference value in the heap.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/stack-vs-heap.png" alt="Image" width="600" height="400" loading="lazy">
<em>A Heap is a data structure used to store reference values</em></p>
<p>This is helps make our applications more efficient. Imagine having to create a duplicate of a complex object every time it is re-assigned to a new variable! Instead, the new variable can just point to the same location in the heap.</p>
<p>As useful as it is, reference values can be problematic when used as a dependency. This is because React will compare the location of the reference value if it is used as a dependency instead of the value's contents.</p>
<p>For example, consider the component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">let</span> data = {
        <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>
    };
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">//other logic</span>
    }, [data]);
}
</code></pre>
<p>In this case, the following occurs:</p>
<ul>
<li>When the component initially renders, the effect is run</li>
<li>When the effect is run, the state is updated. This causes the component to be re-rendered</li>
<li>When the component is re-rendered, a new <code>data</code> object is created, so its reference location is different from the previous</li>
<li>This causes the effect to run again since the dependency <code>data</code> object has changed</li>
<li>The cycle repeats, causing an infinite loop</li>
</ul>
<p>To prevent this from happening, we can use the <code>useRef</code> hook. It allows us to re-use the same value between re-renders.</p>
<p>This hook allows us to store values that will persist between renders, so the object's reference location will be the same throughout all render cycles. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> data = useRef({
        <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
    });
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">// logic</span>
    }, [data.current]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>The <code>useRef</code> hook takes in an initial value and returns a single object with a property called <code>current</code>.</p>
<p>The <code>current</code> property will be the value passed into the <code>useRef</code> hook, and will be the same throughout all renders of the component.</p>
<p>This ensures the effect doesn't run in an infinite loop since the dependency in the <code>useEffect</code> hook will no longer change with each render of the component.</p>
<p>Note that you can also change the value of the <code>data.current</code> property. For example:</p>
<pre><code class="lang-js">data.current = {<span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span>}
</code></pre>
<p>By changing the value of <code>data.current</code>, it <strong>will not</strong> trigger the component to re-render and React is <strong>not</strong> aware of this change.</p>
<h2 id="heading-using-functions-as-dependencies">Using Functions as Dependencies</h2>
<p>Another reason that <code>useEffect</code> may be causing an infinite loop is if you use a function as a dependency.</p>
<p>Since a function is a reference value in JavaScript, we encounter the same issue with using objects as dependencies.</p>
<p>For example, if we have a function in our component, the function will be re-created every time the component is re-rendered:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> submitForm = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    };
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">// logic</span>
    }, [submitForm]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>So when the component initially renders:</p>
<ul>
<li>The effect is run initially, causing the <code>count</code> state to update</li>
<li>Since the state has been updated, the component re-renders, causing the <code>submitForm</code> function to be re-created</li>
<li>The effect will run again as the <code>submitForm</code> dependency of the <code>useEffect</code> hook has changed</li>
<li>When the effect runs again, the <code>count</code> state is updated and the loop goes on </li>
</ul>
<p>To avoid the function from being re-created every time the component is re-rendered, we can use the <code>useCallback</code> hook:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> submitForm = useCallback(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    }, []);
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count++);
        <span class="hljs-comment">// logic</span>
    }, [submitForm]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>The <code>useCallback</code> hook also accepts two arguments, the first being the function that needs to be cached and stored without changing between renders, and the second being a dependency array. If the dependencies in the <code>useCallback</code> hook changes, the function is re-created.</p>
<p>So, similar to using <code>useEffect</code>, we can use an empty dependency array to ensure the function isn't being re-created between renders.</p>
<p>This prevents the effect from running in an infinite loop when a function is used as a dependency.</p>
<h2 id="heading-summary">Summary</h2>
<p>The <code>useEffect</code> hook in React is necessary when working with side effects in your React components. But even with experience, common mistakes can lead to infinite loops in your components. Be sure to watch out for missing dependencies, and using references or functions as dependencies when that happens.</p>
<p>We also took a look at how to use the <code>useRef</code> and <code>useCallback</code> hooks to prevent objects from being re-created in between renders.</p>
<p>If you enjoy my writing, consider checking out my <a target="_blank" href="https://www.youtube.com/@turbinethree">YouTube channel</a> for more.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Loops in Python ]]>
                </title>
                <description>
                    <![CDATA[ Loops are an essential concept in programming. They allow you to execute a block of code repeatedly based on certain conditions. Python offers two types of loops: for and while loops. In this article, we will explore both of these loop types and prov... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-loops-in-python/</link>
                <guid isPermaLink="false">66d460a3230dff016690585f</guid>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jeremiah Oluseye ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 21:36:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Loops.JPG" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Loops are an essential concept in programming. They allow you to execute a block of code repeatedly based on certain conditions.</p>
<p>Python offers two types of loops: for and while loops. In this article, we will explore both of these loop types and provide examples of how to use them in your Python code.</p>
<h2 id="heading-how-to-use-for-loops-in-python">How to Use For Loops in Python</h2>
<p>You'll use a for loop when you want to iterate over a collection of items or when you know the exact number of times you want to execute a block of code.</p>
<p>Here's the code for a for loop in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> variable <span class="hljs-keyword">in</span> iterable:
    <span class="hljs-comment"># code to execute</span>
</code></pre>
<ul>
<li><p>variable is a variable that represents the current item in the iterable that we're iterating over.</p>
</li>
<li><p>iterable is a collection of items that we want to iterate over, such as a list, tuple, string, or range.</p>
</li>
</ul>
<p>For example, let's say we have a list of numbers and we want to print each number:</p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers:
    print(num)
</code></pre>
<p>Output</p>
<pre><code class="lang-python"><span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
</code></pre>
<p>We can also use the <code>range()</code> function to specify a range of numbers to iterate over:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
    print(num)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python"><span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
</code></pre>
<p>The <code>range()</code> function takes two arguments: the starting number and the ending number (exclusive). In this case, the loop will iterate over the numbers from 1 to 5.</p>
<h2 id="heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</h2>
<p>You'll use a while loop when you want to execute a block of code repeatedly based on a condition.</p>
<p>Here's the syntax for a while loop in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">while</span> condition:
    <span class="hljs-comment"># code to execute</span>
</code></pre>
<p><code>condition</code> is a boolean expression that determines whether the loop should continue or not.</p>
<p>For example, let's say we want to print the numbers from 1 to 5 using a while loop:</p>
<pre><code class="lang-python">num = <span class="hljs-number">1</span>
<span class="hljs-keyword">while</span> num &lt;= <span class="hljs-number">5</span>:
    print(num)
    num += <span class="hljs-number">1</span>
</code></pre>
<p>In this example, we initialize the <code>num</code> variable to 1 and then execute the loop as long as <code>num</code> is less than or equal to 5. Inside the loop, we print the current value of <code>num</code> and then increment it by 1.</p>
<p>We can also use a while loop to keep asking the user for input until they enter a valid response:</p>
<pre><code class="lang-python">valid_response = <span class="hljs-literal">False</span>
<span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> valid_response:
    response = input(<span class="hljs-string">"Enter 'yes' or 'no': "</span>)
    <span class="hljs-keyword">if</span> response.lower() == <span class="hljs-string">'yes'</span> <span class="hljs-keyword">or</span> response.lower() == <span class="hljs-string">'no'</span>:
        valid_response = <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"Invalid response. Please enter 'yes' or 'no'."</span>)
</code></pre>
<p>Let's take a look at some advanced uses of loops in Python.</p>
<h2 id="heading-how-to-use-nested-loops-in-python">How to Use Nested Loops in Python</h2>
<p>Nested loops are loops that are contained inside other loops. They allow us to iterate over a collection of items multiple times and are useful for tasks such as generating all possible combinations of items.</p>
<p>Here's an example of how to use nested loops to generate all possible pairs of numbers from two lists:</p>
<pre><code class="lang-python">list1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
list2 = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]

<span class="hljs-keyword">for</span> num1 <span class="hljs-keyword">in</span> list1:
    <span class="hljs-keyword">for</span> num2 <span class="hljs-keyword">in</span> list2:
        print(num1, num2)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python"><span class="hljs-number">1</span> <span class="hljs-number">4</span>
<span class="hljs-number">1</span> <span class="hljs-number">5</span>
<span class="hljs-number">1</span> <span class="hljs-number">6</span>
<span class="hljs-number">2</span> <span class="hljs-number">4</span>
<span class="hljs-number">2</span> <span class="hljs-number">5</span>
<span class="hljs-number">2</span> <span class="hljs-number">6</span>
<span class="hljs-number">3</span> <span class="hljs-number">4</span>
<span class="hljs-number">3</span> <span class="hljs-number">5</span>
<span class="hljs-number">3</span> <span class="hljs-number">6</span>
</code></pre>
<p>In this example, we use a nested for loop to iterate over each item in list1 and list2, and print out all possible pairs of numbers.</p>
<h2 id="heading-list-comprehension-in-python">List Comprehension in Python</h2>
<p>List comprehensions are a concise way to create lists based on existing lists or other iterable objects. They use a for loop and an optional conditional statement to generate the new list.</p>
<p>Here's an example of how to use list comprehension to create a new list of even numbers from an existing list:</p>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]
even_numbers = [num <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers <span class="hljs-keyword">if</span> num % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>]
print(even_numbers)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">[<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>]
</code></pre>
<p>In this example, we use a list comprehension to iterate over each number in the numbers list and add it to the <code>even_numbers</code> list if it is even (that is, the remainder when divided by 2 is 0).</p>
<h2 id="heading-how-to-iterate-over-a-dictionary-in-python">How to Iterate Over a Dictionary in Python</h2>
<p>In Python, we can iterate over the keys, values, or items (key-value pairs) of a dictionary using a for a loop.</p>
<p>Here's an example of how to iterate over the items of a dictionary and print out the key-value pairs:</p>
<pre><code class="lang-python">fruits = {<span class="hljs-string">'apple'</span>: <span class="hljs-string">'red'</span>, <span class="hljs-string">'banana'</span>: <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'orange'</span>: <span class="hljs-string">'orange'</span>}

<span class="hljs-keyword">for</span> fruit, color <span class="hljs-keyword">in</span> fruits.items():
    print(<span class="hljs-string">f"The <span class="hljs-subst">{fruit}</span> is <span class="hljs-subst">{color}</span>."</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">The apple <span class="hljs-keyword">is</span> red.
The banana <span class="hljs-keyword">is</span> yellow.
The orange <span class="hljs-keyword">is</span> orange.
</code></pre>
<p>In this example, we use the <code>items()</code> method of the <code>fruits</code> dictionary to iterate over each key-value pair, and then print out a formatted string that includes the fruit and its corresponding color.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Loops are an essential part of programming in Python. They allow us to automate repetitive tasks and manipulate data in powerful ways.</p>
<p>By understanding the basics of for and while loops, as well as more advanced concepts such as nested loops and list comprehensions, you'll be able to write efficient and effective code in Python.</p>
<p>Let’s connect on <a target="_blank" href="https://twitter.com/Olujerry19">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/jeremiah-oluseye-58457719a/">Linkedin</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Enhanced For Loops in Java – How to Use ForEach Loops on Arrays ]]>
                </title>
                <description>
                    <![CDATA[ You can use enhanced loops in Java to achieve the same results as a for loop. An enhanced loop is also known as a for-each loop in Java.  Enhanced loops simplify the way you create for loops. They are mostly used to iterate through an array or collec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/enhanced-for-loops-in-java-how-to-use-foreach-loops-on-arrays/</link>
                <guid isPermaLink="false">66b0a29f7cd8dca6718a223d</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 17 Feb 2023 00:55:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/java-enhanced-loop.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use enhanced loops in Java to achieve the same results as a <a target="_blank" href="https://www.freecodecamp.org/news/java-for-loop-example/"><code>for</code> loop</a>. An enhanced loop is also known as a <code>for-each</code> loop in Java. </p>
<p>Enhanced loops simplify the way you create <code>for</code> loops. They are mostly used to iterate through an array or collection of variables.</p>
<p>In this tutorial, you'll learn the syntax and how to use the <code>for-each</code> loop (enhanced loop) in Java. </p>
<h2 id="heading-java-for-each-loop-syntax">Java For-Each Loop Syntax</h2>
<p>Here's what the syntax of a <code>for-each</code> loop in Java looks like:</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span>(dataType variable : array) {
    <span class="hljs-comment">// code to be executed</span>
}
</code></pre>
<p>In the syntax above:</p>
<ul>
<li><strong>dataType</strong> denotes the data type of the <strong>array</strong>.</li>
<li><strong>variable</strong> denotes a variable assigned to each element in the array during the iteration (you'll understand this through the examples that follow).</li>
<li><strong>array</strong> denotes the array to be looped through.</li>
</ul>
<h2 id="heading-java-for-each-loop-example">Java For-Each Loop Example</h2>
<p>Let's take a look at some examples to help you understand how a <code>for-each</code> loop works. </p>
<h3 id="heading-java-for-each-loop-example-1">Java For-Each Loop Example #1</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ForEachExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        <span class="hljs-keyword">int</span>[] even_numbers = { <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span> };

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> number : even_numbers){
           System.out.println(number);
           <span class="hljs-comment">// 2</span>
           <span class="hljs-comment">// 4</span>
           <span class="hljs-comment">// 6</span>
           <span class="hljs-comment">// 8</span>
        }

    }
}
</code></pre>
<p>In the code above, we created an array called <code>even_numbers</code>. </p>
<p>To loop through and print all the numbers in the array, we made use of a <code>for-each</code> loop: <code>for(int number : even_numbers){...}</code>. </p>
<p>In the parenthesis for the loop, we created an integer variable called <code>number</code> which would be used to loop through the <code>even_numbers</code> array. </p>
<p>So, for:</p>
<h4 id="heading-iteration-1">Iteration #1</h4>
<p><code>number</code> = first element in the array (2). This gets printed out.</p>
<h4 id="heading-iteration-2">Iteration #2</h4>
<p><code>number</code> = second element in the array (4). This current value gets printed out. </p>
<h4 id="heading-iteration-3">Iteration #3</h4>
<p><code>number</code> = third element in the array (6). This current value gets printed out. </p>
<h4 id="heading-iteration-4">Iteration #4</h4>
<p><code>number</code> = fourth element in the array (8). This current value gets printed out. </p>
<p>The value of <code>number</code> keeps changing to the current index during the iteration process until it gets to the end of the array. After each index is printed out, it moves to the next index. </p>
<p>You can also see it this way: "For every <code>number</code> in the <code>even_numbers</code> array, print <code>number</code>)".</p>
<h3 id="heading-java-for-each-loop-example-2">Java For-Each Loop Example #2</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ForEachExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        <span class="hljs-keyword">int</span>[] even_numbers = { <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span> };

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> number : even_numbers){
            number = number*<span class="hljs-number">2</span>;
            System.out.println(number);
        }

    }
}
</code></pre>
<p>In the code above, we're multiplying the value of each element by two using the <code>number</code> variable: <code>number = number*2;</code>.</p>
<p>The process here is the same with the last example. When <code>number</code> becomes an element in the array, it doubles the element's value and prints it to the console.</p>
<h2 id="heading-summary">Summary</h2>
<p>You can use <code>for-each</code> loops in Java to iterate through elements of an array or collection. </p>
<p>They simplify how you create <code>for</code> loops. For instance, the syntax of a <code>for</code> loop requires that you create a variable, a condition that specifies when the loop should terminate, and an increment/decrement value. </p>
<p>With <code>for-each</code> loops, all you need is a variable and the array to be looped through. </p>
<p>But this doesn't mean that you should always go for <code>for-each</code> loops. </p>
<p><code>for</code> loops give you more control over what happens during the iteration process – controlling and tracking what happens at every index or some indexes. </p>
<p>On the other hand, <code>for-each</code> loops can be used when you have no use for tracking each index. The code just runs through for every element in the array. </p>
<p>You can learn more about <code>for</code> loops in Java by <a target="_blank" href="https://www.freecodecamp.org/news/java-for-loop-example/">reading this article</a>.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript For loop – How to Loop Through an Array in JS ]]>
                </title>
                <description>
                    <![CDATA[ By Dennis Temoye Charity A loop is an instruction in computer programming that allows an application to repeat a process until a specific condition is met. For example, say you want to run through a list of names and output each name on your screen. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-loop-through-an-array-with-for-loop-in-javascript/</link>
                <guid isPermaLink="false">66d45e03680e33282da25e51</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 26 Sep 2022 23:14:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/1_9H5rmyp3MgrcA8i1emsJPg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dennis Temoye Charity</p>
<p>A loop is an instruction in computer programming that allows an application to repeat a process until a specific condition is met.</p>
<p>For example, say you want to run through a list of names and output each name on your screen. If you didn't use a loop, you'd end up repeating code to output each name. But with a loop, you're able to output each name individually without repeating any code.</p>
<p>This article will walk you through the process of how you can loop through an array using the five most common loops in JavaScript.</p>
<h2 id="heading-what-is-an-array-in-javascript"><strong>What Is an Array in JavaScript?</strong></h2>
<p>An array in JavaScript is a variable that you can use to store multiple elements. It is usually in the form of square brackets that contain different elements, strings, and integers (or both strings and integers).</p>
<h2 id="heading-what-is-a-loop-in-javascript"><strong>What Is a Loop in JavaScript?</strong></h2>
<p>A loop is a conditional statement used to run a sequence of instructions until a specified condition is met. It is given a statement that repeats the execution of a block of code and ends the execution once the stated condition is met.</p>
<p>Let's loop through this array – <code>let name = ['Dennis', 'Precious', 'Evelyn']</code>, – using one of the most commonly used loops in JavaScript.</p>
<h2 id="heading-how-to-loop-through-an-array-with-a-for-loop-in-javascript"><strong>How to Loop Through an Array with a For Loop in JavaScript</strong></h2>
<p>A <code>for</code> loop is a statement that repeats the execution of a block of code when the condition has not been met and terminates the execution when the condition has been met.</p>
<p>Let's now loop through an array using the <code>for</code> loop method.</p>
<p>I advise that you go through this article carefully to not miss vital details along the way. But in case you are in a hurry to loop through an array using the <code>for</code> loop statement, you can check out the syntax below.</p>
<h3 id="heading-quick-for-loop-explanation"><strong>Quick for loop explanation:</strong></h3>
<p>This is the fast route to looping through an array using the <code>for</code> loop statement with an example.</p>
<p>Syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = [<span class="hljs-string">'Dennis'</span>, <span class="hljs-string">'Precious'</span>, <span class="hljs-string">'Evelyn'</span>];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; name.length; i++)
 {    
     <span class="hljs-built_in">console</span>.log(name[i]);
}
</code></pre>
<p>And here's the output:</p>
<pre><code class="lang-js">Dennis
Precious
Evelyn
</code></pre>
<h3 id="heading-how-for-loops-work-in-more-detail"><strong>How for loops work – in more detail</strong></h3>
<p>Here we will get to understand what a <code>for</code> loop is and how to use this statement to loop through an array with an example.</p>
<p>To run a <code>for</code> loop statement, you must know that it always needs to have three primary expressions that are always separated by a semicolon.</p>
<p>Syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (expression1; expression2; expression3)
 {  
  <span class="hljs-comment">//code to be executed</span>
}
</code></pre>
<ul>
<li>expression1: This is the <code>initialization</code> expression, which you use to declare a <code>for</code> loop counter variable with either the <code>var</code> or <code>let</code> keywords, such as <code>var i = 0</code> or <code>let i = 0</code>.</li>
<li>expression2: This is the <code>condition</code> expression, which either returns true or false. It determines whether the <code>for</code> loop should continue the execution or end the execution.</li>
</ul>
<p>Remember that a <code>for</code> loop statement continues executing a block of code when the condition has not been met, it only terminates the loop when the condition has been met.</p>
<ul>
<li>expression3: This is the <code>update</code> expression, which is usually used to increment (<code>++i</code>) or decrement (<code>--i</code>) the <code>for</code> loop counter variable whenever the <code>for</code> loop condition has been met.</li>
</ul>
<p>Now that we understand the <code>for</code> loop statement expressions, let's work with an example.</p>
<p>Syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arrayName = [<span class="hljs-string">'Dennis'</span>, <span class="hljs-string">'Precious'</span>, <span class="hljs-string">'Evelyn'</span>]
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arrayName.length; i++) {
    <span class="hljs-built_in">console</span>.log(arrayName[i]);
}
</code></pre>
<p>This syntax above loops through the <code>name</code> array and <code>console.log ()</code> the strings in the array as long as the condition has not been met.</p>
<p>From the syntax above:</p>
<ul>
<li>We first initialized the counter variable, <code>let i = 0;</code>.</li>
<li>Then we gave the loop a condition to terminate the loop once the value of the counter variable (<code>i</code>) is less than (<code>&lt;</code>) the length of the name (<code>name.length;</code>).</li>
<li>You use the keyword <code>length</code> to check the length of a string.</li>
</ul>
<p>Here's the output:</p>
<pre><code class="lang-js">Dennis
Precious
Evelyn
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this tutorial, we discussed the fundamentals of a for loop in JavaScript as well as the definition of an array. We also learned how to use the JavaScript 'for' loop statement to loop through an array.</p>
<p>Thanks for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Iteration in Golang – How to Loop Through Data Structures in Go ]]>
                </title>
                <description>
                    <![CDATA[ By Ubaydah Abdulwasiu In programming, iteration (commonly known as looping) is a process where a step is repeated n number of times until a specific condition is met. Just like every other programming language, Golang has a way of iterating through d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/iteration-in-golang/</link>
                <guid isPermaLink="false">66d4617151f567b42d9f84de</guid>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 26 Sep 2022 22:44:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/How-to-perform-iteration-in-Golang-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ubaydah Abdulwasiu</p>
<p>In programming, iteration (commonly known as looping) is a process where a step is repeated n number of times until a specific condition is met.</p>
<p>Just like every other programming language, Golang has a way of iterating through different data structures and data types like structs, maps, arrays, strings, and so on.</p>
<p>In this article you will learn:</p>
<ul>
<li>How to loop through arrays</li>
<li>How to loop through strings</li>
<li>How to loop through maps</li>
<li>How to loop through structs</li>
</ul>
<h2 id="heading-how-to-loop-through-arrays-and-slices-in-go">How to Loop Through Arrays and Slices in Go</h2>
<p>Arrays are powerful data structures that store similar types of data. You can identify and access the elements in them by their index.</p>
<p>In Golang, you can loop through an array using a <code>for</code> loop by initialising a variable i at 0 and incrementing the variable until it reaches the length of the array.</p>
<p>They syntax is shown below:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(arr); i++ {
    <span class="hljs-comment">// perform an operation</span>
}
</code></pre>
<p>As an example, let's loop through an array of integers:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    numbers := []<span class="hljs-keyword">int</span>{<span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(numbers); i++ {
        fmt.Println(numbers[i])

    }
}
</code></pre>
<p>In the code above, we defined an array of integers named <code>numbers</code> and looped through them by initialising a variable <code>i</code> . We then printed out the value of each index of the array while incrementing <code>i</code> .</p>
<p>The code above outputs the following:</p>
<pre><code><span class="hljs-number">7</span>
<span class="hljs-number">9</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
</code></pre><p>We can also loop through an array using the <code>range</code> keyword which iterates through the entire length of an array. </p>
<p>The syntax is shown below:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> index, arr := <span class="hljs-keyword">range</span> arr {
  <span class="hljs-comment">// perform an operation    </span>
}
</code></pre>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    arr := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>, <span class="hljs-string">"d"</span>, <span class="hljs-string">"e"</span>, <span class="hljs-string">"f"</span>}

    <span class="hljs-keyword">for</span> index, a := <span class="hljs-keyword">range</span> arr {
        fmt.Println(index, a)
    }

}
</code></pre>
<p>In the code above, we defined an array of strings and looped through both its index and value using the <code>for..range</code> keyword. </p>
<p>The <code>for...range</code> is more simpler in syntax and easier to understand. You use it to iterate different data structures like arrays, strings, maps, slices, and so on. </p>
<p>This outputs the following: </p>
<pre><code><span class="hljs-number">0</span> a
<span class="hljs-number">1</span> b
<span class="hljs-number">2</span> c
<span class="hljs-number">3</span> d
<span class="hljs-number">4</span> e
<span class="hljs-number">5</span> f
</code></pre><p>Assuming we were to ignore the index and simply print out the elements of the array, you just replace the <code>index</code> variable with an underscore.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    arr := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>, <span class="hljs-string">"d"</span>, <span class="hljs-string">"e"</span>, <span class="hljs-string">"f"</span>}

    <span class="hljs-keyword">for</span> _, a := <span class="hljs-keyword">range</span> arr {
        fmt.Println(a)
    }

}
</code></pre>
<p>In the code above, we modified the previous example and replaced the <code>index</code> variable with an underscore. We did this to ignore the index and output the elements of the array instead.</p>
<p>This outputs the following:</p>
<pre><code>a
b
c
d
e
f
</code></pre><h2 id="heading-how-to-loop-through-strings-in-go">How to Loop Through Strings in Go</h2>
<p>Strings in programming are immutable – this means you can't modify them after you create them. They're ordered sequences of one or more characters (like letters, numbers, or symbols) that can either be a constant or a variable.</p>
<p>In Golang, <a target="_blank" href="https://golangbot.com/strings/">strings</a> are different from other languages like Python or JavaScript. They are represented as a <a target="_blank" href="https://naveenr.net/unicode-character-set-and-utf-8-utf-16-utf-32-encoding/">UTF-8 sequence of bytes</a> and each element in a string represents a byte.</p>
<p>You loop through strings using the <code>for...range</code> loop or using a regular loop. </p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    word := <span class="hljs-string">"Ab$du"</span>

    <span class="hljs-keyword">for</span> index, a := <span class="hljs-keyword">range</span> word {
        fmt.Println(index, <span class="hljs-keyword">string</span>(a))
    }
}
</code></pre>
<p>In the code above, we defined a string containing different characters and looped through its entries. Strings are represented as bytes in Golang, which is why we needed to convert each value to the type <code>string</code> when printing them out. </p>
<p>This outputs:</p>
<pre><code><span class="hljs-number">0</span> A
<span class="hljs-number">1</span> b
<span class="hljs-number">2</span> $
<span class="hljs-number">3</span> d
<span class="hljs-number">4</span> u
</code></pre><p>If we hadn't converted each entry to a string, Golang would print out the byte representation instead.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    word := <span class="hljs-string">"Ab$du"</span>

    <span class="hljs-keyword">for</span> index, a := <span class="hljs-keyword">range</span> word {
        fmt.Println(index, a)
    }
}
</code></pre>
<p>The outputs:</p>
<pre><code><span class="hljs-number">0</span> <span class="hljs-number">65</span>
<span class="hljs-number">1</span> <span class="hljs-number">98</span>
<span class="hljs-number">2</span> <span class="hljs-number">36</span>
<span class="hljs-number">3</span> <span class="hljs-number">100</span>
<span class="hljs-number">4</span> <span class="hljs-number">117</span>
</code></pre><p>We can also iterate through the string by using a regular <code>for loop</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    word := <span class="hljs-string">"ab$du"</span>

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(word); i++ {
        fmt.Println(i, <span class="hljs-keyword">string</span>(word[i]))
    }
}
</code></pre>
<h2 id="heading-how-to-loop-through-maps-in-go">How to Loop Through Maps in Go</h2>
<p>In Golang, a map is a data structure that stores elements in key-value pairs, where keys are used to identify each value in a map. It is similar to dictionaries and hashmaps in other languages like Python and Java.</p>
<p>You can iterate through a <code>map</code> in Golang using the <code>for...range</code> statement where it fetches the index and its corresponding value. </p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    books := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
        <span class="hljs-string">"maths"</span>:     <span class="hljs-number">5</span>,
        <span class="hljs-string">"biology"</span>:   <span class="hljs-number">9</span>,
        <span class="hljs-string">"chemistry"</span>: <span class="hljs-number">6</span>,
        <span class="hljs-string">"physics"</span>:   <span class="hljs-number">3</span>,
    }
    <span class="hljs-keyword">for</span> key, val := <span class="hljs-keyword">range</span> books {
        fmt.Println(key, val)
    }
}
</code></pre>
<p>In the code above, we defined a map storing the details of a bookstore with type <code>string</code> as its key and type <code>int</code> as its value. We then looped through its keys and values using the <code>for..range</code> keyword. </p>
<p>Iterating through a map in Golang doesn't have any specified order, and we shouldn't expect the keys to be returned in the order we defined when we looped through.</p>
<p>This code outputs:</p>
<pre><code>physics <span class="hljs-number">3</span>
maths <span class="hljs-number">5</span>
biology <span class="hljs-number">9</span>
chemistry <span class="hljs-number">6</span>
</code></pre><p>If we don't want to specify the values and return just the keys instead, we simply don't define a value variable and define a key variable only.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    books := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
        <span class="hljs-string">"maths"</span>:     <span class="hljs-number">5</span>,
        <span class="hljs-string">"biology"</span>:   <span class="hljs-number">9</span>,
        <span class="hljs-string">"chemistry"</span>: <span class="hljs-number">6</span>,
        <span class="hljs-string">"physics"</span>:   <span class="hljs-number">3</span>,
    }
    <span class="hljs-keyword">for</span> key := <span class="hljs-keyword">range</span> books {
        fmt.Println(key)
    }
}
</code></pre>
<p>This outputs the following:</p>
<pre><code>maths
biology
chemistry
physics
</code></pre><p>Likewise, if we aren't interested in the keys of a map, we use an underscore to ignore the keys and define a variable for the value.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    books := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
        <span class="hljs-string">"maths"</span>:     <span class="hljs-number">5</span>,
        <span class="hljs-string">"biology"</span>:   <span class="hljs-number">9</span>,
        <span class="hljs-string">"chemistry"</span>: <span class="hljs-number">6</span>,
        <span class="hljs-string">"physics"</span>:   <span class="hljs-number">3</span>,
    }
    <span class="hljs-keyword">for</span> _, val := <span class="hljs-keyword">range</span> books {
        fmt.Println(val)
    }
}
</code></pre>
<p>This outputs:</p>
<pre><code><span class="hljs-number">5</span>
<span class="hljs-number">9</span>
<span class="hljs-number">6</span>
<span class="hljs-number">3</span>
</code></pre><h2 id="heading-how-to-loop-through-structs-in-go">How to Loop Through Structs in Go</h2>
<p>Struct is a data structure in Golang that you use to combine different data types into one. Unlike an array, a struct can contain integers, strings, booleans and more – all in one place.</p>
<p>Unlike a map, where we can easily loop through its keys and values, looping through a struct in Golang requires that you use a package called <code>reflect</code>. This allows us you modify an object with an arbitrary type.</p>
<p>For example, let's create a struct and loop through it:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"reflect"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name   <span class="hljs-keyword">string</span>
    Age    <span class="hljs-keyword">int</span>
    Gender <span class="hljs-keyword">string</span>
    Single <span class="hljs-keyword">bool</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    ubay := Person{
        Name:   <span class="hljs-string">"John"</span>,
        Gender: <span class="hljs-string">"Female"</span>,
        Age:    <span class="hljs-number">17</span>,
        Single: <span class="hljs-literal">false</span>,
    }
    values := reflect.ValueOf(ubay)
    types := values.Type()
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; values.NumField(); i++ {
        fmt.Println(types.Field(i).Index[<span class="hljs-number">0</span>], types.Field(i).Name, values.Field(i))
    }
}
</code></pre>
<p>This outputs:</p>
<pre><code><span class="hljs-number">0</span> Name John
<span class="hljs-number">1</span> Age <span class="hljs-number">17</span>
<span class="hljs-number">2</span> Gender Female
<span class="hljs-number">3</span> Single <span class="hljs-literal">false</span>
</code></pre><p>In the code above, we defined a <code>struct</code> named <code>Person</code> with different attributes and created a new instance of the <code>struct</code>. We then used the <code>reflect</code> package to get the values of the <code>struct</code> and its <code>type</code>.  </p>
<p>By using the regular <code>for</code> loop, we incremented the initialised variable <code>i</code> until it reached the length of the struct. </p>
<p>We use the <code>NumField</code> method to get the total number of fields in the struct. The <code>types.Field(i).Index</code> method returns the index of each key in a struct. The <code>types.Field(i).Name</code> method returns the field name for each key in the struct. And the <code>values.Field(i)</code> returns the value for each key in the struct.</p>
<p>You can learn more about the reflect package in this article:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://medium.com/capital-one-tech/learning-to-use-go-reflection-822a0aed74b7">https://medium.com/capital-one-tech/learning-to-use-go-reflection-822a0aed74b7</a></div>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have explored how to perform iteration on different data types in Golang. </p>
<p>While you can loop through arrays, maps, and strings using a <code>for</code> loop or <code>for..range</code> loop, structs require an additional package called <code>reflect</code> to loop through their keys and values.</p>
<p>I hope this article helps you understand iteration in Golang better.</p>
<p>Thanks for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Loop Through an Array in JavaScript – JS Iterate Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ An array is a single variable used to store elements of different datatypes so that they can be accessed through a single variable. It is an ordered list of values, and each value is referred to as an element, which is specified by an index. Knowing ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-loop-through-an-array-in-javascript-js-iterate-tutorial/</link>
                <guid isPermaLink="false">66d45fa94a7504b7409c342f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 23 Jun 2022 19:55:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/cover-template--3-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An array is a single variable used to store elements of different datatypes so that they can be accessed through a single variable.</p>
<p>It is an ordered list of values, and each value is referred to as an element, which is specified by an index.</p>
<p>Knowing that these single variables contain a list of elements, you might want to create a list of these elements so that you can perform individual functions with them and much more. This is where the loop comes into play.</p>
<h3 id="heading-heres-an-interactive-scrim-about-how-to-loop-through-an-array-in-javascript">Here's an interactive scrim about how to loop through an array in JavaScript:</h3>
<div class="embed-wrapper"><iframe src="https://scrimba.com/scrim/co0844e78b1b48c6e5bc87da1?embed=freecodecamp,mini-header,no-sidebar" width="100%" height="480" title="Embedded content" loading="lazy"></iframe></div>

<h2 id="heading-what-are-loops-in-javascript">What are Loops in JavaScript?</h2>
<p>A loop is a type of computer program that allows us to repeat a specific operation a predetermined number of times without having to write that operation individually.</p>
<p>For example, if we have an array and want to output each element in the array, rather than using the index number to do so one by one, we can simply loop through and perform this operation once.</p>
<p>There are numerous methods for looping through an array in JavaScript. In this article, we will go over the most commonly used so you can learn different approaches and understand how they work.</p>
<p>We will use the following array for this article:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">22</span>, <span class="hljs-number">54</span>, <span class="hljs-number">76</span>, <span class="hljs-number">92</span>, <span class="hljs-number">43</span>, <span class="hljs-number">33</span>];
</code></pre>
<h2 id="heading-how-to-loop-through-an-array-with-a-while-loop-in-javascript">How to Loop Through an Array with a While Loop in JavaScript</h2>
<p>You can use a <code>while</code> loop to evaluate a condition that is enclosed in parenthesis <code>()</code>. If the condition is <code>true</code>, the code inside the <code>while</code> loop is executed. If it is <code>false</code>, the loop is terminated.</p>
<p>If we want to loop through an array, we can use the <code>length</code> property to specify that the loop should continue until we reach the last element of our array.</p>
<p>Let's now use the while loop method to loop through the array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> (i &lt; scores.length) {
    <span class="hljs-built_in">console</span>.log(scores[i]);
    i++;
}
</code></pre>
<p>This will return each element in our array one after the other:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<p>In the loop above, we first initialized the index number so that it begins with <code>0</code>. Then the number will continue to increase and output each element until the condition we set returns false, indicating that we have reached the end of the array. When <code>i = 6</code>, the condition will no longer be executed because the array's last index is <code>5</code>.</p>
<h2 id="heading-how-to-loop-through-an-array-with-a-dowhile-loop-in-javascript">How to Loop Through an Array with a <code>do…while</code> Loop in JavaScript</h2>
<p>The <code>do...while</code> loop is nearly identical to the while loop, except that it executes the body first before evaluating the condition for subsequent executions. This means that the loop's body is always executed at least once.</p>
<p>Let’s perform the same loop with the <code>do…while</code> loop to see how it works:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">let</span> i = 0;

<span class="hljs-keyword">do</span> {
    console.log(scores[i]);
    i++;
} <span class="hljs-keyword">while</span> (i &lt; scores.length);
</code></pre>
<p>This will return each element in our array:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<p>As previously stated, this will always run once before evaluating any condition set. For example, if we set the index <code>i</code> to <code>6</code> and it is no longer less than <code>scores.length</code>, the body of the loop will run first before checking the condition:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">6</span>;

<span class="hljs-keyword">do</span> {
    <span class="hljs-built_in">console</span>.log(scores[i]);
    i++;
} <span class="hljs-keyword">while</span> (i &lt; scores.length);
</code></pre>
<p>This will return a single <code>undefined</code> because we do not have an element in the array of index <code>6</code> but as you can see it ran once before stopping.</p>
<h2 id="heading-how-to-loop-through-an-array-with-a-for-loop-in-javascript">How to Loop Through an Array with a for Loop in JavaScript</h2>
<p>The <code>for</code> loop is an iterative statement that checks for certain conditions and then executes a block of code repeatedly as long as those conditions are met.</p>
<p>We don't need to initialize the index first when using the <code>for</code> loop method because the initialization, condition, and iteration are all handled in the bracket, as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; scores.length; i++) {
    <span class="hljs-built_in">console</span>.log(scores[i]);
}
</code></pre>
<p>This will return all the elements as other methods have done:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<h2 id="heading-how-to-loop-through-an-array-with-a-forin-loop-in-javascript">How to Loop Through an Array with a <code>for…in</code> Loop in JavaScript</h2>
<p>The <code>for…in</code> loop is an easier way to loop through arrays as it gives us the key which we can now use to get the values from our array this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> scores) {
    <span class="hljs-built_in">console</span>.log(scores[i]);
}
</code></pre>
<p>This will output all the elements in our array:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<h2 id="heading-how-to-loop-through-an-array-with-a-forof-loop-in-javascript">How to Loop Through an Array with a <code>for…of</code> Loop in JavaScript</h2>
<p>The <code>for...of</code> Loop iterates over iterable objects such as arrays, sets, maps, strings, and so on. It has the same syntax as the <code>for...in</code> loop, but instead of getting the <code>key</code>, it gets the element itself.</p>
<p>This is one of the easiest methods for looping through an array and was introduced in later versions of JavaScript ES6.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">for</span> (score of scores) {
    console.log(score);
}
</code></pre>
<p>This gets each element of our array and we no longer need to make use of the index to get each element of our array:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<h2 id="heading-how-to-loop-through-an-array-with-a-foreach-loop-in-javascript">How to Loop Through an Array with a <code>forEach</code> Loop in JavaScript</h2>
<p>The array method <code>forEach()</code> loop's through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.</p>
<p>This is a more advanced method that can do much more than simply loop through each element, but you can also use it to loop through this way:</p>
<pre><code class="lang-js">scores.forEach(<span class="hljs-function">(<span class="hljs-params">score</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(score);
});
</code></pre>
<p>You can write this in one line this way:</p>
<pre><code class="lang-js">scores.forEach(<span class="hljs-function">(<span class="hljs-params">score</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(score));
</code></pre>
<p>And this will give us the same output as all previous methods:</p>
<pre><code class="lang-bash">22
54
76
92
43
33
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, we looked at six different/standard methods for looping through an array.</p>
<p>It is critical that you understand all of these methods and then determine which method is preferable for you, cleaner to use, and easier to read.</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript forEach() – JS Array For Each Loop Example ]]>
                </title>
                <description>
                    <![CDATA[ When working with arrays, there will be times when you need to loop or iterate through the array's values in order to either output or manipulate them. These arrays can hold any datatype, including objects, numbers, strings, and many others. In this ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-foreach-js-array-for-each-example/</link>
                <guid isPermaLink="false">66d45fd49208fb118cc6cfe4</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 16 Jun 2022 14:52:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/cover-template.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When working with arrays, there will be times when you need to loop or iterate through the array's values in order to either output or manipulate them.</p>
<p>These arrays can hold any datatype, including objects, numbers, strings, and many others.</p>
<p>In this article, we'll look at how you can use the JavaScript <code>forEach()</code> array method to loop through all types of arrays, as well as how it differs from the for loop method.</p>
<p>There are many iteration methods in JavaScript, including the <code>forEach()</code> method, and they almost all perform the same function with minor differences. It is entirely up to you whether or not to use a specific loop method, but it is important that we understand each of them and how they work.</p>
<h2 id="heading-javascript-foreach">JavaScript forEach()</h2>
<p>The <code>forEach()</code> array method loops through any array, executing a provided function once for each array element in ascending index order. This function is referred to as a callback function.</p>
<blockquote>
<p><strong>Note:</strong> Arrays are collections of elements that can be of any datatype.</p>
</blockquote>
<h3 id="heading-syntax-and-parameters-of-a-foreach-loop">Syntax and Parameters of a forEach() Loop</h3>
<p>Here are the standard ways of writing the forEach Loop:</p>
<pre><code class="lang-js">array.forEach(callbackFunction);
array.forEach(callbackFunction, thisValue);
</code></pre>
<p>The callback function can accept up to three different arguments, though not all of them are required. Here are some examples of <code>forEach()</code> loops that use both the normal function and the ES6 method to declare the callback function:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using only Current Element</span>
array.forEach(<span class="hljs-function">(<span class="hljs-params">currentElement</span>) =&gt;</span> { <span class="hljs-comment">/* ... */</span> })
array.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentElement</span>) </span>{ <span class="hljs-comment">/* ... */</span> })

<span class="hljs-comment">// Using only Current Element and Index</span>
array.forEach(<span class="hljs-function">(<span class="hljs-params">currentElement, index</span>) =&gt;</span> { <span class="hljs-comment">/* ... */</span> })
array.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentElement, index</span>) </span>{ <span class="hljs-comment">/* ... */</span> })

<span class="hljs-comment">// Using only Current Element, Index and array</span>
array.forEach(<span class="hljs-function">(<span class="hljs-params">currentElement, index, array</span>) =&gt;</span> { <span class="hljs-comment">/* ... */</span> })
array.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentElement, index, array</span>)</span>{ <span class="hljs-comment">/* ... */</span> })

<span class="hljs-comment">// Using all parameters with thisValue (value of this in the callback) </span>
array.forEach(<span class="hljs-function">(<span class="hljs-params">currentElement, index, array</span>) =&gt;</span> { <span class="hljs-comment">/* ... */</span> }, thisValue)
array.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentElement, index, array</span>) </span>{ <span class="hljs-comment">/* ... */</span> }, thisValue)
</code></pre>
<p>The syntax above may appear confusing, but it is the general syntax for writing a forEach loop depending on the value you want to use. Let's go over all of the parameters that we used:</p>
<ul>
<li><code>callbackFunction</code>: The callback function is a function that is executed only once for each element and can accept the following arguments to be used within the callback function:</li>
</ul>
<ol>
<li><p><code>currentElement</code>: The current element, as the name implies, is the element in the array that is being processed at the time the loop occurs. It is the only necessary argument.</p>
</li>
<li><p><code>index</code>: index is an optional argument that carries the index of the <code>currentElement</code>.</p>
</li>
<li><p><code>array</code>: The array is an optional argument that returns the array that was passed to the <code>forEach()</code> method.</p>
</li>
</ol>
<ul>
<li><code>thisValue</code>: This is an optional parameter that specifies the value that will be used in the callback function.</li>
</ul>
<p>In summary, the <code>forEach()</code> array iteration method accepts a callback function that holds arguments that can be used within the callback function for each array item, such as the array item, the <code>index</code> of the item, and the entire array.</p>
<h2 id="heading-foreach-examples-in-javascript">forEach() Examples in JavaScript</h2>
<p>Before we look at other possible examples, let's look at all of the arguments we passed into the callback function and what they could be used for.</p>
<h3 id="heading-how-to-use-the-currentelement-argument">How to use the <code>currentElement</code> Argument</h3>
<p>Assume we have an array of employee details that includes their names, age, salary amount, and currency:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> staffsDetails = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Jam Josh"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">44</span>, <span class="hljs-attr">salary</span>: <span class="hljs-number">4000</span>, <span class="hljs-attr">currency</span>: <span class="hljs-string">"USD"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Justina Kap"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">34</span>, <span class="hljs-attr">salary</span>: <span class="hljs-number">3000</span>, <span class="hljs-attr">currency</span>: <span class="hljs-string">"USD"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Chris Colt"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">37</span>, <span class="hljs-attr">salary</span>: <span class="hljs-number">3700</span>, <span class="hljs-attr">currency</span>: <span class="hljs-string">"USD"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Jane Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">salary</span>: <span class="hljs-number">4200</span>, <span class="hljs-attr">currency</span>: <span class="hljs-string">"USD"</span> }
];
</code></pre>
<p>If we want to display all of the names individually with some words around them, we can use the <code>forEach()</code> method as follows:</p>
<pre><code class="lang-js">staffsDetails.forEach(<span class="hljs-function">(<span class="hljs-params">staffDetail</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> sentence = <span class="hljs-string">`I am <span class="hljs-subst">${staffDetail.name}</span> a staff of Royal Suites.`</span>;
  <span class="hljs-built_in">console</span>.log(sentence);
});
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash"><span class="hljs-string">"I am Jam Josh a staff of Royal Suites."</span>
<span class="hljs-string">"I am Justina Kap a staff of Royal Suites."</span>
<span class="hljs-string">"I am Chris Colt a staff of Royal Suites."</span>
<span class="hljs-string">"I am Jane Doe a staff of Royal Suites."</span>
</code></pre>
<p><strong>Note:</strong> We could also destructure the <code>currentElement</code> value in case it’s an object that contains key/value pairs this way:</p>
<pre><code class="lang-js">staffsDetails.forEach(<span class="hljs-function">(<span class="hljs-params">{ name }, index</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> sentence = <span class="hljs-string">`I am <span class="hljs-subst">${name}</span> a staff of Royal Suites.`</span>;
  <span class="hljs-built_in">console</span>.log(sentence);
});
</code></pre>
<h3 id="heading-how-to-use-the-index-argument">How to use the <code>index</code> Argument</h3>
<p>We could also get the <code>index</code> of each array item by just making use of the unbuilt index argument this way:</p>
<pre><code class="lang-js">staffsDetails.forEach(<span class="hljs-function">(<span class="hljs-params">staffDetail, index</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> sentence = <span class="hljs-string">`index <span class="hljs-subst">${index}</span> : I am <span class="hljs-subst">${staffDetail.name}</span> a staff of Royal Suites.`</span>;
  <span class="hljs-built_in">console</span>.log(sentence);
});
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash"><span class="hljs-string">"index 0 : I am Jam Josh a staff of Royal Suites."</span>
<span class="hljs-string">"index 1 : I am Justina Kap a staff of Royal Suites."</span>
<span class="hljs-string">"index 2 : I am Chris Colt a staff of Royal Suites."</span>
<span class="hljs-string">"index 3 : I am Jane Doe a staff of Royal Suites."</span>
</code></pre>
<h3 id="heading-how-to-use-the-array-argument">How to use the <code>array</code> Argument</h3>
<p>The <code>array</code> argument is the third argument which holds the original array that is being iterated over. For example, we could try displaying the value in our console this way:</p>
<pre><code class="lang-js">staffsDetails.forEach(<span class="hljs-function">(<span class="hljs-params">staffDetail, index, array</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(array);
});
</code></pre>
<p>This would output the entire array 4 times since we have 4 items and the iteration runs 4 times. Let’s do it for an array with a few values so I can add the output here:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>];

scores.forEach(<span class="hljs-function">(<span class="hljs-params">score, index, array</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(array);
});
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[12,55,70]
[12,55,70]
[12,55,70]
</code></pre>
<p>So far, we've used every argument of the callback function. Let's look at some other examples to fully understand how it works before doing a quick comparison with the for loop method.</p>
<h3 id="heading-how-to-add-all-values-in-an-array-of-numbers-with-foreach">How to Add All Values in An Array of Numbers with <code>forEach()</code></h3>
<p>Suppose we have an array of <code>scores</code>. We could use the <code>forEach()</code> array method to loop through and help add up these numbers:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

<span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
scores.forEach(<span class="hljs-function">(<span class="hljs-params">score</span>) =&gt;</span> {
  total += score;
});

<span class="hljs-built_in">console</span>.log(total);
</code></pre>
<p>Recall that earlier on, we were making use of an array of staff details. Now let’s try adding all the staff member's salaries together to see how it works with objects:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">let</span> totalSalary = 0;
staffsDetails.forEach(({salary}) =&gt; {
  totalSalary += salary;
});

console.log(totalSalary + <span class="hljs-string">" USD"</span>); // <span class="hljs-string">"14900 USD"</span>
</code></pre>
<p><strong>Note:</strong> We destructed the <code>currentElement</code>’s Object.</p>
<h3 id="heading-how-to-use-conditionals-in-a-foreach-callback-function">How to Use Conditionals in a <code>forEach()</code> Callback Function</h3>
<p>When looping through arrays, we may want to check for specific conditions, as is commonly done with the for loop method. We can pass these conditions into our callback function or any other operation we want to run on each array item.</p>
<p>For example, if we only want to show the names of people whose salaries are greater than or equal to <code>4000</code> from the array of staff details we declared earlier, we can do the following:</p>
<pre><code class="lang-js">staffsDetails.forEach(<span class="hljs-function">(<span class="hljs-params">{name, salary}</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(salary &gt;= <span class="hljs-number">4000</span>){
    <span class="hljs-built_in">console</span>.log(name);
  }
});
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash"><span class="hljs-string">"Jam Josh"</span>
<span class="hljs-string">"Jane Doe"</span>
</code></pre>
<h2 id="heading-comparing-foreach-with-a-for-loop">Comparing forEach() with a for Loop</h2>
<p>The for loop is very similar to the forEach method, but each possess some features that are unique to them such as:</p>
<h3 id="heading-break-out-and-continue-in-a-loop">Break out and continue in a Loop</h3>
<p>When looping through an array, we may want to either break out or continue the loop when a certain condition is met (meaning we skip). This is possible with the <code>break</code> and <code>continue</code> instruction, but it does not work with the <code>forEach()</code> method, as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

scores.forEach(<span class="hljs-function">(<span class="hljs-params">score</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(score);

  <span class="hljs-keyword">if</span> (score === <span class="hljs-number">70</span>) 
    <span class="hljs-keyword">break</span>;
});
</code></pre>
<p>This will throw a syntax error of <code>Illegal break statement</code>. This applies also to the continue instruction which would also throw an <code>Illegal continue statement: no surrounding iteration statement</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

scores.forEach(<span class="hljs-function">(<span class="hljs-params">score</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (score === <span class="hljs-number">70</span>) 
    <span class="hljs-keyword">continue</span>;

  <span class="hljs-built_in">console</span>.log(score);
});
</code></pre>
<p>But fortunately this works with the for loop method perfectly:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; scores.length; i++) {
  <span class="hljs-built_in">console</span>.log(scores[i]);

  <span class="hljs-keyword">if</span> (scores[i] === <span class="hljs-number">70</span>) 
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">12
55
70
</code></pre>
<p>And the same with the <code>continue</code> instruction:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; scores.length; i++) {
  <span class="hljs-keyword">if</span> (scores[i] === <span class="hljs-number">70</span>) 
    <span class="hljs-keyword">continue</span>;

  <span class="hljs-built_in">console</span>.log(scores[i]);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">12
55
47
</code></pre>
<h3 id="heading-array-with-missing-elements">Array with Missing elements</h3>
<p>Another important comparison to make is in a situation whereby the array we are iterating over has some missing values/array items as seen below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsScores = [<span class="hljs-number">70</span>, , <span class="hljs-number">12</span>, <span class="hljs-number">55</span>, , <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];
</code></pre>
<p>This could be due to a developer error or something else, but these two methods take two different approaches to looping through these types of arrays. The for loop returns undefined where there are missing values, whereas the <code>forEach()</code> method skips them.</p>
<p><strong>For Loop</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsScores = [<span class="hljs-number">70</span>, , <span class="hljs-number">12</span>, <span class="hljs-number">55</span>, , <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; studentsScores.length; i++) {
  <span class="hljs-built_in">console</span>.log(studentsScores[i]);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">70
undefined
12
55
undefined
70
47
</code></pre>
<p><strong>forEach()</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsScores = [<span class="hljs-number">70</span>, , <span class="hljs-number">12</span>, <span class="hljs-number">55</span>, , <span class="hljs-number">70</span>, <span class="hljs-number">47</span>];

studentsScores.forEach(<span class="hljs-function">(<span class="hljs-params">stundentScore</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(stundentScore);
});
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">70
12
55
70
47
</code></pre>
<p><strong>Note:</strong> Async/Await does not work with the <code>forEach()</code> array method but works with the for loop method.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we learned how to use the <code>forEach()</code> array method, which allows us to loop through an array of any type of item. It also allows us to write cleaner, more readable code than the for loop.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript For Loop – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Loops are a programming concept that we constantly encounter and implement as JavaScript developers. And many developers are familiar with loops, but not everyone understands how they work and why or when they should use a specific type of loop. In t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-for-loops/</link>
                <guid isPermaLink="false">66d45fd2264384a65d5a9580</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 27 May 2022 16:32:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/for-loops.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Loops are a programming concept that we constantly encounter and implement as JavaScript developers.</p>
<p>And many developers are familiar with loops, but not everyone understands how they work and why or when they should use a specific type of loop.</p>
<p>In this article, we will learn what for loops are, how they work, and why we use them. We'll also keep in mind that there are several types of loops, each of which performs a specific function even though they can almost all perform the same common function.</p>
<h2 id="heading-what-are-loops">What are Loops?</h2>
<p>Loops are computer programs that execute a set of instructions or a block of code a certain number of times without having to write it again until a certain condition is met. In other words, loops let your code execute one or more statements as many times as desired.</p>
<p>Again, there are many types of loops, but we will only look at the for loop in this article.</p>
<p>Almost every high-level programming language, including JavaScript, has a for loop. We're only going to look at JavaScript in this article, and we'll look at its syntax and some examples.</p>
<h3 id="heading-for-loops-in-javascript">For Loops in JavaScript</h3>
<p>The for loop is an iterative statement which you use to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.</p>
<p><img src="https://paper-attachments.dropbox.com/s_3315FAFA14C012362B87C753E4A1C2D25C00228882CEE2A5B63A9FDA99BA4B77_1653509464069_for+loop+flowchart+1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flowchart for the for loop</em></p>
<h3 id="heading-syntax-of-a-for-loop">Syntax of a for loop</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (initialExpression; condition; updateExpression) {
    <span class="hljs-comment">// for loop body: statement</span>
}
</code></pre>
<p>The code block above is the standard syntax used by for loop. Let's look at each parameter to see what it means and what it does:</p>
<ul>
<li><p><code>initialExpression</code>: This is used to set the value of a counter variable, and it is only evaluated once, before the loop starts. Depending on the scope, these counter variables are usually declared with the <code>var</code> or <code>let</code> keywords.</p>
</li>
<li><p><code>condition</code>: This is a constant-evaluation expression that determines whether the loop should be executed. In simple terms, if this condition returns true, the for loop's block of code is executed. If it returns false, the for loop is terminated.</p>
</li>
<li><p><code>updateExpression</code>: This is commonly used to update or increment the <code>initialExpression</code> counter variable. In other words, when the condition is true, it updates the value of the <code>initialExpression</code>.</p>
</li>
</ul>
<p>In summary, the for loop causes the <code>initialExpression</code> variable, which is set to a starting value, to increase or decrease in response to the <code>updateExpression</code> as long as the condition is met. Finally, the statement, will always be executed if the condition evaluates to true.</p>
<h2 id="heading-for-loop-examples-in-javascript">For Loop Examples in JavaScript</h2>
<p>At this point, we now understand what loops are, so let’s take a look at some examples and see how we can use loops.</p>
<h3 id="heading-how-to-display-text-multiple-times">How to Display Text Multiple Times</h3>
<p>Let’s start by displaying some text several times until our condition is met.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">"John Doe"</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi, my name is "</span> + name);
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash"><span class="hljs-string">"Hi, my name is John Doe"</span>
<span class="hljs-string">"Hi, my name is John Doe"</span>
<span class="hljs-string">"Hi, my name is John Doe"</span>
</code></pre>
<p>Here is how the program processed this loop:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iteration</td><td>Variable</td><td>Condition: i &lt; 3</td><td>Action &amp; variable update</td></tr>
</thead>
<tbody>
<tr>
<td>1st</td><td>i = 0</td><td>true</td><td>Hi, my name is John Doe is printed.</td></tr>
<tr>
<td>2nd</td><td>i = 1</td><td>true</td><td>Hi, my name is John Doe is printed.</td></tr>
<tr>
<td>3rd</td><td>i = 2</td><td>true</td><td>Hi, my name is John Doe is printed.</td></tr>
<tr>
<td>4th</td><td>i=3</td><td>false</td><td>The loop is terminated.</td></tr>
</tbody>
</table>
</div><p><strong>Note:</strong> The loop is terminated because 3 is not less than 3, so it returned <code>false</code>.</p>
<h3 id="heading-how-to-display-a-sequence-of-numbers-with-a-for-loop">How to Display a Sequence of Numbers with a For Loop</h3>
<p>This time around, let’s display a sequence of numbers by displaying the iteration value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
    <span class="hljs-built_in">console</span>.log(i);  <span class="hljs-comment">// printing the value of i</span>
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">2
3
4
5
</code></pre>
<p>Here is how the program processed this loop:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iteration</td><td>Variable</td><td>Condition: i &lt;= 5</td><td>Action&amp; variable update</td></tr>
</thead>
<tbody>
<tr>
<td>1st</td><td>i = 2</td><td>true</td><td>2 is printed.</td></tr>
<tr>
<td>2nd</td><td>i = 3</td><td>true</td><td>3 is printed.</td></tr>
<tr>
<td>3rd</td><td>i = 4</td><td>true</td><td>4 is printed.</td></tr>
<tr>
<td>5th</td><td>i = 5</td><td>true</td><td>5 is printed.</td></tr>
<tr>
<td>6th</td><td>i = 6</td><td>false</td><td>The loop is terminated.</td></tr>
</tbody>
</table>
</div><p><strong>Note:</strong> The loop is terminated because 6 is not less than or equal to 5, so the condition returns false.</p>
<h3 id="heading-how-to-display-a-sequence-of-even-numbers">How to Display a Sequence of Even Numbers</h3>
<p>Let’s now display a sequence of even numbers only by displaying the iteration value:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= <span class="hljs-number">10</span>; i+=<span class="hljs-number">2</span>) {
    <span class="hljs-built_in">console</span>.log(i);  <span class="hljs-comment">// printing the value of i</span>
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">2
4
6
8
10
</code></pre>
<p>Here is how the program processed this loop:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iteration</td><td>Variable</td><td>Condition: i &lt;= 10</td><td>Action &amp; variable update</td></tr>
</thead>
<tbody>
<tr>
<td>1st</td><td>i = 2</td><td>true</td><td>2 is printed.</td></tr>
<tr>
<td>2nd</td><td>i = 4</td><td>true</td><td>4 is printed.</td></tr>
<tr>
<td>3rd</td><td>i = 6</td><td>true</td><td>6 is printed.</td></tr>
<tr>
<td>5th</td><td>i = 8</td><td>true</td><td>8 is printed.</td></tr>
<tr>
<td>6th</td><td>i = 10</td><td>true</td><td>10 is printed.</td></tr>
<tr>
<td>7th</td><td>i = 12</td><td>false</td><td>The loop is terminated.</td></tr>
</tbody>
</table>
</div><p>Suppose we want to obtain the odd numbers. All we have to do is change the <code>initialExpression</code> to equal <code>1</code> or any odd number we wish to start from as seen below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i+=<span class="hljs-number">2</span>) {
    <span class="hljs-built_in">console</span>.log(i);  <span class="hljs-comment">// printing the value of i</span>
}
</code></pre>
<h3 id="heading-how-to-break-a-for-loop-operation">How to Break a For Loop Operation</h3>
<p>So far, we have seen how to create a for loop, but it’s also important to mention that we can break out of a loop using <code>break</code>. The break statement is used to terminate the loop immediately when it is encountered.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++) {    
    <span class="hljs-keyword">if</span> (i == <span class="hljs-number">5</span>) {
        <span class="hljs-keyword">break</span>;
    }
    <span class="hljs-built_in">console</span>.log(i);
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">1
2
3
4
</code></pre>
<h3 id="heading-how-to-display-the-sum-of-natural-numbers">How to Display the Sum of Natural Numbers</h3>
<p>Let’s now loop from 1-10 and then add these numbers together as the iteration is increased:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
    sum += i;  <span class="hljs-comment">// This is same as: sum = sum + i</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The sum of 1 to 10 is: '</span>, sum); <span class="hljs-comment">// "The sum of 1 to 10 is:  55"</span>
</code></pre>
<p><strong>Note:</strong> We are adding <code>console.log(…)</code> outside the loop, so it only gives us the final output when the loop is terminated.</p>
<p>We can also decide to use variables to set the max number of our condition this way:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> n = <span class="hljs-number">10</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= n; i++) {
    sum += i;  <span class="hljs-comment">// this is same as: sum = sum + i</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The sum of 1 to 10 is: '</span>, sum); <span class="hljs-comment">// "The sum of 1 to 10 is:  55"</span>
</code></pre>
<h3 id="heading-how-to-perform-infinite-loops-with-a-for-loop">How to Perform Infinite Loops with a For Loop</h3>
<p>This can hang your system, because it continues to run until the memory is full, since the condition always evaluates as true.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &gt; <span class="hljs-number">0</span>; i++) {
    <span class="hljs-comment">// block of code</span>
}
</code></pre>
<h3 id="heading-how-to-loop-through-an-array-to-check-for-odd-and-even-numbers">How to Loop Through an Array to Check for Odd and Even Numbers</h3>
<p>Most times you will be working with arrays, so let’s see how we can loop through an array of numbers to output all odd and even numbers:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">44</span>, <span class="hljs-number">64</span>, <span class="hljs-number">55</span>, <span class="hljs-number">24</span>, <span class="hljs-number">32</span>, <span class="hljs-number">55</span>, <span class="hljs-number">19</span>, <span class="hljs-number">17</span>, <span class="hljs-number">74</span>, <span class="hljs-number">22</span>, <span class="hljs-number">23</span>];
<span class="hljs-keyword">var</span> evenNumbers = [];
<span class="hljs-keyword">var</span> oddNumbers = [];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
    <span class="hljs-keyword">if</span> (numbers[i] % <span class="hljs-number">2</span> != <span class="hljs-number">1</span>) {
        evenNumbers.push(numbers[i]);
    } <span class="hljs-keyword">else</span> {
        oddNumbers.push(numbers[i]);
    }
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The even numbers are: "</span> + evenNumbers); <span class="hljs-comment">// "The even numbers are: 4,44,64,24,32,74,22"</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The odd numbers are: "</span> + oddNumbers); <span class="hljs-comment">// "The odd numbers are: 1,55,55,19,17,23"</span>
</code></pre>
<h3 id="heading-how-to-loop-through-an-array-of-numbers-to-get-the-maximum-and-minimum-number">How to Loop Through an Array of Numbers to Get the Maximum and Minimum Number</h3>
<p>Finally, before we round up this article, let’s see how to get the maximum and minimum number from an array with for loop:</p>
<p><strong>Maximum:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">44</span>, <span class="hljs-number">64</span>, <span class="hljs-number">55</span>, <span class="hljs-number">24</span>, <span class="hljs-number">32</span>, <span class="hljs-number">55</span>, <span class="hljs-number">19</span>, <span class="hljs-number">17</span>, <span class="hljs-number">74</span>, <span class="hljs-number">22</span>, <span class="hljs-number">23</span>];
<span class="hljs-keyword">var</span> max = <span class="hljs-number">0</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
    <span class="hljs-keyword">if</span> (numbers[i] &gt; max) {
        max = numbers[i];
    }
}

<span class="hljs-built_in">console</span>.log(max); <span class="hljs-comment">// 74</span>
</code></pre>
<p><strong>Minimum:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> numbers = [<span class="hljs-number">4</span>, <span class="hljs-number">44</span>, <span class="hljs-number">64</span>, <span class="hljs-number">55</span>, <span class="hljs-number">24</span>, <span class="hljs-number">32</span>, <span class="hljs-number">55</span>, <span class="hljs-number">19</span>, <span class="hljs-number">17</span>, <span class="hljs-number">74</span>, <span class="hljs-number">22</span>, <span class="hljs-number">23</span>];
<span class="hljs-keyword">var</span> min = numbers[<span class="hljs-number">0</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
    <span class="hljs-keyword">if</span> (numbers[i] &lt; min) {
        min = numbers[i];
    }
}

<span class="hljs-built_in">console</span>.log(min); <span class="hljs-comment">// 4</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we learned what a JavaScript loop is and looked at some examples.</p>
<p>It is important to understand that there are many other types of loops, including the while loop, which is best used when you don't know the number of iterations. Otherwise, always use the for loop when you do know the number of iterations.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python For Loop Example – How to Write Loops in Python ]]>
                </title>
                <description>
                    <![CDATA[ If you are just getting started in Python, for loops are one of the fundamentals you should learn how to use. In the Python programming language, for loops are also called “definite loops” because they perform the instruction a certain number of time... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-for-loop-example-how-to-write-loops-in-python/</link>
                <guid isPermaLink="false">66adf1d3007ea266ef6d9240</guid>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Tue, 26 Apr 2022 19:01:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/forLoop.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you are just getting started in Python, for loops are one of the fundamentals you should learn how to use.</p>
<p>In the Python programming language, for loops are also called “definite loops” because they perform the instruction a certain number of times. </p>
<p>This is in contrast to while loops, or indefinite loops, which execute an action until a condition is met and they are told to stop.</p>
<p>For loops are useful when you want to execute the same code for each item in a given sequence. With a for loop, you can iterate over any iterable data such as lists, sets, tuples, dictionaries, ranges, and even strings.</p>
<p>In this article, I will show you how the for loop works in Python. You will also learn about the keyword you can use while writing loops in Python.</p>
<h2 id="heading-basic-syntax-of-a-for-loop-in-python">Basic Syntax of a For Loop in Python</h2>
<p>The basic syntax or the formula of for loops in Python looks like this:</p>
<pre><code class="lang-py"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> data:
    do something
</code></pre>
<ul>
<li><code>i</code> stands for the iterator. You can replace it with anything you want</li>
<li><code>data</code> stands for any iterable such as lists, tuples, strings, and dictionaries</li>
<li>The next thing you should do is type a colon and then indent. You can do this with a tab or press the spacebar 4 times.</li>
</ul>
<h2 id="heading-python-for-loop-example">Python For Loop Example</h2>
<p>As I mentioned above, you can iterate over any iterable data with a for loop.</p>
<h3 id="heading-how-to-iterate-over-a-string-with-a-for-loop">How to Iterate Over a String with a For Loop</h3>
<p>You can iterate over string as shown below:</p>
<pre><code class="lang-py">name = <span class="hljs-string">"freeCodeCamp"</span>

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> name:
    print(letter)
</code></pre>
<p>This will print all the letters in the string individually:</p>
<pre><code class="lang-py"><span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># f</span>
<span class="hljs-comment"># r</span>
<span class="hljs-comment"># e</span>
<span class="hljs-comment"># e</span>
<span class="hljs-comment"># C</span>
<span class="hljs-comment"># o</span>
<span class="hljs-comment"># d</span>
<span class="hljs-comment"># e</span>
<span class="hljs-comment"># C</span>
<span class="hljs-comment"># a</span>
<span class="hljs-comment"># m</span>
<span class="hljs-comment"># p</span>
</code></pre>
<p>What if you want to print the letters in a single line? </p>
<p>You can do that by passing whitespace to the <code>end</code> parameter right inside the <code>print()</code> statement. With this, you tell Python that you want whitespace instead of a new line in the console.</p>
<pre><code class="lang-py">name = <span class="hljs-string">"freeCodeCamp"</span>

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> name:
    print(letter, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: f r e e C o d e C a m p</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-a-list-with-a-for-loop">How to Iterate Over a List with a For Loop</h3>
<p>To iterate over a list with the for loop, define the list as separate data and then write the for loop, like this:</p>
<pre><code class="lang-py">lang_list = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"PHP"</span>, <span class="hljs-string">"Rust"</span>, <span class="hljs-string">"Solidity"</span>, <span class="hljs-string">"Assembly"</span>]

<span class="hljs-keyword">for</span> lang <span class="hljs-keyword">in</span> lang_list:
    print(lang)

<span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># Python</span>
<span class="hljs-comment"># JavaScript</span>
<span class="hljs-comment"># PHP       </span>
<span class="hljs-comment"># Rust      </span>
<span class="hljs-comment"># Solidity  </span>
<span class="hljs-comment"># Assembly</span>
</code></pre>
<p>Don’t forget that you can print all the items in one line with the end keyword:</p>
<pre><code class="lang-py">lang_list = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"PHP"</span>, <span class="hljs-string">"Rust"</span>, <span class="hljs-string">"Solidity"</span>, <span class="hljs-string">"Assembly"</span>]

<span class="hljs-keyword">for</span> lang <span class="hljs-keyword">in</span> lang_list:
    print(lang, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: Python JavaScript PHP Rust Solidity Assembly</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-a-tuple-with-a-for-loop">How to Iterate Over a Tuple with a For Loop</h3>
<p>A tuple is an iterable data type in Python, so you can write a for loop to print the items in it.</p>
<pre><code class="lang-py">footballers_tuple = (<span class="hljs-string">"Ronaldo"</span>, <span class="hljs-string">"Mendy"</span>, <span class="hljs-string">"Lukaku"</span>, <span class="hljs-string">"Lampard"</span>, <span class="hljs-string">"Messi"</span>, <span class="hljs-string">"Pogba"</span>)

<span class="hljs-keyword">for</span> footballer <span class="hljs-keyword">in</span> footballers_tuple:
    print(footballer, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: Ronaldo Mendy Lukaku Lampard Messi Pogba</span>
</code></pre>
<p>You can get a little more creative by making people know that the names in the tuple represent some active footballers:</p>
<pre><code class="lang-py">footballers_tuple = (<span class="hljs-string">"Ronaldo"</span>, <span class="hljs-string">"Mendy"</span>, <span class="hljs-string">"Lukaku"</span>, <span class="hljs-string">"Lampard"</span>, <span class="hljs-string">"Messi"</span>, <span class="hljs-string">"Pogba"</span>)

<span class="hljs-keyword">for</span> footballer <span class="hljs-keyword">in</span> footballers_tuple:
    print(footballer, <span class="hljs-string">"is an active footballer"</span>)

<span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># Ronaldo is an active footballer</span>
<span class="hljs-comment"># Mendy is an active footballer  </span>
<span class="hljs-comment"># Lukaku is an active footballer </span>
<span class="hljs-comment"># Lampard is an active footballer</span>
<span class="hljs-comment"># Messi is an active footballer  </span>
<span class="hljs-comment"># Pogba is an active footballer</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-a-set-with-for-loop">How to Iterate Over a Set with For Loop</h3>
<p>You can print the individual items in a set with the for loop like this:</p>
<pre><code class="lang-py">soc_set = {<span class="hljs-string">"Twitter"</span>, <span class="hljs-string">"Facebook"</span>, <span class="hljs-string">"Instagram"</span>, <span class="hljs-string">"Quora"</span>}

<span class="hljs-keyword">for</span> platform <span class="hljs-keyword">in</span> soc_set:
    print(platform, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: Twitter Facebook Instagram Quora</span>
</code></pre>
<p>You can also get more creative with this. In the example below, with the help of an if statement, I was able to print the platform that is about to be bought by Elon Musk:</p>
<pre><code class="lang-py">soc_set = {<span class="hljs-string">"Twitter"</span>, <span class="hljs-string">"Facebook"</span>, <span class="hljs-string">"Instagram"</span>, <span class="hljs-string">"Quora"</span>}

<span class="hljs-keyword">for</span> platform <span class="hljs-keyword">in</span> soc_set:
    <span class="hljs-keyword">if</span>(platform == <span class="hljs-string">"Twitter"</span>):
        print(platform, <span class="hljs-string">"is about to be bought by Elon Musk."</span>)

<span class="hljs-comment"># Output: Twitter is about to be bought by Elon Musk.</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-a-dictionary-with-for-loop">How to Iterate Over a Dictionary with For Loop</h3>
<p>Dictionary is a collection of data in key-value pair form. A dictionary is probably the data type you can do the most with using a for loop.</p>
<p>For example, you can get the keys in a dictionary by looping through it:</p>
<pre><code class="lang-py">fcc_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>,
           <span class="hljs-string">"type"</span>: <span class="hljs-string">"non-profit"</span>, 
           <span class="hljs-string">"mode"</span>: <span class="hljs-string">"remote"</span>, 
           <span class="hljs-string">"paid"</span>: <span class="hljs-string">"no"</span>}

<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> fcc_dict:
    print(key, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: name type mode paid</span>
</code></pre>
<p>You can also get the values with a for loop:</p>
<pre><code class="lang-py"><span class="hljs-keyword">for</span> values <span class="hljs-keyword">in</span> fcc_dict.values():
    print(values , end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: freeCodeCamp non-profit remote no</span>
</code></pre>
<p>You can get the keys and values in a dictionary with a for loop:</p>
<pre><code class="lang-py">fcc_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>,
           <span class="hljs-string">"type"</span>: <span class="hljs-string">"non-profit"</span>, 
           <span class="hljs-string">"mode"</span>: <span class="hljs-string">"remote"</span>, 
           <span class="hljs-string">"paid"</span>: <span class="hljs-string">"no"</span>}

<span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> fcc_dict.items():
    print(key, value)

<span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># name freeCodeCamp</span>
<span class="hljs-comment"># type non-profit</span>
<span class="hljs-comment"># mode remote</span>
<span class="hljs-comment"># paid no</span>
</code></pre>
<p>I don’t know any other programming language that can do this in such an elegant and clean way!</p>
<p>You can even replace the <code>key, value</code> with anything you want and it’ll still work as expected:</p>
<pre><code class="lang-py">fcc_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>,
           <span class="hljs-string">"type"</span>: <span class="hljs-string">"non-profit"</span>, 
           <span class="hljs-string">"mode"</span>: <span class="hljs-string">"remote"</span>, 
           <span class="hljs-string">"paid"</span>: <span class="hljs-string">"no"</span>}

<span class="hljs-keyword">for</span> a, b <span class="hljs-keyword">in</span> fcc_dict.items():
    print(a, b)

<span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># name freeCodeCamp</span>
<span class="hljs-comment"># type non-profit</span>
<span class="hljs-comment"># mode remote</span>
<span class="hljs-comment"># paid no</span>
</code></pre>
<p>You can also execute a particular instruction when the iteration reaches a certain key. In the example below, I printed “freeCodeCamp is a non-profit organization” to the console when the key equals <code>type</code>:</p>
<pre><code class="lang-py">fcc_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"freeCodeCamp"</span>,
           <span class="hljs-string">"type"</span>: <span class="hljs-string">"non-profit"</span>, 
           <span class="hljs-string">"mode"</span>: <span class="hljs-string">"remote"</span>, 
           <span class="hljs-string">"paid"</span>: <span class="hljs-string">"no"</span>}

<span class="hljs-keyword">for</span> a, b <span class="hljs-keyword">in</span> fcc_dict.items():
    <span class="hljs-comment"># print(a, b)</span>
    <span class="hljs-keyword">if</span> a == <span class="hljs-string">"type"</span>:
        print(<span class="hljs-string">"freeCodeCamp is a non-profit organization"</span>)

<span class="hljs-comment"># Output: freeCodeCamp is a non-profit organization</span>
</code></pre>
<h3 id="heading-how-to-iterate-over-numbers-with-for-loop-by-using-the-range-function">How to Iterate Over Numbers with For Loop by Using the <code>range()</code> Function</h3>
<p>Iterating through an integer throws the popular <code>int object not iterable</code> error in Python. But you can get around this by using the <code>range()</code> function to specify that you want to iterate through the numbers between two certain numbers.</p>
<p>The range<code>()</code> function accepts two arguments, so you can loop through the numbers within the two arguments. Example below:</p>
<pre><code class="lang-py"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>):
    print(i, end=<span class="hljs-string">""</span>)

<span class="hljs-comment"># Output: 123456789</span>
</code></pre>
<p>You can extract the range to a variable and it would still work:</p>
<pre><code class="lang-py">my_num = range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>)

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> my_num:
    print(i, end=<span class="hljs-string">""</span>)

<span class="hljs-comment"># Output: 123456789</span>
</code></pre>
<p>Note that the result is inclusive of the first number but exclusive of the second number.</p>
<h2 id="heading-how-to-use-the-break-keyword-in-python">How to Use the Break Keyword in Python</h2>
<p>You can use the <code>break</code> keyword to stop the loop before it ends.</p>
<p>In the example below, the execution did not get to Solidity and Assembly because I broke out of the loop when <code>lang</code> was equal to Rust:</p>
<pre><code class="lang-py">lang_list = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"PHP"</span>, <span class="hljs-string">"Rust"</span>, <span class="hljs-string">"Solidity"</span>, <span class="hljs-string">"Assembly"</span>]

<span class="hljs-keyword">for</span> lang <span class="hljs-keyword">in</span> lang_list:
    <span class="hljs-keyword">if</span> lang == <span class="hljs-string">"Rust"</span>:
        <span class="hljs-keyword">break</span>
    print(lang, end=<span class="hljs-string">" "</span>)
<span class="hljs-comment"># Output: Python JavaScript PHP</span>
</code></pre>
<h2 id="heading-how-to-use-the-continue-keyword-in-python">How to Use the Continue Keyword in Python</h2>
<p>You can use the <code>continue</code> keyword to skip the current iteration and continue with the rest.</p>
<p>In the example below, with the continue keyword, I made the loop skip PHP and continue the loop after it:</p>
<pre><code class="lang-py">lang_list = [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"PHP"</span>, <span class="hljs-string">"Rust"</span>, <span class="hljs-string">"Solidity"</span>, <span class="hljs-string">"Assembly"</span>]

<span class="hljs-keyword">for</span> lang <span class="hljs-keyword">in</span> lang_list:
    <span class="hljs-keyword">if</span> lang == <span class="hljs-string">"PHP"</span>:
        <span class="hljs-keyword">continue</span>
    print(lang, end=<span class="hljs-string">" "</span>)

<span class="hljs-comment"># Output: Python JavaScript Rust Solidity Assembly</span>
</code></pre>
<h2 id="heading-how-to-use-the-else-keyword-in-python">How to Use the Else Keyword in Python</h2>
<p>You can use the <code>else</code> keyword to specify that a block of code should run after the loop is done:</p>
<pre><code class="lang-py"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    print(i)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Do + ne = Done"</span>)

<span class="hljs-comment"># Output: </span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 7</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># Do + ne = Done</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The for loop in Python doesn’t look as complicated as it is in many other programming languages. But its implementation remains powerful when it runs.</p>
<p>For loop is a very powerful feature of Python with which you can get a lot done. </p>
<p>Thank you for reading. If you find this article helpful, share it with your friends and family!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ For Loop in Java + forEach Loop Syntax Example ]]>
                </title>
                <description>
                    <![CDATA[ A loop in programming is a sequence of instructions that run continuously until a certain condition is met. In this article, we will learn about the for and forEach loops in Java. Syntax for a for loop in Java Here is the syntax for creating a for lo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/for-loop-in-java-foreach-loop-syntax-example/</link>
                <guid isPermaLink="false">66b0a2a93dc92ea6a5a091dc</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 07 Feb 2022 15:08:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/loop.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A loop in programming is a sequence of instructions that run continuously until a certain condition is met.</p>
<p>In this article, we will learn about the <code>for</code> and <code>forEach</code> loops in Java.</p>
<h2 id="heading-syntax-for-a-for-loop-in-java">Syntax for a <code>for</code> loop in Java</h2>
<p>Here is the syntax for creating a <code>for</code> loop:</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span> (initialization; condition; increment/decrement) {
   <span class="hljs-comment">// code to be executed</span>
}
</code></pre>
<p>Let's break down some of the keywords above.</p>
<p><strong>for</strong> specifies that we are going to create a loop. It is followed by parenthesis nesting everything required for our loop to work. </p>
<p><strong>initialization</strong> defines an initial variable as the starting point of the loop, usually an integer (whole number). </p>
<p><strong>condition</strong> specifies the number of times the loop is supposed to run.</p>
<p><strong>increment/decrement</strong> increases/decreases the value of the initial variable every time the loop runs. As the increment/decrement happens, the variable's value tends towards the specified <strong>condition</strong>.</p>
<p>Note that each keyword is separated by a semi colon (;).</p>
<p>Here are a few examples:</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> x = <span class="hljs-number">1</span>; x &lt;=<span class="hljs-number">5</span>; x++) {
  System.out.println(x);
}

<span class="hljs-comment">/*
1
2
3
4
5
*/</span>
</code></pre>
<p>In the example above, the initial variable is <code>x</code> with a value of 1. The loop will keep running as long as the value of <code>x</code> is less than or equal to 5 – this is the condition. <code>x++</code> increases the value of <code>x</code> after each run.</p>
<p>We went on to print the value of <code>x</code> which stops after 5 because the condition has been met. Incrementing to 6 is impossible because it is greater than and not equal to 5. </p>
<p>In the next example, we will use the <code>for</code> loop to print all the values of an array.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span>[] randomNumbers = {<span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>};
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; randomNumbers.length; i++) {
  System.out.println(randomNumbers[i]);
}

<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 7</span>
</code></pre>
<p>This is almost the same as the last example. Here, we used the length of the array as the condition and the initial variable's value as zero because the index number of the first element of an array is zero.</p>
<h2 id="heading-syntax-for-a-foreach-loop-in-java">Syntax for a <code>forEach</code> loop in Java</h2>
<p>You use a <code>forEach</code> loop specifically for looping through the elements of an array. Here is what the syntax looks like:</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span> (dataType variableName : arrayName) {
  <span class="hljs-comment">// code to be executed</span>
}
</code></pre>
<p>You'll notice that the syntax here is shorter than the <code>for</code> loop's. The <code>forEach</code> loop also starts with the <strong>for</strong> keyword.</p>
<p>Instead of initializing a variable with a value, we first specify the <strong>data type</strong> (this must match the array's data type). This is followed by our <strong>variable's name</strong> and the <strong>name of the array</strong> separated by a colon. </p>
<p>Here is an example to help you understand the syntax better:</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span>[] randomNumbers = {<span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>};
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : randomNumbers) {
  System.out.println(x + <span class="hljs-number">1</span>);
}

<span class="hljs-comment">/*
3
6
5
8
*/</span>
</code></pre>
<p>In this example, we looped through each element and increased their initial value by 1. </p>
<p>By default, the loop will stop once it has iterated through all the elements in the array. This means that we are not required to pass any value to our variable or specify any condition to terminate the loop.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we learned what loops are as well as the syntax for creating a <code>for</code> and <code>forEach</code> loop in Java. We also saw a few examples that helped us understand when and how to use them. </p>
<p>Happy Coding!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ For Loops in C – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In programming, you'll use loops when you need to repeat a block of code multiple times.  These repetitions of the same block of code a certain number of times are called iterations. And there's a looping condition that decides the number of iteratio... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/for-loops-in-c/</link>
                <guid isPermaLink="false">66bb8b2e6b3bd8d6bf25ae50</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 03 Nov 2021 15:56:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/for.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In programming, you'll use loops when you need to repeat a block of code multiple times. </p>
<p>These repetitions of the same block of code a certain number of times are called <em>iterations</em>. And there's a looping condition that decides the number of iterations. </p>
<p>The <code>for</code> and the <code>while</code> loops are widely used in almost all programming languages.</p>
<p>In this tutorial, you'll learn about <code>for</code> loops in C. In particular, you'll learn:</p>
<ul>
<li>the syntax to use <code>for</code> loops, </li>
<li>how <code>for</code> loops work in C, and</li>
<li>the possibility of an infinite <code>for</code> loop.</li>
</ul>
<p>Let's get started.</p>
<h2 id="heading-c-for-loop-syntax-and-how-it-works">C <code>for</code> Loop Syntax and How it Works</h2>
<p>In this section, you'll learn the basic syntax of <code>for</code> loops in C.</p>
<p>The general syntax to use the <code>for</code> loop is shown below:</p>
<pre><code><span class="hljs-keyword">for</span>(initialize; check_condition; update)
    {
        <span class="hljs-comment">//do this</span>
    }
</code></pre><p>In the above syntax:</p>
<ul>
<li><code>initialize</code> is the initialization statement – the loop control variable is initialized here.</li>
<li><code>check_condition</code> is the condition that determines if the looping should continue. </li>
</ul>
<blockquote>
<p>So long as <code>check_condition</code> is <em>true,</em> the body of the loop is executed.</p>
</blockquote>
<ul>
<li>The <code>update</code> statement updates the loop control variable after the statements in the loop body are executed.</li>
</ul>
<h3 id="heading-control-flow-in-c-for-loops">Control Flow in C <code>for</code> Loops</h3>
<p>The control flow is as follows:</p>
<ol>
<li>Initialize the counter – the <code>initialize</code> statement is executed. This happens only once, at the beginning of the loop.</li>
<li>Check if the looping condition is true – the expression <code>check_condition</code> is evaluated. If the condition is <em>true</em>, go to step 3. If <em>false</em>, exit the loop.</li>
<li>Execute statements in the loop body.</li>
<li>Update the counter – the <code>update</code> statement is executed.</li>
<li>Go to step 2.</li>
</ol>
<p>This is also illustrated below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/image-66.png" alt="Image" width="600" height="400" loading="lazy">
<em>C For Loop</em></p>
<p>Now that you have an idea of how <code>for</code> loops work, let's take a simple example to see the for loop in action.</p>
<h3 id="heading-c-for-loop-example">C <code>for</code> Loop Example</h3>
<p>Let's write a simple <code>for</code> loop to count up to 10, and print the count value during each pass through the loop.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
   <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>; count &lt;= <span class="hljs-number">10</span>; count++)
   {
       <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>,count);
   }
   <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In the above code snippet,</p>
<ul>
<li><code>count</code> is the counter variable, and it's initialized to <code>0</code>.</li>
<li>The test condition here is <code>count &lt;= 10</code>. Therefore, <code>count</code> can be at most 10 for looping to continue.</li>
<li>In the body of the loop, the value of <code>count</code> is printed out.</li>
<li>And the value of <code>count</code> is increased by 1.</li>
<li>The control then reaches the condition <code>count &lt;= 10</code> and the looping continues if the condition evaluates to true.</li>
<li>In this example, the looping condition <code>count &lt; = 10</code> evaluates to <em>false</em> when the count value is 11 – and your loop terminates. </li>
</ul>
<p>And here's the output:</p>
<pre><code><span class="hljs-comment">//Output</span>
<span class="hljs-number">0</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
<span class="hljs-number">6</span>
<span class="hljs-number">7</span>
<span class="hljs-number">8</span>
<span class="hljs-number">9</span>
<span class="hljs-number">10</span>
</code></pre><p>When using loops, you should always make sure that your loop <em>does terminate</em> at some point. </p>
<blockquote>
<p>You know that the looping continues so long as <code>check_condition</code> is <em>true</em>. And the looping stops once <code>check_condition</code> becomes <em>false</em>. But what happens when your looping condition is <em>always true</em>? </p>
</blockquote>
<p>Well, that's when you run into an infinite loop – your loop goes on forever, until your program crashes, or your system powers off.😢</p>
<p>You'll learn more about infinite loops in the next section.</p>
<h2 id="heading-infinite-for-loop">Infinite <code>for</code> Loop</h2>
<p>When your loop doesn't stop and keeps running forever, you'll have an infinite loop. Let's take a few examples to understand this.</p>
<p>▶ In the <code>for</code> loop construct, if you don't specify the test condition (<code>check_condition</code>), it's assumed to be <em>true</em> by default. </p>
<p>As a result, your condition never becomes false. And the loop will keep running forever until you force stop the program.</p>
<p>This is shown in the code snippet below:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; ; i++) <span class="hljs-comment">//test condition is not mentioned</span>
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d "</span>,i);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>▶ Here's another example. </p>
<p>You initialize the counter variable <code>i</code> to 10. And <code>i</code> increases by 1 after every iteration. </p>
<p>Notice how the test condition is <code>i &gt; 0</code>. Won't the value of <code>i</code> be always greater than 0?</p>
<p>So you have another infinite loop, as shown:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">10</span>; i &gt; <span class="hljs-number">0</span> ; i++) <span class="hljs-comment">//test condition is always TRUE</span>
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d "</span>,i);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>▶ In this example, your counter variable <code>i</code> is initialized to <code>0</code>. But it decreases by 1 with every iteration. </p>
<p>As a result, <code>i</code> always less than 10. So the condition <code>i &lt; 10</code> is <em>always true</em>, and you'll have an infinite loop.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span> ; i--) <span class="hljs-comment">//test condition is always TRUE</span>
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d"</span>,i);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>To avoid running into infinite loops, you should define the looping condition correctly.</p>
<p>If you're a beginner, asking yourself the following questions may help.</p>
<blockquote>
<p>What do I want this loop to do?<br>How many times do I want the loop to run?<br>When should my loop stop? </p>
</blockquote>
<p>And then you can go ahead and define your loop construct accordingly. 🙂</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you found this tutorial helpful.</p>
<p>To sum up, you've learned the syntax of <code>for</code> loops and how they work. You also know how to anticipate the possibility of infinite <code>for</code> loops and how to avoid them by defining your looping condition carefully. </p>
<p>See you all soon in another tutorial. Until then, happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
