<?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[ Abhilekh gautam - 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[ Abhilekh gautam - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 11:06:27 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/abhilekh/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Python Coding Challenges For Beginner Developers – Code and Explanations ]]>
                </title>
                <description>
                    <![CDATA[ Learning Python can be challenging, especially if you're not actually writing enough code. As a beginner, you may go through lessons and tutorials without practicing on your own – and this makes it harder to learn the language. The truth is, you cann... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-coding-challenges-for-beginners/</link>
                <guid isPermaLink="false">66baef8eff91e9c03fcb30a3</guid>
                
                    <category>
                        <![CDATA[ coding challenge ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Tue, 04 Jun 2024 20:18:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/pexels-pixabay-139392.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Learning Python can be challenging, especially if you're not actually writing enough code. As a beginner, you may go through lessons and tutorials without practicing on your own – and this makes it harder to learn the language.</p>
<p>The truth is, you cannot truly learn programming without writing code. It is through this process that you learn new things and discover how small errors, like missing a quote or space, can frustrate you for hours.</p>
<p>No course can teach you the intricacies of Python the way finding and solving errors does.</p>
<p>That's why coding challenges are important if you are starting your coding journey. They help you implement your knowledge in practice and boost your confidence.</p>
<p>So to help you start coding more, here are eight Python challenges you can try as a beginner. </p>
<p><strong>And here's a tip</strong>: really try to solve the challenge on your own after reading through the question/prompt. If you get stuck, then you can look at the code below and the explanation to help you figure it out.</p>
<h2 id="heading-here-are-the-challenges">Here Are the Challenges:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-python-challenge-1-check-if-a-list-is-sorted">Python Challenge #1: Check if a List is Sorted</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-2-convert-binary-numbers-to-decimal">Python Challenge #2: Convert Binary number to decimal</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-3-loves-me-loves-me-not">Python Challenge #3: Loves Me, Loves Me Not</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-4-the-tribonacci-sequence-challenge">Python Challenge #4: The Tribonacci Sequence Challenge</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-5-hide-a-credit-card-number">Python Challenge #5: Hide a Credit Card Number</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-6-spongecase">Python Challenge #6: SpongeCase</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-7-caesar-encryption">Python Challenge #7: Caesar Encryption</a></li>
<li><a class="post-section-overview" href="#heading-python-challenge-8-is-the-product-divisible-by-the-sum">Python Challenge #8: Is the Product Divisible by the Sum?</a></li>
</ol>
<p>All of these challenges help you in enhancing your problem-solving and algorithmic thinking skills. You'll also gain experience with writing and testing code to ensure correctness and efficiency.</p>
<h2 id="heading-python-challenge-1-check-if-a-list-is-sorted">Python Challenge #1: Check if a List is Sorted</h2>
<p>The challenge: Write a function that checks whether a given list of numbers is sorted in either ascending or descending order.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_sorted</span>(<span class="hljs-params">lst</span>):</span>
    asc, desc = <span class="hljs-literal">True</span>, <span class="hljs-literal">True</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(lst) - <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> lst[i] &gt; lst[i + <span class="hljs-number">1</span>]:
            asc = <span class="hljs-literal">False</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(lst) - <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> lst[i] &lt; lst[i + <span class="hljs-number">1</span>]:
            desc = <span class="hljs-literal">False</span>
    <span class="hljs-keyword">return</span> asc <span class="hljs-keyword">or</span> desc
</code></pre>
<h3 id="heading-code-explanation">Code explanation:</h3>
<p>In the above code, we define a function <code>is_sorted</code> that takes in a <code>list</code> as a parameter. We initialize two booleans, <code>asc</code> (for ascending) and <code>desc</code> (for descending) to <code>True</code>. </p>
<p>We then iterate through the list. If the <code>i</code>th element of the list is greater than the <code>(i+1)</code>th element, the <code>asc</code> flag is set to <code>False</code>, indicating that the list is not sorted in ascending order.</p>
<p>Then we iterate through the list again. If the <code>i</code>th element of the list is smaller than the <code>i+1</code> th element, the <code>desc</code> flag is set to <code>False</code>, indicating that the list is not sorted in descending order.</p>
<p>If any element is found to be greater than the next element, the <code>asc</code> flag is set to <code>False</code>. Within the loop, we check to see if the <code>i</code>th element of the list is greater than the <code>i+1</code> th element. </p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(lst) - <span class="hljs-number">1</span>):
    <span class="hljs-keyword">if</span> lst[i] &lt; lst[i + <span class="hljs-number">1</span>]:
        desc = <span class="hljs-literal">False</span>
</code></pre>
<p>We return <code>True</code> if either <code>asc</code> or <code>desc</code> is <code>True</code>. This means that the list is sorted, either in ascending or descending order.</p>
<h2 id="heading-python-challenge-2-convert-binary-numbers-to-decimal">Python Challenge #2: Convert Binary Numbers to Decimal</h2>
<p>The challenge: Write a function that converts a binary number to its decimal equivalent.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">binary_to_decimal</span>(<span class="hljs-params">binary</span>):</span>
    decimal, i = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span>(binary != <span class="hljs-number">0</span>):
        dec = binary % <span class="hljs-number">10</span>
        decimal = decimal + dec * pow(<span class="hljs-number">2</span>, i)
        binary = binary//<span class="hljs-number">10</span>
        i += <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> decimal
</code></pre>
<h3 id="heading-code-explanation-1">Code explanation:</h3>
<p>In the above code, we define a function <code>binary_to_decimal</code> that takes a <code>binary</code> number as a parameter. We then initialized the variables <code>decimal</code> and <code>i</code> to <code>0</code>.</p>
<p>The variable <code>decimal</code> is used to store the resulting decimal value and the variable <code>i</code> represents the current position when processing a binary number, starting from <code>0</code>.</p>
<p>We loop through each binary digit until all digits of the binary number become <code>0</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">while</span> binary != <span class="hljs-number">0</span>:
</code></pre>
<p>Now, we extract the least significant digit of the current binary number using the modulus operator.</p>
<pre><code class="lang-python">dec = binary % <span class="hljs-number">10</span>
</code></pre>
<p>And then we convert the extracted digit to its decimal equivalent by multiplying it by 2 power raised to <code>i</code>.</p>
<pre><code class="lang-python">decimal = decimal + dec * pow(<span class="hljs-number">2</span>, i)
</code></pre>
<p>Then we remove the processed digit:</p>
<pre><code class="lang-python">Binary = binary // <span class="hljs-number">10</span>
</code></pre>
<p>And increment the position <code>i</code> to process the next binary digit:</p>
<pre><code class="lang-python">i += <span class="hljs-number">1</span>
</code></pre>
<p>Finally, we return the calculated decimal value.</p>
<h2 id="heading-python-challenge-3-loves-me-loves-me-not">Python Challenge #3: Loves Me, Loves Me Not</h2>
<p>The challenge: Given an integer n, print a string that alternates between the phrases "Loves me" and "Loves me not" for each number from 1 to n.</p>
<p>The sequence should start with "Loves me" and alternate accordingly.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">phrase_loves_me_not</span>(<span class="hljs-params">n</span>):</span>
    phrases = []
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>,n+<span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>:
            phrases.append(<span class="hljs-string">"Loves me"</span>)
        <span class="hljs-keyword">else</span>:
            phrases.append(<span class="hljs-string">"Loves me not"</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-string">", "</span>.join(phrases)
</code></pre>
<h3 id="heading-code-explanation-2">Code explanation:</h3>
<p>We define a function <code>phrase_loves_me_not</code> that takes a single parameter <code>n</code>.</p>
<p>Then, we initialize an empty list, <code>phrases</code>, which stores the result for each number from <code>1</code> to <code>n</code>.</p>
<p>We iterate from <code>1</code> to <code>n</code> inclusive:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, n+<span class="hljs-number">1</span>):
</code></pre>
<p>We then check for odd indices. If the number is odd, we append “Loves me” to the list ‘phrases’.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>:
    phrases.append(<span class="hljs-string">"Loves me"</span>)
</code></pre>
<p>For even indices, we append “Loves me not” in the list ‘phrases’.</p>
<pre><code class="lang-python"><span class="hljs-keyword">else</span>:
    phrases.append(<span class="hljs-string">"Loves me not"</span>)
</code></pre>
<p>We then use the <code>join</code> method to concatenate all the elements in the ‘phrases’ list into a single string and return that string.</p>
<p>Finally we return the resulting string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> <span class="hljs-string">", "</span>.join(phrases)
</code></pre>
<h2 id="heading-python-challenge-4-the-tribonacci-sequence-challenge">Python Challenge #4: The Tribonacci Sequence Challenge</h2>
<p>The "Tribonacci sequence" challenge is a twist on the famous Fibonacci sequence, where each number is the sum of the preceding three numbers.</p>
<p>For example, 0, 1, 1, 2, 4, 7 …</p>
<p>The challenge: Write a function that returns the nth number in the Tribonacci sequence.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find_nth_tribonacci</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-comment"># Base cases for n = 0, 1, 2</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    <span class="hljs-keyword">elif</span> n == <span class="hljs-number">1</span> <span class="hljs-keyword">or</span> n == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-comment"># Initialize the first three terms of the Tribonacci sequence</span>
    a, b, c = <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">3</span>, n + <span class="hljs-number">1</span>):
        next_term = a + b + c
        a, b, c = b, c, next_term
    <span class="hljs-keyword">return</span> c
</code></pre>
<h3 id="heading-code-explanation-3">Code explanation:</h3>
<p>First, we define a function named <code>find_nth_tribonacci</code> which takes a number <code>n</code> as a parameter.</p>
<p>We then define base cases as:</p>
<ul>
<li>If <code>n</code> is <code>0</code>, the function returns <code>0</code>.</li>
<li>If <code>n</code> is <code>1</code> or <code>2</code>, the function returns <code>1</code>.</li>
</ul>
<p>Note<em>:</em> These conditions handle the starting values of the Tribonacci sequence.</p>
<p>We then initialize the first three values of the Tribonacci sequence, from <code>n</code> = <code>0</code> to <code>n</code> = <code>2</code>.</p>
<pre><code class="lang-python">a, b, c = <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>
</code></pre>
<p>Then, we iterate from <code>3</code> to the number <code>n</code>, where we calculate the next term by summing the three preceding terms (<code>a</code>, <code>b</code>, and <code>c</code>). We also update the values of <code>a</code>, <code>b</code>, and <code>c</code> to the next set of three terms in the sequence.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">3</span>, n + <span class="hljs-number">1</span>):
    next_term = a + b + c
    a, b, c = b, c, next_term
</code></pre>
<p>At the end of the loop, <code>c</code> holds the value of the nth term in the Tribonacci sequence, so we return <code>c</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> c
</code></pre>
<h2 id="heading-python-challenge-5-hide-a-credit-card-number">Python Challenge #5: Hide a Credit Card Number</h2>
<p>Write a function that takes a credit card number and transforms it into a string where all digits except the last four are replaced with asterisks.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mask_credit_card</span>(<span class="hljs-params">card_number</span>):</span>
    card=str(card_number)
    <span class="hljs-keyword">return</span> <span class="hljs-string">"*"</span>*(len(card) - <span class="hljs-number">4</span>) + (card[<span class="hljs-number">-4</span>:])
</code></pre>
<h3 id="heading-code-explanation-4">Code explanation:</h3>
<p>We define a function <code>mask_credit_card</code> that takes <code>card_number</code> as a parameter.</p>
<p>First, we convert the number into a string.</p>
<pre><code class="lang-python">card = str(card_number)
</code></pre>
<p>Then to mask the card_number, we generate a string of asterisks with a length equal to the total number of digits in the credit card minus four. This masks all digits except the last four digits.</p>
<pre><code class="lang-python"><span class="hljs-string">"*"</span>*(len(card) - <span class="hljs-number">4</span>)
</code></pre>
<p>Then, we use the slice operation to retrieve the last four digits of the credit card number.</p>
<pre><code class="lang-python">card[<span class="hljs-number">-4</span>:]
</code></pre>
<p>Finally, we return the concatenated result of the asterisk string and the last four digits of the card number.</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> <span class="hljs-string">"*"</span>*(len(card) - <span class="hljs-number">4</span>) + card[<span class="hljs-number">-4</span>:]
</code></pre>
<h2 id="heading-python-challenge-6-spongecase">Python Challenge #6: SpongeCase</h2>
<p>SpongeCase is a style of text where letters alternately appear in lower and upper case. For example, the word in spongeCase would be sPoNgEcAsE.</p>
<p>The challenge: Write a function that converts the given string into spongcase.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">to_spongecase</span>(<span class="hljs-params">text</span>):</span>
    result = []
    i = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> text:
        <span class="hljs-keyword">if</span> char.isalpha():
            <span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
                result.append(char.lower())
            <span class="hljs-keyword">else</span>:
                result.append(char.upper())
            i += <span class="hljs-number">1</span>
        <span class="hljs-keyword">else</span>:
            result.append(char)

    <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>.join(result)
</code></pre>
<h3 id="heading-code-explanation-5">Code explanation:</h3>
<p>We define a function <code>to_spongecase</code> that takes a string <code>text</code> as a parameter.</p>
<p>Then we initialize an empty list result, and counter <code>i</code> to <code>0</code>.  </p>
<p>We iterate the function over each character char in the input string and check if the current character is alphabetic. </p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> text:
    <span class="hljs-keyword">if</span> char.isalpha():
</code></pre>
<p>If the character at index <code>i</code> (adjusted for only alphabetic characters) is even, we append the result with the character converted to lowercase.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
    result.append(char.lower())
</code></pre>
<p>If the index is odd, we append the result with the character converted to uppercase.</p>
<pre><code class="lang-python"><span class="hljs-keyword">else</span>:
    result.append(char.upper())
</code></pre>
<p>After processing an alphabetic character, the index <code>i</code> is incremented.</p>
<p>In case of non-alphabetic characters, append them to the result list as they appear, without alternating their case.</p>
<p>After all characters have been processed, we combine them back into a string using <code>join</code> .</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> <span class="hljs-string">""</span>.join(result)
</code></pre>
<h2 id="heading-python-challenge-7-caesar-encryption">Python Challenge #7: Caesar Encryption</h2>
<p>Caesar Encryption (also known as the Caesar Cipher) is a simple encryption technique that works by shifting the letters in the plaintext message by a certain number of positions.</p>
<p>The challenge: Create a function that has two parameters – a string to be encoded and an integer representing the number of positions each letter should be shifted.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">caesar_encryption</span>(<span class="hljs-params">text, shift</span>):</span>
    result = <span class="hljs-string">""</span>
    <span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> text:
        <span class="hljs-keyword">if</span> char.isalpha():
            start = ord(<span class="hljs-string">'A'</span>) <span class="hljs-keyword">if</span> char.isupper() <span class="hljs-keyword">else</span> ord(<span class="hljs-string">'a'</span>)
            shifted = (ord(char) - start + shift) % <span class="hljs-number">26</span> + start
            result += chr(shifted)
        <span class="hljs-keyword">else</span>:
            result += char
    <span class="hljs-keyword">return</span> result
</code></pre>
<h3 id="heading-code-explanation-6">Code explanation:</h3>
<p>We define a function <code>caesar_encryption</code> that takes two parameters: a string <code>text</code> and an integer <code>shift</code>.</p>
<p>Then we initialize an empty string to accumulate the encoded characters.</p>
<pre><code class="lang-python">result = <span class="hljs-string">""</span>
</code></pre>
<p>Next, we loop through each character in the input string text.</p>
<p>For alphabetic characters, we calculate the new character after applying the shift.</p>
<p>Then we add the non-alphabetic characters like numbers to the result unchanged.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> text:
    <span class="hljs-keyword">if</span> char.isalpha():
        start = ord(<span class="hljs-string">'A'</span>) <span class="hljs-keyword">if</span> char.isupper() <span class="hljs-keyword">else</span> ord(<span class="hljs-string">'a'</span>)
    shifted = (ord(char) - start + shift) % <span class="hljs-number">26</span> + start
</code></pre>
<p>So how do we calculate the new character?</p>
<p>We determine the ASCII value of 'A' for uppercase or 'a' for lowercase letters.</p>
<p>First, convert the character to its ASCII code, normalize to a 0-25 range by subtracting the start and adding the shift, and then wrap it around using modulo 26 to ensure it stays within alphabet bounds.</p>
<p>Finally, we add the start back to map it to the correct ASCII range.</p>
<p>Convert the shifted value back to a character using <code>chr()</code> and add to the result.</p>
<pre><code class="lang-python">result += chr(shifted)
</code></pre>
<p>After all characters are processed, return the encoded string.</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> result
</code></pre>
<h2 id="heading-python-challenge-8-is-the-product-divisible-by-the-sum">Python Challenge #8: Is the Product Divisible by the Sum?</h2>
<p>The challenge: Create a function that takes a list of integers and returns whether the product of those integers is divisible by their sum or not.</p>
<p>The function should return <code>True</code> if the product of all the integers in the list is divisible by their sum and <code>False</code> otherwise.</p>
<p>Here's the code solution:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_product_divisible_by_sum</span>(<span class="hljs-params">numbers</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> numbers:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    product = <span class="hljs-number">1</span>
    summation = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers:
        product *= num
        summation += num

    <span class="hljs-keyword">if</span> summation == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">return</span> product % summation == <span class="hljs-number">0</span>
</code></pre>
<h3 id="heading-code-explanation-7">Code explanation:</h3>
<p>First, we define a function <code>is_product_divisible_by_sum</code>, which takes a list of integers, <code>numbers</code>, as a parameter.</p>
<p>Then, we check if the input list <code>numbers</code> is empty. If it is empty, return <code>False</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> numbers:
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Else, initialize two variables: <code>product</code> to <code>1</code> and <code>summation</code> to <code>0</code>.</p>
<pre><code class="lang-python">product = <span class="hljs-number">1</span>
summation = <span class="hljs-number">0</span>
</code></pre>
<p>Iterate over each number in the list to calculate the total product and sum of all numbers in the list.</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers:
    product *= num
    summation += num
</code></pre>
<p>After calculating the sum, check if the sum is zero. Dividing by zero is undefined in mathematics and would raise an error in programming, so return <code>False</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> summation == <span class="hljs-number">0</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Finally, check if the product is divisible by the sum using the modulus operator <code>%</code>.</p>
<p>Here, if the remainder is zero, that is the product is perfectly divisible by the sum, return <code>True</code>. Otherwise, return <code>False</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">return</span> product % summation == <span class="hljs-number">0</span>
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>These are just a few challenges that can help you build your problem-solving skills. I would suggest you try these challenges on your own.</p>
<p>If you want to solve more challenges, you can try out the following platforms:</p>
<ul>
<li><a target="_blank" href="https://leetcode.com/">Leetcode</a></li>
<li><a target="_blank" href="https://app.programiz.pro/community-challenges">Programiz PRO Community Challenges</a></li>
<li>Exercism</li>
</ul>
<p>They are free and help you build your logical skills with hands-on experience.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Virtual Inheritance? ]]>
                </title>
                <description>
                    <![CDATA[ C++ supports the concept of inheritance – that is, a class can inherit properties from other classes.  But sometimes you might need to use what is commonly referred as virtual inheritance.  In this article we will discuss when you might need to use v... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-virtual-inheritance/</link>
                <guid isPermaLink="false">66baef9166a27aea1d2a4019</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 21:09:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-ruiyang-zhang-3717242.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ supports the concept of inheritance – that is, a class can inherit properties from other classes. </p>
<p>But sometimes you might need to use what is commonly referred as virtual inheritance. </p>
<p>In this article we will discuss when you might need to use virtual inheritance and how to implement it in C++.</p>
<h2 id="heading-what-is-virtual-inheritance">What is Virtual Inheritance?</h2>
<p>In C++, a class can inherit from multiple classes which is commonly referred as multiple inheritance. But this can cause problems sometimes, as you can have multiple instances of the base class.</p>
<p>To tackle this problem, C++ uses a technique which ensures only one instance of a base class is present. That technique is referred as virtual inheritance.</p>
<h3 id="heading-example-of-when-virtual-inheritance-is-useful">Example of When Virtual Inheritance is Useful</h3>
<p>Let's look at an example and then explain what's happening:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
     <span class="hljs-comment">//some other things</span>
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C { <span class="hljs-comment">// inherit from both class B and C</span>
    <span class="hljs-comment">// something can go here..</span>
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Let's see what's going on here:</p>
<p>First, we have a class <code>A</code> which is being inherited by two classes <code>B</code> and <code>C</code>.  Both of these classes are then inherited by another class <code>D</code>. </p>
<p>Inside our <code>main</code> function, we create a new instance (object) of the class <code>D</code>. We then simply tried to print the value of <code>x</code> to the console. </p>
<p>It might look legit to access the value of <code>x</code> here, because class <code>D</code> is inherited from both <code>B</code> and <code>C</code> which are ultimately inherited from the class <code>A</code>. </p>
<p>But when you try to compile the above program, you get the following error:</p>
<pre><code>&lt;source&gt;: In <span class="hljs-function"><span class="hljs-keyword">function</span> '<span class="hljs-title">int</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>)':
&lt;<span class="hljs-title">source</span>&gt;:21:22: <span class="hljs-title">error</span>: <span class="hljs-title">request</span> <span class="hljs-title">for</span> <span class="hljs-title">member</span> '<span class="hljs-title">x</span>' <span class="hljs-title">is</span> <span class="hljs-title">ambiguous</span>
   21 |     <span class="hljs-title">std</span>::<span class="hljs-title">cout</span> &lt;&lt; <span class="hljs-title">obj</span>.<span class="hljs-title">x</span> &lt;&lt; <span class="hljs-title">std</span>::<span class="hljs-title">endl</span>;
      |                      ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>: <span class="hljs-title">candidates</span> <span class="hljs-title">are</span>: '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'
    5 |      <span class="hljs-title">int</span> <span class="hljs-title">x</span> = 5;
      |          ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>:                 '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'</span>
</code></pre><p>The error is pretty clear: <strong><code>error:</code></strong> <code>request for member '</code><strong><code>x</code></strong><code>' is ambiguous</code>. Let's now see how the request is ambiguous. </p>
<p>If we draw the hierarchical class structure, it should become pretty clear:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/hierarchial-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hierarchical class structure</em></p>
<p>We can see that we have multiple instances of the class <code>A</code>. So the request to the variable <code>x</code> becomes ambiguous because the compiler doesn't know which instance we are referring to – is it through <code>B</code> or through <code>C</code> ? That's the real problem. </p>
<h3 id="heading-one-way-to-solve-this-problem">One Way to Solve this Problem</h3>
<p>One way to tackle the problem is to use the <code>scope-resolution operator (::)</code> with which we can directly specify which instance of <code>A</code> we want.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.B::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.C::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Using the  <code>scope-resolution operator</code> we explicitly told the compiler which instance of <code>A</code> we referred to.</p>
<p>The main problem with this approach is that it doesn't solve our problem – because our main problem is having multiple instances of class <code>A</code>, and we still have that. So we need to look around for some other solutions.</p>
<p>And the other solution is to use virtual inheritance. Let's see how it works now.</p>
<h3 id="heading-how-to-use-virtual-inheritance">How to Use Virtual Inheritance</h3>
<p>To inherit virtually we simply add a keyword <code>virtual</code> before our base class name in the derived class declaration like this:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
</code></pre>
<p>The addition of the <code>virtual</code> keyword indicates that we want to inherit from <code>A</code> virtually. </p>
<p>Inheriting virtually guarantees that there will be only one instance of the base class among the derived classes that virtually inherited it. After the changes, our hierarchical class structure becomes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/diamond-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Hierarchical structure after virtual inheritance</em></p>
<p>So now if we try to compile the following code, it will successfully compile.</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C{

};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

}
</code></pre>
<p>So with the introduction of <code>virtual</code> inheritance we are able to remove the ambiguities we had earlier.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article you learnt about the problem you might face while inheriting a class and a way to solve it using <code>virtual</code> inheritance.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Your Own Browser Extension [Example Project Included] ]]>
                </title>
                <description>
                    <![CDATA[ In this article we will talk about Browser extensions – what they are, how they work, and how you can build your own. We will finish by actually writing our own extension (Super Fun!) which allows us to copy any code snippet to our clipboard with a c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/write-your-own-browser-extensions/</link>
                <guid isPermaLink="false">66baef94d453cb5eb795159f</guid>
                
                    <category>
                        <![CDATA[ Browsers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chrome extension ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Tue, 02 Nov 2021 15:57:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/browsers.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article we will talk about Browser extensions – what they are, how they work, and how you can build your own.</p>
<p>We will finish by actually writing our own extension (Super Fun!) which allows us to copy any code snippet to our clipboard with a click of a single button.</p>
<p>To continue with this article:</p>
<ul>
<li><p>You need to have a basic understanding of JavaScript.</p>
</li>
<li><p>You need the Firefox browser (or any other browser will also work)</p>
</li>
</ul>
<h2 id="heading-what-is-a-browser-extension">What is a Browser Extension?</h2>
<p>A browser extension is something you add to your browser which enhances your browsing experience by extending the capacity of your browser.</p>
<p>As an example, think about an ad blocker which you might have installed on your device. This makes your browsing experience better by blocking ads when you surf the web.</p>
<h2 id="heading-how-to-write-your-own-basic-browser-extension">How to Write Your Own Basic Browser Extension</h2>
<p>Now let's start by writing a very basic extension.</p>
<p>To begin, we'll create a folder inside which we create a file named <code>manifest.json</code>.</p>
<h3 id="heading-what-is-a-manifest-file">What is a manifest file?</h3>
<p>A manifest file is a must have file in any browser extension. This file contains basic data about our extension like name, version, and so on.</p>
<p>Now inside the <code>manifest.json</code> file copy the following snippet:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"manifest_version"</span>:<span class="hljs-number">2</span>,
  <span class="hljs-attr">"version"</span>:<span class="hljs-string">"1.0"</span>,
  <span class="hljs-attr">"name"</span>:<span class="hljs-string">"Test"</span>,
}
</code></pre>
<p>[<strong>2025 Update</strong>: Chrome <a target="_blank" href="https://developer.chrome.com/docs/extensions/reference/manifest">currently only supports version 3</a> for manifest.json]</p>
<h3 id="heading-how-to-load-the-extension-file">How to load the extension file</h3>
<p>For Firefox users, follow these steps:</p>
<p>In the address bar, search for this:</p>
<pre><code class="lang-javascript">about:debugging#/runtime/<span class="hljs-built_in">this</span>-firefox
</code></pre>
<p>You will see an option to <em>Load Temporary Add-on</em>. Click on that option and choose the <code>manifest.json</code> file from the directory.</p>
<p>For Chrome users:</p>
<p>In the address bar search for this:</p>
<pre><code class="lang-javascript">chrome:<span class="hljs-comment">//extensions</span>
</code></pre>
<ul>
<li><p>Enable Developer Mode and switch into it.</p>
</li>
<li><p>Click the Load unpacked button and select the extension directory.</p>
</li>
</ul>
<p>Hurray! You've installed the extension successfully. But the extension doesn't do anything currently. Now let's add some functionality to our extension. To do this, we'll edit our <code>manifest.json</code> file like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"manifest_version"</span>:<span class="hljs-number">2</span>,
  <span class="hljs-attr">"version"</span>:<span class="hljs-string">"1.0"</span>,
  <span class="hljs-attr">"name"</span>:<span class="hljs-string">"Test"</span>,
  <span class="hljs-attr">"content_scripts"</span>:[
    {
     <span class="hljs-attr">"matches"</span>:[<span class="hljs-string">"&lt;all_urls&gt;"</span>],
     <span class="hljs-attr">"js"</span>:[<span class="hljs-string">"main.js"</span>]
    }
  ]
}
</code></pre>
<p>In the above code, we added a content script to <code>manifest.json</code>. Content scripts can manipulate the Document Object Model of the web page. We can inject JS (and CSS) into a web page using a content script.</p>
<p><code>"matches"</code> contains the list of domains and subdomains where the content script should be added and <code>js</code> is an array of the JS files to be loaded.</p>
<p>Now inside the same directory create a <code>main.js</code> file and add the following code:</p>
<pre><code class="lang-js">alert(<span class="hljs-string">"The test extension is up and running"</span>)
</code></pre>
<p>Now reload the extension and when you visit any <code>URLs</code> you will see an alert message.</p>
<p><strong>Don't forget to reload the extension anytime you edit the code.</strong></p>
<h2 id="heading-how-to-customize-your-browser-extension">How to Customize Your Browser Extension</h2>
<p>Now let's have some more fun with our extension.</p>
<p>What we are going to do now is create a web extension that changes all the images of a webpage we visit to an image we choose.</p>
<p>For this, just add any image to the current directory and change the <code>main.js</code> file to:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The extension is up and running"</span>);

<span class="hljs-keyword">var</span> images = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'img'</span>)

<span class="hljs-keyword">for</span> (elt <span class="hljs-keyword">of</span> images){
   elt.src = <span class="hljs-string">`<span class="hljs-subst">${browser.runtime.getURL(<span class="hljs-string">"pp.jpg"</span>)}</span>`</span>
   elt.alt = <span class="hljs-string">'an alt text'</span>
}
</code></pre>
<p>Let's see whats going on here:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> images = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'img'</span>)
</code></pre>
<p>This line of code selects all the elements in the web page with the <code>img</code> tag .</p>
<p>Then we loop through the array images using a for loop where we change the <code>src</code> attribute of all the <code>img</code> elements to a URL with the help of the <code>runtime.getURL</code> function.</p>
<p>Here <code>pp.jpg</code> is the name of the image file in the current directory in my device.</p>
<p>We need to inform our content script about the <code>pp.jpg</code> file by editing the <code>manifest.json</code> file to:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"manifest_version"</span>:<span class="hljs-number">2</span>,
  <span class="hljs-string">"version"</span>:<span class="hljs-string">"1.0"</span>,
  <span class="hljs-string">"name"</span>:<span class="hljs-string">"Test"</span>,
  <span class="hljs-string">"content_scripts"</span>:[
   {
    <span class="hljs-string">"matches"</span>:[<span class="hljs-string">"&lt;all_urls&gt;"</span>],
    <span class="hljs-string">"js"</span>:[<span class="hljs-string">"main.js"</span>]
   }
  ],
  <span class="hljs-string">"web_accessible_resources"</span>: [
        <span class="hljs-string">"pp.jpg"</span>
  ]
}
</code></pre>
<p>Then just reload the extension and visit any URL you like. Now you should see all the images being changed to the image which is in your current working directory.</p>
<h3 id="heading-how-to-add-icons-to-your-extension">How to add icons to your extension</h3>
<p>Add the following code in the <code>manifest.json</code> file:</p>
<pre><code class="lang-json"><span class="hljs-string">"icons"</span>: {
  <span class="hljs-attr">"48"</span>: <span class="hljs-string">"icon-48.png"</span>,
  <span class="hljs-attr">"96"</span>: <span class="hljs-string">"icon-96.png"</span>
}
</code></pre>
<h3 id="heading-how-to-add-a-toolbar-button-to-your-extension">How to add a toolbar button to your extension</h3>
<p>Now we'll add a button located in the toolbar of your browser. Users can interact with the extension using this button.</p>
<p>To add a toolbar button, add the following lines to the <code>manifest.json</code> file:</p>
<pre><code class="lang-json"><span class="hljs-string">"browser_action"</span>:{
   <span class="hljs-attr">"default_icon"</span>:{
     <span class="hljs-attr">"19"</span>:<span class="hljs-string">"icon-19.png"</span>,
     <span class="hljs-attr">"38"</span>:<span class="hljs-string">"icon-38.png"</span>
   }
  }
</code></pre>
<p>All the image files should be present in your current directory.</p>
<p>Now, if we reload the extension we should see an icon for our extension in the toolbar of our browser.</p>
<h3 id="heading-how-to-add-listening-events-for-the-toolbar-button">How to add listening events for the toolbar button</h3>
<p>Maybe we want to do something when a user clicks the button – let's say we want to open a new tab every time the button is clicked.</p>
<p>For this, we'll again add the following to the <code>manifest.json</code> file:</p>
<pre><code class="lang-json"><span class="hljs-string">"background"</span>:{
        <span class="hljs-attr">"scripts"</span>:[<span class="hljs-string">"background.js"</span>]
  },
  <span class="hljs-string">"permissions"</span>:[
      <span class="hljs-string">"tabs"</span>
  ]
</code></pre>
<p>Then we'll create a new file named <code>background.js</code> in the current working directory and add the following lines in the file:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">openTab</span>(<span class="hljs-params"></span>)</span>{

    <span class="hljs-keyword">var</span> newTab = browser.tabs.create({
        <span class="hljs-attr">url</span>:<span class="hljs-string">'https://twitter.com/abhilekh_gautam'</span>,
        <span class="hljs-attr">active</span>:<span class="hljs-literal">true</span>
    })
}

browser.browserAction.onClicked.addListener(openTab)
</code></pre>
<p>Now reload the extension!</p>
<p>Whenever someone clicks the button, it calls the <code>openTab</code> function which opens a new tab with the URL that links to my twitter profile. Also, the active key, when set to true, makes the newly created tab the current tab.</p>
<p>Note that you can use APIs provided by browsers in the background script. For more about APIs refer to the following article: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API">Javacript APIs</a>.</p>
<p>Now that we've learned some of the basics of browser extensions, let's create an extension that we as developers can use in our daily lives.</p>
<h2 id="heading-final-project">Final Project</h2>
<p>Alright, now we're going to write something that will be useful for us in daily life. We'll create an extension that allows you to copy code snippets from StackOverflow with a single click. So our extension will add a <code>Copy</code> button to the webpage which copies the code to our clipboard.</p>
<h3 id="heading-demo">Demo</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/demo.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>First we'll create a new folder/directory, inside which we'll add a <code>manifest.json</code> file.</p>
<p>Add the following code to the file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"manifest_version"</span>:<span class="hljs-number">2</span>,
  <span class="hljs-attr">"version"</span>:<span class="hljs-string">"1.0"</span>,
  <span class="hljs-attr">"name"</span>:<span class="hljs-string">"copy code"</span>,
  <span class="hljs-attr">"content_scripts"</span>:[
    {
     <span class="hljs-attr">"matches"</span>:[<span class="hljs-string">"*://*.stackoverflow.com/*"</span>],
     <span class="hljs-attr">"js"</span>:[<span class="hljs-string">"main.js"</span>]
    }
  ]
}
</code></pre>
<p>Look at the <code>matches</code> inside the <code>content script</code> – the extension will only work for StackOverflow's domain and subdomain.</p>
<p>Now create another JavaScript file called <code>main.js</code> in the same directory and add the following lines of code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> arr =<span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"s-code-block"</span>)

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span> ; i &lt; arr.length ; i++){
 <span class="hljs-keyword">var</span> btn = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"button"</span>)
 btn.classList.add(<span class="hljs-string">"copy_code_button"</span>)
 btn.appendChild(<span class="hljs-built_in">document</span>.createTextNode(<span class="hljs-string">"Copy"</span>))
 arr[i].appendChild(btn)
 <span class="hljs-comment">//styling the button</span>
 btn.style.position = <span class="hljs-string">"relative"</span>

 <span class="hljs-keyword">if</span>(arr[i].scrollWidth === arr[i].offsetWidth &amp;&amp; arr[i].scrollHeight === arr[i].offsetHeight)
  btn.style.left = <span class="hljs-string">`<span class="hljs-subst">${arr[i].offsetWidth - <span class="hljs-number">70</span>}</span>px`</span>

  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(arr[i].scrollWidth != arr[i].offsetWidth &amp;&amp; arr[i].scrollHeight === arr[i].offsetWidth)
   btn.style.left = <span class="hljs-string">`<span class="hljs-subst">${arr[i].offsetWidth - <span class="hljs-number">200</span>}</span>px`</span>
 <span class="hljs-keyword">else</span> 
   btn.style.left = <span class="hljs-string">`<span class="hljs-subst">${arr[i].offsetWidth - <span class="hljs-number">150</span>}</span>px`</span>

 <span class="hljs-keyword">if</span>(arr[i].scrollHeight === arr[i].offsetHeight)
   btn.style.bottom = <span class="hljs-string">`<span class="hljs-subst">${arr[i].offsetHeight - <span class="hljs-number">50</span>}</span>px`</span>

 <span class="hljs-keyword">else</span>
   btn.style.bottom = <span class="hljs-string">`<span class="hljs-subst">${arr[i].scrollHeight - <span class="hljs-number">50</span>}</span>px`</span>
 <span class="hljs-comment">//end of styling the button</span>

   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Appended"</span>)
}
</code></pre>
<p>First of all, I selected all the elements with the class name <code>s-code-block</code> – but why? This is because when I inspected StackOverflow's site I found that all the code snippets were kept in a class with that name.</p>
<p>And then we loop through all those elements and append a button in those elements. Finally, we just position and style the button properly (the styling's not perfect yet – this is just a start).</p>
<p>When we load the extension using the process we went through above and visit StackOverflow, we should see a copy button.</p>
<h3 id="heading-how-to-add-functionality-to-the-button">How to add functionality to the button</h3>
<p>Now, when the button is clicked we want the entire snippet to be copied to our clip board. To do this, add the following line of code to the <code>main.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> button = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".copy_code_button"</span>)
 button.forEach(<span class="hljs-function">(<span class="hljs-params">elm</span>)=&gt;</span>{
  elm.addEventListener(<span class="hljs-string">'click'</span>,<span class="hljs-function">(<span class="hljs-params">e</span>)=&gt;</span>{
    navigator.clipboard.writeText(elm.parentNode.childNodes[<span class="hljs-number">0</span>].innerText)
    alert(<span class="hljs-string">"Copied to Clipboard"</span>)
  })
 })
</code></pre>
<p>First of all, we select all the buttons we have added to the site using <code>querySelectorAll</code>. Then we listen for the click event whenever the button is clicked.</p>
<pre><code class="lang-js">navigator.clipboard.writeText(elm.parentNode.childNodes[<span class="hljs-number">0</span>].innerText)
</code></pre>
<p>The above line of code copies the code to our clipboard. Whenever a snippet is copied we alert the user with the message <code>Copied to clipboard</code> and we are done.</p>
<h2 id="heading-final-words">Final Words</h2>
<p>Web Extensions can be useful in various way and I hope with the help of this article you will be able to write your own extensions.</p>
<p>All the code can be found in <a target="_blank" href="https://github.com/Abhilekhgautam/Copy-Code">this GitHub</a> repository. Don't forget to give a pull request anytime you come up with some good styling or a new feature like clipboard history and others.</p>
<p><strong>Happy Coding!</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Keywords You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ C++ has various keywords, and you should know what they are and how to use them. So in this article, I will be talking about some of the most important keywords you'll find in the language. What are Keywords in C++? Keywords are certain reserved word... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-keywords-you-should-know/</link>
                <guid isPermaLink="false">66baef85e2f22beb3be3a574</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Mon, 22 Mar 2021 16:39:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/keyword.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ has various keywords, and you should know what they are and how to use them. So in this article, I will be talking about some of the most important keywords you'll find in the language.</p>
<h2 id="heading-what-are-keywords-in-c">What are Keywords in C++?</h2>
<p>Keywords are certain reserved words which have a predefined meaning in C++. Since keywords have their own predefined meaning, they cannot be used as identifiers (for example, a function's name or a variable's name). </p>
<p>The function definition below is an error because <strong>friend</strong> is a keyword in c++.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">friend</span><span class="hljs-params">()</span></span>{
<span class="hljs-comment">/*.......*/</span>
}
</code></pre>
<p>Let's look at some of the common keywords in C++ and how they're used.</p>
<h2 id="heading-c-keywords">C++ Keywords</h2>
<h3 id="heading-the-typedef-keyword-in-c">The <code>typedef</code> keyword in C++</h3>
<p>Sometime it can be tedious to declare a variable of a certain type like this:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span>
</code></pre>
<p>Programmers have hard time declaring such variables, and they're too long to use frequently. Can't we make it shorter or create something different? Yes we can.</p>
<p>Using <strong><code>typedef</code></strong> we can create synonyms:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span> CON_UCHAR;
</code></pre>
<p>So instead of using such long base types, like this:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span> x;
</code></pre>
<p>We can use this:</p>
<pre><code class="lang-c++">CON_UCHAR x;
</code></pre>
<p><strong>typedefs</strong> are helpful for pointer declaration, too:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">char</span> *<span class="hljs-keyword">const</span> CON_PTRCHAR; <span class="hljs-comment">//const pointer to char</span>

<span class="hljs-keyword">typedef</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span>* PTR_CONCHAR; <span class="hljs-comment">//pointer to const char</span>
</code></pre>
<h3 id="heading-the-bool-keyword-in-c">The <code>bool</code> keyword in C++</h3>
<p><strong>bool</strong> is a type name which has two values – it is either <strong>true</strong> or <strong>false.</strong> </p>
<p>Every non-zero value is <strong>true</strong>, while zero is <strong>false.</strong></p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span>(<span class="hljs-number">1</span>){
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Hello World"</span>&lt;&lt;<span class="hljs-string">'\n'</span>;
}
<span class="hljs-keyword">else</span>{
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Sorry World&lt;&lt;'\n';
}</span>
</code></pre>
<p>Since all non zero values are true, every time the program runs, it outputs <strong>Hello World.</strong></p>
<p>Remember that the two bool values, <strong>true</strong> and <strong>false</strong>, are also keywords.</p>
<h3 id="heading-the-using-keyword-in-c">The <code>using</code> keyword in C++</h3>
<pre><code class="lang-c++"><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
</code></pre>
<p>You might have used the <strong>using</strong> keyword unknowingly. It can be used like this:</p>
<p><strong><code>using-declaration</code>:</strong></p>
<pre><code class="lang-c++"><span class="hljs-keyword">namespace</span> My_space{

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">My_class</span>{</span>
<span class="hljs-comment">/*Your code here*/</span>
};
}

<span class="hljs-keyword">namespace</span> Her_space{

<span class="hljs-keyword">using</span> My_space:: My_class;

}
</code></pre>
<p>This is what a using declaration looks like. A using declaration brings every declaration with a given name to a scope.</p>
<p><strong><code>using directive</code>:</strong></p>
<p>The most common example of a using directive is this:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
</code></pre>
<p>The above line of code makes every name from std namespace available.</p>
<h3 id="heading-the-public-protected-and-private-keywords-in-c">The <code>public</code>, <code>protected</code>, and <code>private</code> keywords in C++</h3>
<p>The keywords <strong>public</strong>, <strong>protected</strong>, and <strong>private</strong> are used as access specifiers in a class.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Home</span>{</span>
<span class="hljs-keyword">private</span>:
<span class="hljs-keyword">int</span> members;
<span class="hljs-keyword">protected</span>:
<span class="hljs-keyword">double</span> tot_expenditure;
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display_detail</span><span class="hljs-params">()</span></span>;
};
</code></pre>
<p>The members after the <strong>private</strong> label are only accessible through member functions. If no label is provided, then it is private by default.</p>
<p>The members after the <strong>public</strong> label are accessible everywhere.</p>
<p>The members after the <strong>protected</strong> label are similar to <strong>public</strong> members for derived class and are similar to <strong>private</strong> members for non-derived class.</p>
<h3 id="heading-the-enum-keyword-in-c">The <code>enum</code> keyword in C++</h3>
<p>An enumeration is a user defined type. We declare enumeration using the <strong>enum</strong> keyword.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">enum</span> days{SUN, MON, TUE, WED, THU, FRI, SAT};
</code></pre>
<p>Here, SUN, MON, TUE ... are called enumerators and their values are assigned increasing from 0.</p>
<p>By default, SUN==0, MON ==1 and so on.</p>
<p>However, we can initialize enumerators ourselves too.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">enum</span>{ a = <span class="hljs-number">5</span>, b = <span class="hljs-number">6</span>};
</code></pre>
<p>By default, enumerations are converted to integers for arithmetic operations. Since enums are <em>user defined types</em>, we can <a target="_blank" href="https://www.freecodecamp.org/news/how-to-overload-operators-in-cplusplus/">overload operators for them</a>, too.</p>
<h3 id="heading-the-new-keyword-in-c">The <code>new</code> keyword in C++</h3>
<p>The <strong>new</strong> keyword (also a operator) is used to create objects in free store (also referred to as heap).</p>
<pre><code class="lang-c++"><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> *p = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>;

*p = <span class="hljs-number">20</span>;
<span class="hljs-comment">//..</span>

}
</code></pre>
<p>For the above line of code, the new operator allocates a memory for storing an object of integer type and returns a pointer pointing to that allocated address.</p>
<h3 id="heading-the-delete-keyword-in-c">The <code>delete</code> keyword in C++</h3>
<p>Memory is an important resource for us. So we should use it wisely. Unwanted memory should not be occupied. So <strong>delete</strong> (also a operator) is used to deallocate memory that was previously allocated by the <strong>new</strong> operator.</p>
<pre><code class="lang-c++"><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> *p = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>;
*p =<span class="hljs-number">20</span>;

<span class="hljs-keyword">delete</span> p;
<span class="hljs-comment">//..</span>

}
</code></pre>
<h3 id="heading-the-this-keyword-in-c">The <code>this</code> keyword in C++</h3>
<p>All the (non-static) member functions know for which object they were invoked and they can refer to it using the pointer <strong>this</strong>.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span>{</span>
<span class="hljs-keyword">int</span> b;
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//...</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>;
};
</code></pre>
<p>Consider a class which has a private member b and a member function display.</p>
<p>Our display function would be the following:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">A::display</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>{
<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"b = "</span>&lt;&lt;b&lt;&lt;<span class="hljs-string">'\n'</span>;
}
</code></pre>
<p>The same code above can be written using <strong>this</strong> like so:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">A::display</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>{
<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"b = "</span>&lt;&lt;<span class="hljs-keyword">this</span>-&gt;b&lt;&lt;<span class="hljs-string">'\n'</span>;
}
</code></pre>
<p>Note that <strong>this</strong> is a pointer, so we should use the -&gt; operator. Furthermore <strong>this</strong> here refers to the object which invoked the function.</p>
<h3 id="heading-the-class-keyword-in-c">The <code>class</code> keyword in C++</h3>
<p>C++ supports object oriented programming, so we have the concept of classes. The keyword <strong>class</strong> is used to declare / define a class.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Fb_user</span>{</span>
<span class="hljs-comment">//..your code here</span>
};
</code></pre>
<p><strong>struct</strong> is also a keyword. It's a class with all the members labelled public by default.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Fb_user</span>{</span>
<span class="hljs-comment">//...Your code here</span>
};
</code></pre>
<p>The above code is shorthand for this code:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Fb_user</span>{</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//..your code here</span>
};
</code></pre>
<p>To learn more about classes you can refer to my in-depth article about classes <a target="_blank" href="https://www.freecodecamp.org/news/how-classes-work-in-cplusplus/">here</a>.</p>
<h3 id="heading-the-operator-keyword-in-c">The <code>operator</code> keyword in C++</h3>
<p>The keyword <strong>operator</strong> is used while overloading operators. The syntax for overloading an operator is the following:</p>
<pre><code class="lang-c++">return_type <span class="hljs-keyword">operator</span> <span class="hljs-keyword">operator</span><span class="hljs-number">'</span>s_symbol(parameters){
<span class="hljs-comment">//...Your code here...</span>
}
</code></pre>
<p>To learn more about overloading operators in c++ you can refer to my article <a target="_blank" href="https://www.freecodecamp.org/news/how-to-overload-operators-in-cplusplus/">here</a>.</p>
<h3 id="heading-the-inline-keyword-in-c">The <code>inline</code> keyword in C++</h3>
<p>The keyword <strong>inline</strong> is used with functions which are expanded " in line " during every call.</p>
<p>A member function defined within the class definition is taken to be an inline function.</p>
<p>But we can use the keyword <strong>inline</strong> to inline a member function like this:</p>
<pre><code class="lang-c++"><span class="hljs-function">class <span class="hljs-title">Random</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">int</span> a;
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">int</span> display <span class="hljs-title">const</span><span class="hljs-params">()</span></span>;
<span class="hljs-comment">//...</span>
};

<span class="hljs-function"><span class="hljs-keyword">inline</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Random::display</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>{
<span class="hljs-keyword">return</span> a;
}
</code></pre>
<p>The 'inline' specification is just a request to the compiler to inline a function. The compiler may ignore that request.</p>
<h3 id="heading-the-goto-keyword-in-c">The <code>goto</code> keyword in C++</h3>
<p>C++ also supports the <strong>goto</strong> keyword. <strong>goto</strong> is used as a jump statement to jump in and out of a block. The restriction is that we cannot jump into an exception handler. </p>
<p><strong>goto</strong> statements are useful for breaking out from a nested loop or any switch case statement.</p>
<pre><code class="lang-c++"><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">5</span> ; i++){
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span> ; j &lt; <span class="hljs-number">5</span> ; j++{
    <span class="hljs-keyword">if</span>(){<span class="hljs-comment">//check for some condition</span>
    <span class="hljs-keyword">goto</span> here;
    }
  }
}

here:
<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"I am here"</span>&lt;&lt;;

}
</code></pre>
<p>So basically we use goto to jump from one block to another.</p>
<p>It is a good idea to avoid using goto in general, though it can sometimes be useful.</p>
<h2 id="heading-thats-it">That's It!</h2>
<p>These are some of the most common keywords in C++. I hope you had a good time reading about this (not the <strong>this</strong> pointer :) ) </p>
<p>Happy Coding!</p>
<p>You can read my other blogs <a target="_blank" href="https://abhilekhblogs.blogspot.com/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Overload Operators in C++ ]]>
                </title>
                <description>
                    <![CDATA[ Classes are user-defined types. They allow us to represent the meaning of various entities. Defining an operator for a class gives us a better way to deal with objects.  So how can we define operators for our classes, and how should we use such opera... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-overload-operators-in-cplusplus/</link>
                <guid isPermaLink="false">66baef8bdd8063e11713c5b9</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Mon, 15 Mar 2021 13:52:01 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/6043a406a7946308b76830ab.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://www.freecodecamp.org/news/how-classes-work-in-cplusplus/">Classes</a> are user-defined types. They allow us to represent the meaning of various entities. Defining an operator for a class gives us a better way to deal with objects. </p>
<p>So how can we define operators for our classes, and how should we use such operators? I will show you how in this article.</p>
<p>Let's begin!</p>
<h2 id="heading-what-are-operators-in-c">What are Operators in C++?</h2>
<p>Operators are symbols which are used to perform operations on various operands. For example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">10</span>;

<span class="hljs-keyword">int</span> z = x + y;
</code></pre>
<p>For the above example <code>+</code> is an operator which performs the addition operation on the two operands <code>x</code> and <code>y</code>.</p>
<h2 id="heading-what-is-operator-overloading-in-c">What is Operator Overloading in C++?</h2>
<p>Let's check out an example first.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x=<span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> y= <span class="hljs-number">10</span>;

<span class="hljs-keyword">int</span> z = x+y;<span class="hljs-comment">//z==15</span>

<span class="hljs-built_in">string</span> s1=<span class="hljs-string">"Abhi"</span>;
<span class="hljs-built_in">string</span> s2=<span class="hljs-string">"gautam"</span>;

<span class="hljs-built_in">string</span> s3= s1+s3;<span class="hljs-comment">//s3==Abhigautam</span>
</code></pre>
<p>Have you ever wondered about this type of code <strong>–</strong> why is <code>z== 15</code> and <code>s3== Abhigautam</code>? This is because operators have different meanings for different types of operands. </p>
<p>For an integer type, the <code>+</code> operator gives the sum of two numbers, and for the string type it concatinates (joins) them.</p>
<p>So, operator overloading is all about giving new meaning to an operator. But:</p>
<ul>
    <li>You cannot set new meaning to an operator for a built-in type.</li>
    <li>You cannot create new operators.</li>
</ul>

<p>So, basically what I mean is you cannot redefine an operator and you can't create a new operator, either.</p>
<p>If you wished to create new operator like <code>**</code> for exponential purposes, you couldn't do it.</p>
<h3 id="heading-how-does-overloading-work">How does overloading work?</h3>
<p>So operator overloading lets us define the meaning of an existing operator (note that you cannot overload some operators) for the operands of a user defined type (for example, a class is a user defined type).</p>
<p>Overloaded operators are just functions (but of a special type) with a special keyword <code>operator</code> followed by the symbol of the operator to be overloaded.</p>
<pre><code class="lang-c++"><span class="hljs-comment">/*overloading + for class type object*/</span>

return_type <span class="hljs-keyword">operator</span>+(params..){}
</code></pre>
<p>As I already mentioned, overloaded operators are just a special type of functions. They must have a return type, and parameters are always optional (as per their requirements).</p>
<p>So let's overload some operators for our class now to see how it works:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Complex</span>{</span>
<span class="hljs-keyword">int</span> real,imag;
<span class="hljs-keyword">public</span>:
Complex(<span class="hljs-keyword">int</span> re,<span class="hljs-keyword">int</span> im):real(re),imag(im){}
Complex(){
real = <span class="hljs-number">0</span>;
imag = <span class="hljs-number">0</span>;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>;
<span class="hljs-comment">//overloading operators</span>
Complex <span class="hljs-keyword">operator</span>+(<span class="hljs-keyword">const</span> Complex);
Complex <span class="hljs-keyword">operator</span>-(<span class="hljs-keyword">const</span> Complex);
};
</code></pre>
<p>Here we have two functions as a member function with the syntax mentioned above. So first let's understand the syntax.</p>
<pre><code>Complex operator+(<span class="hljs-keyword">const</span> Complex);
Complex operator-(<span class="hljs-keyword">const</span> Complex);
</code></pre><p>Both of the functions here return an object of <code>Complex</code> type. The operator keyword followed by the operators symbol tells us which operator is being overloaded.</p>
<p>We also have a display function to allow us to see the display of the object's member values. We will substituted this with the overloaded operator (<code>&lt;&lt;</code>) later in the post.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Complex::display</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">if</span>(imag&lt;<span class="hljs-number">0</span>)
<span class="hljs-built_in">cout</span>&lt;&lt;real&lt;&lt;imag&lt;&lt;<span class="hljs-string">"i"</span>&lt;&lt;<span class="hljs-string">'\n'</span>;
<span class="hljs-keyword">else</span>
<span class="hljs-built_in">cout</span>&lt;&lt;real&lt;&lt;<span class="hljs-string">'+'</span>&lt;&lt;imag&lt;&lt;<span class="hljs-string">"i"</span>&lt;&lt;<span class="hljs-string">'\n'</span>;
}
</code></pre>
<h2 id="heading-how-to-overload-the-binary-plus-operator-in-c">How to Overload the Binary Plus (+) Operator in C++</h2>
<p>Let's overload the <code>+</code> operator now.</p>
<pre><code class="lang-c++">Complex Complex::<span class="hljs-keyword">operator</span>+(<span class="hljs-keyword">const</span> Complex c1){
Complex temp;
temp.real = real + c1.real;
temp.imag = imag + c1.imag;
<span class="hljs-keyword">return</span> temp;
}
</code></pre>
<p>After this definition, if we do the following:</p>
<pre><code>Complex c1(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>);
Complex c2(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>);
Complex c3 = c1+c2;
c3.display();
</code></pre><p>It should be clear that c1+c2 is equivalent to this:</p>
<pre><code class="lang-c++">c1.<span class="hljs-keyword">operator</span>+(c2);
</code></pre>
<p>and</p>
<pre><code class="lang-c++"><span class="hljs-keyword">operator</span>(c1,c2);
</code></pre>
<p>After the call to the member function display, the output looks like this:</p>
<pre><code><span class="hljs-number">4</span>+<span class="hljs-number">4</span>i
</code></pre><p>So basically we defined the meaning of the <code>+</code> operator for our object of type <code>Complex</code>.</p>
<h2 id="heading-how-to-overload-the-binary-minus-operator-in-c">How to Overload the Binary Minus (-) Operator in C++</h2>
<p>Now let's overload the minus operator.</p>
<pre><code class="lang-c++">Complex Complex::<span class="hljs-keyword">operator</span>-(<span class="hljs-keyword">const</span> Complex c1){
Complex temp;
temp.real = real - c1.real;
temp.imag = imag - c1.imag;
<span class="hljs-keyword">return</span> temp;
}
</code></pre>
<p>So this is how we overload operators in c++. Let's now discuss the number of parameters that should be passed in the function.</p>
<p>The number of parameters passed to the function is equal to the number of operands taken by the operator. </p>
<p>But in case of a (non-static) member function, the number of parameters reduces by one. This is because the (non-static) member function somehow knows the object it was invoked for.</p>
<p>Isn't that fun? Let's now overload more operators for our class.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">bool</span> <span class="hljs-keyword">operator</span>!=(<span class="hljs-keyword">const</span> Complex);
<span class="hljs-keyword">bool</span> <span class="hljs-keyword">operator</span>==(<span class="hljs-keyword">const</span> Complex);
</code></pre>
<h2 id="heading-how-to-overload-the-not-equal-to-operator-in-c">How to Overload the Not Equal To (!=) Operator in C++</h2>
<p>So our function definition for the <code>!=</code> operator function will be this:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">bool</span> Complex::<span class="hljs-keyword">operator</span>!=(<span class="hljs-keyword">const</span> Complex c1){
<span class="hljs-keyword">if</span>(real!=c1.real || real!=c1.imag){
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
<span class="hljs-keyword">else</span>
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}
</code></pre>
<p>The return type is a bool, so it returns either true or false.</p>
<h2 id="heading-how-to-overload-the-equal-to-operator-in-c">How to Overload the Equal To (==) Operator in C++</h2>
<p>Similarly for the operator <code>==</code>: </p>
<pre><code class="lang-c++"><span class="hljs-keyword">bool</span> Complex::<span class="hljs-keyword">operator</span>==(<span class="hljs-keyword">const</span> Complex c1){
  <span class="hljs-keyword">if</span>(real == c1.real &amp;&amp; imag == c1.imag){
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
  <span class="hljs-keyword">else</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}
</code></pre>
<h3 id="heading-how-to-overload-the-get-from-ltlt-operator-in-c">How to Overload the Get From (&lt;&lt;) Operator in C++</h3>
<p>So let's now overload the <code>&lt;&lt;</code> operator. It will be fun!</p>
<p>Let's see the function declaration first:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">friend</span> ostream&amp; <span class="hljs-keyword">operator</span>&lt;&lt;(ostream&amp;,Complex);
</code></pre>
<p>There are few changes from the previous functions. Let's understand it more clearly.</p>
<p>The function is a friend function. This means that it is not within the scope of any class and cannot be invoked by an object. Also the function returns a reference to the ostream object and it takes two arguments as parameters:</p>
<ul>
    <li>Reference to an ostream object.</li>
    <li>Reference to an object of class type.</li>
 <ul>

You might be wondering why a friend function? Let's talk about why we need friend functions now.

If an operator function is a (non-static) member function, then the left hand side operand will be bound to the <strong><code>this</code></strong> pointer that refers to the object which is calling the function.

But we don't want it to be here in the case of the <code>&lt;&lt;</code> operator because the left hand side operand for the <code>&lt;&lt;</code> operator should be <code>cout</code>. And <code>cout</code> is an object of ostream. So to avoid the binding with the object, we used a friend function here.

We can define the <code>&lt;&lt;</code> operator like this for our class.

<code>c++
ostream&amp; operator&lt;&lt;(ostream&amp; os,Complex c1){
if(c1.imag&lt;0)
os&lt;&lt;c1.real&lt;&lt;c1.imag&lt;&lt;"i";
else
os&lt;&lt;c1.real&lt;&lt;"+"&lt;&lt;c1.imag&lt;&lt;"i";

return os;
}</code>

So in this way we can overload most of the operators for our class.

## Some Operators Can't Be Overloaded in C++

We cannot overload the following operators in c++:

<ul>
    <li>:: (scope resolution operator)</li>
    <li>. (dot operator)</li>
    <li>.* (member selection through pointer)</li>
</ul>

<blockquote>
<p>They take a name, rather than a value, as their second operand and provide a primary means of referring to members. Allowing them to be overloaded would lead to subtleties. [Stroustroup, 1994]</p>
</blockquote>
<p>Moreover the ternary operator (?:) and the named operators <strong>sizeof</strong> and <strong>typeid</strong> also cannot be overloaded.</p>
<h3 id="heading-errors-to-keep-in-mind">Errors to Keep in Mind</h3>
<p>Also remember that the following declaration is an error:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> <span class="hljs-keyword">operator</span>+(<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>);
<span class="hljs-comment">/*error : cannot redefine operators for built in type.*/</span>
</code></pre>
<p>As mentioned earlier, Redefining an operator for built in type is an error.</p>
<h3 id="heading-one-last-point">One last point</h3>
<p>You should not overload operators like <code>&amp;&amp;</code> and <code>||</code> . This is because these operators have a particular order in which an operand is evaluated. Since overloaded operators are just function calls, we cannot guarantee the order of evaluation of the operands.</p>
<h2 id="heading-thats-it">That's it!</h2>
<p>Happy Coding!</p>
<p>You can read my other blogs <a target="_blank" href="https://abhilekhblogs.blogspot.com/">here.</a></p>
</ul></ul> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Classes Work in C++ ]]>
                </title>
                <description>
                    <![CDATA[ C++ supports Object Oriented Programming, and classes and objects are the heart of this programming paradigm.  You might be wondering – what is a class and why do we need them? In this article I'll go over some basics to help you understand how class... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-classes-work-in-cplusplus/</link>
                <guid isPermaLink="false">66baef8890ea1057a46fdfa1</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ class ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Tue, 09 Mar 2021 01:48:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/60424789a7946308b7682566.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ supports Object Oriented Programming, and classes and objects are the heart of this programming paradigm. </p>
<p>You might be wondering – what is a class and why do we need them? In this article I'll go over some basics to help you understand how classes work in C++.</p>
<h2 id="heading-how-classes-work-in-c">How Classes Work in C++</h2>
<p>C++ has various built in types (like <code>bool</code>, <code>int</code>, <code>floats</code>, and so on). Each of these types has various features (for example, the size of their memory occupancy). Operators have different meanings for each different type.</p>
<p>For example: The '+' operator  adds ints, floats, and doubles:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">6</span>;

<span class="hljs-keyword">int</span> z= x+y;<span class="hljs-comment">//z==11</span>
</code></pre>
<p>However if we use the '+' operator with strings, it concatenates those strings.</p>
<pre><code class="lang-c++"><span class="hljs-built_in">string</span> s1 = <span class="hljs-string">"abhilekh"</span>;
<span class="hljs-built_in">string</span> s2 = <span class="hljs-string">"gautam"</span>;

<span class="hljs-built_in">string</span> s3=s1+s2;<span class="hljs-comment">//s3 will be abhilekhgautam</span>
</code></pre>
<p>Here, x, y, and z represent an integer, while s1, s2, and s3 represent strings. So x, y, and z are objects of type <code>int</code>. Meanwhile s1, s2, and s3 are objects of type <code>string</code>.</p>
<p><strong>Note: don't confuse this with the word 'Object'</strong>. An object is anything that occupies memory.</p>
<p>But what if we want to have a type that represents objects in our daily life? How could you represent a house, a car, books, animals, and so on? This is why we need Classes.</p>
<p><strong>A class is a user defined type</strong>. This means that you can define your own types. You can make your own types like ints, floats, and chars. You can define operators for your types and set various properties for your own types.</p>
<p>Classes are really a powerful feature. Let's see how they work:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-built_in">string</span> author_name,title;
<span class="hljs-keyword">int</span> no_of_pages,edition_no;
<span class="hljs-comment">//...</span>
};
</code></pre>
<p>Here we have created a class named Book. The keyword class is enough for us to understand that.</p>
<p>A book must have an author, a title, and pages – these are the members of our class. Here, <code>book</code> represents an entity which has those features. </p>
<p>But creating our own type won't be useful until we have an object of that type. So how do we do that?</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x;<span class="hljs-comment">//x is an object of type x.</span>

Book y;<span class="hljs-comment">//y is an object of type Book</span>
</code></pre>
<p>The only difference here is that x is an object of a built-in type (that is, <code>int</code>) and y is an object of the type Book (Book is a user-defined type, defined by you).</p>
<p>So now let's discuss the basics of defining a class, how to create objects of that class, and ways we can use those objects.</p>
<h2 id="heading-what-are-member-functions-in-c">What Are Member Functions in C++?</h2>
<p>Functions declared in a class are member functions. They can only be invoked by the object of the class in which the function is defined.</p>
<p>Let's now update our <code>Book</code> class a little bit:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">update_edition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> edition)</span></span>;
<span class="hljs-comment">//..</span>
};
</code></pre>
<p>Thats it – <code>update_edition</code> is a member function of our class book. We can define our function in two ways: inside the class, and outside the class.</p>
<p>Let's see how each of them works:</p>
<pre><code class="lang-c++"><span class="hljs-comment">/*Inside class declaration*/</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">update_edition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> edition)</span></span>{
<span class="hljs-comment">//Define your function </span>
edition_no = edition;
}
};
</code></pre>
<pre><code class="lang-c++"><span class="hljs-comment">/* Outside Class declaration*/</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Book::update_edition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> edition)</span></span>{
<span class="hljs-comment">//Define your function here</span>
<span class="hljs-comment">//..</span>
}
</code></pre>
<p>So what about calling the function?</p>
<pre><code class="lang-c++">Book y;<span class="hljs-comment">//y is an object of type Book</span>

y.update_edition(<span class="hljs-number">5</span>);
</code></pre>
<p>Remember that only the objects of type Book can invoke the function. <strong>A call from objects of any other type will result in a syntactical error.</strong></p>
<p>A (non-static) member function always knows the object for which it was invoked and can refer to it like this:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Book::update_edition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> edition)</span></span>{
<span class="hljs-keyword">this</span>-&gt;edition_no = edition;
}
</code></pre>
<h2 id="heading-types-of-member-functions-in-c">Types of Member Functions in C++</h2>
<p>There are a number of types of member functions in C++. Let's look at each one in more detail here.</p>
<h3 id="heading-constant-member-functions">Constant Member Functions</h3>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//..</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">display_edition</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>{
<span class="hljs-keyword">return</span> edition_no;
}
<span class="hljs-comment">//..</span>
};
</code></pre>
<p>The <code>const</code> keyword indicates that this function does not change the state of the function.</p>
<p>Changing the state of the function from constant member function will result in an error.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Book::book_edition</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span></span>{
edition_no = edition_no + <span class="hljs-number">1</span>;<span class="hljs-comment">//error:cannot change value in constant function</span>
}
</code></pre>
<h3 id="heading-static-member-functions">Static Member Functions</h3>
<p>If you have a member function that needs access to the members of the class but does not need to be invoked by each and every object of that class, you should declare it as static.</p>
<p>Such functions will be part of the class but will not be part of the object.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">my_static_func</span><span class="hljs-params">()</span></span>;
};
</code></pre>
<p>A static member can be referred to without using an object.</p>
<pre><code><span class="hljs-keyword">void</span> Book::my_static_func(){
<span class="hljs-comment">//define here.</span>
}
</code></pre><p>The <strong>static</strong> keyword should not be repeated in the function declaration. Static member functions do not have access to the <strong><code>this</code></strong> pointer.</p>
<h3 id="heading-friend-functions">Friend Functions</h3>
<p>Friend functions are not within the scope of a class and don't have any access to <strong><code>this</code></strong>.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//..</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">check</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>;
<span class="hljs-comment">//..</span>
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">E_book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//..</span>
<span class="hljs-function"><span class="hljs-keyword">friend</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Book::check</span><span class="hljs-params">()</span></span>;
};
</code></pre>
<p>Here, the member function <code>check</code> of class <code>Book</code> is a friend of class <code>E_book</code>.</p>
<p>If we want all the member functions of a class to be the friend of another class, we can use the following syntax:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">E_book</span>{</span>
<span class="hljs-comment">//...</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">friend</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>;</span>
};
</code></pre>
<p>Now all the functions of class <code>Book</code> are now friends to class <code>E-book</code>.</p>
<h3 id="heading-access-specifiers">Access Specifiers</h3>
<p>If you have a background in C, you might remember creating your own type using the <strong>struct</strong> keyword.</p>
<pre><code class="lang-c,c++">struct Book{
char author_name[20];
char title[20];
int no_of_page,edition_no;
};

Book b1;//b1 is an object of type Book
</code></pre>
<p>Structure is a user defined type. In fact, <strong>structure is a type of class that has all its members public by default.</strong> Confused?</p>
<p>Do you remember the <strong><code>public:</code></strong> label we used in one of our previous code snippets above? That is what we call an access specifier.</p>
<p>So what's the difference between private and public access specifiers?</p>
<p>Members after a <code>private</code> label are said to be private members. This means that they can only accessed by the member function of that class. If no label is provided, it is private by default.</p>
<p>On the other hand, members after <code>public</code> label are accessible everywhere.</p>
<p>These specifiers are used for the purpose of <strong>data hiding</strong>, <strong>data abstraction,</strong> and <strong>data encapsulation</strong>.</p>
<h3 id="heading-constructors">Constructors</h3>
<p>A constructor is a member function which is used to initialize an object. A constructor is run whenever an object of that class type is created. </p>
<p>The name of the constructor function is the same as the name of the class and it does not have any return type, either.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//Constructor</span>

Book(){  <span class="hljs-comment">//no return type and name same as the class name</span>

<span class="hljs-comment">//define constructor here</span>

}
};
</code></pre>
<p>There can be multiple constructor of a class because there can be multiple functions with the same name reffered as function overloading.</p>
<h3 id="heading-destructors">Destructors</h3>
<p>The destructor releases the memory occupied by the object. It simply destroys the object. The <code>~</code> (tilde) symbol denotes a destructor.</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>{</span>
<span class="hljs-comment">//..</span>
<span class="hljs-keyword">public</span>:
<span class="hljs-comment">//constructor</span>
<span class="hljs-comment">//..</span>
<span class="hljs-comment">//destructor</span>
~Book(){
<span class="hljs-comment">//destroy object here</span>
}
};
</code></pre>
<h2 id="heading-thats-it">That's it!</h2>
<p>By using these various class concepts in c++, you can easily create new types (your own types) which you can conveniently use as built in types.</p>
<p>You can read my other articles <a target="_blank" href="https://abhilekhblogs.blogspot.com/">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
