<?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[ beginner - 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[ beginner - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 22:36:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/beginner/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Key Metrics That Can Make or Break Your Startup ]]>
                </title>
                <description>
                    <![CDATA[ If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order. I have seen too many found... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/key-metrics-that-can-make-or-break-your-startup/</link>
                <guid isPermaLink="false">6894eea1ba8a1138e41767a1</guid>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Founder ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ideas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ business ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Business and Finance  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ metrics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Product Management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #reporting ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ycombinator ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Aditya Vikram Kashyap ]]>
                </dc:creator>
                <pubDate>Thu, 07 Aug 2025 18:21:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754590848364/2e68c07e-d5d8-4da7-bc41-3798c991bfbc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’ve built something worth pitching – something more than a fancy hobby with a login screen – you need to know your numbers. Not "I’ll get back to you" know them, know them like you know your co-founder's coffee order.</p>
<p>I have seen too many founders who are smart, legit, and ambitious get ghosted by investors simply because they couldn't walk through their unit economics.</p>
<p>It's not personal. It's math.</p>
<p>So here it is: Numbers that will either carry your pitch or quietly kill it, explained by someone who has sat through them time and time again, with examples, and no fluff.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-real-experience">Real Experience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-this-matters">Why This Matters</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-and-final-thoughts">Conclusion and Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-1-burn-rate-how-fast-are-you-lighting-your-cash-on-fire">1. Burn Rate: How Fast Are You Lighting Your Cash on Fire?</h2>
<p>Burn rate is the speed at which a startup is spending its cash. Basically, how fast are you consuming your venture capital to cover over overhead until you generate positive cash flow from operations? It’s a measure of negative cash flow.</p>
<p>If you’re spending $80K a month to keep the lights on (payroll, AWS, your workspace snacks, and so on), that’s how much cash you’re burning each month. But many startups calculate two different burn rates: gross burn (how much cash you’re spending, ignoring any revenue), and net burn (monthly operating experiences minus any cash you take in each month). Net burn basically measures how fast your cash is shrinking, and it’s often what investors care more about.</p>
<p>Real talk: investors want to know when the plane runs out of fuel before they board. Thats what this metric helps them understand – how fast you’re going through the money you have.</p>
<p>At some point, if a company has a high burn rate, it has to reduce structural costs by cutting expenditures on labor, rent, marketing, and/or capital equipment. The burn rate is an important metric for any company, but it's particularly important for startups that aren't yet generating revenue. It tells managers and investors how fast the company is spending its capital</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=BpS3shZI35A">Watch this video</a> to understand more about Burn Rate.</p>
<h2 id="heading-2-cash-runway-how-long-before-you-run-out-of-cash">2. Cash Runway: How Long Before You Run Out of Cash?</h2>
<p>Cash runway tells how long a startup can continue to operate at a certain burn rate until they are out of cash. For startups without revenue, you can calculate this by dividing available cash by total monthly expenses. Available cash is defined as the funds that are accessible now or can be accessed at a later time relatively quickly to pay for expenses.</p>
<p>When you’re making this calculation, it’s important to not include any anticipated fundraising and other uncertain sources of capital.</p>
<p>Actively managing cash runway is crucial for startup survival and growth. With a significant percentage of startups failing due to cash shortages, founders need to closely monitor their cash burn rate and runway.</p>
<p>The length of runway needed varies based on factors including the startup’s stage, industry, and milestones. In tighter venture capital markets, startups should plan for longer runways and consider strategies such as increasing revenue, reducing expenses, or raising additional capital. Regularly updating financial models and understanding metrics like the burn multiple can help you make informed decisions to extend your runway and align your growth ambitions with financial stability.</p>
<p>While it’s a simple calculation at face value, a cash runway analysis is nuanced and unique to every startup and can be impacted by a multitude of circumstances.</p>
<p>To calculate this, you just divide your total cash reserves by the amount you’re spending each month. Say you’ve got $250K in the bank and you’re spending $50K/month: 250/50 = 5. So you’ve got 5 months. Not 6. Not “it depends” – 5. That’s your runway.</p>
<p>Investors ask “If we don’t fund you, how long do you survive?” If you don’t know that answer, you're not fundraising – you’re freelancing with hope.</p>
<p><a target="_blank" href="https://youtu.be/vtaMwtQgFGE?si=-Hcf_h_LxKYChdBa">Here is a video</a> that explains cash runway with real world examples and the thought process behind it.</p>
<p>And <a target="_blank" href="https://www.jpmorgan.com/insights/business-planning/does-your-startup-have-enough-runway-to-survive">here’s an article</a> from JP Morgan breaking down cash runway, its importance, and what can you to to maximize it.</p>
<h3 id="heading-burn-rate-vs-runway">Burn Rate vs Runway</h3>
<p>So, let’s just make this super clear: burn rate is simply how much you spend each month to run your operation – that is, your negative cash flow. Runway is how many months there are left before your bank balance reaches zero.</p>
<p>So again, why do these numbers matter?</p>
<p>Because burn rate tells you how quickly you need to find more revenue or funding. Runway tells investors whether you are going to still be around by the time they finish their due diligence.</p>
<p>They are not just numbers. They are your survival clock.</p>
<p>Smart founders utilize these metrics to:</p>
<ul>
<li><p>Trim the fat without cutting muscle – know what to focus on and what to let go</p>
</li>
<li><p>Forecast hiring/fundraising deadlines – know the process and prep for it. Numbers don’t line but they sure can get you ghosted.</p>
</li>
<li><p>Assure investors you’re not going to come knocking again in 90 days – establishing credibility is key, make an investor realize its not just a hobby, you mean business.</p>
</li>
</ul>
<p>The goal: Extend runway without stalling momentum. Keep the plane in the air, while building a bigger engine.</p>
<h2 id="heading-3-cac-customer-acquisition-cost-how-much-does-it-cost-to-convince-someone-to-pay-you">3. CAC (Customer Acquisition Cost): How Much Does it Cost to Convince Someone to Pay You?</h2>
<p>Cost of acquisition refers to the entire cost that a business incurs to obtain a new client or asset. This includes the purchase price, shipping, installation, and marketing costs for the asset acquired. CAC takes into account the total expenditure on all marketing, advertising, and sales for the period, which you then divide by the number of new customers for the period.</p>
<p>In this case, all the upfront costs incurred to purchase a business asset, including equipment or inventory, are part of the cost of acquisition. Cost of acquisition includes:</p>
<ul>
<li><p>Purchase price of the item</p>
</li>
<li><p>Costs to ship it to its point of use</p>
</li>
<li><p>Costs to install the item</p>
</li>
<li><p>Costs to get it up and running (in the case of equipment) or ready for sale (in the case of inventory) condition</p>
</li>
<li><p>Marketing sales teams salaries</p>
</li>
<li><p>All sales and consulting marketing expenses geared to get new consumers should all be included</p>
</li>
</ul>
<p><strong>Formula:</strong><br>CAC = (Total Marketing + Sales Expenses) / Number of New Customers Acquired</p>
<p>Say you spent $10K last month across paid ads, content creation, outbound campaigns, and sales team costs. You onboarded 100 new customers, so your CAC = $100.</p>
<p>But is that good?</p>
<p>It depends on:</p>
<ul>
<li><p>Your pricing model (one-time vs. subscription)</p>
</li>
<li><p>Your margin (how much of that sale do you actually keep?)</p>
</li>
<li><p>Your customer retention (how long do they stick around?)</p>
</li>
</ul>
<p>If you’re selling a $20 product once, a $100 CAC is a non-starter. But if that customer brings in $50/month for 12 months, you’ve got a solid return.</p>
<p><strong>Watch for red flags:</strong></p>
<ul>
<li><p>CAC is rising but revenue isn’t</p>
</li>
<li><p>You’re overly reliant on paid ads (especially if organic/referral is flat)</p>
</li>
<li><p>You don’t know CAC by channel (averages hide leaks)</p>
</li>
</ul>
<p>A healthy CAC is one that pays itself back quickly and can be improved over time as you optimize funnels and messaging</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KFJ3ip30QPM">Here is a video</a> that breaks down CAC for you.</p>
<h2 id="heading-4-customer-lifetime-value-ltv-how-much-is-one-customer-worth-over-time">4. Customer Lifetime Value (LTV): How Much is One Customer Worth Over Time?</h2>
<p>Customer Lifetime Value is the average monetary value of each customer to your business. LTV takes into account how much a unique customer is expected to spend with your business. It’s an important metric so you know how much new customers are worth to your business over their lifespan as a customer.</p>
<p>Let’s say you charge $25/month. The average customer sticks around 12 months.<br>LTV = $300.</p>
<p>In this case, if your CAC is $80? You’re in the green. But if it’s $350? You’re basically paying people to hang out (and losing money on them).</p>
<p>Now, let’s connect this to CAC.</p>
<p>Say your CAC is $80. You’re doing fine – your LTV is ~4x CAC. That’s what investors want to see.</p>
<p>Rule of thumb: you want your LTV to be at least 3x your CAC. A 1:1 ratio means you’re barely breaking even, before operational costs and the math stops working at scale. So if you can hit a 3:1 ratio, great – and based off my experience, your business will be much more appealing if it’s closer to 5:1.</p>
<p>And keep in mind that different models can have different thresholds. For example, a SaaS company with low churn can afford higher CACs, while an e-commerce platform might need faster payback. And marketplaces and freemium models may have lower LTV per user, but they can often more easily offset it with volume.</p>
<p>If you don’t know your LTV or can’t defend it with data, it becomes hard to justify spend – and easy for investors to walk.</p>
<p>If you want to know more, <a target="_blank" href="https://www.youtube.com/watch?v=vA1YX8963ts">this video</a> walks you through the basics.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=773zBQVPx_Q">here’s a video</a> that beautifully explains the CAC and LTV relationship.</p>
<h2 id="heading-5-gross-profit-margin-what-do-you-actually-keep-after-delivering-your-service-or-product">5. Gross Profit Margin: What Do You Actually Keep After Delivering Your Service or Product?</h2>
<p>Gross profit margin shows the amount of money a business collects after it pays for all its expenses. It’s usually calculated as a percentage of sales. This specific metric is also referred to as the gross margin ratio.</p>
<p>Companies use gross margin as a measure of how production costs relate to revenue. If a company's gross margin falls because it is making less revenue, it may try to cut labor costs, find cheaper suppliers of materials, or increase prices to increase revenue.</p>
<p>Gross profit margins can also allow a business to measure how efficient a company is, or compare two very differently sized companies that share a common revenue stream or product</p>
<p>If you sell a subscription for $50/month and it costs you $10/month to host, maintain, and support it, your gross margin is 80%.</p>
<ul>
<li><p>Good: SaaS companies often hit 70–90%.</p>
</li>
<li><p>Bad: If you're below 30%, your "scalable" business will collapse under weight.</p>
</li>
</ul>
<p>Want to know the conceptual math behind this metric and how it differs from Profit Margin? <a target="_blank" href="https://www.youtube.com/watch?v=9xAMe0QBFhU&amp;t=45s">Here is a fantastic video</a> that easily breaks it down.</p>
<h2 id="heading-6-monthly-annual-recurring-revenue-mrr-arr">6. Monthly / Annual Recurring Revenue (MRR / ARR)</h2>
<p>Annual recurring revenue (ARR) is revenue a company expects to see from its product and service offerings, calculated over the course of a year. Companies that sell annual subscriptions like using ARR as a sales metric to track what they anticipate making in a year.</p>
<p>ARR tends to be used if companies sell a product or service in the software as a service (SaaS) space, but it can also be useful in terms of streaming services, cell phone bills, and (almost) anything else with a predictable, recurring charge.</p>
<p>ARR is calculated annually, whereas monthly recurring revenue (MRR) is calculated monthly. MRR is useful in that it shows what’s happening on a month-to-month basis. For example, if you change your price in April, you can see the immediate effects of that change in May. MRR also helps track fluctuations in revenue based on outside factors like holiday shopping seasons and economic conditions.</p>
<p>In a nutshell, Monthly / Annual Recurring Revenue = predictable income.</p>
<p>If you’re pulling $20K/month in subscriptions, that’s $240K ARR. Simple.</p>
<p>What investors care about:</p>
<ul>
<li><ul>
<li><p>Is it growing?</p>
<ul>
<li><p>How fast?</p>
</li>
<li><p>And how stable is it?</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><a target="_blank" href="https://youtu.be/qwo7WFWusO4?si=pCelTr2slb2OLuw9">Here is a founder breaking down the metric</a> and explaining the relationship between MRR/ARR.</p>
<h2 id="heading-7-churn-rate-how-fast-are-your-users-leaving">7. Churn Rate: How Fast Are Your Users Leaving</h2>
<p>The churn rate, also known as attrition rate, represents the rate at which a customer stops doing business with a company. Customer churn is typically expressed as the percentage of service subscribers that discontinue their service subscriptions within a time frame. Churn can also be expressed as the rate at which employees leave their jobs in a given time.</p>
<p>In order for a business to grow its number of clients, its growth rate (which takes into account new customers) must be higher than its churn rate.</p>
<p>The benefit of calculating a churn rate is that it can clarify how well a business is retaining its customers, which is a measure of the quality of service the business is providing and the usefulness of that service.</p>
<p>When a business can see its churn rate increasing from period to period, this suggests that a critical aspect of how it is running the business might be problematic or flawed.</p>
<p>It could be the result of:</p>
<ul>
<li><p>A faulty product(s)</p>
</li>
<li><p>Bad customer service</p>
</li>
<li><p>Costs exceed utility to customers</p>
</li>
</ul>
<p>And so on.</p>
<p>The churn rate will indicate to a business that it needs to learn why its customers are leaving, and where it needs to adjust its business. It’s more expensive to attract new customers than it is to retain them, so reducing the churn rate can save a business resources in the future.</p>
<p>Real talk: Say you had 500 users at the start of the month, and you lost 50 by the end of the month. That’s 10% churn – which is high! Annualize that and…ouch. You're not growing. You're replacing.</p>
<p>Make sure you fix this before you fundraise. Or at least explain why churn’s high and what you’re doing to plug the holes.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=Jlg5J_Mpq7g">Here is a video</a> that beautifully explains Churn Rate.</p>
<h2 id="heading-8-payback-period-how-long-before-you-recover-your-cac">8. Payback Period: How Long Before You Recover Your CAC?</h2>
<p>The payback period is a popular tool for determining investment return. People invest money for the purpose of getting it back and generating a positive return on the money they invested. The shorter the payback period, the more beneficial the investment will be.</p>
<p>The payback period does not factor in the time value of money. You can determine it simply by counting the number of years until the principal paid in is returned.</p>
<p>This metric measures how quickly your customer pays you back for the cost of acquiring them. The payback period doesn’t take into account the total profitability of an investment. It’s just concerned with paying the investment back.</p>
<p>There are two common interpretations:</p>
<ol>
<li><p><strong>Customer-Level Payback:</strong> If your CAC is $250 and your customer pays $50/month, it’ll take 5 months to recover the acquisition cost.</p>
</li>
<li><p><strong>Investment-Level Payback:</strong> You spend $100,000 on a new sales hire, tool stack, or feature. You want to know how long it takes for that investment to generate $100,000 in profit.</p>
</li>
</ol>
<p>Both use the same principle: the shorter the payback period, the less cash you need to float your growth.</p>
<p>If you want a target, aim for 6 months for customer-level payback. Closer to 3-6 is ideal. Long payback periods mean you need deep pockets – or exceptional retention – to stay afloat.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=KbtTk2azIjY">Here’s a video</a> where you can learn more.</p>
<h2 id="heading-9-earnings-before-interest-taxes-depreciation-and-amortization-ebitda">9. Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA)</h2>
<p>EBITDA stands for Earning Before Interest, Taxes, Depreciation, and Amortization. You can think of this as just your company's operating profit if you wanted a very rudimentary way of referring to it.</p>
<p>It’s not flashy. It’s not fun. But it tells investors: “Here’s what we really make once the accounting fog clears.” and “Are we generating real profits from our actual operations?”</p>
<p>EBITDA is what investors look at because it is the best way of comparing apples to apples when considering startups. EBITDA can provide investors a measure of your operational health.</p>
<p>A negative EBITDA for an early stage company isn't going to raise any eyebrows. Just don’t act surprised when someone brings it up. You need to do that math before the pitch. But, if you have a growing early stage company that's moving from negative EBITDA to positive? Now your getting into grown folks business.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=DH901SrBv9Q">Here’s a video</a> that explains the basics of EBITDA.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=D58oCe_7BBM">here’s another video</a> that explains how investors look at EBITDA and its value in determining your business’s worth.</p>
<h2 id="heading-10-valuation-whats-your-company-worth-and-what-supports-that-number">10. Valuation: What’s Your Company Worth – and What Supports that Number?</h2>
<p>Valuation is a focused exercise that determines the value of an asset, investment, or company. So, how much your company’s worth. And the goal is typically to determine whether that value is a fair value.</p>
<p>Valuations can be conducted in one of two ways:</p>
<ul>
<li><p>an absolute valuation, which evaluates a company on its own merits and entirely independently of other factors/companies, or</p>
</li>
<li><p>a relative valuation, which evaluates the company relative to other similar firms, or assets, in the same sector or industry. This determines if the company, or asset, is worth that much relative to others.</p>
</li>
</ul>
<p>Depending on how the analysis and conclusions are reached, there are a variety of methods and techniques used to develop valuations. And as you’d expect, there’s often significant variability between outputs (or valuations) based on the inputs and context.</p>
<p>While valuations are predominantly quantitatively driven, there’s often a significant subjective influence that come from the assumptions and estimates made along the way. Valuations are also subject to developing situations and events outside of the analysis or the control of the analyst – for example, earnings reports or material news, or economic news – that can result in a change to a valuation stance.</p>
<p>If you’re pre-revenue and you’re saying $30M because a friend raised at that, please stop. Their experience likely has nothing to do with yours.</p>
<p>Valuation = traction + market comps + revenue + momentum + team.</p>
<p>Valuation isn’t just about what you want – it’s about what you can defend.</p>
<p>Startups are typically valued using:</p>
<ul>
<li><p><strong>Comparable Analysis (Comps):</strong> What similar companies are worth</p>
</li>
<li><p><strong>Discounted Cash Flow (DCF):</strong> Projecting future cash and discounting it back</p>
</li>
<li><p><strong>Revenue Multiples:</strong> Often 5x–10x for SaaS, but varies wildly</p>
</li>
<li><p><strong>Precedent Transactions:</strong> What investors paid in past rounds for similar startups</p>
</li>
</ul>
<p>But that’s the math.</p>
<p>Here’s the messy truth: <strong>Valuation = Traction + Team + TAM (total addressable market) + Timing + Storytelling.</strong></p>
<p>Hard factors:</p>
<ul>
<li><p>MRR/ARR</p>
</li>
<li><p>Growth rate</p>
</li>
<li><p>Churn</p>
</li>
<li><p>CAC:LTV</p>
</li>
<li><p>Gross margins</p>
</li>
</ul>
<p>Soft factors:</p>
<ul>
<li><p>Founding team’s track record</p>
</li>
<li><p>Market momentum</p>
</li>
<li><p>Hype or scarcity</p>
</li>
</ul>
<p>Don’t inflate. Don’t anchor to your friend’s raise. Know your comps. And show why <em>your</em> model is defensible, not just desirable. Inflated numbers make investors run. They don’t correct you – they just ghost you.</p>
<p>There are numerous books written on valuation and each technique could be its own PhD. But my role here is to give you a sneak peak into the metrics.</p>
<p>Here’s a <a target="_blank" href="https://www.youtube.com/watch?v=T3Ud5WQCrzQ">basic video on valuation</a> if you’re interested in a deeper dive.</p>
<p>And <a target="_blank" href="https://www.youtube.com/watch?v=znmQ7oMiQrM&amp;list=PLUkh9m2BorqnKWu0g5ZUps_CbQ-JGtbI9">here’s a more detailed video course</a> outlining different forms of valuation. Professor Damodaran from New York University is considered to be one of the aces and thought leaders when it comes to valuation. In this video course he explains stepwise and beautifully so you can understand and explore the fascinating world of valuations.</p>
<h2 id="heading-real-talk-before-you-close-that-tab">Real Talk Before You Close That Tab</h2>
<h3 id="heading-real-experience">Real Experience</h3>
<p>I met a founder once – early days, rough product, but you could tell he actually cared. He wasn't trying to look good. No buzzwords. No "disrupt" talk. Just someone trying to solve something annoying and important.</p>
<p>He walked into the room with a twinkle. Not swagger – just that gentle intensity. We were leaning in.</p>
<p>Then, in the middle of the pitch, someone asked, "So what's your monthly burn?" And I swear to you, he said, "Umm... I think my co-founder has that. I haven't looked in a while."</p>
<p>That was it.</p>
<p>No freak out. No awkward pause. Just... a cluck. Like a window closing in the background.</p>
<p>The product? Still smart. But the moment? Gone.</p>
<p>Nobody was mad. Nobody laughed. We even said thank you. But nobody followed up.</p>
<p>Why? Because it didn't feel like a business. It felt like a maybe.</p>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>I’ve seen so many versions of that same scene play out. It’s never about charisma. It’s not even about the idea, half the time.</p>
<p>It’s about whether the person asking for money actually knows what they’re building. Not the dream, the mechanics. The guts, nuts and bolds of the business. The ugly Excel math nobody brags about on Twitter.</p>
<p>Unfortunately, no simple pitch deck will do that part for you. No co-founder can answer those questions on your behalf.</p>
<p>If it’s your vision, own the math. If it’s your company, learn the cost of keeping it alive.</p>
<p>The rest? The logos, the taglines, the “go-to-market” plans?.... All of that’s just packaging.</p>
<p>And you don’t have to be perfect either. You just have to be in it. Eyes open. Numbers in your head.<br>Because if you’re asking people to believe in what you’re building, you’d better believe in the scaffolding holding it up.</p>
<p>So yeah, know your CAC. Your LTV. Your margins. Your churn. Not to check some box on an investor’s sheet, but to prove to yourself and the investor that the thing you’re spending your life on…has legs. That it can stand. And run.</p>
<p>And maybe, someday, outlast you. Maybe!</p>
<h2 id="heading-conclusion-and-final-thoughts"><strong>Conclusion and Final Thoughts</strong></h2>
<p>I hope this was helpful to you, especially if you’re a founder or aspiring founder trying to build the next big thing. While there a many more ratios and concepts, these are the crux of them.</p>
<p>A lot of other complex ratios and valuations are either built using these metrics or refer them in some way. And each of these metrics could be an article of its own. But I wanted to give you my top 10 run down so that you could get a head start. Numbers are very much a part of the ideation stage itself, and omitting them from your strategy could prove to be a fatal mistake.</p>
<p>I’ll leave you with <a target="_blank" href="https://youtu.be/Pg72m3CjuK4?si=GtIFdvC5WzbKna79">one last video</a> on How to Start a Start Up with Michael Seibel (Reddit, YC, Twitch) that I hope you find valuable. It lays out, in a crash course format, the mindset of a founder who has been there and done that. The fun fact is that a lot of the themes he speaks of tie in to the metrics here, directly or indirectly.</p>
<p>I hope this gives you a perspective of being on the other side, evaluating your hard work and passion, and I hope it sets you up for success in your next Investor Review.</p>
<p>I look forward to your thoughts, comments, and feedback. If this was helpful, engaging, and informative, do share it – you never know who may need it, or could benefit from it. I wish you all the very best in your funding rounds.</p>
<p>Until then, keep learning, unlearning, and relearning, folks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript vs C#: How to Choose the Right Language as a Beginner ]]>
                </title>
                <description>
                    <![CDATA[ If you're just starting your coding journey or trying to pick your next language, two names you’ll often hear — among others — are JavaScript and C#. Both are powerful, widely used, and respected in the software world. But they serve different purpos... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/choose-the-right-language-js-vs-c-sharp/</link>
                <guid isPermaLink="false">6893b598ffc433dd809aa59d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Wed, 06 Aug 2025 20:05:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754510673710/75f0501b-9d42-43ee-bc90-cc028afdeb3a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're just starting your coding journey or trying to pick your next language, two names you’ll often hear — among others — are JavaScript and C#. Both are powerful, widely used, and respected in the software world.</p>
<p>But they serve different purposes, feel different to write, and open up different types of job opportunities.</p>
<p>This article will help you understand what each language is, what they’re good at, and how they compare in real-world use cases.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-javascript">What Is JavaScript?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-c">What Is C#?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance">Performance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-community-and-support">Community and Support</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ease-of-learning">Ease of Learning</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-career-opportunities">Career Opportunities</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-what-is-javascript">What Is JavaScript?</h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-javascript-definition-of-js/">JavaScript</a> is the language of the web. It runs in your browser and powers everything from simple websites to complex web apps. Want to make a button do something when clicked? That’s JavaScript. Want to load data without reloading the page? JavaScript again.</p>
<p>But here’s the cool part, JavaScript isn’t just for the front end anymore. With <a target="_blank" href="https://nodejs.org/en">Node.js</a>, it can run on servers too. This means JavaScript is now used to build entire applications, front to back. You can build APIs, handle databases, run background jobs, and more, all with the same language.</p>
<p>This makes JavaScript beginner-friendly. You can write your first script in a browser and still use the same language to build large systems. It’s fast to start, and you’ll find lots of resources and jobs if you go down this path.</p>
<h2 id="heading-what-is-c"><strong>What Is C#?</strong></h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/learn-c-sharp-programming-1/">C# (pronounced “C sharp”)</a> is a language built by Microsoft. It’s often used in combination with the .NET framework to create desktop apps, web services, and enterprise software. If a business runs a Windows-based software, chances are that it’s built with C#.</p>
<p>C# is also a top choice for game development, thanks to its strong connection with <a target="_blank" href="https://unity.com/">Unity</a>, one of the most popular game engines in the world.</p>
<p>Unlike JavaScript, C# is statically typed. This means you need to define your variables clearly and follow more rules. That sounds like a lot at first, but it actually helps you catch errors early and keep big projects neat and tidy.</p>
<p>Now that you know what JavaScript and C# are, let’s compare them across five key areas.</p>
<h2 id="heading-performance"><strong>Performance</strong></h2>
<p>C# usually performs better than JavaScript, especially when dealing with heavy workloads or tasks that demand a lot from the processor. This advantage comes from the fact that C# is a compiled language.</p>
<p>When you run a C# program, the code is first converted into an intermediate language and then compiled into machine code that your computer’s processor can execute directly. This compilation step removes much of the overhead that comes with interpreting code on the fly.</p>
<p>The result is faster execution and more efficient memory usage, which makes C# ideal for scenarios like handling large files, running complex mathematical calculations, or powering game engines where every millisecond counts.</p>
<p>JavaScript works differently. It’s an interpreted language, which means the code runs line by line in a runtime environment like a web browser or Node.js. Instead of being compiled to machine code ahead of time, the JavaScript engine reads and executes the code as it runs.</p>
<p>This approach offers flexibility and makes it easy to develop and deploy scripts quickly, which is a big reason why JavaScript dominates web development. But because it doesn’t have the same direct link to the machine as compiled languages do, it can struggle in situations that require extremely high performance, like processing massive datasets, rendering complex graphics, or building high-frequency trading systems.</p>
<p>However, modern JavaScript engines have come a long way. Engines like V8, which powers Chrome and Node.js, use <a target="_blank" href="https://en.wikipedia.org/wiki/Just-in-time_compilation">Just-In-Time (JIT)</a> compilation to optimize code while it’s running. They can identify patterns and compile parts of the code into machine instructions on the fly, dramatically improving speed compared to older interpreters.</p>
<p>This means that for most everyday web applications, the difference in performance between JavaScript and C# won’t be noticeable. Web dashboards, e-commerce sites, and typical server-side APIs run perfectly fine in JavaScript. But if your project involves raw computational power, game graphics, or real-time simulations, C# will still give you a clear edge.</p>
<h2 id="heading-community-and-support"><strong>Community and Support</strong></h2>
<p>JavaScript has one of the largest and most active developer communities in the world. Since it's used in almost every corner of the tech world, from websites and browsers to mobile apps and even desktop apps, it has become a go-to language for millions of developers.</p>
<p>That popularity means you’re never alone when learning or building with JavaScript. Whatever problem you run into, chances are that someone else has already faced it and posted about it online. Whether you prefer watching YouTube tutorials, reading blog posts, browsing GitHub repositories, or asking questions on Stack Overflow, you’ll find an overwhelming amount of help and resources to guide you.</p>
<p>C# also has a strong and dedicated community, though it’s more concentrated in the enterprise and professional development space. Backed by Microsoft, C# is consistently updated, well-documented, and deeply integrated with tools like Visual Studio and the .NET ecosystem.</p>
<p>You’ll find a wealth of high-quality documentation, official guides, and forums where professionals share their knowledge. While it might not generate the same buzz as JavaScript in startup circles or web-first communities, C# has a long-standing presence in large-scale systems, corporate software, game development (especially with Unity), and Windows applications. In those environments, it’s not uncommon to find teams of seasoned developers with years of experience in C#.</p>
<p>In short, both languages enjoy excellent support. JavaScript might feel more beginner-friendly due to its widespread usage and endless online tutorials, making it easy to pick up quickly. C#, on the other hand, shines in more structured, professional settings where stability, performance, and long-term maintainability are key. It may not have the same trendy reputation, but within its ecosystem, it’s trusted, respected, and well-loved.</p>
<h2 id="heading-ease-of-learning"><strong>Ease of Learning</strong></h2>
<p>JavaScript is one of the easiest languages to start with because it requires almost no setup. You can open your browser, type a few lines of code in the console, and immediately see the results.</p>
<p>This instant feedback loop makes learning feel exciting and interactive, especially for beginners who want to experiment and see quick outcomes. You can start small, tweak your code, and watch it come to life without installing tools, setting up projects, or even leaving the browser. This low barrier to entry is one of the biggest reasons JavaScript has become the go-to language for people taking their very first steps in programming.</p>
<p>But this simplicity comes with quirks. JavaScript is a very flexible language, which is both a blessing and a curse. It often lets you write code that “just works,” even if it isn’t the best approach. While this makes it forgiving in the early stages, it can also lead to confusing bugs down the line.</p>
<p>Small mistakes might not throw errors immediately, and behavior can change in unexpected ways. Anyone who has wrestled with tricky type conversions knows that JavaScript’s freedom can sometimes backfire. This flexibility demands that you develop discipline on your own if you want to avoid messy, hard-to-maintain code.</p>
<p>C#, on the other hand, feels more structured from the start. It enforces rules like defining types, organizing code into classes, and following a clear syntax. This can feel strict and even a little intimidating at first because you can’t just write anything and hope it works.</p>
<p>The compiler checks your code before it runs and points out mistakes early, which can be frustrating as a beginner. But this structure pays off as your projects grow. The rules and strong typing help you catch errors before they become serious problems, guide you toward better programming habits, and make large, complex codebases easier to manage. Once you get used to its style, C# actually makes programming feel more predictable and less error-prone.</p>
<p>In simple terms, JavaScript gives you the quickest path to start coding and see results, which is perfect for learning and experimenting. C# takes longer to warm up to, but it rewards that effort with cleaner, safer, and more maintainable projects as they grow in size and complexity.</p>
<h2 id="heading-career-opportunities"><strong>Career Opportunities</strong></h2>
<p>Learning JavaScript unlocks a wide range of career opportunities because it powers so much of the modern digital world.</p>
<p>Starting with front-end development, you can build interactive websites and web applications that run in the browser using frameworks like <a target="_blank" href="https://react.dev/">React</a>, Vue, or Angular. If you want to go deeper, Node.js allows you to use JavaScript for back-end development as well, which means you can handle server logic, databases, and APIs without ever switching languages.</p>
<p>This flexibility makes full-stack roles especially accessible to JavaScript developers, since you can manage both the front-end and back-end with a single skillset. On top of that, JavaScript extends into mobile app development with tools like React Native and Ionic, letting you build apps for both iOS and Android.</p>
<p>Because nearly every business needs a website or web application, the demand for JavaScript developers is both high and consistent, making it a strong career path for anyone entering the tech industry.</p>
<p>C# leads to a slightly different set of roles, often tied to enterprise or specialized development. It is heavily used in backend systems that run on the .NET ecosystem, where reliability and performance are critical. Many large companies rely on C# for internal tools, financial applications, and large-scale software products that power their core operations.</p>
<p>One of the most exciting areas for C# developers is game development, thanks to its deep integration with Unity, the most popular game engine in the world. From indie studios to major game companies, Unity uses C# as its primary scripting language, opening the door to careers in the gaming industry. Additionally, C# is a natural fit for building Windows desktop applications and enterprise-level cloud solutions, especially within companies already invested in Microsoft technologies.</p>
<p>Both languages can lead to solid salaries and stable careers, but the paths they open are different. JavaScript thrives in web and mobile-focused roles with a steady demand across startups, agencies, and tech companies of all sizes. C# excels in enterprise, backend, and game development, where the projects are often larger, more complex, and built for long-term reliability. Choosing between them really comes down to the type of work that excites you most and the industry you want to grow in.</p>
<h2 id="heading-final-thoughts"><strong>Final Thoughts</strong></h2>
<p>JavaScript and C# are both modern, useful, and in demand. JavaScript is light, fast, and flexible, perfect for websites and small-to-large web apps. C# is powerful, structured, and ideal for Windows apps, enterprise systems, and games.</p>
<p>If you're new to coding and want to see results fast, start with JavaScript. If you're interested in game dev or building strong business apps, try C#.</p>
<p>You don’t have to choose forever. Many developers learn both. Start with one, explore the other later, and you’ll become a well-rounded coder ready for anything.</p>
<p><a target="_blank" href="https://blog.manishshivanandhan.com/">Join my newsletter</a> for a summary of my articles every Friday. You can also <a target="_blank" href="https://linkedin.com/in/manishmshiva">connect with me on Linkedin</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Collections in C# – Lists, Arrays, Dictionaries, and More ]]>
                </title>
                <description>
                    <![CDATA[ One of the first challenges beginners face when developing applications in C# is organising and managing data efficiently. Imagine keeping track of a list of items, mapping unique keys to values, or ensuring there are no duplicates in a collection – ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-collections-in-csharp/</link>
                <guid isPermaLink="false">6793a90ea69c4db6e76c194a</guid>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Fri, 24 Jan 2025 14:51:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737729136643/4cc12d37-da1c-45f0-928f-fbe02d7fdf52.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>One of the first challenges beginners face when developing applications in C# is organising and managing data efficiently. Imagine keeping track of a list of items, mapping unique keys to values, or ensuring there are no duplicates in a collection – these are all common tasks where choosing the right data structure can make a big difference.</p>
<p>C# provides a rich set of built-in data structures, such as <strong>lists</strong>, <strong>dictionaries</strong>, and more, making it easier to work with data differently. Each structure has strengths and is optimised for specific scenarios, so understanding their differences is key to writing clean, efficient, and maintainable code.</p>
<p>In this tutorial, we’ll explore:</p>
<ul>
<li><p><strong>Lists</strong>: Your go-to for dynamic, ordered collections where elements can grow and shrink effortlessly.</p>
</li>
<li><p><strong>Arrays</strong>: The efficient choice for fixed-size collections with predictable memory usage and blazing-fast indexing.</p>
</li>
<li><p><strong>Dictionaries</strong>: Perfect for quick lookups and managing key-value pairs with unmatched speed and clarity.</p>
</li>
<li><p><strong>Stacks</strong>: Ideal for last-in-first-out (LIFO) operations, like tracking history or nested structures.</p>
</li>
<li><p><strong>Queues</strong>: Best for first-in-first-out (FIFO) tasks, like processing jobs or managing sequential workflows.</p>
</li>
<li><p><strong>HashSets:</strong> The choice for collections where uniqueness matters and fast lookups are key.</p>
</li>
</ul>
<p>By the end of this guide, you'll understand the differences between these structures and be equipped to choose the right one for your next project.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-arrays">Arrays in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-lists">Lists in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dictionaries">Dictionaries in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hashsets">HashSets in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-queues">Queues in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-stacks">Stacks in C#</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-problems">Common Problems</a></p>
</li>
</ol>
<p>For some of the following examples, you’ll need the <code>Animal</code> record below:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Animal</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> Age, <span class="hljs-keyword">string</span> Name, <span class="hljs-keyword">int</span> Legs, <span class="hljs-keyword">string</span> Sound</span>)</span>;
</code></pre>
<h2 id="heading-arrays">Arrays</h2>
<p>An <strong>array</strong> in C# is a fixed-size collection of elements. Arrays are indexed, and their size is set when they are created unlike Lists and other collections. Once defined, the size of an array cannot be changed, making the memory efficient with a low overhead.</p>
<h3 id="heading-single-dimension-arrays">Single-Dimension Arrays</h3>
<p>Arrays are zero-index based, meaning their index begins at 0, rather than 1. If you’re not familiar, an index is a pointer to help you find an item.</p>
<p>For example, if you have 5 names in an Array, the first name is index [0], and the last name would be at index [4].</p>
<p>Arrays are great in scenarios where low-level performance is critical, as they have very little overhead due to their lack of metadata (additional attached information).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] numbers = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[] { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span> };

<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> numbers){
    Console.Write(number);
}
<span class="hljs-comment">//Ouput</span>
<span class="hljs-comment">// 1 2 3 4 5</span>
</code></pre>
<p>In the above example, we instantiate an array with its values (thus giving it a fixed length). But we can assign values after the array is created by using index assignment.</p>
<p><em>Note: You must still specify the size of the array at the time of creation, as the code needs to know the fixed size of the Array.</em></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// create an empty array of 20 indexes</span>
<span class="hljs-keyword">var</span> numbers = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">20</span>];

<span class="hljs-comment">// loop over available indexes and assign `i` </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numbers.Length; i++)
{
    numbers[i] = i + <span class="hljs-number">1</span>;
}

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> numbers)
{
    Console.Write(<span class="hljs-string">$" <span class="hljs-subst">{number}</span>"</span>);
}
<span class="hljs-comment">// Output</span>
<span class="hljs-comment">//  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20</span>
</code></pre>
<h3 id="heading-multi-dimensional-arrays">Multi-Dimensional Arrays</h3>
<p>Arrays can also be multi-dimensional (for example, rows and columns), meaning they can hold two values. This makes them perfect for building grid-like structures.  </p>
<p>Unlike a jagged array, where each element is an array that can have different lengths, a multidimensional array is a matrix-like structure where each dimension has a fixed size.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Create a 2D multi-dimensional array to represent a chessboard</span>

<span class="hljs-keyword">string</span>[,] chessBoard = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[<span class="hljs-number">8</span>, <span class="hljs-number">8</span>];

<span class="hljs-comment">// Creating the starting positions of a Chessboard</span>
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Rook"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Queen"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"King"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">0</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Rook"</span>;

chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">1</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Pawn"</span>;

chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Pawn"</span>;
chessBoard[<span class="hljs-number">6</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Pawn"</span>;

chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">0</span>] = <span class="hljs-string">"Rook"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">1</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">2</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">3</span>] = <span class="hljs-string">"Queen"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">4</span>] = <span class="hljs-string">"King"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">5</span>] = <span class="hljs-string">"Bishop"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">6</span>] = <span class="hljs-string">"Knight"</span>;
chessBoard[<span class="hljs-number">7</span>, <span class="hljs-number">7</span>] = <span class="hljs-string">"Rook"</span>;


<span class="hljs-comment">// Print the chessboard</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> row = <span class="hljs-number">0</span>; row &lt; <span class="hljs-number">8</span>; row++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> col = <span class="hljs-number">0</span>; col &lt; <span class="hljs-number">8</span>; col++)
    {
        <span class="hljs-keyword">string</span> piece = chessBoard[row, col] ?? <span class="hljs-string">"Empty"</span>;
        Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{piece}</span>\t"</span>);
    }
    Console.WriteLine();
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">Rook    Knight  Bishop  Queen   King    Bishop  Knight  Rook    
Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Empty   Empty   Empty   Empty   Empty   Empty   Empty   Empty   
Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    Pawn    
Rook    Knight  Bishop  Queen   King    Bishop  Knight  Rook
</code></pre>
<h3 id="heading-jagged-array">Jagged Array</h3>
<p>Welcome to inception. A <strong>jagged array</strong> in C# is an array of arrays, where each "inner" array can have a different length.</p>
<p>Unlike multi-dimensional arrays, jagged arrays are not rectangular, meaning the rows can have varying sizes.</p>
<p>A usage example could be building a Calendar app. Below is a basic usage outputting the days of each month in the year:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[][] daysInMonths = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">12</span>][];

<span class="hljs-comment">// Initialize each month with its corresponding number of days</span>
daysInMonths[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// January</span>
daysInMonths[<span class="hljs-number">1</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">28</span>]; <span class="hljs-comment">// February (non-leap year)</span>
daysInMonths[<span class="hljs-number">2</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// March</span>
daysInMonths[<span class="hljs-number">3</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// April</span>
daysInMonths[<span class="hljs-number">4</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// May</span>
daysInMonths[<span class="hljs-number">5</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// June</span>
daysInMonths[<span class="hljs-number">6</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// July</span>
daysInMonths[<span class="hljs-number">7</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// August</span>
daysInMonths[<span class="hljs-number">8</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// September</span>
daysInMonths[<span class="hljs-number">9</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// October</span>
daysInMonths[<span class="hljs-number">10</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">30</span>]; <span class="hljs-comment">// November</span>
daysInMonths[<span class="hljs-number">11</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">31</span>]; <span class="hljs-comment">// December</span>

<span class="hljs-comment">// Print the number of days in each month</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> month = <span class="hljs-number">0</span>; month &lt; daysInMonths.Length; month++)
{
    Console.WriteLine(<span class="hljs-string">$"Month <span class="hljs-subst">{month + <span class="hljs-number">1</span>}</span>: <span class="hljs-subst">{daysInMonths[month].Length}</span> days"</span>);
}
</code></pre>
<p>You should use an <code>Array</code> in:</p>
<ul>
<li><p><strong>Performance-critical applications</strong> where memory overhead and speed matter.</p>
</li>
<li><p><strong>Fixed data sets</strong> where the size will not change.</p>
</li>
<li><p><strong>Multi-dimensional data</strong>, for example, graph coordinates (x, y)</p>
</li>
</ul>
<h2 id="heading-lists">Lists</h2>
<p>A <code>List&lt;T&gt;</code> in C# is a resizable collection of items of the same type, signaled above by the letter <code>T</code>. It allows adding, removing, and accessing items by index. Unlike arrays, lists grow dynamically as needed.  </p>
<p>Commonly used for sequential data, they support <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-linq/">LINQ</a> queries and various utility methods for data manipulation.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animals = <span class="hljs-keyword">new</span> List&lt;Animal&gt;()
{
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">10</span>, <span class="hljs-string">"Dog"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Woof"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Cat"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Meow"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">6</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">15</span>, <span class="hljs-string">"Red-Panda"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Squeak"</span>)    
};

animals.Add(<span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Hamster"</span>,<span class="hljs-number">4</span>,<span class="hljs-string">"Squeak"</span>));
animals.Remove(x=&gt;x.Sound == <span class="hljs-string">"Meow"</span>); <span class="hljs-comment">// Remove all squeaking animals</span>
</code></pre>
<p>Lists are a highly versatile data structure, where the order of items remains the same order in which they are added or removed (no manipulation. For example, whenever you call <code>.Add()</code> a method on a list, it will append the item to the list, and the order stays the same as before but with the additional animal.</p>
<p>You can modify the data (for example, filter, map, or sort) before sending lists to other areas of your application thanks to the extensive utility methods available in the <code>List&lt;T&gt;</code> class.</p>
<h2 id="heading-dictionaries">Dictionaries</h2>
<p>Dictionaries work just like the term we know in the English language.</p>
<p>We have a key (a lookup term) and a value (the mapped object or data). Because of this, you might hear the term 'key-value pair' when referring to dictionaries.</p>
<p>Dictionaries are best used to efficiently retrieve data based on a unique identifier, such as an ID, name, or other uniquely identifying fields. They ensure their unique keys are ideal for scenarios requiring optimal performance without iterative searching.  </p>
<p>I recommend using dictionaries when the order of elements is unimportant and you need to represent relationships, such as mapping countries to capitals, products to prices, or people to addresses.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animalDictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, Animal&gt;()
{
    { <span class="hljs-string">"Dog"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">10</span>, <span class="hljs-string">"Dog"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Woof"</span>) },
    { <span class="hljs-string">"Cat"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Cat"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Meow"</span>) },
    { <span class="hljs-string">"Elephant"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">8</span>, <span class="hljs-string">"Elephant"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>) },
    { <span class="hljs-string">"Lion"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>) },
    { <span class="hljs-string">"Giraffe"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">6</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>) },
};
<span class="hljs-comment">// Add</span>
animalDictionary.Add(<span class="hljs-string">"Red panda"</span>, <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Red Panda"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Squeaker"</span>));

<span class="hljs-comment">// Remove</span>
animalDictionary.Remove(<span class="hljs-string">"Cat"</span>);

<span class="hljs-comment">//Get</span>
<span class="hljs-keyword">var</span> giraffe = animalDictionary[<span class="hljs-string">"Giraffe"</span>];
</code></pre>
<h2 id="heading-hashsets">HashSets</h2>
<p>A <code>HashSet&lt;T&gt;</code> is a collection in C# that stores unique elements. It uses a hash-based implementation to ensure very efficient lookups, additions, and deletions. This means it uses hash functions to quickly map keys to values, you can read more about that here.</p>
<p>Duplicate elements are automatically ignored.</p>
<p>How does this differ from a Dictionary? HashSets don't have keys like Dictionaries. Instead, they store values directly and are accessed by iterating over the elements using a <code>foreach</code> loop or LINQ queries.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animalHashSet = <span class="hljs-keyword">new</span> HashSet&lt;Animal&gt;()
{
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">3</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">5</span>, <span class="hljs-string">"Tiger"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">2</span>, <span class="hljs-string">"Elephant"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Trumpet"</span>),
    <span class="hljs-keyword">new</span> Animal(<span class="hljs-number">1</span>, <span class="hljs-string">"Giraffe"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Neigh"</span>)
};
<span class="hljs-comment">// Add</span>
animalHashSet.Add(<span class="hljs-keyword">new</span> Animal(<span class="hljs-number">3</span>, <span class="hljs-string">"Lion"</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"Roar"</span>));
<span class="hljs-comment">// Remove</span>
animalHashSet.Remove(x=&gt;x.Sound == <span class="hljs-string">"Neigh"</span>);
<span class="hljs-comment">// Get</span>
animalHashSet.FirstOrDefault(x=&gt;x.Name == <span class="hljs-string">"Elephant"</span>);
</code></pre>
<p>Above, we create a <code>HashSet&lt;Animal&gt;</code> and attempt to add a duplicate object. You may expect this to throw an error, as we know HashSets can only store unique values. But instead it handles it quite beautifully and simply doesn’t add the duplicate object, so the output is:</p>
<pre><code class="lang-bash">Animal { Age = 3, Name = Lion, Legs = 4, Sound = Roar }
Animal { Age = 5, Name = Tiger, Legs = 4, Sound = Roar }
Animal { Age = 2, Name = Elephant, Legs = 4, Sound = Trumpet }
</code></pre>
<h2 id="heading-queues">Queues</h2>
<p>Queues work in just the same way as a queue does in everyday life, with a first-in, first-out approach.</p>
<p><code>Queue&lt;T&gt;</code> does not implement the ICollection interface like Dictionaries and Lists, meaning it doesn't have an <strong>Add()</strong> method. This means you cannot add elements to the Queue whilst instantiating. It also means you cannot use the <strong>Add()</strong> method to add items – instead, you use the <strong>Enqueue()</strong> method.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> arc = <span class="hljs-keyword">new</span> Queue&lt;<span class="hljs-keyword">string</span>&gt;();
arc.Enqueue(<span class="hljs-string">"2 Lions"</span>);
arc.Enqueue(<span class="hljs-string">"2 Tigers"</span>);
arc.Enqueue(<span class="hljs-string">"2 Bears"</span>);

<span class="hljs-comment">// Peek method allows to peek at the front of the queue</span>
Console.WriteLine(<span class="hljs-string">"Front of the Queue: "</span> + arc.Peek());

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// Front of the Queue: 2 Lions</span>

Console.WriteLine(<span class="hljs-string">$"Processing: <span class="hljs-subst">{arc.Dequeue()}</span>"</span>); <span class="hljs-comment">// Output: 2 Lions</span>
Console.WriteLine(<span class="hljs-string">$"Processing: <span class="hljs-subst">{arc.Dequeue()}</span>"</span>); <span class="hljs-comment">// Output: 2 Tigers</span>
</code></pre>
<p>The <code>Dequeue</code> method not only returns the next item in the queue but also removes the item from the queue as expected. You can also clear the queue using the <code>Clear()</code> method.</p>
<h2 id="heading-stacks">Stacks</h2>
<p>Stacks work oppositely to <code>Queue&lt;T&gt;</code>, in that instead of first-in-first-out, they work on a last-in-first-out mechanic.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> stack = <span class="hljs-keyword">new</span> Stack&lt;<span class="hljs-keyword">int</span>&gt;();
stack.Push(<span class="hljs-number">1</span>);
stack.Push(<span class="hljs-number">2</span>);
stack.Push(<span class="hljs-number">3</span>);
stack.Push(<span class="hljs-number">4</span>);
stack.Push(<span class="hljs-number">5</span>);

<span class="hljs-comment">// iterate over the Stack</span>
<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">var</span> number <span class="hljs-keyword">in</span> stack )
{
    Console.WriteLine(number);
}

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// 5 4 3 2 1</span>
</code></pre>
<p>You may think looping through the items in a <code>Stack</code> would work the same as a List or Queue and would still print them out in order of going in. But the system knows it’s a stack, and so it enumerates the items in reverse order of how they were added – that is, the most recently added element (<code>5</code>) is returned first.</p>
<p>You can also utilise the <code>Pop()</code> method which will return the last item in the collection, and remove it at the same time.</p>
<h2 id="heading-common-problems">Common Problems</h2>
<p>When using various collections, you will more than likely come across common problems, such as <code>KeyNotFoundException</code> when using dictionaries, <code>IndexOutOfRangeException</code> on lists/arrays, or <code>InvalidOperationException</code> when modifying a collection during iteration.</p>
<h3 id="heading-keynotfoundexception"><code>KeyNotFoundException</code></h3>
<p><strong>Scenario:</strong> You try to access a Dictionary key that doesn’t exist in the Dictionary. This will result in a <code>KeyNotFoundException</code>, and error.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> dictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;()
{
    { <span class="hljs-string">"Morning"</span>, <span class="hljs-string">"Good Morning"</span> },
    { <span class="hljs-string">"Afternoon"</span>, <span class="hljs-string">"Good afternoon"</span> },
    { <span class="hljs-string">"Evening"</span>, <span class="hljs-string">"Good evening"</span> },
    { <span class="hljs-string">"Night"</span>, <span class="hljs-string">"Good night"</span> },
};

<span class="hljs-keyword">var</span> message = dictionary[<span class="hljs-string">"Dusk"</span>];

Console.WriteLine(message);

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">//Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'Dusk' was not present in the dictionary.</span>
</code></pre>
<p><strong>Solution:</strong> I recommend using the <code>TryGetValue</code> function, which will handle it gracefully and return the item as an <code>out</code> parameter (if it can be found, otherwise the default value).</p>
<p><code>TryGetValue</code> returns a boolean to show whether it could or couldn’t find the provided key. This boolean value can then be utilised to determine functionality based on successful retrieval or not, rather than checking the output parameter, for example (if it is null/empty or not).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> dictionary = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;()
{
    { <span class="hljs-string">"Morning"</span>, <span class="hljs-string">"Good Morning"</span> },
    { <span class="hljs-string">"Afternoon"</span>, <span class="hljs-string">"Good afternoon"</span> },
    { <span class="hljs-string">"Evening"</span>, <span class="hljs-string">"Good evening"</span> },
    { <span class="hljs-string">"Night"</span>, <span class="hljs-string">"Good night"</span> },
};

<span class="hljs-keyword">var</span> input = Console.ReadLine(); <span class="hljs-comment">// Dusk</span>

dictionary.TryGetValue(input, <span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> message);
Console.WriteLine(<span class="hljs-string">$"`Message:<span class="hljs-subst">{message}</span>`"</span>);
<span class="hljs-comment">// Ouput = `Message ` (blank message as default string value is empty string</span>

<span class="hljs-comment">//or check if was able to retrieve and access output if it was</span>
<span class="hljs-keyword">if</span>(dictionary.TryGetValue(input,<span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> m)){
    Console.WriteLine(message);
}
</code></pre>
<h3 id="heading-indexoutofrangeexception-listsarrays"><code>IndexOutOfRangeException</code> (Lists/Arrays):</h3>
<p><strong>Scenario</strong>: Trying to access an index that’s outside the valid range of a list or array.  </p>
<p>As we know, Arrays are 0 index-based, so trying to access an index of [5] on an Array of 5 items will throw the <code>IndexOutOfRangeException</code>.</p>
<p><strong>Solutions:</strong></p>
<ol>
<li>Ensure the index is within bounds using <code>list.Count</code> or <code>array.Length</code> before access.</li>
</ol>
<ol start="2">
<li>Use the <code>ElementAtOrDefault()</code> method. If it can’t access an item at the given index, it will return the default value, which can then be handled accordingly.</li>
</ol>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> names = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[]
{
    <span class="hljs-string">"Tony"</span>, <span class="hljs-string">"Clint"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Lisa"</span>
};

<span class="hljs-keyword">var</span> name = names.ElementAtOrDefault(<span class="hljs-number">6</span>);
Console.WriteLine(name ?? <span class="hljs-string">"Name not found."</span>);
</code></pre>
<h3 id="heading-invalidoperationexception-iterating-collections"><code>InvalidOperationException</code> (Iterating Collections):</h3>
<p><strong>Scenario</strong>: Modifying a collection (for example, adding or removing items) while iterating over it with a <code>foreach</code> loop will throw an <code>InvalidOperationException</code> because you're trying to remove an item from the list while iterating over it with a <code>foreach</code> loop.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> myList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> myList)
{
    <span class="hljs-keyword">if</span> (item == <span class="hljs-string">"Banana"</span>)
    {
        myList.Remove(item); <span class="hljs-comment">// Throws InvalidOperationException</span>
    }
}
</code></pre>
<h4 id="heading-why-this-happens"><strong>Why This Happens:</strong></h4>
<ul>
<li><p>The <code>foreach</code> loop maintains an internal enumerator for the collection.</p>
</li>
<li><p>Modifying the collection (for example, adding/removing items) invalidates the enumerator, which causes the runtime to throw an <code>InvalidOperationException</code>.</p>
</li>
</ul>
<p><strong>Solution 1: Use a</strong> <code>for</code> <strong>Loop</strong></p>
<p>You can use a <code>for</code> loop with an index to safely modify the list during iteration:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> fruits = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; fruits; i++)
{
    <span class="hljs-keyword">if</span> (fruits[i] == <span class="hljs-string">"Banana"</span>)
    {
        fruits.RemoveAt(i);
        <span class="hljs-comment">// Adjust the index to account for the removed item</span>
        i--; 
    }
}
Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, fruits)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<p><strong>Solution 2: Iterate Over a Copy</strong></p>
<p>Another approach is to iterate over a copy of the list using <code>ToList()</code>. This way, you’re not directly iterating over the original collection, so modifications won’t affect the loop.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> originalList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> originalList.ToList()) <span class="hljs-comment">// Create a copy</span>
{
    <span class="hljs-keyword">if</span> (item == <span class="hljs-string">"Banana"</span>)
    {
        originalList.Remove(item); <span class="hljs-comment">// Safe removal</span>
    }
}
Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, originalList)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<p><strong>Solution 3: Use LINQ to Filter</strong></p>
<p>If you only want to remove items based on a condition, you can use LINQ to create a new filtered list:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> fruits = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt; { <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Cherry"</span>, <span class="hljs-string">"Banana"</span> };

fruits = fruits.Where(item =&gt; item != <span class="hljs-string">"Banana"</span>).ToList(); <span class="hljs-comment">// Filter out "Banana"</span>

Console.WriteLine(<span class="hljs-keyword">string</span>.Join(<span class="hljs-string">", "</span>, fruits)); 
<span class="hljs-comment">// Output: Apple, Cherry</span>
</code></pre>
<h2 id="heading-closing-thoughts">Closing Thoughts</h2>
<p>In this article, you’ve learned about many of the common Data Structures for storing multiple objects and values.</p>
<p>Whether you're storing data in a fixed-size array, managing a dynamic list, working with first-in-first-out queues, last-in-first-out stacks, or key-value pair dictionaries, knowing when and how to use each collection is key to becoming a confident and proficient C# developer.</p>
<p>Mastering these concepts will not only improve your ability to handle data effectively but also lay the groundwork for more advanced topics in data structures and algorithms. Combining these data structures with LINQ can provide some performant and easy-to-use mechanics. To learn more about LINQ you can check out my article <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-linq/">here</a>.  </p>
<p>As you continue your coding journey, keep experimenting with these collections, apply them in real-world scenarios, and deepen your understanding of their inner workings.</p>
<p>As always should you wish to discuss this article further, any other coding-related problems, or hear about other articles I’m writing, drop me a follow on <a target="_blank" href="https://x.com/grantdotdev">X(Twitter)</a>  </p>
<p>Happy coding! 😊</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Variables and Data Types in JavaScript – Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ A variable is like a box where you can store data or a reference to data. In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them. Let's get started! Table of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-variables-and-data-types-in-javascript/</link>
                <guid isPermaLink="false">66c3499e4f7405e6476b019b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 13:33:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723754441356/34416215-e12b-41ec-8c11-332d2c8214e1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A variable is like a box where you can store data or a reference to data.</p>
<p>In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-1">What is a Variable? Example #1</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-2">What is a Variable? Example #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-3">What is a Variable? Example #3</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-a-variable">How to Declare a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-assignment-and-initialization">Variable Assignment and Initialization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-call-a-variable">How to Call a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-name-variables">How to Name Variables</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-reserved-words-in-javascript">Reserved Words in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rules-for-naming-variables-in-javascript">Rules for Naming Variables in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-variable-naming-conventions">Popular Variable Naming Conventions</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-data-types">Variable Data Types</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-primitive-data-types">Primitive Data Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reference-types-in-javascript">Reference types in JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h3 id="heading-what-is-a-variable-example-1">What is a Variable? Example #1</h3>
<p>When a child is born, they are given a name and throughout their life, they'll be referred to b<a class="post-section-overview" href="#reference-types-in-javascript">y</a> that name (unless the name gets changed at some point).</p>
<p>Have you seen anyone without a name? How were you able to call them?<br>In an ideal world, everyone should have a name or a unique way we can refer to them. In JavaScript, every variable has a name.</p>
<blockquote>
<p>Everyone must have a name or a way by which we can refer to them.</p>
</blockquote>
<h3 id="heading-what-is-a-variable-example-2"><strong>What is a Variable? Example #2</strong></h3>
<p>In a math equation, when we say <code>x = 1</code> it means, "anywhere you see <code>x</code>, you should replace it with <code>1</code>". In this case, <code>x</code> is a variable, while <code>1</code> is the value of it. That is: <code>x</code> points to <code>1</code>.</p>
<p>This means that without <code>x</code>, there will be no reference to <code>1</code>. There could be other occurrences of <code>1</code> in the equation but those will be different than the <code>1</code> which <code>x</code> was referring to. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* The code below means x is 1 
 * So during execution, anywhere x appears after the line below, 
 * the complier replace x with 1.
 */</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">1</span>; <span class="hljs-comment">// the value which y refers to is different from that of x</span>
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// This line will log 1 to the console.</span>
</code></pre>
<p>In the code snippet above, <code>x</code> refers to the value 1, and <code>y</code> It also refers to another value 1, but note that both values are distinct, just like you can have two different brands of bottled water even though they both contain water.</p>
<p>So, when we mention the variable name <code>x</code>, we get the value assigned to that variable.</p>
<h3 id="heading-what-is-a-variable-example-3"><strong>What is a Variable? Example #3</strong></h3>
<p>A variable can be conceptualized as a container. The variable's name serves as its identifier, its value represents the container's contents, and its type specifies the nature of those contents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690903992237/a783721f-1fbc-4c84-8df6-24a49e7dddb3.jpeg" alt="Bottle of water" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>A popular water brand here in Nigeria is known as "Eva".</p>
<p>Let's say you bought Eva water, took it home, and placed it amongst other water brands. You can easily say to someone, "Please get me the Eva water over there" and because of the name, it becomes easy for the person to identify and get exactly what you need.</p>
<p>Just as you can easily distinguish your Eva water from other water brands by its name, a variable is uniquely identified by its name within a program. While there may be multiple variables storing data, the specific name of a variable allows you to reference its contents precisely.</p>
<p>In JavaScript, values are assigned a name and anytime we need that value, we simply mention the name to which it was assigned. When the code executes, the name of that variable is replaced by the value it refers to.</p>
<p>In the case of the analogy above, the content of the bottle is water and the type is a liquid. But assuming we have a variable <code>x</code> which refers to the value <code>1</code>, the type of the variable is <code>number</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add the line of code below to the previous code snippet to</span>
<span class="hljs-comment">// find out the data type of x;</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x)
</code></pre>
<p>In the code snippet above, <code>number</code> is printed to the console because variable x holds the value <code>1</code> which is a number.</p>
<p><strong>Variables exist in our program to help us hold values and be able to refer to them whenever we need to</strong>. <strong>Anywhere a variable is mentioned, the value of that variable is what's being used for the computation at the time</strong>.</p>
<h2 id="heading-how-to-declare-a-variable">How to Declare a Variable</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score;
</code></pre>
<p>The program above declares/creates a variable called <code>score</code>.</p>
<p>In JavaScript, creating variables is that simple. The type of the variable is the type of the value stored in it. That is, if the variable <code>score</code> holds a value of <code>1</code>, the type for the <code>score</code> variable is <code>number</code>. So we can say, <code>score</code> is a number variable.</p>
<p>To create a variable, we have to do the following;</p>
<ol>
<li><p>Declare the variable using one of these keywords: <code>let</code>, <code>const</code> or <code>var</code>.</p>
</li>
<li><p>Determine a name to call the variable and write it on the same line as the keyword used in step 1.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score; <span class="hljs-comment">// creates variable 'score'</span>
</code></pre>
<p>Notice that this time, we did not give it a value. We just simply created a container that will store something. For now, it is empty. Although it has no content at the moment, we'll surely provide content for it.</p>
<h2 id="heading-variable-assignment-and-initialization">Variable Assignment and Initialization</h2>
<p>We can assign a value to a variable by using the assignment (<code>=</code>) operator—the variable name to the left of it, and the value to the right.</p>
<pre><code class="lang-javascript">score = <span class="hljs-number">1</span>;
</code></pre>
<p>The code snipped above assigns <code>1</code> as the value of <code>score</code> (this is called <strong>variable assignment</strong>).</p>
<p>When we combine variable declaration and assignment in one operation, it is called <strong>variable initialization</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score = <span class="hljs-number">1</span>;
</code></pre>
<p>As seen above, we declare the variable <code>score</code>, and immediately on the same line, assign the value <code>1</code> to it.</p>
<p>This means that we provided an initial value for the variable when it was created.</p>
<h2 id="heading-how-to-call-a-variable">How to Call a Variable</h2>
<p>If you want to use a variable for an operation at any time in your program, you can simply just "call" it. To <strong>call</strong> a variable is the same as <strong>mentioning</strong> or <strong>using</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(score + <span class="hljs-number">1</span>) <span class="hljs-comment">// 2</span>
</code></pre>
<p>In the code snippet above, the variable <code>score</code> was <strong>used</strong> in the line of code. Therefore, It will be replaced with its actual value <code>1</code> during the code execution. This means we'd have <code>1 + 1</code> executed, resulting in <code>2</code>.</p>
<p>In the next section, let's learn how to properly name our variables in other to ensure our codes are neat and readable.</p>
<h2 id="heading-how-to-name-variables">How to Name Variables</h2>
<p>Just like naming a human or pet or labeling an object, we always put in much thought to ensure that the name tells a story and gives an idea of how we feel about the role of that pet, human, or object.</p>
<p>JavaScript is somewhat liberal when it comes to how variable naming can be done and also how long it could be.</p>
<p>For example, <code>pneumonoultramicroscopicsilicovolcanoconiosis</code> is a valid variable name in JavaScript even though it is long.</p>
<p>It is generally a good practice to give meaningful names to variables and they should be of a reasonable length.</p>
<p>Let your variables be simple and contextual. For example: <code>author</code>, <code>publishedDate</code>, <code>readTime</code>, <code>shouldCompress</code>, and so on.</p>
<p>It should be self-explanatory. Just avoid cryptic names where possible.</p>
<h3 id="heading-reserved-words-in-javascript">Reserved Words in JavaScript</h3>
<p>Even though we can create variables as we wish, some names are already being used within JavaScript to mean something specific. These names cannot be used by a developer to identify a variable. They are called reserved words.</p>
<p>For instance, the keyword <code>catch</code> is used to properly handle an error and prevent it from crashing an application. Hence, you cannot call a variable <code>catch</code> in your program.</p>
<p>Below are all the reserved words in JavaScript:</p>
<p><code>arguments</code> <code>await</code> <code>break</code> <code>case</code> <code>catch</code> <code>class</code> <code>const</code> <code>continue</code> <code>debugger</code> <code>default</code> <code>delete</code> <code>do</code> <code>else</code> <code>enum</code> <code>eval</code> <code>export</code> <code>extends</code> <code>false</code> <code>finally</code> <code>for</code> <code>function</code> <code>if</code> <code>implements</code> <code>import</code> <code>in</code> <code>Infinity</code> <code>instanceof</code> <code>interface</code> <code>let</code> <code>NaN</code> <code>new</code> <code>null</code> <code>package</code> <code>private</code> <code>protected</code> <code>public</code> <code>return</code> <code>static</code> <code>super</code> <code>switch</code> <code>this</code> <code>throw</code> <code>true</code> <code>try</code> <code>typeof</code> <code>undefined</code> <code>var</code> <code>void</code> <code>while</code> <code>with</code> <code>yield</code></p>
<p><strong>NOTE</strong>: You do not need to memorize these keywords. If you try to use them, you'll get an error and you'll learn to recognize and know them with experience.</p>
<p>Also, JavaScript has some rules that you must follow when naming variables as well as generally accepted conventions (best practices) that you should know about. Let's talk about them in the next section.</p>
<h3 id="heading-rules-for-naming-variables-in-javascript"><strong>Rules for Naming Variables in JavaScript</strong></h3>
<ul>
<li><p>Reserved words cannot be used as variable names.</p>
</li>
<li><p>The first letter of your variable name should be an alphabet, underscore (_), or a dollar sign ($). You cannot use a number as the first character of your variable name. Even though other kinds of special characters are allowed to start a variable name, as a way of good practice and avoiding complexities at the start, you should just always start with a letter. Using an underscore or dollar sign is symbolic by convention and we'll learn what they mean in the future.</p>
</li>
<li><p>The rest of the variable name may contain anything but symbols, punctuations, and reserved characters (+, -, *, and so on).</p>
</li>
<li><p>Variable names are case-sensitive. This means <code>Boy</code> and <code>boy</code> will be treated as different variables in your program.</p>
</li>
<li><p>A variable name can be as long as is necessary for it to make sense. There is no limit imposed by the language.</p>
</li>
<li><p>Spaces are not allowed in variable names.</p>
</li>
</ul>
<h3 id="heading-popular-variable-naming-conventions"><strong>Popular Variable Naming Conventions</strong></h3>
<ul>
<li><p>Variable names with multiple words should use <strong>camel casing.</strong> That is, the first word has to be all lowercase while the first letter of subsequent words should be uppercase: <code>studentRegistrationNumber</code></p>
</li>
<li><p>Use uppercase letters for constant variables: <code>const PI = 3.1432</code></p>
</li>
<li><p>If a constant variable is composed of multiple words, use snake casing (separation of words with an underscore): <code>const PROGRAM_NAME = "Vacation planner"</code></p>
</li>
<li><p>If a variable is meant to be private, prefix its name with an underscore: <code>let _memorySize = 2042</code>.<br>  <strong>Note</strong>: This is just to let the team (others working on the project) know that the author intends to use it as private. It doesn't prevent the value of the variable from being accessed (there are other ways to ensure this).</p>
</li>
<li><p>It is common practice to prefix Boolean variables with <code>is</code> or <code>has</code>: <code>let isMarked = true</code>.</p>
</li>
</ul>
<p>In the next section, we'll learn about different data types and how to work with them.</p>
<h2 id="heading-variable-data-types">Variable Data Types</h2>
<p>Data type simply means "type of data" 😉.</p>
<p>The word "data" in this context means a piece of information. We'll use the word "value<strong>"</strong> sometimes to mean data and vice versa.</p>
<p>In JavaScript, we store values of different types in variables. These values have different attributes/properties and the type of data a variable holds will determine the operations you can perform with that variable.</p>
<p>For example, if you have water (value) stored in a container (variable), you can use the water (value) to wash or drink, but if what is stored in the container are candies, you can eat them but you won't be able to use them for washing.</p>
<p>If you have a variable that holds numbers, you can use them to perform arithmetic operations. If the variable holds a Boolean, you cannot use it for arithmetic operations but it can be used for logical operations.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The kind of value stored in the variable determines what you can do with it.</div>
</div>

<p>The data types in JavaScript are categorized into two primary groups, namely;</p>
<ul>
<li><p><strong>Primitive</strong>: Number, String, Boolean, Undefined, Null, BigInt, Symbol</p>
</li>
<li><p><strong>Reference</strong>: Object, Array, Function</p>
</li>
</ul>
<p>In this article, we will not talk about Symbols and BigInt to avoid complexities. The goal is to do our best to explain fundamental concepts to beginners in the most simple way possible.</p>
<p>Let's consider primitive data types.</p>
<h3 id="heading-primitive-data-types"><strong>Primitive Da</strong>ta Types</h3>
<p>Variables having these type of data are called primitives because they hold simple values. The word <a target="_blank" href="https://www.google.com/search?q=primitive&amp;rlz=1C5CHFA_enNG1050NG1050&amp;oq=primitive&amp;aqs=chrome..69i57j0i271.760j0j7&amp;sourceid=chrome&amp;ie=UTF-8">primitive</a> can be translated to mean non-complex.</p>
<p>Primitive values are usually a single unit like 1, "cup", null, undefined, true, and so on. Let's briefly consider how these data types are used and what kind of operations you can perform with them.</p>
<ul>
<li><strong>NUMBER:</strong> In JavaScript, all numbers are floating-point values. Whether they are numbers without decimal points like a whole number that can be negative, positive, zero, or values with a decimal point like 0.2, -0.5, 1, -2, 0. They are all of the <code>number</code> type.</li>
</ul>
<p>This type of value can be used in arithmetic operations like multiplication, division, subtraction, addition, modulus, and so on.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> score2 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> averageScore = (score1 + score2) <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(averageScore) <span class="hljs-comment">// 3.5</span>
</code></pre>
<p>To check the data type of a variable's value, use the <code>typeof</code> operator like this: <code>typeof variableName</code>. That is: <code>typeof score1</code></p>
<p>In the code snippet above, <code>score1</code> is a variable which holds a value of <code>2</code>, <code>score2</code> holds a value of <code>5</code>, while the <code>averageScore</code> variable stores the result from dividing the sum of <code>score1</code> and <code>score2</code> by <code>2</code>, which evaluates to <code>3.5</code>.</p>
<p>Using the <code>typeof</code> operator on the <code>score1</code> variable will return <code>number</code>.</p>
<p><strong>Exercise</strong>: Copy the code in the snippet above and run it in your code editor to see how it works for you. You can play around with the values and use the <code>typeof</code> operator to check the variables' data type.</p>
<p>When performing arithmetic operations, you may run into other Number types like <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code>.</p>
<p><strong>Infinity</strong> means something without any limit. One way to reach infinity is to divide a number by 0.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = <span class="hljs-number">12</span> / <span class="hljs-number">0</span>;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Infinity</span>
</code></pre>
<p>In the code above, we divided <code>12</code> by <code>0</code> and logged the result to the console which prints out <code>Infinity</code>.</p>
<p><strong>Negative Infinity</strong> is used to denote a number that is less than any natural number. To arrive at negative infinity, copy the code in the snippet below and run it in your coding environment.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Number</span>.NEGATIVE_INFINITY) <span class="hljs-comment">// -Infinity</span>
</code></pre>
<p><strong>NaN</strong> means Not <strong>a</strong> Number. This will occur when you try to carry out an impossible mathematical operation as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = <span class="hljs-string">"Ella"</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// Trying to divide a string with a number</span>
<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// NaN</span>
</code></pre>
<p>The first line in the code above tries to divide a string by a number and the result is <code>NaN</code>.</p>
<p>You will not often reach infinity or -Infinity as a beginner doing basic/intermediate stuff, but it is something you should be aware of so that you do not get worked up when you see it occur in your code (this is something you do not want to cram in your head). <code>NaN</code> is will occur more often than the others. When you see it, just know something is wrong with the operation you are trying to perform.</p>
<ul>
<li><strong>STRING:</strong> In JavaScript, a string is a collection of characters enclosed in quotes: <code>"Cathy"</code>.</li>
</ul>
<p>The snippet below shows how a string can be used in a JavaScript program:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> author = <span class="hljs-string">"Sleekcodes"</span>;
<span class="hljs-keyword">let</span> publishedDate = <span class="hljs-string">"14 August 2023"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Written by: "</span> + author); <span class="hljs-comment">// Written by: Sleekcodes</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Published on: "</span> + publishedDate); <span class="hljs-comment">// Published on: 14 August 2023"</span>
</code></pre>
<p>I am sure you noticed the + operator used with strings. When this occurs, the result is that the string on the right and that on the left will be joined together to become one. This is called string concatenation.</p>
<p>The code above is simply saying, "Create a variable called <code>author</code> and store the text <code>"sleekCodes"</code> as its value, create another variable <code>publishedDate</code> and store the text <code>"14 August 2023"</code> in it."</p>
<p>Then in line 4, we tell the JavaScript engine to log (print) the string "Written by: Sleekcodes<strong>"</strong> to the console. Line 5 also says log <strong>"</strong>Published on: 14 August 2023<strong>"</strong> to the console.</p>
<p>Notice that in the code above, during execution, <code>author</code> gets replaced with the value "Sleekcodes" and <code>publishedDate</code> gets replaced with "14 August 2023" where used.</p>
<p>Strings are used to depict or convey data in text/alphabetic format. A string can be made up of zero or more characters. A string that has no character in it is called an empty string. For example: <code>""</code>.</p>
<ul>
<li><strong>BOOLEAN</strong>: When we need to represent data in two possible states only like true/false, on/of, or yes/no, we use Boolean values. The value of a Boolean variable is either <code>true</code> or <code>false</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isQualified = <span class="hljs-literal">true</span>

<span class="hljs-keyword">if</span> (isQualified) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tola is qualified"</span>); <span class="hljs-comment">// Tola is qualified</span>
}
</code></pre>
<p>The code above will print the statement "Tola is qualified", because the value of the variable <code>isQualified</code> is true. That operation is a type of conditional operation. This is where Boolean values shine.</p>
<p><strong>Exercise</strong>: Change the value of <code>isQualified</code> to be <code>false</code> and observe what happens.</p>
<ul>
<li><strong>UNDEFINED</strong>: This is both a value and a data type. <code>undefined</code> is used to indicate that a variable has no defined value. For instance, when a variable is declared (<code>let age</code>), and you try to access its value, the result would be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age; <span class="hljs-comment">// note that there is no value assigned to the variable here</span>

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the code snippet above, because age isn't given any explicit value, the compiler assigns the value <code>undefined</code> to the variable by default.</p>
<p><strong>Exercise</strong>: Use the <code>typeof</code> operator on the variable <code>age</code> and see what you get. Also, assign the value <code>undefined</code> to <code>age</code> and use the <code>typeof</code> operator on it again to see the result.</p>
<ul>
<li><strong>NULL</strong>: Null is a value we can assign to a variable to indicate that it has no value. It is used to represent "empty" or "unknown".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-literal">null</span>;

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// null</span>
</code></pre>
<p>As seen in the code snippet above, instead of letting the compiler assign <code>undefined</code> for us, we explicitly indicate that the variable has no value by assigning the value <code>null</code> to it.</p>
<p>This means <code>age</code> is empty or unknown.</p>
<p>People often get confused about the difference between <code>undefined</code> and <code>null</code>. One is the default value assigned to a variable without an explicit value, while the other (<code>null</code>) is a value assigned to a variable by the programmer deliberately to indicate that the variable is empty. As a rule of thumb, do not assign <code>undefined</code> to a variable, instead use <code>null</code> (the compiler auto-assigns <code>undefined</code> where needed).</p>
<p>Primitive data types have no complexity. They are plain and simple (a single value). This statement will make more sense when you read about how reference types work in the next section.</p>
<p>Consider the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691169563292/8cd6a8de-e6c5-46fe-8271-c2a522b6c663.png" alt="primitive types concept" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Part A</strong> above is the code you write, while <strong>Part</strong> <strong>B</strong> is what happens when the code runs. For primitive data types, the value is simply assigned to the variable (it is straightforward).</p>
<p>Primitive values are passed by value (they generate no reference). Do not worry about what this means yet because we'll explain in the next section.</p>
<h2 id="heading-reference-types-in-javascript">Reference Types in JavaScript</h2>
<p>Reference data types are data passed by "reference". A thorough understanding of this statement is crucial throughout your career as a JavaScript developer, so do well to pay close attention to the concept we are about to learn.</p>
<p>Consider the image below carefully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691062567476/e31e1bfe-6b85-418e-a88a-e19810f11839.png" alt="Reference types concept" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>In the image above, <strong>part A</strong> is the code you write, while <strong>part B</strong> is what happens "behind the scenes".</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Use the image above to follow through with the following explanation.sa</div>
</div>

<p>When you create a variable whose data type is in the reference category (objects, functions, arrays), instead of the value being directly assigned to the variable, a reference is generated for the value and that reference is what gets assigned to the variable<strong>.</strong></p>
<p>The reference gets assigned to the variable, but it points to the actual value.</p>
<p>This means that when you try to use the variable anywhere, you are working with the reference to the actual value and anything done to the reference affects the actual value.</p>
<p>Think of it like a middleman between the actual value and the variable name.</p>
<p>Consider the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}

<span class="hljs-keyword">let</span> staffInfo = studentInfo <span class="hljs-comment">//6. This means; assign the ref of studentInfo to staffInfo</span>

staffInfo.name = <span class="hljs-string">"Lorry Sante"</span> <span class="hljs-comment">//8. Change the value of name key in the reference which staffInfo holds.</span>

<span class="hljs-built_in">console</span>.log(studentInfo.name) <span class="hljs-comment">//9. Lorry Sante</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Try this:</strong> In line 7 and 8, log the value of <a target="_blank" href="http://studentInfo.name"><code>studentInfo.name</code></a> and <a target="_blank" href="http://staffInfo.name"><code>staffInfo.name</code></a> to the console to see what they are.</div>
</div>

<p>You should notice that, changing <code>name</code> in <code>staffInfo</code> object (line 8), causes the name in <code>studentInfo</code> object to change too (as seen in the output of line 9).</p>
<p>In fact, both variables are pointing to the same value technically (see image below);</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691069171621/a53d4f52-6b86-4581-85fc-57452cbc90be.png" alt="reference types variable storage " class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>When we say that a variable is passed by reference<strong>,</strong> it means that anywhere that variable is used, you are interacting with a reference (that points) to its actual value.</p>
<p>So in the code snippet above, when <code>studentInfo</code> was assigned to <code>staffInfo</code>, we just made <code>staffInfo</code> to store the reference of the <code>studentInfo</code> variable, effectively saying that both <code>staffInfo</code> and <code>studentInfo</code> variables are pointing to the same value.</p>
<p>Therefore, if the reference generated for <code>studentInfo</code> is <code>000xx2</code> and it is true that during execution, variables are replaced by whatever they hold, then <code>staffInfo = studentInfo</code> would become <code>staffInfo = 000xx2</code> during execution, while <code>staffInfo.name</code> would become <code>000xx2.name</code>.</p>
<p>If we had written <code>studentInfo.name</code>, then during execution, it becomes <code>000xx2.name</code>, it should be clear now that both <code>studentInfo</code> and <code>staffInfo</code> holds references to one value. They are like different roads to one destination.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If this is your first time learning this concept, you should repeat the section above before you proceed. It will become clearer and when we start operating with reference types, you'll be glad you read this article.</div>
</div>

<p>There are three main reference data types that you'll mostly come across in your journey as a JavaScript developer: Object, Array, and Function. Let's look into them one after the other.</p>
<ul>
<li><strong>OBJECT</strong>: An object is a data structure used to store complex data in key/value pairs. The variable created in the previous session has an object type like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}
</code></pre>
<p>You can see that it isn't primitive (simple). Unlike primitive types with just simple values, an object can be used to store different information which can be made up of even primitive and reference types.</p>
<p>Objects store data in key/value pairs like so: <code>{key: value}</code></p>
<p>In the code snippet above, <code>name</code> is key, while <code>"John Doe"</code> is its value. Also, <code>age</code> is key, while <code>205</code> is its value.</p>
<p>If you notice, both <code>name</code> and <code>age</code> have primitive values (string and number).</p>
<p>To access the value of an object, we use the object name, dot (.) notation, and the key whose value we want to access. For example: <code>objectName.key</code>.</p>
<p>Objects can also contain nested objects like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>,
    <span class="hljs-attr">beneficiary</span>: {
       <span class="hljs-attr">name</span>: <span class="hljs-string">"Tira Doe"</span>,
       <span class="hljs-attr">age</span>: <span class="hljs-number">200</span>,
       <span class="hljs-attr">relationship</span>: <span class="hljs-string">"Wife"</span>
    }
}
</code></pre>
<p>In the above example, the <code>studentInfo</code> object has a nested object called <code>beneficiary</code>. <code>beneficiary</code> is a key whose value is an object (reference type). Objects can still hold arrays and functions too.</p>
<p>Accessing the value associated with a key in an object within another object (nested object) is natural. We simply use dot notation. Like so: <code>parentObjectName.nestedObjectName.key</code></p>
<p>For example, to access the name of the beneficiary in <code>studentInfo</code> object above, we simply write <code>studentInfo.beneficiary.name</code>.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">There's no limit to nesting objects in objects. However, ensure that nesting is necessary for what you want to achieve and too much nesting should be avoided for simplicity.</div>
</div>

<p>This is not all that you need to know about objects but it is a very sound way to start.</p>
<ul>
<li><strong>ARRAY</strong>: An array is a kind of object but stores data using automatically assigned indexes instead of keys.</li>
</ul>
<p>An array is created by writing a comma-separated list of values enclosed with square brackets: <code>[0, 1, 2, 3, "Tosin", "Mike", {name: "Abel Joe", age: 250}]</code></p>
<p>If you pay close attention to the values used in the array above, you'll notice that they are of different data types. Yes, arrays also allow you to store values of different types in one place but this is strongly discouraged (you shouldn't do it at all). The values in an array should all be of the same type<strong><em>.</em></strong></p>
<p>Example of a proper array: <code>let scores = [1, 3, 5, 6, 9, 12]</code></p>
<p>To access a value in an array, we simply specify the array name, followed by a square bracket <code>[]</code> without any space between the name and the bracket. Then inside the square bracket, provide the index of the value you wish to access. That is: <code>arrayName[index]</code>.</p>
<p>What's an index and how do we know what index refers to the value we want to access?</p>
<p>An index is simply a number automatically assigned to an array value<strong>.</strong> You can think of it as an address for values in the array. Arrays are <code>0</code> indexed (meaning they start counting from zero)<strong>.</strong></p>
<p>To determine the index of the value you wish to access, start counting from the start of the array and your count should start from 0.</p>
<p>Consider the image below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691072847798/ca5bc276-f024-40eb-b69e-b8e31f17314f.png" alt="array and indexes" width="600" height="400" loading="lazy"></p>
<p>To access the value <code>80</code> in the <code>scores</code> array depicted in the image above, we simply write <code>scores[3]</code></p>
<p>There is a lot you can do with arrays as a JavaScript developer. For now, this is a simple introduction to the array data type.</p>
<ul>
<li><strong>FUNCTION</strong>: A function is a different kind of variable and it's declared differently (using the <code>function</code> keyword instead of <code>let</code>, <code>const</code> or <code>var</code>). It is a construct used to carry out a specific task.</li>
</ul>
<p>For example, if you need to add two numbers together multiple times within your code, it's best practice to create a dedicated function for this task. By reusing this function, you avoid redundant code and improve code maintainability compared to repeatedly writing the addition logic. Wait!!! You are not lost. The example below will confirm this 😊</p>
<p>Scenario 1 (without function):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> result = num1 + num2;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 5</span>

<span class="hljs-keyword">let</span> num3 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> num4 = <span class="hljs-number">8</span>;
<span class="hljs-keyword">let</span> result2 = num3 + num4;

<span class="hljs-built_in">console</span>.log(result2) <span class="hljs-comment">// 11</span>
</code></pre>
<p>Scenario 2 (with function):</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function declaration.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">3</span>, <span class="hljs-number">8</span>)); <span class="hljs-comment">// 11</span>
</code></pre>
<p>You will agree that, scenario 2 contains less code, looks neater, and even feels more natural.</p>
<p>Functions allow us write helpers that we can call to get a specific job done for us any time we want. We just have to tell it how to do the job once and call it anytime we need it to do that job (passing in any information required for the task as arguments) and it delivers.</p>
<p>Function Syntax:</p>
<p>To write a function, we use the <code>function</code> keyword, followed by the name of the function: <code>functionName</code>, a pair of brackets <code>()</code>, and a pair of curly braces <code>{}</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span> (<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>There are a few things/conventions you should have in mind when writing functions:</p>
<ul>
<li><p>Function names should follow the same naming rules as variables.</p>
</li>
<li><p>Function names should be verbs (to depict an action).</p>
</li>
<li><p>The code logic for the actual task should be written between the opening <code>{</code> and closing <code>}</code> curly braces.</p>
</li>
<li><p>If there are values required to carry out the task, they should be passed into the function as arguments. In this case, during the function declaration, parameters should be stated between the opening <code>(</code> and closing <code>)</code> brackets in a comma-separated fashion. That is: <code>function addNumbers(num1, num2)...</code>.</p>
</li>
<li><p>If no data is required to carry out the task, then the opening <code>(</code> and closing <code>)</code> brackets should be left empty: <code>function sayHi()...</code>.</p>
</li>
</ul>
<p>A parameter is a variable defined between the opening <code>(</code> and closing <code>)</code> of a function during its declaration: <code>function doSomething (param1, param2) {...}</code>.</p>
<p>An argument is the value passed into the function during its invocation/call: <code>doSomething(1, 2)</code></p>
<p>As seen above, to call/invoke a function, write the function name, followed by an opening and a closing bracket (without any whitespace). Required arguments should be provided between the opening and closing brackets (if any).</p>
<p>To drive this concept home, let's create a function to multiply two digits:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//        functionName   param1 param2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 * num2; <span class="hljs-comment">// task to carry out.</span>
}
</code></pre>
<p>It's as simple as that.</p>
<p>Having done that, let's call/invoke the function.</p>
<pre><code class="lang-javascript">multiplyNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6</span>
</code></pre>
<p>Notice that while creating the function, we declared two parameters: <code>num1</code> and <code>num2</code>. When calling the function, we assigned values to the two arguments: 1 and 2.</p>
<p><code>return</code> <strong>keyword</strong></p>
<p>Functions may return values or not.</p>
<p>If a function contains a <code>return</code> statement, like the <code>multiplyNumbers</code> function, then it will return a value if everything goes well. If there is no return statement for the function, it will return <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi"</span>);
}
</code></pre>
<p>If we invoke <code>sayHi</code>, it would log the text <code>Hi</code> to the console and it will also return <code>undefined</code>.</p>
<p>Remember that functions are like helpers, when you send a helper to carry out an assignment, you may require them to give you feedback (the result of the task they carried out) or you may not need feedback.</p>
<p>If you need feedback, add a <code>return</code> statement about what feedback you need. Otherwise, do not add a <code>return</code> statement to the function.</p>
<p>There is still a lot to learn about every data type we have highlighted in this article so take your time to practice these basics and when you feel comfortable enough using them, you'll see the need to dive deeper.</p>
<h2 id="heading-summary">Summary</h2>
<p>Variables are "pointers" to values. When you mention (use) a variable anywhere in your code, the variable identifier (name) is replaced with the value it points to. It's just like calling someone's name. The name doesn't respond, the person (value) behind the name is what you hope to get as a response.</p>
<p>By way of retention, do not try to cram all these rules and conventions. Feel free to refer back to this article when programming and in a short amount of time, you'll be used to all of them and you won't need to refer to any article ever again to name your variables properly.</p>
<p>If you should have anything in mind, remember to start variables with a lowercase letter if the variable is made of multiple words, subsequent words should start with uppercase letters. That is: <code>age</code>, <code>dateOfBirth</code>.</p>
<p>To create a variable, use the keyword <code>let</code>, <code>const</code>, or <code>var</code>, followed by the variable name. If you wish to initialize the variable, then on the same line before the semi-colon, input the assignment operator and variable value after it.</p>
<p>For example: <code>let score;</code> or <code>let score = 3;</code> (if you wish to initialize during declaration).</p>
<p>If you wish to use a variable, just mention its name and the value will be used during the execution of your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(a + b) <span class="hljs-comment">// 4</span>
</code></pre>
<p>This article also showed you the different data types in JavaScript and how to use them.</p>
<p>Did this post help? Let’s keep the conversation going. Feel free to share your thoughts or questions on Twitter (x) or LinkedIn. You can find me on Twitter (x) <a target="_blank" href="https://x.com/asoluka_tee">@asoluka_tee</a> and <a target="_blank" href="https://www.linkedin.com/in/tochukwu-austin-asoluka-415326155/">Tochukwu Austin Asoluka</a> on LinkedIn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Variables and Constants in Go? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data. In this article, we'll take a look at how variables and constant work in Go. Table of contents: What are Vari... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/variables-and-constants-in-go/</link>
                <guid isPermaLink="false">66c2f3bae041c8717c0645d2</guid>
                
                    <category>
                        <![CDATA[ Go ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Temitope Oyedele ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 07:26:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724052347929/f54eba57-fa4b-4b81-821e-41826d592933.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data.</p>
<p>In this article, we'll take a look at how variables and constant work in Go.</p>
<h2 id="heading-table-of-contents">Table of contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-variables">What are Variables?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-variable-in-go">How to Create a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-explicit-declaration">Explicit Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-shorthand-variable-declaration">Shorthand Variable Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-multiple-variable-declarations">Multiple Variable Declarations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-zero-values">Zero Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-scope">What is a Variable Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-naming-conventions-in-go">Naming Conventions in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-constants-in-go">What are Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-constants-in-go">How to Declare Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-constants-in-go">Type of Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-thats-a-wrap">That's a Wrap</a></p>
</li>
</ul>
<h2 id="heading-what-are-variables">What are Variables ?</h2>
<p>A variable is a storage location identified by a name (or identifier) that holds a value. This value can change (or vary) during a program's execution. This is why it's called a variable.</p>
<p>For example:</p>
<pre><code class="lang-go">myName := “temitope”

fmt.Println(myName)

myName:= ”oyedele”

fmt.Println(myName)
</code></pre>
<p>We created a variable with an identifier of <code>myName</code> which holds a string value.</p>
<p>If you noticed, we changed the value to another string, and we can do that multiple times because variables are allowed to do that.</p>
<p>Variables allow you to store data, which can be of different types, such as integers, floating-point numbers, strings, or objects.</p>
<h2 id="heading-how-to-create-a-variable-in-go">How to Create a Variable in Go</h2>
<p>There are two primary ways to create a variable in Go, explicit declaration and shorthand declaration.</p>
<h3 id="heading-explicit-declaration">Explicit Declaration</h3>
<p>This is the traditional way to create a variable in Go. It works by using the <code>var</code> keyword and declaring the variable’s type, making your code more readable and clear.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span> = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>You can see that, for each variable, we declared its datatype before assigning a value to it.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>The <code>var</code> keyword and data type can also be used without having an initial value:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span>
    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span>

    age = <span class="hljs-number">25</span>
    name = <span class="hljs-string">"Temitope"</span>
    height = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)
}
</code></pre>
<p>This way, the variables are declared first without an initial value. They are then assigned values later in the code. You'll still have the same output as the first.</p>
<h3 id="heading-shorthand-variable-declaration">Shorthand Variable Declaration</h3>
<p>The shorthand variable declaration syntax (<code>:=</code>) is a more concise way to declare variables. This method allows you to declare and initialize a variable in a single line without explicitly stating its type, as the type is inferred from the value assigned.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    age := <span class="hljs-number">25</span>

    name := <span class="hljs-string">"Temitope"</span>

    height := <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>Here, each variable was declared alongside its value, with Go inferring the datatype. For example, <code>age</code> was declared and initialized with a value of 25, and Go inferred its type as <code>int</code>. <code>name</code> was declared with the value "Temitope", and Go inferred its type as <code>string</code>. Lastly, <code>height</code> was declared with 5.7, and Go inferred its type as <code>float64</code>.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>One of the drawbacks of the shorthand variable declaration is that you can only use it inside of a function.</p>
<h2 id="heading-multiple-variable-declarations">Multiple Variable Declarations</h2>
<p>You can declare and initialize multiple variables on the same line by separating each variable with a comma. This approach is simple and straightforward. it is commonly used when the variables are related or when you want to initialize them together. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    <span class="hljs-keyword">var</span> age, height <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>, <span class="hljs-number">180</span>

    <span class="hljs-keyword">var</span> name, city <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>, <span class="hljs-string">"New York"</span>

    fmt.Println(age, height)

    fmt.Println(name, city)
}
</code></pre>
<p>Here, the variable <code>age</code> and <code>height</code> are both declared as integers and initialized with the values 25 and 180, respectively. Variable <code>name</code> and <code>city</code> are also both declared as strings and initialized with "Temitope" and "New York":</p>
<pre><code class="lang-plaintext">Output:
25 180
Temitope New York
</code></pre>
<p>You can also declare multiple variables in a block like so:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    <span class="hljs-keyword">var</span> (
        age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

        name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

        height <span class="hljs-keyword">int</span> = <span class="hljs-number">180</span>

        city <span class="hljs-keyword">string</span> = <span class="hljs-string">"New York"</span>
    )

    fmt.Println(age, name, height, city)

}
</code></pre>
<p>Here, the variables <code>age</code>, <code>name</code>, <code>height</code>, and <code>city</code> are declared within a single var block, with each variable getting its own line.</p>
<pre><code class="lang-plaintext">Output:
25 Temitope 180 New York
</code></pre>
<h3 id="heading-zero-values">Zero Values</h3>
<p>When variables are declared without being initialized, they are assigned zero values by default. These values differ depending on the type of variable. Below is an example of how you can declare default values:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    <span class="hljs-keyword">var</span> intValue <span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> floatValue <span class="hljs-keyword">float64</span>

    <span class="hljs-keyword">var</span> boolValue <span class="hljs-keyword">bool</span>

    <span class="hljs-keyword">var</span> stringValue <span class="hljs-keyword">string</span>

    <span class="hljs-keyword">var</span> ptrValue *<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> sliceValue []<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> mapValue <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>

    fmt.Println(<span class="hljs-string">"Zero values:"</span>)

    fmt.Println(<span class="hljs-string">"int:"</span>, intValue)

    fmt.Println(<span class="hljs-string">"float64:"</span>, floatValue)

    fmt.Println(<span class="hljs-string">"bool:"</span>, boolValue)

    fmt.Println(<span class="hljs-string">"string:"</span>, stringValue)

    fmt.Println(<span class="hljs-string">"pointer:"</span>, ptrValue)

    fmt.Println(<span class="hljs-string">"slice:"</span>, sliceValue)

    fmt.Println(<span class="hljs-string">"map:"</span>, mapValue)

}
</code></pre>
<p>In the code above, here’s what’s going to happen:</p>
<ul>
<li><p>The integer <code>intValue</code> will be given the zero value 0.</p>
</li>
<li><p>The floating-point number <code>floatValue</code> will be given the zero value 0.</p>
</li>
<li><p>The Boolean <code>boolValue</code> will be given the zero value <code>false</code>.</p>
</li>
<li><p>The string <code>stringValue</code> will be given the zero value "" (empty string).</p>
</li>
<li><p>The pointer <code>ptrValue</code>, slice <code>sliceValue</code>, and map <code>mapValue</code> will all be given the zero value <code>nil</code>.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-plaintext">Output:
Zero values:
int: 0
float64: 0
bool: false
string: 
pointer: &lt;nil&gt;
slice: []
map: map[]
</code></pre>
<h3 id="heading-what-is-a-variable-scope">What is a Variable Scope?</h3>
<p>Variables can be declared either globally or locally. The scope of a variable determines where it can be accessed and modified within your code.</p>
<p>Global variables are declared outside of any function, typically at the top of a file, and they can be accessed by any function within the same package.  Here’s an example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-keyword">var</span> globalCounter <span class="hljs-keyword">int</span> = <span class="hljs-number">0</span>

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

    globalCounter++

}

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

    fmt.Println(<span class="hljs-string">"Initial Counter:"</span>, globalCounter)

    incrementCounter()

    fmt.Println(<span class="hljs-string">"After Increment:"</span>, globalCounter)

}
</code></pre>
<p>In the above example, <code>globalCounter</code> is the global variable, and it is accessible by both the <code>incrementCounter</code> function and the <code>main</code> function.</p>
<p>Also, the value of <code>globalCounter</code> persists across function calls. This means that whatever change is made to it in one function affects its value in other parts of the program.</p>
<p>Local variables, on the other hand, are declared within a function or a block and are only accessible within that specific function or block. They are created when the function or block is executed and destroyed once it is completed. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    localCounter := <span class="hljs-number">0</span>

    localCounter++

    fmt.Println(<span class="hljs-string">"Local Counter:"</span>, localCounter)

}

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

    incrementCounter()

    incrementCounter()

}
</code></pre>
<p>In the code above, we have the <code>localCounter</code> as the local variable inside the <code>incrementCounter</code> function. Each time <code>incrementCounter</code> is called, a new <code>localCounter</code> is created, initialized to 0, and incremented.</p>
<p>The value of <code>localCounter</code> does not persist between function calls, so it cannot affect any part of a program when a change is made to the function.</p>
<h2 id="heading-naming-conventions-in-go">Naming Conventions in Go</h2>
<p>Proper naming of variables is crucial for writing clean, readable, and maintainable code. Go has some specific conventions and rules for naming variables. Below are some of them:</p>
<ul>
<li><p><strong>Use descriptive names:</strong>  Use names that clearly describe the purpose or content of the variable. For example, instead of using vague names like x or y, use names like <code>age</code>, <code>totalPrice</code>, or <code>userName</code> that clearly convey what the variable represents.</p>
</li>
<li><p><strong>Use CamelCase for Multi-Word Names:</strong> In Go, it's common practice to use camelCase for variable names that consist of multiple words. The first word is lowercase, and the first letter of each subsequent word is capitalized.</p>
</li>
<li><p><strong>Avoid Using Underscores:</strong> Unlike some other languages, Go prefers camelCase over using underscores to separate words in variable names. Stick to camelCase to adhere to Go’s idiomatic style.</p>
</li>
<li><p><strong>Use Short Names for Short-Lived Variables:</strong> For short-lived variables, such as loop counters or indices, it's acceptable to use short names like i, j, or k.</p>
</li>
</ul>
<h2 id="heading-what-are-constants-in-go">What are Constants in Go?</h2>
<p>Constants are immutable values defined at compile time that cannot be modified throughout the program's execution. They are useful for defining values that are known ahead of time and will remain the same.</p>
<p>Imagine you're building an online store where the standard shipping fee is always $10. You can declare it as a constant, so you can use it throughout your program whenever shipping charges need to be applied. If the shipping rates change, you only need to update the value in one place.</p>
<h2 id="heading-how-to-declare-constants-in-go">How to Declare Constants in Go</h2>
<p>You can declare constants using the <code>const</code> keyword, followed by the name, the type (optional if the value implies the type), and the value of the constant. Here’s how:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

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

    <span class="hljs-keyword">const</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14159</span>

    <span class="hljs-keyword">const</span> greeting <span class="hljs-keyword">string</span> = <span class="hljs-string">"Hello, World!"</span>

    fmt.Println(<span class="hljs-string">"Pi:"</span>, pi)

    fmt.Println(<span class="hljs-string">"Greeting:"</span>, greeting)

}
</code></pre>
<p>If you try to change a constant after being declared, then you’ll get a compile-time error.</p>
<h2 id="heading-types-of-constants-in-go">Types of Constants in Go</h2>
<p>Constants can be categorized as either typed or untyped. Both types of constants serve the same purpose. They provide fixed, immutable values throughout the program. However, they differ in how Go handles their types and how flexible they are when used.</p>
<p>Untyped constants are not assigned a type unless they are used in a context that requires a type. When you declare an untyped constant, Go will infer the type at the point where the constant is used. This makes untyped constants more flexible because they can be used in a number of settings without requiring type conversion.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-keyword">const</span> gravity = <span class="hljs-number">9.81</span>

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

    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">int</span> = <span class="hljs-number">10</span>

    <span class="hljs-keyword">var</span> acceleration <span class="hljs-keyword">float64</span> = gravity * <span class="hljs-keyword">float64</span>(height)

    fmt.Println(<span class="hljs-string">"Acceleration:"</span>, acceleration)

}
</code></pre>
<p>Here, <code>gravity</code> is the untyped constant. This means Go can infer its type based on how it is used. When <code>gravity</code> is used in a calculation with a <code>float64</code>, Go will automatically treat it as a <code>float64</code>.</p>
<p>Unlike untyped constants, the typed constants have an explicitly declared type. This means they can only be used in contexts that match that type or can be converted to a compatible type. Typed constants are stricter, ensuring that the value is always treated as the specific type it was declared with.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-keyword">const</span> speedOfLight <span class="hljs-keyword">int</span> = <span class="hljs-number">299792458</span>

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

    <span class="hljs-keyword">var</span> distance <span class="hljs-keyword">int</span> = speedOfLight * <span class="hljs-number">2</span>

    fmt.Println(<span class="hljs-string">"Distance:"</span>, distance)

}
</code></pre>
<p>Here, <code>speedOfLight</code> is the typed constant with the type <code>int</code>.</p>
<p>It can only be used in operations with other <code>int</code> values or converted explicitly to a different type.</p>
<h2 id="heading-thats-a-wrap">That’s a Wrap</h2>
<p>In this article, we took a look at what variables and constants are and how to declare them in Go.</p>
<p>Variables and constants are critical tools in programming. They allow developers to efficiently manage and manipulate data. When you understand how to use them, you can improve the quality of your code. </p>
<p>Please share if you found this helpful.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Beginner's Guide to LLMs – What's a Large-Language Model and How Does it Work? ]]>
                </title>
                <description>
                    <![CDATA[ ChatGPT was released in November 2022. Since then, we’ve witnessed rapid advancements in the field of AI and technology. But did you know that the journey of AI chatbots began way back in 1966 with ELIZA? ELIZA was not as sophisticated as today’s mod... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-beginners-guide-to-large-language-models/</link>
                <guid isPermaLink="false">66be59dfcea37428c836a987</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Open Source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavishya Pandit ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 19:41:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723750839199/0dc3a4ff-3e4e-4055-b3c1-955474946b0f.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>ChatGPT was released in November 2022. Since then, we’ve witnessed rapid advancements in the field of AI and technology.</p>
<p>But did you know that the journey of AI chatbots began way back in 1966 with ELIZA? ELIZA was not as sophisticated as today’s models like GPT, but it marked the beginning of the exciting path that led us to where we are now.</p>
<p>Language is the essence of human interaction, and in the digital age, teaching machines to understand and generate language has become a cornerstone of artificial intelligence.</p>
<p>The models we interact with today—such as GPT, Llama3, Gemini, and Claude—are known as Large Language Models (LLMs). This is because they are trained on vast datasets of text, enabling them to perform a wide range of language-related tasks.</p>
<p>But what exactly are LLMs, and why is there so much hype surrounding them?</p>
<p>In this article, you'll learn what LLMs are and what is the hype all about.</p>
<h2 id="heading-what-are-llms"><strong>What Are LLMs?</strong></h2>
<p>Large Language Models are AI models trained on vast amounts of text data to understand, generate, and manipulate human language. They are based on deep learning architectures like transformers, which allow them to process and predict text in a way that mimics human understanding.</p>
<p>In simpler terms, an LLM is a computer program that has been trained on many examples to differentiate between an apple and a Boeing 787 – and to be able to describe each of them.</p>
<p>Before they're ready for use and can answer your questions, LLMs are trained on massive datasets. Realistically, a program cannot conclude anything from a single sentence. But after analyzing, say, trillions of sentences, it's able to build a logic to complete sentences or even generate its own.</p>
<h3 id="heading-how-to-train-an-llm">How to Train an LLM</h3>
<p>Here’s how the training process works:</p>
<ol>
<li><p><strong>Data Collection:</strong> The first step involves gathering millions (or even billions) of text documents from diverse sources, including books, websites, research papers, and social media. This extensive dataset serves as the foundation for the model’s learning process.</p>
</li>
<li><p><strong>Learning Patterns:</strong> The model analyzes the collected data to identify and learn patterns in the text. These patterns include grammar rules, word associations, contextual relationships, and even some level of common sense. By processing this data, the model begins to understand how language works.</p>
</li>
<li><p><strong>Fine-Tuning:</strong> After the initial training, the model is fine-tuned for specific tasks. This involves adjusting the model’s parameters to optimize its performance for tasks such as translation, summarization, sentiment analysis, or question-answering.</p>
</li>
<li><p><strong>Evaluation and Testing:</strong> Once trained, the model is rigorously tested against a series of benchmarks to evaluate its accuracy, efficiency, and reliability. This step ensures that the model performs well in real-world applications.</p>
</li>
</ol>
<p>After the training process is completed, the models are heavily tested on a series of benchmarks for accuracy, efficiency, security, and so on.</p>
<h2 id="heading-applications-of-llms"><strong>Applications of LLMs</strong></h2>
<p>LLMs have a wide range of applications, from content generation to prediction and a lot more.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723742816242/6e40d678-96ed-4f51-aa35-61c565548a32.png" alt="Applications of LLMs in different domains like Healthcare, Education, Customer Support, and so on." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-content-creation"><strong>Content Creation:</strong></h3>
<ul>
<li><p><strong>Writing Assistance:</strong> Tools like Grammarly utilize LLMs to provide real-time suggestions for improving grammar, style, and clarity in writing. Whether you’re drafting an email or writing a novel, LLMs can help you polish your text.</p>
</li>
<li><p><strong>Automated Storytelling:</strong> AI models can now generate creative content, from short stories to full-length novels. These models can emulate the style of famous authors or even create entirely new literary styles.</p>
</li>
</ul>
<h3 id="heading-customer-service"><strong>Customer Service:</strong></h3>
<ul>
<li><p><strong>Chatbots:</strong> Many companies deploy AI-powered chatbots that can understand and respond to customer inquiries in real time. These chatbots can handle a wide range of tasks, from answering frequently asked questions to processing orders.</p>
</li>
<li><p><strong>Personal Assistants:</strong> Virtual assistants like Siri and Alexa use LLMs to interpret and respond to voice commands, providing users with information, reminders, and entertainment on demand.</p>
</li>
</ul>
<h3 id="heading-healthcare"><strong>Healthcare:</strong></h3>
<ul>
<li><p><strong>Medical Record Summarization:</strong> LLMs can assist healthcare professionals by summarizing patient records, making it easier to review critical information and make informed decisions.</p>
</li>
<li><p><strong>Diagnostic Assistance:</strong> AI models can analyze patient data and medical literature to assist doctors in diagnosing diseases and recommending treatments.</p>
</li>
</ul>
<h3 id="heading-research-and-education"><strong>Research and Education:</strong></h3>
<ul>
<li><p><strong>Literature Review:</strong> LLMs can sift through vast amounts of research papers to provide concise summaries, identify trends, and suggest new research directions.</p>
</li>
<li><p><strong>Educational Tools:</strong> AI-powered tutors can offer personalized learning experiences by adapting to a student’s progress and needs. These tools can provide instant feedback and tailored study plans.</p>
</li>
</ul>
<h3 id="heading-entertainment"><strong>Entertainment:</strong></h3>
<ul>
<li><p><strong>Game Development:</strong> LLMs are used to create more dynamic and responsive characters in video games. These AI-driven characters can engage with players more realistically and interactively.</p>
</li>
<li><p><strong>Music and Art Generation:</strong> AI models are now capable of composing music, generating artwork, and even writing scripts for movies, pushing the boundaries of creative expression.</p>
</li>
</ul>
<h2 id="heading-challenges-with-llms"><strong>Challenges with LLMs</strong></h2>
<p>While LLMs are powerful, they are not without their challenges. ChatGPT has over 150 Million monthly users, this gives us an idea about how big the impact of AI is. But new technologies pose some challenges too.</p>
<h3 id="heading-bias-and-fairness"><strong>Bias and Fairness:</strong></h3>
<ul>
<li>LLMs learn from the data they are trained on, which can include biases present in society. This can lead to biased or unfair outcomes in their predictions or responses. Addressing this requires careful dataset curation and algorithm adjustments to minimize bias.</li>
</ul>
<h3 id="heading-data-privacy"><strong>Data Privacy:</strong></h3>
<ul>
<li>LLMs may inadvertently learn and retain sensitive information from the data they are trained on, raising privacy concerns. There’s ongoing research on how to make LLMs more privacy-preserving.</li>
</ul>
<h3 id="heading-resource-intensive"><strong>Resource Intensive:</strong></h3>
<ul>
<li>Training LLMs require immense computational power and large datasets, which can be costly and environmentally taxing. Efforts are being made to create more efficient models that require less energy and data.</li>
</ul>
<h3 id="heading-interpretability"><strong>Interpretability:</strong></h3>
<ul>
<li>LLMs are often seen as "black boxes," meaning it’s challenging to understand exactly how they arrive at certain conclusions. Developing methods to make AI more interpretable and explainable is an ongoing research area.</li>
</ul>
<h2 id="heading-coding-with-llms-a-replicate-example"><strong>Coding with LLMs: A Replicate Example</strong></h2>
<p>For those of you who like to get your hands dirty with code, here’s a quick example of how to use an LLM with the Replicate library.</p>
<p><strong>Replicate</strong> is a Python package that simplifies the process of running machine learning models in the cloud. It provides a user-friendly interface to access and utilize a vast collection of pre-trained models from the Replicate platform.</p>
<p>With Replicate, you can easily:</p>
<ul>
<li><p>Run models directly from your Python code or Jupyter notebooks.</p>
</li>
<li><p>Access various model types, including image generation, text generation, and more.</p>
</li>
<li><p>Leverage powerful cloud infrastructure for efficient model execution.</p>
</li>
<li><p>Integrate AI capabilities into your applications without the complexities of model training and deployment.</p>
</li>
</ul>
<p>Here’s a simple code snippet to generate text using Meta's llama3-70b-instruct model. <strong>Llama 3</strong> is one of the latest open-source large language models developed by Meta. It's designed to be highly capable, versatile, and accessible, allowing users to experiment, innovate, and scale their AI applications.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> replicate <span class="hljs-comment"># pip install replicate</span>

<span class="hljs-comment"># Get your token from -&gt; https://replicate.com/account/api-tokens</span>
os.environ[<span class="hljs-string">"REPLICATE_API_TOKEN"</span>] = <span class="hljs-string">"TOKEN"</span>
api = replicate.Client(api_token=os.environ[<span class="hljs-string">"REPLICATE_API_TOKEN"</span>])

<span class="hljs-comment"># Running llama3 model using replicate</span>
output = api.run(
    <span class="hljs-string">"meta/meta-llama-3-70b-instruct"</span>,
        input={<span class="hljs-string">"prompt"</span>: <span class="hljs-string">'Hey how are you?'</span>}
    )

<span class="hljs-comment"># Printing llama3's response</span>
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> output:
    print(item, end=<span class="hljs-string">""</span>)
</code></pre>
<p>Explanation:</p>
<ul>
<li><p>We first save the replicate token using the os package as an environment variable.</p>
</li>
<li><p>Then we use the Llama3 70b-instruct model to give a response based on our prompt. You can customize the output by changing the prompt.</p>
</li>
</ul>
<p>And what is a prompt? <strong>A prompt is essentially a text-based instruction or query given to an AI model.</strong> It's like providing a starting point or direction for the AI to generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way.</p>
<p>For example:</p>
<ul>
<li><p><strong>"Write a poem about a robot exploring the ocean."</strong></p>
</li>
<li><p><strong>"Translate 'Hello, how are you?' into Spanish."</strong></p>
</li>
<li><p><strong>"Explain quantum computing in simple terms."</strong></p>
</li>
</ul>
<p>These are all prompts that guide the AI to produce a specific output.</p>
<p>Using Meta's <strong>llama-3-70b-instruct</strong>, you can build various tools around applications that are mentioned in this article. Tweak the prompts based on your use case and you will be ready to go! ⚡️</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, we explored the world of Large Language Models, providing a high-level understanding of how they work and their training process. We delved into the core concepts of LLMs, including data collection, pattern learning, and fine-tuning, and discussed the extensive applications of LLMs across various industries.</p>
<p>While LLMs offer immense potential, they also come with challenges such as bias, privacy concerns, resource demands, and interpretability. Addressing these challenges is crucial as AI continues to evolve and integrate more deeply into our lives.</p>
<p>We also provided a glimpse into how you can start working with LLMs using the Replicate library, showing that even complex models like Llama3 70b-instruct can be accessible to developers with the right tools.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create A Color Picker Tool Using HTML, CSS, and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wanted to create your own interactive tools using just HTML, CSS, and JavaScript? In this article, we'll create a fun and straightforward project: a color picker tool. This handy little tool will let users select any color they like and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-color-picker-using-html-css-and-javascript/</link>
                <guid isPermaLink="false">66bde01135055423d89b698f</guid>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Fanny Nyayic ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 11:01:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723709466316/80aae148-6211-4070-ba33-eb4290408912.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wanted to create your own interactive tools using just HTML, CSS, and JavaScript? In this article, we'll create a fun and straightforward project: a color picker tool.</p>
<p>This handy little tool will let users select any color they like and instantly see its HEX and RGB values.</p>
<p>So, grab your favorite code editor, and let's get started!</p>
<h2 id="heading-step-1-set-up-your-project">Step 1: Set Up Your Project</h2>
<ol>
<li><p><strong>Create a New Folder</strong>: Start by creating a new folder on your computer for this project. You can name it <strong>color-picker-tool</strong>.</p>
</li>
<li><p><strong>Create Files</strong>: Inside the folder, create three files:</p>
<ul>
<li><p><strong>index.html</strong></p>
</li>
<li><p><strong>styles.css</strong></p>
</li>
<li><p><strong>script.js</strong></p>
</li>
</ul>
</li>
</ol>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723707100431/55c7cc93-7b0d-4d67-abb1-8104dbeda18d.png" alt="55c7cc93-7b0d-4d67-abb1-8104dbeda18d" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-step-2-build-the-html-structure">Step 2: Build the HTML Structure</h2>
<ol>
<li><p>Open the <strong>index.html</strong> file in your code editor.</p>
</li>
<li><p><strong>Add Basic HTML Structure</strong>: Add the following code into <strong>index.html</strong>: or press <code>SHIFT+!</code> then press <code>Enter</code> to set the Emmet structure, then change the document title to <code>"Color Picker Tool".</code></p>
</li>
<li><p>Link your <strong>styles.css</strong> and <strong>script.js</strong> files too.</p>
<pre><code class="lang-html"> <span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Color Picker Tool<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

     <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
</li>
</ol>
<h3 id="heading-explanation">Explanation:</h3>
<ul>
<li><p><code>&lt;!DOCTYPE html&gt;</code>: This tells the browser that the document is an HTML5 document.</p>
</li>
<li><p><code>&lt;html lang="en"&gt;</code>: The root element of the HTML document, with the language set to English.</p>
</li>
<li><p><code>&lt;head&gt;</code>: Contains meta-information about the document, like character set and title.</p>
</li>
<li><p><code>&lt;title&gt;</code>: Sets the title of the webpage, which appears in the browser tab.</p>
</li>
<li><p><code>&lt;link rel="stylesheet" href="styles.css"&gt;</code>: Links to the CSS file that styles the page.</p>
</li>
<li><p><code>&lt;body&gt;</code>: Contains the content of the webpage.</p>
</li>
<li><p><code>&lt;script src="script.js"&gt;&lt;/script&gt;</code>: Links to the JavaScript file that adds interactivity to the page.</p>
</li>
</ul>
<ol start="3">
<li><p><strong>Add the body content:</strong></p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"color-picker"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"colorInput"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"#ff0000"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"color-info"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>HEX: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"hexValue"</span>&gt;</span>#ff0000<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>RGB: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"rgbValue"</span>&gt;</span>rgb(255, 0, 0)<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-explanation-1">Explanation:</h3>
</li>
</ol>
<ul>
<li><p><code>&lt;div class="color-picker"&gt;</code>: A container for the color picker elements.</p>
</li>
<li><p><code>&lt;input type="color" id="colorInput" value="#ff0000"&gt;</code>: An input element that lets users pick a color. The <code>value</code> attribute sets the default color.</p>
</li>
<li><p><code>&lt;div class="color-info"&gt;</code>: A container for displaying color information.</p>
</li>
<li><p><code>&lt;p&gt;HEX: &lt;span id="hexValue"&gt;#ff0000&lt;/span&gt;&lt;/p&gt;</code>: Displays the HEX value of the selected color.</p>
</li>
<li><p><code>&lt;p&gt;RGB: &lt;span id="rgbValue"&gt;rgb(255, 0, 0)&lt;/span&gt;&lt;/p&gt;</code>: Displays the RGB value of the selected color.</p>
</li>
</ul>
<p>Here is what we'll have:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723708023384/8a3b4b0f-39a3-4cc6-9550-64b593cd5662.png" alt="8a3b4b0f-39a3-4cc6-9550-64b593cd5662" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-step-3-style-with-css">Step 3: Style with CSS</h2>
<ol>
<li><p>Open the <strong>styles.css</strong> file in your code editor.</p>
</li>
<li><p><strong>Add CSS Styles</strong>: Copy and paste the following code into <strong>styles.css</strong>:</p>
<pre><code class="lang-css"> <span class="hljs-selector-tag">body</span> {
     <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
     <span class="hljs-attribute">display</span>: flex;
     <span class="hljs-attribute">justify-content</span>: center;
     <span class="hljs-attribute">align-items</span>: center;
     <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
     <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
     <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f0f0f0</span>;
 }
 <span class="hljs-selector-class">.color-picker</span> {
     <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
     <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
     <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
     <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">4px</span> <span class="hljs-number">8px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
     <span class="hljs-attribute">text-align</span>: center;
 }
 <span class="hljs-selector-class">.color-info</span> {
     <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
 }
 <span class="hljs-selector-tag">p</span> {
     <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span> <span class="hljs-number">0</span>;
     <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
 }
</code></pre>
</li>
</ol>
<h3 id="heading-explanation-2">Explanation:</h3>
<ul>
<li><p><code>body</code>: Styles the body of the page. It centers the content both vertically and horizontally and sets a light gray background.</p>
</li>
<li><p><code>font-family: Arial, sans-serif;</code>: Sets the font for the text on the page.</p>
</li>
<li><p><code>display: flex;</code>: Uses Flexbox to layout the page.</p>
</li>
<li><p><code>justify-content: center;</code> and <code>align-items: center;</code>: Centers the content.</p>
</li>
<li><p><code>height: 100vh;</code>: Sets the height to 100% of the viewport height.</p>
</li>
<li><p><code>margin: 0;</code>: Removes default margin.</p>
</li>
<li><p><code>background-color: #f0f0f0;</code>: Sets the background color of the page.</p>
</li>
<li><p><code>.color-picker</code>: Styles the color picker container with a white background, padding, rounded corners, and a shadow for a card-like appearance.</p>
</li>
<li><p><code>.color-info</code>: Adds a margin at the top to separate it from the color input.</p>
</li>
<li><p><code>p</code>: Styles the paragraphs within the color info, setting margin and font size.</p>
</li>
</ul>
<p>Here is what we will have:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723708068790/0b16e350-d292-4076-b5ee-29016970f762.png" alt="0b16e350-d292-4076-b5ee-29016970f762" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>At this point, we can pick a color but the color codes won't be displayed. To have the color codes displayed, we'll have to add some JavaScript.</p>
<h2 id="heading-step-4-add-javascript-functionality">Step 4: Add JavaScript Functionality</h2>
<ol>
<li><p>Open the <code>script.js</code> file in your code editor.</p>
</li>
<li><p><strong>Add JavaScript Code</strong>: Add the following code into <code>script.js</code>:</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'colorInput'</span>).addEventListener(<span class="hljs-string">'input'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-keyword">const</span> color = <span class="hljs-built_in">this</span>.value;
     <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'hexValue'</span>).textContent = color;
     <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'rgbValue'</span>).textContent = hexToRgb(color);
 });
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hexToRgb</span>(<span class="hljs-params">hex</span>) </span>{
     <span class="hljs-keyword">const</span> r = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">const</span> g = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">const</span> b = <span class="hljs-built_in">parseInt</span>(hex.slice(<span class="hljs-number">5</span>, <span class="hljs-number">7</span>), <span class="hljs-number">16</span>);
     <span class="hljs-keyword">return</span> <span class="hljs-string">`rgb(<span class="hljs-subst">${r}</span>, <span class="hljs-subst">${g}</span>, <span class="hljs-subst">${b}</span>)`</span>;
 }
</code></pre>
<h3 id="heading-explanation-3">Explanation:</h3>
<ul>
<li><p><code>document.getElementById('colorInput')</code>: Selects the color input element by its <code>ID</code>.</p>
</li>
<li><p><code>.addEventListener('input', function() {...})</code>: Adds an event listener that triggers whenever the user selects a new color.</p>
</li>
<li><p><code>const color = this.value;</code>: Gets the current value of the color input, which is in HEX format.</p>
</li>
<li><p><code>document.getElementById('hexValue').textContent = color;</code>: Updates the text content of the HEX value display with the selected color.</p>
</li>
<li><p><code>document.getElementById('rgbValue').textContent = hexToRgb(color);</code>: Converts the HEX color to RGB and updates the RGB value display.</p>
</li>
<li><p><code>function hexToRgb(hex) {...}</code>: A function that converts a HEX color string to an RGB string.</p>
<ul>
<li><p><code>parseInt(hex.slice(1, 3), 16)</code>: Converts the first two characters of the HEX color (after the <code>#</code>) to a decimal number, representing the red component.</p>
</li>
<li><p><code>parseInt(hex.slice(3, 5), 16)</code>: Converts the next two characters to the green component.</p>
</li>
<li><p><code>parseInt(hex.slice(5, 7), 16)</code>: Converts the last two characters to the blue component.</p>
</li>
<li><p><code>return</code> rgb(${r}, ${g}, ${b})<code>;</code>: Returns the RGB color as a string.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h2 id="heading-step-5-test-your-color-picker-tool">Step 5: Test Your Color Picker Tool</h2>
<ol>
<li><p><strong>Open the Project in a Browser</strong>: Open the <strong>index.html</strong> file in a web browser to view your color picker tool.</p>
</li>
<li><p><strong>Interact with the Tool</strong>: Use the color input to select different colors. The HEX and RGB values should update automatically as you select new colors.</p>
</li>
</ol>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Congratulations! You've successfully created a color picker tool using HTML, CSS, and JavaScript.</p>
<p>This project is a great way to practice working with user input and manipulating the DOM. You can further enhance this tool by adding features like copying color values to the clipboard or saving favorite colors.</p>
<p>Enjoy experimenting and learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Does Recursion Work? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn about recursion and how it works. You need a good understanding of how functions work before learning recursion. I have used Python code for examples in this article because of its simple syntax, but the concept of rec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-recursion/</link>
                <guid isPermaLink="false">66d4608b230dff016690584b</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Recursion ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Palistha Singh ]]>
                </dc:creator>
                <pubDate>Thu, 25 Jul 2024 15:03:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/Frame-1--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn about recursion and how it works.</p>
<p>You need a good understanding of how functions work before learning recursion. I have used Python code for examples in this article because of its simple syntax, but the concept of recursion is the same for every programming language.</p>
<h2 id="heading-what-is-recursion">What is Recursion?</h2>
<p>In most programming languages, a function can call another function. But a function can also call itself. Recursion is the technique where a function calls itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-bash">def call_me():
    call_me()
</code></pre>
<p>Here, the function calls itself, which is called recursion.</p>
<p>But "calling itself" is just a programmatic definition of recursion. Recursion involves breaking down a problem into smaller pieces to the point that it cannot be further broken down. You solve the small pieces and put them together to solve the overall problem.</p>
<h2 id="heading-real-life-analogy-of-recursion">Real Life Analogy of Recursion</h2>
<p>Lets understand how recursion really works with the help of an example.</p>
<p>Imagine you're in line for a Disney ride, and you don't know how many people are ahead of you.</p>
<p>To find out, you ask the person in front of you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--4-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Trying to find out how many people are in front of you in line</em></p>
<p>That person also doesn't know, so they ask the person in front of them.</p>
<p>This process continues until the question reaches the person at the very front of the line, who sees that there is no one in front of them and replies that there are zero people ahead.</p>
<p>The replies then start to propagate back through the line. Each person adds one to the number they were told before passing the information back.</p>
<p>When the person at the front replies, <strong>"There are 0 people ahead"</strong> the next person adds one and replies, <strong>"There is 1 person ahead"</strong> and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--5-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Everyone knows how many people are in front of them in line</em></p>
<p>By the time the response reaches the person directly in front of you, they add one more and tell you. This way, you can determine your position in the line by just adding <strong>1</strong> to the number the person in front of you gave.</p>
<p>This example illustrates how recursion breaks a problem into smaller subproblems and then combines their solutions to solve the original problem.</p>
<p>Each person in the line represents a smaller instance of the same problem: determining the number of people ahead. By solving these smaller instances and combining their results, the overall problem is resolved. This is exactly how recursion works.</p>
<h2 id="heading-technical-details-of-recursion">Technical Details of Recursion</h2>
<p>The most important things to consider while coding recursion is to find out:</p>
<ul>
<li><p><strong>Recursive Case:</strong> Minimum work we can do. In the above example, asking the person in front of you how many people are ahead of them is the least amount of work we can do.</p>
</li>
<li><p><strong>Base Case:</strong> Condition where no work is required. In the above example, the person on the front of the line doesn’t have to ask anything so it is the condition where no work is required.</p>
</li>
</ul>
<h2 id="heading-simple-example-of-recursion">Simple Example of Recursion</h2>
<p>Calculating a factorial is the simplest example of recursion that will really help you understand how it works.</p>
<p>There are many ways to calculate the factorial of a number. But here we will see the recursive way to find it.</p>
<p>Before thinking about how we do it, we need to know what the factorial of a number is.</p>
<p>The factorial of a number is the multiplication of all numbers from <strong>1</strong> up to that number.</p>
<p>For example, the factorial of <strong>5</strong> is <strong>120</strong> – that is <strong>5</strong>×<strong>4</strong>×<strong>3</strong>×<strong>2</strong>×<strong>1</strong>.</p>
<p>We can also represent this mathematically like this:</p>
<p><code>5×(5−1)!</code></p>
<p>This means that if we know the value of <code>(5−1)!</code> we can easily get the factorial by just multiplying <strong>5</strong> by it.</p>
<p>Here’s how we find the factorials of <strong>4</strong>, <strong>3</strong>, <strong>2</strong>, <strong>1</strong>, and <strong>0</strong>:</p>
<pre><code class="lang-bash">Factorial of 4 = 4×(4−1)!
Factorial of 3 = 3×(3−1)!
Factorial of 2 = 2×(2−1)!
Factorial of 1 = 1
Factorial of 0 = 1
</code></pre>
<p>By looking at this, it is clear that to find the factorial of <strong>5</strong>, we must multiply <strong>5</strong> by <code>4!</code>.</p>
<h3 id="heading-more-general-example">More general example</h3>
<p>To find the factorial of <code>n</code>, we need to multiply <code>n</code> with <code>(n−1)!</code>. This is something you need to do recursively.</p>
<p>Now, there must be a stopping condition for recursion. The stopping condition is where we perform no further operation. When <code>n</code> is <strong>1</strong> or <code>n</code> is <strong>0</strong>, we can simply stop the recursion as these values have known factorials. We can simply say the factorial of <strong>1</strong> is <strong>1</strong> and the same is true for <strong>0</strong>.</p>
<p>So, breaking it down, the minimum amount of work we need to do to find the factorial of n is <code>n×(n−1)!</code>. And we can stop performing operations on it when we find the factorial of <strong>1</strong> or <strong>0</strong>.</p>
<p>Let's see how it looks in code:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># calculate factorial of n</span>
def fact(n):

   <span class="hljs-comment"># no work required</span>
    <span class="hljs-keyword">if</span> n == 1 or n == 0:
        <span class="hljs-built_in">return</span> 1

    <span class="hljs-comment"># minimum amount of work</span>
    <span class="hljs-built_in">return</span> n * fact(n - 1)

n = 5

<span class="hljs-comment"># calculate factorial</span>
factorial = fact(n)
<span class="hljs-built_in">print</span>(factorial)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">120
</code></pre>
<p>Let's see how it works:</p>
<p>In the first function call, the factorial of <strong>5</strong> is evaluated. Then in the second call, the factorial of <strong>4</strong> is evaluated, and so on until the factorial of <strong>2</strong> is evaluated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-1--5-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Recursively calculating Factorial of 5</em></p>
<p>While calling the factorial of <strong>2</strong>, we have <code>2×fact(2−1)</code>, which is <code>2×fact(1)</code>.</p>
<p>This hits our base case. So, the recursion stops and <code>2×fact(1)</code> returns <code>2×1</code> to the preceding function call, and the result gets popped up the stack.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Fourth function call returning 2 to preceding function call and getting popped up from the stack</em></p>
<p>Similarly, here’s how everything else evaluates:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>3rd function call returning 6 to the preceding function call and getting popped up from the stack</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>2nd function call returning 24 to the preceding function call and getting popped up from the stack</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>1st function call returning 120 to the initial function call and getting popped up from the stack</em></p>
<p>So the function finally returns the value <strong>120</strong> to the initial function call.</p>
<h3 id="heading-why-do-we-need-a-base-case">Why Do We Need a Base Case?</h3>
<p>In the above example we have used the stopping condition for the code. But what if we don’t add a stopping condition or what if the function we write never meets the stopping condition?</p>
<p>Will the code run forever?</p>
<p>No – even if you don’t terminate, your code won't run forever. Let’s understand why this is the case with the help of an example.</p>
<pre><code class="lang-bash">def print_five():
    <span class="hljs-built_in">print</span>(5)

    <span class="hljs-comment"># call itself</span>
    print_five()

<span class="hljs-comment"># function call</span>
print_five()
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-bash">5
5
5
...

RecursionError: maximum recursion depth exceeded
</code></pre>
<p>If you run the above code, you will see that the function doesn’t run forever and ends with a message <code>RecursionError: maximum recursion depth exceeded</code>.</p>
<p>When a function is invoked, it is stored in a call stack. Here's how the function <code>print_five()</code> is stored in the call stack when it is invoked for the first time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--6-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Call stack on the first function call</em></p>
<p>The function calls itself again and again, and the function is stored in the call stack with each call.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--8-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Call stack after n function calls</em></p>
<p>But the call stack has a limited size and cannot store an unlimited number of functions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/How-many--7-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>No space on call stack resulting in stack overflow</em></p>
<p>When the stack is full, it cannot accommodate any more calls, causing a stack overflow error.</p>
<p>Therefore, the base case is essential to prevent such errors and ensure the recursion terminates properly.</p>
<p>Now let's see another example to understand recursion even more.</p>
<h2 id="heading-how-to-check-if-a-word-is-a-palindrome">How to Check if a Word is a Palindrome</h2>
<p>Before we dive into the code, you should know what a palindrome is. A palindrome is a word that reads the same forwards and backwards.</p>
<p>For example, <code>racecar</code> reads the same forwards and backwards.</p>
<p>To check if a word is a palindrome, we have to check if the first and last letters are the same. If they are, we then check if the second and second-to-last letters are the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if first and last characters of racecar are the same</em></p>
<p>In the context of <code>racecar</code>, the first and last letters are the same, so we check if the second and second-to-last letters are the same. They are, so now we check if the third and third-to-last letters are the same. Now there is only one letter left to check. A single letter is always a palindrome because it reads the same both ways.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>How to check if racecar is a palindrome</em></p>
<p>So, now let's try thinking about it recursively, which involves the minimum amount of work and determining when no work is required.</p>
<h3 id="heading-minimum-amount-of-work">Minimum amount of work</h3>
<p>Check if the first and last letters are the same, and if they are, remove the first and last letters from the word.</p>
<h3 id="heading-no-work-required">No work required</h3>
<p>When there is one letter or no letters left at all, we can simply say it is a palindrome.</p>
<p>Now, let's see how the code looks:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># check palindrome</span>
def check_palindrome(text):

    <span class="hljs-comment"># stopping condition</span>
    <span class="hljs-comment"># if the size of text is 1 or 0 return true</span>
    <span class="hljs-keyword">if</span> len(text) == 0 or len(text) == 1:
        <span class="hljs-built_in">return</span> True

    <span class="hljs-comment"># least amount of work</span>
    <span class="hljs-comment"># check if first and last char are the same</span>
    <span class="hljs-comment"># if same remove first and last char from string</span>
    <span class="hljs-keyword">if</span>(text[0]==text[-1]):
        <span class="hljs-built_in">return</span>(check_palindrome(text[1:-1]))

    <span class="hljs-built_in">return</span> False

<span class="hljs-comment"># check if string is palindrome</span>
text = <span class="hljs-string">"racecar"</span>
is_palindrome = check_palindrome(text)
<span class="hljs-built_in">print</span>(is_palindrome)
</code></pre>
<p>Here's how the above code works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/Frame-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if racecar is a palindrome</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/checkpalindrome.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Check if racecar is a palindrome</em></p>
<h2 id="heading-when-to-use-recursion">When to Use Recursion</h2>
<p>Recursion can appear elegant and simple. But it often requires many steps to solve even simple problems due to the CPU overhead from repeatedly adding methods to the stack. So before using it, make sure you carefully consider whether it's the right solution for your problem.</p>
<p>When code requires multiple loops and looks confusing and messy, recursion can offer a cleaner solution. Its use, however, depends on the specific code and the type of data or data structure involved. For data structures like trees and graphs, recursion can be particularly useful.</p>
<p>Despite its simplicity in appearance, recursion can be hard to understand and may take multiple steps even for simple problems. So again, make sure you think about your particular use case.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>This is just an introduction to recursion. There are many cases where recursion is used, and you might be confused about how everything works. I will cover more advanced examples on recursion in the next article.</p>
<p>By the way, here are the resources that I found simple and useful while learning recursion:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=IJDJ0kBx2LM&amp;t=657s">freeCodeCamp video on recursion</a>: I have to give a shout-out to freeCodeCamp for their excellent video on recursion, which inspired much of this article.</p>
</li>
<li><p><a target="_blank" href="https://programiz.pro/course/learn-recursion-with-python">Recursion by Programiz Pro</a>: Another good resource is the Recursion course by Programiz. It's a premium course, so it's not free, but it's thoughtfully designed. Plus, you can actually practice directly on their platform, which makes it well worth it.</p>
</li>
</ul>
<p>No matter where you learn from, don't spend too much time searching for the perfect resource. Just grasp the concepts and start practicing—that's the only way you'll truly learn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Linux for Beginners: From Basics to Advanced Techniques [Full Book] ]]>
                </title>
                <description>
                    <![CDATA[ Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux. While empowering you in your current role, lear... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-linux-for-beginners-book-basic-to-advanced/</link>
                <guid isPermaLink="false">66912d3051ed9fa23c06c654</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zaira Hira ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jul 2024 13:18:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720790242560/764782a4-1bf3-45a5-857c-7fe3921bfb08.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Learning Linux is one of the most valuable skills in the tech industry. It can help you get things done faster and more efficiently. Many of the world's powerful servers and supercomputers run on Linux.</p>
<p>While empowering you in your current role, learning Linux can also help you transition into other tech careers like DevOps, Cybersecurity, and Cloud Computing.</p>
<p>In this handbook, you'll learn the basics of the Linux command line, and then transition to more advanced topics like shell scripting and system administration. Whether you are new to Linux or have been using it for years, this book has something for you.</p>
<p>Important Note: All examples in this book are demonstrated in Ubuntu 22.04.2 LTS (Jammy Jellyfish). Most command line tools are more or less the same in other distributions. However, some GUI applications and commands may differ if you are working on another Linux distribution.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-11-getting-started-with-linux">1.1. Getting Started with Linux</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-22-command-structure">2.2. Command Structure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-43-managing-files-and-directories">4.3. Managing Files and Directories</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-52-mastering-nano">5.2. Mastering Nano</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-6-bash-scripting">Part 6: Bash Scripting</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-71-packages-and-package-management">7.1. Packages and Package Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-81-user-management">8.1. User Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-87-linux-networking-basics">8.7. Linux Networking Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-810-diagnosing-hardware-problems">8.10 Diagnosing Hardware Problems</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-part-1-introduction-to-linux">Part 1: Introduction to Linux</h2>
<h3 id="heading-11-getting-started-with-linux">1.1. Getting Started with Linux</h3>
<h4 id="heading-what-is-linux">What is Linux?</h4>
<p>Linux is an open-source operating system that is based on the Unix operating system. It was created by Linus Torvalds in 1991.</p>
<p>Open source means that the source code of the operating system is available to the public. This allows anyone to modify the original code, customise it, and distribute the new operating system to potential users.</p>
<h4 id="heading-why-should-you-learn-about-linux">Why should you learn about Linux?</h4>
<p>In today's data center landscape, Linux and Microsoft Windows stand out as the primary contenders, with Linux having a major share.</p>
<p>Here are several compelling reasons to learn Linux:</p>
<ul>
<li><p>Given the prevalence of Linux hosting, there is a high chance that your application will be hosted on Linux. So learning Linux as a developer becomes increasingly valuable.</p>
</li>
<li><p>With cloud computing becoming the norm, chances are high that your cloud instances will rely on Linux.</p>
</li>
<li><p>Linux serves as the foundation for many operating systems for the Internet of Things (IoT) and mobile applications.</p>
</li>
<li><p>In IT, there are many opportunities for those skilled in Linux.</p>
</li>
</ul>
<h4 id="heading-what-does-it-mean-that-linux-is-an-open-source-operating-system">What does it mean that Linux is an open-source operating system?</h4>
<p>First, what is open source? Open source software is software whose source code is freely accessible, allowing anyone to utilize, modify, and distribute it.</p>
<p>Whenever source code is created, it is automatically considered copyrighted, and its distribution is governed by the copyright holder through software licenses.</p>
<p>In contrast to open source, proprietary or closed-source software restricts access to its source code. Only the creators can view, modify, or distribute it.</p>
<p>Linux is primarily open source, which means that its source code is freely available. Anyone can view, modify, and distribute it. Developers from anywhere in the world can contribute to its improvement. This lays the foundation of collaboration which is an important aspect of open source software.</p>
<p>This collaborative approach has led to the widespread adoption of Linux across servers, desktops, embedded systems, and mobile devices.</p>
<p>The most interesting aspect of Linux being open source is that anyone can tailor the operating system to their specific needs without being restricted by proprietary limitations.</p>
<p>Chrome OS used by Chromebooks is based on Linux. Android, that powers many smartphones globally, is also based on Linux.</p>
<p><strong>What is a Linux Kernel?</strong></p>
<p>The kernel is the central component of an operating system that manages the computer and its hardware operations. It handles memory operations and CPU time.</p>
<p>The kernel acts as a bridge between applications and the hardware-level data processing using inter-process communication and system calls.</p>
<p>The kernel loads into memory first when an operating system starts and remains there until the system shuts down. It is responsible for tasks like disk management, task management, and memory management.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719844849011/f4bb226e-f319-4cb5-bfc9-c1a80401123e.png" alt="Linux Kernel Layout showing interaction of kernal with applications and OS" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If you are curious about what the Linux kernel looks like, <a target="_blank" href="https://github.com/torvalds/linux">here</a> is the GitHub link.</p>
<h4 id="heading-what-is-a-linux-distribution">What is a Linux distribution?</h4>
<p>By this point, you know that you can re-use the Linux kernel code, modify it, and create a new kernel. You can further combine different utilities and software to create a completely new operating system.</p>
<p>A Linux distribution or distro is a version of the Linux operating system that includes the Linux kernel, system utilities, and other software. Being open source, a Linux distribution is a collaborative effort involving multiple independent open-source development communities.</p>
<p><strong>What does it mean that a distribution is derived?</strong> When you say that a distribution is "derived" from another, the newer distro is built upon the base or foundation of the original distro. This derivation can include using the same package management system (more on this later), kernel version, and sometimes the same configuration tools.</p>
<p>Today, there are thousands of Linux distributions to choose from, offering differing goals and criteria for selecting and supporting the software provided by their distribution.</p>
<p>Distributions vary from one to the other, but they generally have several common characteristics:</p>
<ul>
<li><p>A distribution consists of a Linux kernel.</p>
</li>
<li><p>It supports user space programs.</p>
</li>
<li><p>A distribution may be small and single-purpose or include thousands of open-source programs.</p>
</li>
<li><p>Some means of installing and updating the distribution and its components should be provided.</p>
</li>
</ul>
<p>If you view the <a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/1/1b/Linux_Distribution_Timeline.svg">Linux Distributions Timeline</a>, you'll see two major distros: Slackware and Debian. Several distributions are derived from them. For example, Ubuntu and Kali are derived from Debian.</p>
<p><strong>What are the advantages of derivation?</strong> There are various advantages of derivation. Derived distributions can leverage the stability, security, and large software repositories of the parent distribution.</p>
<p>When building on an existing foundation, developers can drive their focus and effort entirely on the specialized features of the new distribution. Users of derived distributions can benefit from the documentation, community support, and resources already available for the parent distribution.</p>
<p>Some popular Linux distributions are:</p>
<ol>
<li><p><strong>Ubuntu</strong>: One of the most widely used and popular Linux distributions. It is user-friendly and recommended for beginners. <a target="_blank" href="https://ubuntu.com/">Learn more about Ubuntu here</a>.</p>
</li>
<li><p><strong>Linux Mint</strong>: Based on Ubuntu, Linux Mint provides a user-friendly experience with a focus on multimedia support. <a target="_blank" href="https://linuxmint.com/">Learn more about Linux Mint here</a>.</p>
</li>
<li><p><strong>Arch Linux</strong>: Popular among experienced users, Arch is a lightweight and flexible distribution aimed at users who prefer a DIY approach. <a target="_blank" href="https://www.archlinux.org/">Learn more about Arch Linux here</a>.</p>
</li>
<li><p><strong>Manjaro</strong>: Based on Arch Linux, Manjaro provides a user-friendly experience with pre-installed software and easy system management tools. <a target="_blank" href="https://manjaro.org/">Learn more about Manjaro here</a>.</p>
</li>
<li><p><strong>Kali Linux</strong>: Kali Linux provides a comprehensive suite of security tools and is mostly focused on cybersecurity and hacking. <a target="_blank" href="https://www.kali.org/">Learn more about Kali Linux here</a>.</p>
</li>
</ol>
<h4 id="heading-how-to-install-and-access-linux">How to install and access Linux</h4>
<p>The best way to learn is to apply the concepts as you go. In this section, we'll learn how to install Linux on your machine so you can follow along. You'll also learn how to access Linux on a Windows machine.</p>
<p>I recommend that you follow any one of the methods mentioned in this section to get access to Linux so you may follow along.</p>
<h5 id="heading-install-linux-as-the-primary-os">Install Linux as the primary OS</h5>
<p>Installing Linux as the primary OS is the most efficient way to use Linux, as you can use the full power of your machine.</p>
<p>In this section, you will learn how to install Ubuntu, which is one of the most popular Linux distributions. I have left out other distributions for now, as I want to keep things simple. You can always explore other distributions once you are comfortable with Ubuntu.</p>
<ul>
<li><p><strong>Step 1 – Download the Ubuntu iso:</strong> Go to the official <a target="_blank" href="https://ubuntu.com/download/desktop">website</a> and download the iso file. Make sure to select a stable release that is labeled "LTS". LTS stands for Long Term Support which means you can get free security and maintenance updates for a long time (usually 5 years).</p>
</li>
<li><p><strong>Step 2 – Create a bootable pendrive:</strong> There are a number of softwares that can create a bootable pendrive. I recommend using Rufus, as it is quite easy to use. You can download it from <a target="_blank" href="https://rufus.ie/">here</a>.</p>
</li>
<li><p><strong>Step 3 – Boot from the pendrive:</strong> Once your bootable pendrive is ready, insert it and boot from the pendrive. The boot menu depends on your laptop. You can google the boot menu for your laptop model.</p>
</li>
<li><p><strong>Step 4 – Follow the prompts.</strong> Once, the boot process starts, select <code>try or install ubuntu</code>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304227675/5b706f94-7368-47ca-a4d6-d55a0d92eff9.png" alt="Screen prompt to either try or install Ubuntu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>  The process will take some time. Once the GUI appears, you can select the language, and keyboard layout and continue. Enter your login and name. Remember the credentials as you will need them to log in to your system and access full privileges. Wait for the installation to complete.</p>
</li>
<li><p><strong>Step 5 – Restart:</strong> Click on restart now and remove the pen drive.</p>
</li>
<li><p><strong>Step 6 – Login:</strong> Login with the credentials you entered earlier.</p>
</li>
</ul>
<p>And there you go! Now you can install apps and customize your desktop.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719304547967/d150c6eb-d04e-47e0-8473-d1a837df45c4.png" alt="Ubuntu 22.04.4 LTS Desktop screen" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>For advanced installation, you can explore the following topics:</p>
<ul>
<li><p>Disk partitioning.</p>
</li>
<li><p>Setting swap memory for enabling hibernation.</p>
</li>
</ul>
<p><strong>Accessing the terminal</strong></p>
<p>An important part of this handbook is learning about the terminal where you'll run all the commands and see the magic happen. You can search for the terminal by pressing the "windows" key and typing "terminal". You can pin the Terminal in the dock where other apps are located for easy access.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305113272/4dd30c5e-da73-4cd4-86bb-7dcd8cd2084c.png" alt="Search results for &quot;terminal&quot;" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>💡 The shortcut for opening the terminal is <code>ctrl+alt+t</code></p>
</blockquote>
<p>You can also open the terminal from inside a folder. Right click where you are and click on "Open in Terminal". This will open the terminal in the same path.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719305289021/284a4a53-2d1a-4eaa-925a-1002a32c1dce.png" alt="Opening the terminal with right click menu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-use-linux-on-a-windows-machine">How to use Linux on a Windows machine</h5>
<p>Sometimes you might need to run both Linux and Windows side by side. Luckily, there are some ways you can get the best of both worlds without getting different computers for each operating system.</p>
<p>In this section, you'll explore a few ways to use Linux on a Windows machine. Some of them are browser-based or cloud-based and do not need any OS installation before using them.</p>
<p><strong>Option 1: "Dual-boot" Linux + Windows</strong> With dual boot, you can install Linux alongside Windows on your computer, allowing you to choose which operating system to use at startup.</p>
<p>This requires partitioning your hard drive and installing Linux on a separate partition. With this approach, you can only use one operating system at a time.</p>
<p><strong>Option 2: Use Windows Subsystem for Linux (WSL)</strong> Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.</p>
<p>Using WSL has some advantages. The setup for WSL is simple and not time-consuming. It is lightweight compared to VMs where you have to allocate resources from the host machine. You don't need to install any ISO or virtual disc image for Linux machines which tend to be heavy files. You can use Windows and Linux side by side.</p>
<p><strong>How to install WSL2</strong></p>
<p>First, enable the Windows Subsystem for Linux option in settings.</p>
<ul>
<li><p>Go to Start. Search for "Turn Windows features on or off."</p>
</li>
<li><p>Check the option "Windows Subsystem for Linux" if it isn't already.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306102095/84f23bae-faa5-4ece-a9b6-e40f8789a061.png" alt="Checking the option &quot;Windows Subsystem for Linux&quot; in Windows features" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Next, open your command prompt and provide the installation commands.</p>
</li>
<li><p>Open Command Prompt as an administrator:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720451480640/6052c9b4-cf07-47e0-ae89-18c3a2d3e385.png" alt="Running command prompt as an admin by right clicking the app and choosing &quot;run as admin£" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Run the command below:</p>
</li>
</ul>
<pre><code class="lang-markdown">wsl --install
</code></pre>
<p>This is the output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306131053/b7272031-ddb7-4e04-8d7b-bafc0911da04.png" alt="Downloading progress of Ubuntu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Note: By default, Ubuntu will be installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306144861/a01f95df-1d95-4b79-bff9-08759be0d3dc.png" alt="Ubuntu installed by default using WSL" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<ul>
<li>Once installation is complete, you'll need to reboot your Windows machine. So, restart your Windows machine.</li>
</ul>
<p>After restarting, you might see a window like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306157704/15620fbe-59d1-40da-9cd6-119a1fab0802.png" alt="Window that shows after a restart" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Once installation of Ubuntu is complete, you'll be prompted to enter your username and password.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306167380/5e3058cd-b7a1-45b1-a16d-c23b5a451504.png" alt="User prompted to enter a username and password" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>And, that's it! You are ready to use Ubuntu.</p>
<p>Launch Ubuntu by searching from the start menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306185110/77c17856-08ac-4ec7-9380-5b06f93be095.png" alt="Launching Ubuntu from the start menu" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>And here we have your Ubuntu instance launched.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306196320/13be3a71-5b40-440c-a6bf-d742e5b5934b.png" alt="Successful installation of Ubuntu using WSL" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Option 3: Use a Virtual Machine (VM)</strong></p>
<p>A virtual machine (VM) is a software emulation of a physical computer system. It allows you to run multiple operating systems and applications on a single physical machine simultaneously.</p>
<p>You can use virtualization software such as Oracle VirtualBox or VMware to create a virtual machine running Linux within your Windows environment. This allows you to run Linux as a guest operating system alongside Windows.</p>
<p>VM software provides options to allocate and manage hardware resources for each VM, including CPU cores, memory, disk space, and network bandwidth. You can adjust these allocations based on the requirements of the guest operating systems and applications.</p>
<p>Here are some of the common options available for virtualization:</p>
<ul>
<li><p><a target="_blank" href="https://www.virtualbox.org/">Oracle virtual box</a></p>
</li>
<li><p><a target="_blank" href="https://multipass.run/">Multipass</a></p>
</li>
<li><p><a target="_blank" href="https://www.vmware.com/content/vmware/vmware-published-sites/us/products/workstation-player.html.html">VMware workstation player</a></p>
</li>
</ul>
<p><strong>Option 4: Use a Browser-based Solution</strong></p>
<p>Browser-based solutions are particularly useful for quick testing, learning, or accessing Linux environments from devices that don't have Linux installed.</p>
<p>You can either use online code editors or web-based terminals to access Linux. Note that you usually don't have full administration privileges in these cases.</p>
<h4 id="heading-online-code-editors"><strong>Online code editors</strong></h4>
<p>Online code editors offer editors with built-in Linux terminals. While their primary purpose is coding, you can also utilize the Linux terminal to execute commands and perform tasks.</p>
<p><a target="_blank" href="https://replit.com/">Replit</a> is an example of an online code editor, where you can write your code and access the Linux shell at the same time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306257260/d85d5541-b78f-4c8b-99a8-dbd8c097f661.gif" alt="Running scripts and a bash shell in Replit" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-web-based-linux-terminals"><strong>Web-based Linux terminals:</strong></h4>
<p>Online Linux terminals allow you to access a Linux command-line interface directly from your browser. These terminals provide a web-based interface to a Linux shell, enabling you to execute commands and work with Linux utilities.</p>
<p>One such example is <a target="_blank" href="https://jslinux.org/">JSLinux</a>. The screenshot below shows a ready-to-use Linux environment:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719306276915/ddaabfc3-9a20-43b2-bedc-0af6875d2008.png" alt="Using JSLinux to access Linux terminal" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Option 5: Use a Cloud-based Solution</strong></p>
<p>Instead of running Linux directly on your Windows machine, you can consider using cloud-based Linux environments or virtual private servers (VPS) to access and work with Linux remotely.</p>
<p>Services like Amazon EC2, Microsoft Azure, or DigitalOcean provide Linux instances that you can connect to from your Windows computer. Note that some of these services offer free tiers, but they are not usually free in the long run.</p>
<h2 id="heading-part-2-introduction-to-bash-shell-and-system-commands">Part 2: Introduction to Bash Shell and System Commands</h2>
<h3 id="heading-21-getting-started-with-the-bash-shell">2.1. Getting Started with the Bash shell</h3>
<h4 id="heading-introduction-to-the-bash-shell">Introduction to the bash shell</h4>
<p>The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.</p>
<p>Different users can be configured to use different shells. But, most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (<code>bash</code>). Bash is succeeded by the Bourne shell (<code>sh</code>).</p>
<p>To find out your current shell, open your terminal and enter the following command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
</code></pre>
<p>Command breakdown:</p>
<ul>
<li><p>The <code>echo</code> command is used to print on the terminal.</p>
</li>
<li><p>The <code>$SHELL</code> is a special variable that holds the name of the current shell.</p>
</li>
</ul>
<p>In my setup, the output is <code>/bin/bash</code>. This means that I am using the bash shell.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># output</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$SHELL</span>
/bin/bash
</code></pre>
<p>Bash is very powerful as it can simplify certain operations that are hard to accomplish efficiently with a GUI (or Graphical User Interface). Remember that most servers do not have a GUI, and it is best to learn to use the powers of a command line interface (CLI).</p>
<p><strong>Terminal vs Shell</strong></p>
<p>The terms "terminal" and "shell" are often used interchangeably, but they refer to different parts of the command-line interface.</p>
<p>The terminal is the interface you use to interact with the shell. The shell is the command interpreter that processes and executes your commands. You'll learn more about shells in Part 6 of the handbook.</p>
<h4 id="heading-what-is-a-prompt">What is a prompt?</h4>
<p>When a shell is used interactively, it displays a <code>$</code> when it is waiting for a command from the user. This is called the shell prompt.</p>
<p><code>[username@host ~]$</code></p>
<p>If the shell is running as <code>root</code> (you'll learn more about the root user later on), the prompt is changed to <code>#</code>.</p>
<p><code>[root@host ~]#</code></p>
<h3 id="heading-22-command-structure">2.2. Command Structure</h3>
<p>A command is a program that performs a specific operation. Once you have access to the shell, you can enter any command after the <code>$</code> sign and see the output on the terminal.</p>
<p>Generally, Linux commands follow this syntax:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">command</span> [options] [arguments]
</code></pre>
<p>Here is the breakdown of the above syntax:</p>
<ul>
<li><p><code>command</code>: This is the name of the command you want to execute. <code>ls</code> (list), <code>cp</code> (copy), and <code>rm</code> (remove) are common Linux commands.</p>
</li>
<li><p><code>[options]</code>: Options, or flags, often preceded by a hyphen (-) or double hyphen (--), modify the behavior of the command. They can change how the command operates. For example, <code>ls -a</code> uses the <code>-a</code> option to display hidden files in the current directory.</p>
</li>
<li><p><code>[arguments]</code>: Arguments are the inputs for the commands that require one. These could be filenames, user names, or other data that the command will act upon. For example, in the command <code>cat access.log</code>, <code>cat</code> is the command and <code>access.log</code> is the input. As a result, the <code>cat</code> command displays the contents of the <code>access.log</code> file.</p>
</li>
</ul>
<p>Options and arguments are not required for all commands. Some commands can be run without any options or arguments, while others might require one or both to function correctly. You can always refer to the command's manual to check the options and arguments it supports.</p>
<p>💡<strong>Tip:</strong> You can view a command's manual using the <code>man</code> command.</p>
<p>You can access the manual page for <code>ls</code> with <code>man ls</code>, and it'll look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719312523336/5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7.png" alt="5b1232a6-8c0b-4a97-86f0-9f15f2e14ed7" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Manual pages are a great and quick way to access the documentation. I highly recommend going through man pages for the commands that you use the most.</p>
<h3 id="heading-23-bash-commands-and-keyboard-shortcuts">2.3. Bash Commands and Keyboard Shortcuts</h3>
<p>When you are in the terminal, you can speed up your tasks by using shortcuts.</p>
<p>Here are some of the most common terminal shortcuts:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Shortcut</td></tr>
</thead>
<tbody>
<tr>
<td>Look for the previous command</td><td>Up Arrow</td></tr>
<tr>
<td>Jump to the beginning of the previous word</td><td>Ctrl+LeftArrow</td></tr>
<tr>
<td>Clear characters from the cursor to the end of the command line</td><td>Ctrl+K</td></tr>
<tr>
<td>Complete commands, file names, and options</td><td>Pressing Tab</td></tr>
<tr>
<td>Jumps to the beginning of the command line</td><td>Ctrl+A</td></tr>
<tr>
<td>Displays the list of previous commands</td><td>history</td></tr>
</tbody>
</table>
</div><h3 id="heading-24-identifying-yourself-the-whoami-command">2.4. Identifying Yourself: The <code>whoami</code> Command</h3>
<p>You can get the username you are logged in with by using the <code>whoami</code> command. This command is useful when you are switching between different users and want to confirm the current user.</p>
<p>Just after the <code>$</code> sign, type <code>whoami</code> and press enter.</p>
<pre><code class="lang-bash">whoami
</code></pre>
<p>This is the output I got.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ whoami
zaira
</code></pre>
<h2 id="heading-part-3-understanding-your-linux-system">Part 3: Understanding Your Linux System</h2>
<h3 id="heading-31-discovering-your-os-and-specs">3.1. Discovering Your OS and Specs</h3>
<h4 id="heading-print-system-information-using-the-uname-command">Print system information using the <code>uname</code> Command</h4>
<p>You can get detailed system information from the <code>uname</code> command.</p>
<p>When you provide the <code>-a</code> option, it prints all the system information.</p>
<pre><code class="lang-bash">uname -a
<span class="hljs-comment"># output</span>
Linux zaira 6.5.0-21-generic <span class="hljs-comment">#21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb  9 13:32:52 UTC 2 x86_64 x86_64 x86_64 GNU/Linux</span>
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>Linux</code>: Indicates the operating system.</p>
</li>
<li><p><code>zaira</code>: Represents the hostname of the machine.</p>
</li>
<li><p><code>6.5.0-21-generic #21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 9 13:32:52 UTC 2</code>: Provides information about the kernel version, build date, and some additional details.</p>
</li>
<li><p><code>x86_64 x86_64 x86_64</code>: Indicates the architecture of the system.</p>
</li>
<li><p><code>GNU/Linux</code>: Represents the operating system type.</p>
</li>
</ul>
<h4 id="heading-find-details-of-the-cpu-architecture-using-the-lscpu-command">Find details of the CPU architecture using the <code>lscpu</code> Command</h4>
<p>The <code>lscpu</code> command in Linux is used to display information about the CPU architecture. When you run <code>lscpu</code> in the terminal, it provides details such as:</p>
<ul>
<li><p>The architecture of the CPU (for example, x86_64)</p>
</li>
<li><p>CPU op-mode(s) (for example, 32-bit, 64-bit)</p>
</li>
<li><p>Byte Order (for example, Little Endian)</p>
</li>
<li><p>CPU(s) (number of CPUs), and so on</p>
<p>  Let's try it out:</p>
</li>
</ul>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
Vendor ID:               AuthenticAMD
  Model name:            AMD Ryzen 5 5500U with Radeon Graphics
    Thread(s) per core:  2
    Core(s) per socket:  6
    Socket(s):           1
    Stepping:            1
    CPU max MHz:         4056.0000
    CPU min MHz:         400.0000
</code></pre>
<p>That was a whole lot of information, but useful too! Remember you can always skim the relevant information using specific flags. See the command manual with <code>man lscpu</code>.</p>
<h2 id="heading-part-4-managing-files-from-the-command-line">Part 4: Managing Files From the Command line</h2>
<h3 id="heading-41-the-linux-file-system-hierarchy">4.1. The Linux File-system Hierarchy</h3>
<p>All files in Linux are stored in a file-system. It follows an inverted-tree-like structure because the root is at the topmost part.</p>
<p>The <code>/</code> is the root directory and the starting point of the file system. The root directory contains all other directories and files on the system. The <code>/</code> character also serves as a directory separator between path names. For example, <code>/home/alice</code> forms a complete path.</p>
<p>The image below shows the complete file system hierarchy. Each directory servers a specific purpose.</p>
<p>Note that this is not an exhaustive list and different distributions may have different configurations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322457140/02fdbf2c-f4fa-438b-af2f-c23f59f9ddf4.png" alt="Linux file system hierarchy" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Here is a table that shows the purpose of each directory:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Location</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td>/bin</td><td>Essential command binaries</td></tr>
<tr>
<td>/boot</td><td>Static files of the boot loader, needed in order to start the boot process.</td></tr>
<tr>
<td>/etc</td><td>Host-specific system configuration</td></tr>
<tr>
<td>/home</td><td>User home directories</td></tr>
<tr>
<td>/root</td><td>Home directory for the administrative root user</td></tr>
<tr>
<td>/lib</td><td>Essential shared libraries and kernel modules</td></tr>
<tr>
<td>/mnt</td><td>Mount point for mounting a filesystem temporarily</td></tr>
<tr>
<td>/opt</td><td>Add-on application software packages</td></tr>
<tr>
<td>/usr</td><td>Installed software and shared libraries</td></tr>
<tr>
<td>/var</td><td>Variable data that is also persistent between boots</td></tr>
<tr>
<td>/tmp</td><td>Temporary files that are accessible to all users</td></tr>
</tbody>
</table>
</div><p>💡 <strong>Tip:</strong> You can learn more about the file system using the <code>man hier</code> command.</p>
<p>You can check your file system using the <code>tree -d -L 1</code> command. You can modify the <code>-L</code> flag to change the depth of the tree.</p>
<pre><code class="lang-bash">tree -d -L 1
<span class="hljs-comment"># output</span>
.
├── bin -&gt; usr/bin
├── boot
├── cdrom
├── data
├── dev
├── etc
├── home
├── lib -&gt; usr/lib
├── lib32 -&gt; usr/lib32
├── lib64 -&gt; usr/lib64
├── libx32 -&gt; usr/libx32
├── lost+found
├── media
├── mnt
├── opt
├── proc
├── root
├── run
├── sbin -&gt; usr/sbin
├── snap
├── srv
├── sys
├── tmp
├── usr
└── var

25 directories
</code></pre>
<p>This list is not exhaustive and different distributions and systems may be configured differently.</p>
<h3 id="heading-42-navigating-the-linux-file-system">4.2. Navigating the Linux File-system</h3>
<h4 id="heading-absolute-path-vs-relative-path">Absolute path vs relative path</h4>
<p>The absolute path is the full path from the root directory to the file or directory. It always starts with a <code>/</code>. For example, <code>/home/john/documents</code>.</p>
<p>The relative path, on the other hand, is the path from the current directory to the destination file or directory. It does not start with a <code>/</code>. For example, <code>documents/work/project</code>.</p>
<h4 id="heading-locating-your-current-directory-using-the-pwd-command">Locating your current directory using the <code>pwd</code> command</h4>
<p>It is easy to lose your way in the Linux file system, especially if you are new to the command line. You can locate your current directory using the <code>pwd</code> command.</p>
<p>Here is an example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">pwd</span>
<span class="hljs-comment"># output</span>
/home/zaira/scripts/python/free-mem.py
</code></pre>
<h4 id="heading-changing-directories-using-the-cd-command">Changing directories using the <code>cd</code> command</h4>
<p>The command to change directories is <code>cd</code> and it stands for "change directory". You can use the <code>cd</code> command to navigate to a different directory.</p>
<p>You can use a relative path or an absolute path.</p>
<p>For example, if you want to navigate the below file structure (following the red lines):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719389950079/640cce46-6c52-4f38-9787-581747fb9798.png" alt="Example file structure" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>and you are standing at "home", the command would be like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> home/bob/documents/work/project
</code></pre>
<p>Some other commonly used <code>cd</code> shortcuts are:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>cd ..</code></td><td>Go back one directory</td></tr>
<tr>
<td><code>cd ../..</code></td><td>Go back two directories</td></tr>
<tr>
<td><code>cd</code> or <code>cd ~</code></td><td>Go to the home directory</td></tr>
<tr>
<td><code>cd -</code></td><td>Go to the previous path</td></tr>
</tbody>
</table>
</div><h3 id="heading-43-managing-files-and-directories">4.3. Managing Files and Directories</h3>
<p>When working with files and directories, you might want to copy, move, remove, and create new files and directories. Here are some commands that can help you with that.</p>
<p>💡<strong>Tip:</strong> You can differentiate between a file and folder by looking at the first letter in the output of <code>ls -l</code>. A<code>'-'</code> represents a file and a <code>'d'</code> represents a folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719390306244/4f1688cd-ded5-43fe-b13a-9ca44ac7c4ad.png" alt="&quot;d&quot; represents a folder" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-creating-new-directories-using-the-mkdir-command">Creating new directories using the <code>mkdir</code> command</h4>
<p>You can create an empty directory using the <code>mkdir</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates an empty directory named "foo" in the current folder</span>
mkdir foo
</code></pre>
<p>You can also create directories recursively using the <code>-p</code> option.</p>
<pre><code class="lang-bash">mkdir -p tools/index/helper-scripts
<span class="hljs-comment"># output of tree</span>
.
└── tools
    └── index
        └── helper-scripts

3 directories, 0 files
</code></pre>
<h4 id="heading-creating-new-files-using-the-touch-command">Creating new files using the <code>touch</code> command</h4>
<p>The <code>touch</code> command creates an empty file. You can use it like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty file "file.txt" in the current folder</span>
touch file.txt
</code></pre>
<p>The file names can be chained together if you want to create multiple files in a single command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># creates empty files "file1.txt", "file2.txt", and "file3.txt" in the current folder</span>

touch file1.txt file2.txt file3.txt
</code></pre>
<h4 id="heading-removing-files-and-directories-using-the-rm-and-rmdir-command">Removing files and directories using the <code>rm</code> and <code>rmdir</code> command</h4>
<p>You can use the <code>rm</code> command to remove both files and non-empty directories.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>rm file.txt</code></td><td>Removes the file <code>file.txt</code></td></tr>
<tr>
<td><code>rm -r directory</code></td><td>Removes the directory <code>directory</code> and its contents</td></tr>
<tr>
<td><code>rm -f file.txt</code></td><td>Removes the file <code>file.txt</code> without prompting for confirmation</td></tr>
<tr>
<td><code>rmdir</code> directory</td><td>Removes an empty directory</td></tr>
</tbody>
</table>
</div><p>🛑 Note that you should use the <code>-f</code> flag with caution as you won't be asked before deleting a file. Also, be careful when running <code>rm</code> commands in the <code>root</code> folder as it might result in deleting important system files.</p>
<h4 id="heading-copying-files-using-the-cp-command">Copying files using the <code>cp</code> command</h4>
<p>To copy files in Linux, use the <code>cp</code> command.</p>
<ul>
<li><strong>Syntax to copy files:</strong><code>cp source_file destination_of_file</code></li>
</ul>
<p>This command copies a file named <code>file1.txt</code> to a new file location <code>/home/adam/logs</code>.</p>
<pre><code class="lang-bash">cp file1.txt /home/adam/logs
</code></pre>
<p>The <code>cp</code> command also creates a copy of one file with the provided name.</p>
<p>This command copies a file named <code>file1.txt</code> to another file named <code>file2.txt</code> in the same folder.</p>
<pre><code class="lang-bash">cp file1.txt file2.txt
</code></pre>
<h4 id="heading-moving-and-renaming-files-and-folders-using-the-mv-command">Moving and renaming files and folders using the <code>mv</code> command</h4>
<p>The <code>mv</code> command is used to move files and folders from one directory to the other.</p>
<p><strong>Syntax to move files:</strong><code>mv source_file destination_directory</code></p>
<p><strong>Example:</strong> Move a file named <code>file1.txt</code> to a directory named <code>backup</code>:</p>
<pre><code class="lang-bash">mv file1.txt backup/
</code></pre>
<p>To move a directory and its contents:</p>
<pre><code class="lang-bash">mv dir1/ backup/
</code></pre>
<p>Renaming files and folders in Linux is also done with the <code>mv</code> command.</p>
<p><strong>Syntax to rename files:</strong><code>mv old_name new_name</code></p>
<p><strong>Example:</strong> Rename a file from <code>file1.txt</code> to <code>file2.txt</code>:</p>
<pre><code class="lang-bash">mv file1.txt file2.txt
</code></pre>
<p>Rename a directory from <code>dir1</code> to <code>dir2</code>:</p>
<pre><code class="lang-bash">mv dir1 dir2
</code></pre>
<h3 id="heading-44-locating-files-and-folders-using-the-find-command">4.4. Locating Files and Folders Using the <code>find</code> Command</h3>
<p>The <code>find</code> command lets you efficiently search for files, folders, and character and block devices.</p>
<p>Below is the basic syntax of the <code>find</code> command:</p>
<pre><code class="lang-bash">find /path/ -<span class="hljs-built_in">type</span> f -name file-to-search
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>/path</code> is the path where the file is expected to be found. This is the starting point for searching files. The path can also be<code>/</code>or <code>.</code> which represents the root and current directory, respectively.</p>
</li>
<li><p><code>-type</code> represents the file descriptors. They can be any of the below:<br>  <code>f</code> – <strong>Regular file</strong> such as text files, images, and hidden files.<br>  <code>d</code> – <strong>Directory</strong>. These are the folders under consideration.<br>  <code>l</code> – <strong>Symbolic link</strong>. Symbolic links point to files and are similar to shortcuts.<br>  <code>c</code> – <strong>Character devices</strong>. Files that are used to access character devices are called character device files. Drivers communicate with character devices by sending and receiving single characters (bytes, octets). Examples include keyboards, sound cards, and the mouse.<br>  <code>b</code> – <strong>Block devices</strong>. Files that are used to access block devices are called block device files. Drivers communicate with block devices by sending and receiving entire blocks of data. Examples include USB and CD-ROM</p>
</li>
<li><p><code>-name</code> is the name of the file type that you want to search.</p>
</li>
</ul>
<h4 id="heading-how-to-search-files-by-name-or-extension">How to search files by name or extension</h4>
<p>Suppose we need to find files that contain "style" in their name. We'll use this command:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"style*"</span>
<span class="hljs-comment">#output</span>
./style.css
./styles.css
</code></pre>
<p>Now let's say we want to find files with a particular extension like <code>.html</code>. We'll modify the command like this:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.html"</span>
<span class="hljs-comment"># output</span>
./services.html
./blob.html
./index.html
</code></pre>
<h4 id="heading-how-to-search-hidden-files">How to search hidden files</h4>
<p>A dot at the beginning of the filename represents hidden files. They are normally hidden but can be viewed with <code>ls -a</code> in the current directory.</p>
<p>We can modify the <code>find</code> command as shown below to search for hidden files:</p>
<pre><code class="lang-bash">find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
</code></pre>
<p><strong>List and find hidden files</strong></p>
<pre><code class="lang-bash">ls -la
<span class="hljs-comment"># folder contents</span>
total 5
drwxrwxr-x  2 zaira zaira 4096 Mar 26 14:17 .
drwxr-x--- 61 zaira zaira 4096 Mar 26 14:12 ..
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_history
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bash_logout
-rw-rw-r--  1 zaira zaira    0 Mar 26 14:17 .bashrc

find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">".*"</span>
<span class="hljs-comment"># find output</span>
./.bash_logout
./.bashrc
./.bash_history
</code></pre>
<p>Above you can see a list of hidden files in my home directory.</p>
<h4 id="heading-how-to-search-log-files-and-configuration-files">How to search log files and configuration files</h4>
<p>Log files usually have the extension <code>.log</code>, and we can find them like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.log"</span>
</code></pre>
<p>Similarly, we can search for configuration files like this:</p>
<pre><code class="lang-bash"> find . -<span class="hljs-built_in">type</span> f -name <span class="hljs-string">"*.conf"</span>
</code></pre>
<h4 id="heading-how-to-search-other-files-by-type">How to search other files by type</h4>
<p>We can search for character block files by providing <code>c</code> to <code>-type</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> c
</code></pre>
<p>Similarly, we can find device block files by using <code>b</code>:</p>
<pre><code class="lang-bash">find / -<span class="hljs-built_in">type</span> b
</code></pre>
<h4 id="heading-how-to-search-directories">How to search directories</h4>
<p>In the example below, we are finding the folders using the <code>-type d</code> flag.</p>
<pre><code class="lang-bash">ls -l
<span class="hljs-comment"># list folder contents</span>
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 hosts
-rw-rw-r-- 1 zaira zaira    0 Mar 26 14:23 hosts.txt
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 images
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:23 style
drwxrwxr-x 2 zaira zaira 4096 Mar 26 14:22 webp 

find . -<span class="hljs-built_in">type</span> d 
<span class="hljs-comment"># find directory output</span>
.
./webp
./images
./style
./hosts
</code></pre>
<h4 id="heading-how-to-search-files-by-size">How to search files by size</h4>
<p>An incredibly helpful use of the <code>find</code> command is to list files based on a particular size.</p>
<pre><code class="lang-bash">find / -size +250M
</code></pre>
<p>Here, we are listing files whose size exceeds <code>250MB</code>.</p>
<p>Other units include:</p>
<ul>
<li><p><code>G</code>: GigaBytes.</p>
</li>
<li><p><code>M</code>: MegaBytes.</p>
</li>
<li><p><code>K</code>: KiloBytes</p>
</li>
<li><p><code>c</code> : bytes.</p>
</li>
</ul>
<p>Just replace with the relevant unit.</p>
<pre><code class="lang-bash">find &lt;directory&gt; -<span class="hljs-built_in">type</span> f -size +N&lt;Unit Type&gt;
</code></pre>
<h4 id="heading-how-to-search-files-by-modification-time">How to search files by modification time</h4>
<p>By using the <code>-mtime</code> flag, you can filter files and folders based on the modification time.</p>
<pre><code class="lang-bash">find /path -name <span class="hljs-string">"*.txt"</span> -mtime -10
</code></pre>
<p>For example,</p>
<ul>
<li><p><strong>-mtime +10</strong> means you are looking for a file modified 10 days ago.</p>
</li>
<li><p><strong>-mtime -10</strong> means less than 10 days.</p>
</li>
<li><p><strong>-mtime 10</strong> If you skip + or – it means exactly 10 days.</p>
</li>
</ul>
<h3 id="heading-45-basic-commands-for-viewing-files">4.5. Basic Commands for Viewing Files</h3>
<h4 id="heading-concatenate-and-display-files-using-the-cat-command">Concatenate and display files using the <code>cat</code> command</h4>
<p>The <code>cat</code> command in Linux is used to display the contents of a file. It can also be used to concatenate files and create new files.</p>
<p>Here is the basic syntax of the <code>cat</code> command:</p>
<pre><code class="lang-bash">cat [options] [file]
</code></pre>
<p>The simplest way to use <code>cat</code> is without any options or arguments. This will display the contents of the file on the terminal.</p>
<p>For example, if you want to view the contents of a file named <code>file.txt</code>, you can use the following command:</p>
<pre><code class="lang-bash">cat file.txt
</code></pre>
<p>This will display all the contents of the file on the terminal at once.</p>
<h4 id="heading-viewing-text-files-interactively-using-less-and-more">Viewing text files interactively using <code>less</code> and <code>more</code></h4>
<p>While <code>cat</code> displays the entire file at once, <code>less</code> and <code>more</code> allow you to view the contents of a file interactively. This is useful when you want to scroll through a large file or search for specific content.</p>
<p>The syntax of the <code>less</code> command is:</p>
<pre><code class="lang-bash">less [options] [file]
</code></pre>
<p>The <code>more</code> command is similar to <code>less</code> but has fewer features. It is used to display the contents of a file one screen at a time.</p>
<p>The syntax of the <code>more</code> command is:</p>
<pre><code class="lang-bash">more [options] [file]
</code></pre>
<p>For both commands, you can use the <code>spacebar</code> to scroll one page down, the <code>Enter</code> key to scroll one line down, and the <code>q</code> key to exit the viewer.</p>
<p>To move backward you can use the <code>b</code> key, and to move forward you can use the <code>f</code> key.</p>
<h4 id="heading-displaying-the-last-part-of-files-using-tail">Displaying the last part of files using <code>tail</code></h4>
<p>Sometimes you might need to view just the last few lines of a file instead of the entire file. The <code>tail</code> command in Linux is used to display the last part of a file.</p>
<p>For example, <code>tail file.txt</code> will display the last 10 lines of the file <code>file.txt</code> by default.</p>
<p>If you want to display a different number of lines, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Display the last 50 lines of the file file.txt</span>
tail -n 50 file.txt
</code></pre>
<p>💡<strong>Tip:</strong> Another usage of the <code>tail</code> is its follow-along (<code>-f</code>) option. This option enables you to view the contents of a file as they are being written. This is a useful utility for viewing and monitoring log files in real-time.</p>
<h4 id="heading-displaying-the-beginning-of-files-using-head">Displaying the beginning of files using <code>head</code></h4>
<p>Just like <code>tail</code> displays the last part of a file, you can use the <code>head</code> command in Linux to display the beginning of a file.</p>
<p>For example, <code>head file.txt</code> will display the first 10 lines of the file <code>file.txt</code> by default.</p>
<p>To change the number of lines displayed, you can use the <code>-n</code> option followed by the number of lines you want to display.</p>
<h4 id="heading-counting-words-lines-and-characters-using-wc">Counting words, lines, and characters using <code>wc</code></h4>
<p>You can count words, lines and characters in a file using the <code>wc</code> command.</p>
<p>For example, running <code>wc syslog.log</code> gave me the following output:</p>
<pre><code class="lang-bash">1669 9623 64367 syslog.log
</code></pre>
<p>In the output above,</p>
<ul>
<li><p><code>1669</code> represents the number of lines in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>9623</code> represents the number of words in the file <code>syslog.log</code>.</p>
</li>
<li><p><code>64367</code> represents the number of characters in the file <code>syslog.log</code>.</p>
</li>
</ul>
<p>So, the command <code>wc syslog.log</code> counted <code>1669</code> lines, <code>9623</code> words, and <code>64367</code> characters in the file <code>syslog.log</code>.</p>
<h4 id="heading-comparing-files-line-by-line-using-diff">Comparing files line by line using <code>diff</code></h4>
<p>Comparing and finding differences between two files is a common task in Linux. You can compare two files right within the command line using the <code>diff</code> command.</p>
<p>The basic syntax of the <code>diff</code> command is:</p>
<pre><code class="lang-bash">diff [options] file1 file2
</code></pre>
<p>Here are two files, <code>hello.py</code> and <code>also-hello.py</code>, that we will compare using the <code>diff</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of hello.py</span>

def greet(name):
    <span class="hljs-built_in">return</span> f<span class="hljs-string">"Hello, {name}!"</span>

user = input(<span class="hljs-string">"Enter your name: "</span>)
<span class="hljs-built_in">print</span>(greet(user))
</code></pre>
<pre><code class="lang-bash"><span class="hljs-comment"># contents of also-hello.py</span>

more also-hello.py
def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<ol>
<li>Check whether the files are the same or not</li>
</ol>
<pre><code class="lang-bash">diff -q hello.py also-hello.py
<span class="hljs-comment"># Output</span>
Files hello.py and also-hello.py differ
</code></pre>
<ol start="2">
<li>See how the files differ. For that, you can use the <code>-u</code> flag to see a unified output:</li>
</ol>
<pre><code class="lang-bash">diff -u hello.py also-hello.py
--- hello.py    2024-05-24 18:31:29.891690478 +0500
+++ also-hello.py    2024-05-24 18:32:17.207921795 +0500
@@ -3,4 +3,5 @@

 user = input(Enter your name: )
 <span class="hljs-built_in">print</span>(greet(user))
+<span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the above output:</p>
<ul>
<li><p><code>--- hello.py 2024-05-24 18:31:29.891690478 +0500</code> indicates the file being compared and its timestamp.</p>
</li>
<li><p><code>+++ also-hello.py 2024-05-24 18:32:17.207921795 +0500</code> indicates the other file being compared and its timestamp.</p>
</li>
<li><p><code>@@ -3,4 +3,5 @@</code> shows the line numbers where the changes occur. In this case, it indicates that lines 3 to 4 in the original file have changed to lines 3 to 5 in the modified file.</p>
</li>
<li><p><code>user = input(Enter your name: )</code> is a line from the original file.</p>
</li>
<li><p><code>print(greet(user))</code> is another line from the original file.</p>
</li>
<li><p><code>+print("Nice to meet you")</code> is the additional line in the modified file.</p>
</li>
</ul>
<ol start="3">
<li>To see the diff in a side-by-side format, you can use the <code>-y</code> flag:</li>
</ol>
<pre><code class="lang-bash">diff -y hello.py also-hello.py
<span class="hljs-comment"># Output</span>
def greet(name):                        def greet(name):
    <span class="hljs-built_in">return</span> fHello, {name}!                        <span class="hljs-built_in">return</span> fHello, {name}!

user = input(Enter your name: )                    user = input(Enter your name: )
<span class="hljs-built_in">print</span>(greet(user))                        <span class="hljs-built_in">print</span>(greet(user))
                                        &gt;    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Nice to meet you"</span>)
</code></pre>
<p>In the output:</p>
<ul>
<li><p>The lines that are the same in both files are displayed side by side.</p>
</li>
<li><p>Lines that are different are shown with a <code>&gt;</code> symbol indicating the line is only present in one of the files.</p>
</li>
</ul>
<h2 id="heading-part-5-the-essentials-of-text-editing-in-linux">Part 5: The Essentials of Text Editing in Linux</h2>
<p>Text editing skills using the command line are one of the most crucial skills in Linux. In this section, you will learn how to use two popular text editors in Linux: Vim and Nano.</p>
<p>I suggest that you master any one text editor of your choice and stick to it. It will save you time and make you more productive. Vim and nano are safe choices as they are present on most Linux distributions.</p>
<h3 id="heading-51-mastering-vim-the-complete-guide">5.1. Mastering Vim: The Complete Guide</h3>
<h4 id="heading-introduction-to-vim">Introduction to Vim</h4>
<p>Vim is a popular text editing tool for the command line. Vim comes with its advantages: it is powerful, customizable, and fast. Here are some reasons why you should consider learning Vim:</p>
<ul>
<li><p>Most servers are accessed via a CLI, so in system administration, you don't necessarily have the luxury of a GUI. But Vim has got your back – it'll always be there.</p>
</li>
<li><p>Vim uses a keyboard-centric approach, as it is designed to be used without a mouse, which can significantly speed up editing tasks once you have learned the keyboard shortcuts. This also makes it faster than GUI tools.</p>
</li>
<li><p>Some Linux utilities, for example editing cron jobs, work in the same editing format as Vim.</p>
</li>
<li><p>Vim is suitable for all – beginners and advanced users. Vim supports complex string searches, highlighting searches, and much more. Through plugins, Vim provides extended capabilities to developers and system admins that includes code completion, syntax highlighting, file management, version control, and more.</p>
</li>
</ul>
<p>Vim has two variations: Vim (<code>vim</code>) and Vim tiny (<code>vi</code>). Vim tiny is a smaller version of Vim that lacks some features of Vim.</p>
<h4 id="heading-how-to-start-using-vim">How to start using <code>vim</code></h4>
<p>Start using Vim with this command:</p>
<pre><code class="lang-bash">vim your-file.txt
</code></pre>
<p><code>your-file.txt</code> can either be a new file or an existing file that you want to edit.</p>
<h4 id="heading-navigating-vim-mastering-movement-and-command-modes">Navigating Vim: Mastering movement and command modes</h4>
<p>In the early days of the CLI, the keyboards didn't have arrow keys. Hence, navigation was done using the set of available keys, <code>hjkl</code> being one of them.</p>
<p>Being keyboard-centric, using <code>hjkl</code> keys can greatly speed up text editing tasks.</p>
<p>Note: Although arrow keys would work totally fine, you can still experiment with <code>hjkl</code> keys to navigate. Some people find this this way of navigation efficient.</p>
<p>💡<strong>Tip:</strong> To remember the <code>hjkl</code> sequence, use this: <strong>h</strong>ang back, <strong>j</strong>ump down, <strong>k</strong>ick up, <strong>l</strong>eap forward.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392462442/1a667ede-5f03-4acb-b40f-b10cefc64de3.png" alt="hjkl navigation guide" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-the-three-vim-modes">The three Vim modes</h4>
<p>You need to know the 3 operating modes of Vim and how to switch between them. Keystrokes behave differently in each command mode. The three modes are as follows:</p>
<ol>
<li><p>Command mode.</p>
</li>
<li><p>Edit mode.</p>
</li>
<li><p>Visual mode.</p>
</li>
</ol>
<p><strong>Command Mode.</strong> When you start Vim, you land in the command mode by default. This mode allows you to access other modes.</p>
<p>⚠ To switch to other modes, you need to be present in the command mode first</p>
<p><strong>Edit Mode</strong></p>
<p>This mode allows you to make changes to the file. To enter edit mode, press <code>I</code> while in command mode. Note the <code>'-- INSERT'</code> switch at the end of the screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392526710/d44cecd7-64be-4c89-9a31-dbf395b77fcb.png" alt="Insert mode in Vim" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Visual mode</strong></p>
<p>This mode allows you to work on a single character, a block of text, or lines of text. Let's break it down into simple steps. Remember, use the below combinations when in command mode.</p>
<ul>
<li><p><code>Shift + V</code> → Select multiple lines.</p>
</li>
<li><p><code>Ctrl + V</code> → Block mode</p>
</li>
<li><p><code>V</code> → Character mode</p>
</li>
</ul>
<p>The visual mode comes in handy when you need to copy and paste or edit lines in bulk.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392557097/b61a1515-cac0-4470-856b-b2c15de581e8.gif" alt="Selectind text using visual mode" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>Extended command mode.</strong></p>
<p>The extended command mode allows you to perform advanced operations like searching, setting line numbers, and highlighting text. We'll cover extended mode in the next section.</p>
<p>How to stay on track? If you forget your current mode, just press <code>ESC</code> twice and you will be back in Command Mode.</p>
<h4 id="heading-editing-efficiently-in-vim-copypasting-and-searching">Editing Efficiently in Vim: Copy/pasting and searching</h4>
<p><strong>1. How to copy and paste in Vim</strong></p>
<p>Copy-paste is known as 'yank' and 'put' in Linux terms. To copy-paste, follow these steps:</p>
<ul>
<li><p>Select text in visual mode.</p>
</li>
<li><p>Press <code>'y'</code> to copy/ yank.</p>
</li>
<li><p>Move your cursor to the required position and press <code>'p'</code>.</p>
</li>
</ul>
<p><strong>2. How to search for text in Vim</strong></p>
<p>Any series of strings can be searched with Vim using the <code>/</code> in command mode. To search, use <code>/string-to-match</code>.</p>
<p>In the command mode, type <code>:set hls</code> and press <code>enter</code>. Search using <code>/string-to-match</code>. This will highlight the searches.</p>
<p>Let's search a few strings:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719392684097/11c4a45e-0698-4fb7-bef7-f193684ea21a.gif" alt="Highlighting searches in Vim" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><strong>3. How to exit Vim</strong></p>
<p>First, move to command mode (by pressing escape twice) and then use these flags:</p>
<ul>
<li><p>Exit without saving → <code>:q!</code></p>
</li>
<li><p>Exit and save → <code>:wq!</code></p>
</li>
</ul>
<h4 id="heading-shortcuts-in-vim-making-editing-faster">Shortcuts in Vim: Making Editing Faster</h4>
<p>Note: All these shortcuts work in the command mode only.</p>
<ul>
<li><p><strong>Basic Navigation</strong></p>
<ul>
<li><p><code>h</code>: Move left</p>
</li>
<li><p><code>j</code>: Move down</p>
</li>
<li><p><code>k</code>: Move up</p>
</li>
<li><p><code>l</code>: Move right</p>
</li>
<li><p><code>0</code>: Move to the beginning of the line</p>
</li>
<li><p><code>$</code>: Move to the end of the line</p>
</li>
<li><p><code>gg</code>: Move to the beginning of the file</p>
</li>
<li><p><code>G</code>: Move to the end of the file</p>
</li>
<li><p><code>Ctrl+d</code>: Move half-page down</p>
</li>
<li><p><code>Ctrl+u</code>: Move half-page up</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>i</code>: Enter insert mode before the cursor</p>
</li>
<li><p><code>I</code>: Enter insert mode at the beginning of the line</p>
</li>
<li><p><code>a</code>: Enter insert mode after the cursor</p>
</li>
<li><p><code>A</code>: Enter insert mode at the end of the line</p>
</li>
<li><p><code>o</code>: Open a new line below the current line and enter insert mode</p>
</li>
<li><p><code>O</code>: Open a new line above the current line and enter insert mode</p>
</li>
<li><p><code>x</code>: Delete the character under the cursor</p>
</li>
<li><p><code>dd</code>: Delete the current line</p>
</li>
<li><p><code>yy</code>: Yank (copy) the current line (use this in visual mode)</p>
</li>
<li><p><code>p</code>: Paste below the cursor</p>
</li>
<li><p><code>P</code>: Paste above the cursor</p>
</li>
</ul>
</li>
<li><p><strong>Searching and Replacing</strong></p>
<ul>
<li><p><code>/</code>: Search for a pattern which will take you to its next occurrence</p>
</li>
<li><p><code>?</code>: Search for a pattern that will take you to its previous occurrence</p>
</li>
<li><p><code>n</code>: Repeat the last search in the same direction</p>
</li>
<li><p><code>N</code>: Repeat the last search in the opposite direction</p>
</li>
<li><p><code>:%s/old/new/g</code>: Replace all occurrences of <code>old</code> with <code>new</code> in the file</p>
</li>
</ul>
</li>
<li><p><strong>Exiting</strong></p>
<ul>
<li><p><code>:w</code>: Save the file but don't exit</p>
</li>
<li><p><code>:q</code>: Quit Vim (fails if there are unsaved changes)</p>
</li>
<li><p><code>:wq</code> or <code>:x</code>: Save and quit</p>
</li>
<li><p><code>:q!</code>: Quit without saving</p>
</li>
</ul>
</li>
<li><p><strong>Multiple Windows</strong></p>
<ul>
<li><p><code>:split</code> or <code>:sp</code>: Split the window horizontally</p>
</li>
<li><p><code>:vsplit</code> or <code>:vsp</code>: Split the window vertically</p>
</li>
<li><p><code>Ctrl+w followed by h/j/k/l</code>: Navigate between split windows</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-52-mastering-nano">5.2. Mastering Nano</h3>
<h4 id="heading-getting-started-with-nano-the-user-friendly-text-editor">Getting started with Nano: The user-friendly text editor</h4>
<p>Nano is a user-friendly text editor that is easy to use and is perfect for beginners. It is pre-installed on most Linux distributions.</p>
<p>To create a new file using Nano, use the following command:</p>
<pre><code class="lang-bash">nano
</code></pre>
<p>To start editing an existing file with Nano, use the following command:</p>
<pre><code class="lang-bash">nano filename
</code></pre>
<h4 id="heading-list-of-key-bindings-in-nano">List of key bindings in Nano</h4>
<p>Let's study the most important key bindings in Nano. You'll use the key bindings to perform various operations like saving, exiting, copying, pasting, and more.</p>
<p><strong>Write to a file and save</strong></p>
<p>Once you open Nano using the <code>nano</code> command, you can start writing text. To save the file, press <code>Ctrl+O</code>. You'll be prompted to enter the file name. Press <code>Enter</code> to save the file.</p>
<p><strong>Exit nano</strong></p>
<p>You can exit Nano by pressing <code>Ctrl+X</code>. If you have unsaved changes, Nano will prompt you to save the changes before exiting.</p>
<p><strong>Copying and pasting</strong></p>
<p>To select a region, use <code>ALT+A</code>. A marker will show. Use arrows to select the text. Once selected, exit the marker with with <code>ALT+^</code>.</p>
<p>To copy the selected text, press <code>Ctrl+K</code>. To paste the copied text, press <code>Ctrl+U</code>.</p>
<p><strong>Cutting and pasting</strong></p>
<p>Select the region with <code>ALT+A</code>. Once selected, cut the text with <code>Ctrl+K</code>. To paste the cut text, press <code>Ctrl+U</code>.</p>
<p><strong>Navigation</strong></p>
<p>Use <code>Alt \</code> to move to the beginning of the file.</p>
<p>Use <code>Alt /</code> to move to the end of the file.</p>
<p><strong>Viewing line numbers</strong></p>
<p>When you open a file with <code>nano -l filename</code>, you can view line numbers on the left side of the file.</p>
<p><strong>Searching</strong></p>
<p>You can search for a specific line number with <code>ALt + G</code>. Enter the line number to the prompt and press <code>Enter</code>.</p>
<p>You can also initiate search for a string with <code>CTRL + W</code> and press Enter. If you want to search backwards, you can press <code>Alt+W</code> after initiating the search with <code>Ctrl+W</code>.</p>
<h4 id="heading-summary-of-keybindings-in-nano">Summary of keybindings in Nano</h4>
<ul>
<li><p><strong>General</strong></p>
<ul>
<li><p><code>Ctrl+X</code>: Exit Nano (prompting to save if changes are made)</p>
</li>
<li><p><code>Ctrl+O</code>: Save the file</p>
</li>
<li><p><code>Ctrl+R</code>: Read a file into the current file</p>
</li>
<li><p><code>Ctrl+G</code>: Display the help text</p>
</li>
</ul>
</li>
<li><p><strong>Editing</strong></p>
<ul>
<li><p><code>Ctrl+K</code>: Cut the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+U</code>: Paste the contents of the cutbuffer into the current line</p>
</li>
<li><p><code>Alt+6</code>: Copy the current line and store it in the cutbuffer</p>
</li>
<li><p><code>Ctrl+J</code>: Justify the current paragraph</p>
</li>
</ul>
</li>
<li><p><strong>Navigation</strong></p>
<ul>
<li><p><code>Ctrl+A</code>: Move to the beginning of the line</p>
</li>
<li><p><code>Ctrl+E</code>: Move to the end of the line</p>
</li>
<li><p><code>Ctrl+C</code>: Display the current line number and file information</p>
</li>
<li><p><code>Ctrl+_</code> (<code>Ctrl+Shift+-</code>): Go to a specific line (and optionally, column) number</p>
</li>
<li><p><code>Ctrl+Y</code>: Scroll up one page</p>
</li>
<li><p><code>Ctrl+V</code>: Scroll down one page</p>
</li>
</ul>
</li>
<li><p><strong>Search and Replace</strong></p>
<ul>
<li><p><code>Ctrl+W</code>: Search for a string (then <code>Enter</code> to search again)</p>
</li>
<li><p><code>Alt+W</code>: Repeat the last search but in the opposite direction</p>
</li>
<li><p><code>Ctrl+\</code>: Search and replace</p>
</li>
</ul>
</li>
<li><p><strong>Miscellaneous</strong></p>
<ul>
<li><p><code>Ctrl+T</code>: Invoke the spell checker, if available</p>
</li>
<li><p><code>Ctrl+D</code>: Delete the character under the cursor (does not cut it)</p>
</li>
<li><p><code>Ctrl+L</code>: Refresh (redraw) the current screen</p>
</li>
<li><p><code>Alt+U</code>: Undo the last operation</p>
</li>
<li><p><code>Alt+E</code>: Redo the last undone operation</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-part-6-bash-scripting">Part 6: Bash Scripting</h2>
<h3 id="heading-61-definition-of-bash-scripting">6.1. Definition of Bash scripting</h3>
<p>A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.</p>
<p>By saving commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.</p>
<h3 id="heading-62-advantages-of-bash-scripting">6.2. Advantages of Bash Scripting</h3>
<p>Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems.</p>
<p>Some advantages of shell scripting are:</p>
<ul>
<li><p><strong>Automation</strong>: Shell scripts allow you to automate repetitive tasks and processes, saving time and reducing the risk of errors that can occur with manual execution.</p>
</li>
<li><p><strong>Portability</strong>: Shell scripts can be run on various platforms and operating systems, including Unix, Linux, macOS, and even Windows through the use of emulators or virtual machines.</p>
</li>
<li><p><strong>Flexibility</strong>: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.</p>
</li>
<li><p><strong>Accessibility</strong>: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.</p>
</li>
<li><p><strong>Integration</strong>: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.</p>
</li>
<li><p><strong>Debugging</strong>: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.</p>
</li>
</ul>
<h3 id="heading-63-overview-of-bash-shell-and-command-line-interface">6.3. Overview of Bash Shell and Command Line Interface</h3>
<p>The terms "shell" and "bash" are often used interchangeably. But there is a subtle difference between the two.</p>
<p>The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.</p>
<p>Till now, the commands that you have been entering were basically being entered in a "shell".</p>
<p>Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.</p>
<p>You can determine your shell type using the <code>ps</code> command:</p>
<pre><code class="lang-markdown">ps
<span class="hljs-section"># output:</span>

<span class="hljs-code">    PID TTY          TIME CMD
  20506 pts/0    00:00:00 bash &lt;--- the shell type
  20931 pts/0    00:00:00 ps</span>
</code></pre>
<p>In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.</p>
<p>Note: In this section, we will be using the "bash" shell.</p>
<h3 id="heading-64-how-to-create-and-execute-bash-scripts">6.4. How to Create and Execute Bash scripts</h3>
<p><strong>Script naming conventions</strong></p>
<p>By naming convention, bash scripts end with <code>.sh</code>. However, bash scripts can run perfectly fine without the <code>sh</code> extension.</p>
<p><strong>Adding the Shebang</strong></p>
<p>Bash scripts start with a <code>shebang</code>. Shebang is a combination of <code>bash #</code> and <code>bang !</code> followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.</p>
<p>Below is an example of the shebang statement.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
</code></pre>
<p>You can find your bash shell path (which may vary from the above) using the command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">which</span> bash
</code></pre>
<p><strong>Creating your first bash script</strong></p>
<p>Our first script prompts the user to enter a path. In return, its contents will be listed.</p>
<p>Create a file named <code>run_all.sh</code> using any editor of your choice.</p>
<pre><code class="lang-bash">vim run_all.sh
</code></pre>
<p>Add the following commands in your file and save it:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
<span class="hljs-built_in">read</span> the_path

<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
ls <span class="hljs-variable">$the_path</span>
</code></pre>
<p>Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.</p>
<pre><code class="lang-bash">  1 <span class="hljs-comment">#!/bin/bash</span>
  2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"Today is "</span> `date`
  3
  4 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nenter the path to directory"</span>
  5 <span class="hljs-built_in">read</span> the_path
  6
  7 <span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\n you path has the following files and folders: "</span>
  8 ls <span class="hljs-variable">$the_path</span>
</code></pre>
<ul>
<li><p>Line #1: The shebang (<code>#!/bin/bash</code>) points toward the bash shell path.</p>
</li>
<li><p>Line #2: The <code>echo</code> command displays the current date and time on the terminal. Note that the <code>date</code> is in backticks.</p>
</li>
<li><p>Line #4: We want the user to enter a valid path.</p>
</li>
<li><p>Line #5: The <code>read</code> command reads the input and stores it in the variable <code>the_path</code>.</p>
</li>
<li><p>line #8: The <code>ls</code> command takes the variable with the stored path and displays the current files and folders.</p>
</li>
</ul>
<p><strong>Executing the bash script</strong></p>
<p>To make the script executable, assign execution rights to your user using this command:</p>
<pre><code class="lang-bash">chmod u+x run_all.sh
</code></pre>
<p>Here,</p>
<ul>
<li><p><code>chmod</code> modifies the ownership of a file for the current user :<code>u</code>.</p>
</li>
<li><p><code>+x</code> adds the execution rights to the current user. This means that the user who is the owner can now run the script.</p>
</li>
<li><p><code>run_all.sh</code> is the file we wish to run.</p>
</li>
</ul>
<p>You can run the script using any of the mentioned methods:</p>
<ul>
<li><p><code>sh run_all.sh</code></p>
</li>
<li><p><code>bash run_all.sh</code></p>
</li>
<li><p><code>./run_all.sh</code></p>
</li>
</ul>
<p>Let's see it running in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/run-script-bash-2.gif" alt="Running a bash script" width="600" height="400" loading="lazy"></p>
<h3 id="heading-65-bash-scripting-basics">6.5. Bash Scripting Basics</h3>
<h4 id="heading-comments-in-bash-scripting">Comments in bash scripting</h4>
<p>Comments start with a <code>#</code> in bash scripting. This means that any line that begins with a <code>#</code> is a comment and will be ignored by the interpreter.</p>
<p>Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.</p>
<p>These are examples of comments:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># This is an example comment</span>
<span class="hljs-comment"># Both of these lines will be ignored by the interpreter</span>
</code></pre>
<h4 id="heading-variables-and-data-types-in-bash">Variables and data types in Bash</h4>
<p>Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.</p>
<p>There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.</p>
<p>In Bash, you can use and set the variable values in the following ways:</p>
<ol>
<li>Assign the value directly:</li>
</ol>
<pre><code class="lang-bash">country=Netherlands
</code></pre>
<p>2.  Assign the value based on the output obtained from a program or command, using command substitution. Note that <code>$</code> is required to access an existing variable's value.</p>
<pre><code class="lang-bash">same_country=<span class="hljs-variable">$country</span>
</code></pre>
<p>This assigns the value of <code>country</code> to the new variable <code>same_country</code>.</p>
<p>To access the variable value, append <code>$</code> to the variable name.</p>
<pre><code class="lang-bash">country=Netherlands
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$country</span>
<span class="hljs-comment"># output</span>
Netherlands
new_country=<span class="hljs-variable">$country</span>
<span class="hljs-built_in">echo</span> <span class="hljs-variable">$new_country</span>
<span class="hljs-comment"># output</span>
Netherlands
</code></pre>
<p>Above, you can see an example of assigning and printing variable values.</p>
<h4 id="heading-variable-naming-conventions">Variable naming conventions</h4>
<p>In Bash scripting, the following are the variable naming conventions:</p>
<ol>
<li><p>Variable names should start with a letter or an underscore (<code>_</code>).</p>
</li>
<li><p>Variable names can contain letters, numbers, and underscores (<code>_</code>).</p>
</li>
<li><p>Variable names are case-sensitive.</p>
</li>
<li><p>Variable names should not contain spaces or special characters.</p>
</li>
<li><p>Use descriptive names that reflect the purpose of the variable.</p>
</li>
<li><p>Avoid using reserved keywords, such as <code>if</code>, <code>then</code>, <code>else</code>, <code>fi</code>, and so on as variable names.</p>
</li>
</ol>
<p>Here are some examples of valid variable names in Bash:</p>
<pre><code class="lang-bash">name
count
_var
myVar
MY_VAR
</code></pre>
<p>And here are some examples of invalid variable names:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># invalid variable names</span>

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)
</code></pre>
<p>Following these naming conventions helps make Bash scripts more readable and easier to maintain.</p>
<h4 id="heading-input-and-output-in-bash-scripts">Input and output in Bash scripts</h4>
<h4 id="heading-gathering-input">Gathering input</h4>
<p>In this section, we'll discuss some methods to provide input to our scripts.</p>
<ol>
<li>Reading the user input and storing it in a variable</li>
</ol>
<p>We can read the user input using the <code>read</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"What's your name?"</span>
<span class="hljs-built_in">read</span> entered_name
<span class="hljs-built_in">echo</span> -e <span class="hljs-string">"\nWelcome to bash tutorial"</span> <span class="hljs-variable">$entered_name</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh.gif" alt="Reading the name from a script" width="600" height="400" loading="lazy"></p>
<p>2.  Reading from a file</p>
<p>This code reads each line from a file named <code>input.txt</code> and prints it to the terminal. We'll study while loops later in this section.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> <span class="hljs-built_in">read</span> line
<span class="hljs-keyword">do</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-variable">$line</span>
<span class="hljs-keyword">done</span> &lt; input.txt
</code></pre>
<p>3.  Command line arguments</p>
<p>In a bash script or function, <code>$1</code> denotes the initial argument passed, <code>$2</code> denotes the second argument passed, and so forth.</p>
<p>This script takes a name as a command-line argument and prints a personalized greeting.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$1</span>!"</span>
</code></pre>
<p>We have supplied <code>Zaira</code> as our argument to the script.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/name-sh-1.gif" alt="Providing arguments to the bash script" width="600" height="400" loading="lazy"></p>
<h4 id="heading-displaying-output">Displaying output</h4>
<p>Here we'll discuss some methods to receive output from the scripts.</p>
<ol>
<li>Printing to the terminal:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello, World!"</span>
</code></pre>
<p>This prints the text "Hello, World!" to the terminal.</p>
<p>2.  Writing to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"This is some text."</span> &gt; output.txt
</code></pre>
<p>This writes the text "This is some text." to a file named <code>output.txt</code>. Note that the <code>&gt;</code> operator overwrites a file if it already has some content.</p>
<p>3.  Appending to a file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"More text."</span> &gt;&gt; output.txt
</code></pre>
<p>This appends the text "More text." to the end of the file <code>output.txt</code>.</p>
<p>4.  Redirecting output:</p>
<pre><code class="lang-bash">ls &gt; files.txt
</code></pre>
<p>This lists the files in the current directory and writes the output to a file named <code>files.txt</code>. You can redirect output of any command to a file this way.</p>
<p>You'll learn about output redirection in detail in section 8.5.</p>
<h4 id="heading-conditional-statements-ifelse">Conditional statements (if/else)</h4>
<p>Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including <code>if</code>, <code>if-else</code>, <code>if-elif-else</code>, and nested conditionals.</p>
<p><strong>Syntax</strong>:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [[ condition ]];
<span class="hljs-keyword">then</span>
    statement
<span class="hljs-keyword">elif</span> [[ condition ]]; <span class="hljs-keyword">then</span>
    statement 
<span class="hljs-keyword">else</span>
    <span class="hljs-keyword">do</span> this by default
<span class="hljs-keyword">fi</span>
</code></pre>
<h4 id="heading-syntax-of-bash-conditional-statements">Syntax of bash conditional statements</h4>
<p>We can use logical operators such as AND <code>-a</code> and OR <code>-o</code> to make comparisons that have more significance.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">if</span> [ <span class="hljs-variable">$a</span> -gt 60 -a <span class="hljs-variable">$b</span> -lt 100 ]
</code></pre>
<p>This statement checks if both conditions are <code>true</code>: <code>a</code> is greater than <code>60</code> AND <code>b</code> is less than <code>100</code>.</p>
<p>Let's see an example of a Bash script that uses <code>if</code>, <code>if-else</code>, and <code>if-elif-else</code> statements to determine if a user-inputted number is positive, negative, or zero:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Script to determine if a number is positive, negative, or zero</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Please enter a number: "</span>
<span class="hljs-built_in">read</span> num

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$num</span> -gt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is positive"</span>
<span class="hljs-keyword">elif</span> [ <span class="hljs-variable">$num</span> -lt 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is negative"</span>
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$num</span> is zero"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<p>The script first prompts the user to enter a number. Then, it uses an <code>if</code> statement to check if the number is greater than <code>0</code>. If it is, the script outputs that the number is positive. If the number is not greater than <code>0</code>, the script moves on to the next statement, which is an <code>if-elif</code> statement.</p>
<p>Here, the script checks if the number is less than <code>0</code>. If it is, the script outputs that the number is negative.</p>
<p>Finally, if the number is neither greater than <code>0</code> nor less than <code>0</code>, the script uses an <code>else</code> statement to output that the number is zero.</p>
<p>Seeing it in action 🚀</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/test-odd.gif" alt="Checking if a number is even or odd" width="600" height="400" loading="lazy"></p>
<h4 id="heading-looping-and-branching-in-bash">Looping and branching in Bash</h4>
<p><strong>While loop</strong></p>
<p>While loops check for a condition and loop until the condition remains <code>true</code>. We need to provide a counter statement that increments the counter to control loop execution.</p>
<p>In the example below, <code>(( i += 1 ))</code> is the counter statement that increments the value of <code>i</code>. The loop will run exactly 10 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
i=1
<span class="hljs-keyword">while</span> [[ <span class="hljs-variable">$i</span> -le 10 ]] ; <span class="hljs-keyword">do</span>
   <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$i</span>"</span>
  (( i += 1 ))
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-187.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>For loop</strong></p>
<p>The <code>for</code> loop, just like the <code>while</code> loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.</p>
<p>In the example below, the loop will iterate 5 times.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> {1..5}
<span class="hljs-keyword">do</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$i</span>
<span class="hljs-keyword">done</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-186.png" alt="Looping from 1 to 10 using " width="600" height="400" loading="lazy"></p>
<p><strong>Case statements</strong></p>
<p>In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:</p>
<pre><code class="lang-bash"><span class="hljs-keyword">case</span> expression <span class="hljs-keyword">in</span>
    pattern1)
        <span class="hljs-comment"># code to execute if expression matches pattern1</span>
        ;;
    pattern2)
        <span class="hljs-comment"># code to execute if expression matches pattern2</span>
        ;;
    pattern3)
        <span class="hljs-comment"># code to execute if expression matches pattern3</span>
        ;;
    *)
        <span class="hljs-comment"># code to execute if none of the above patterns match expression</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against.</p>
<p>The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.</p>
<p>Let's see an example:</p>
<pre><code class="lang-bash">fruit=<span class="hljs-string">"apple"</span>

<span class="hljs-keyword">case</span> <span class="hljs-variable">$fruit</span> <span class="hljs-keyword">in</span>
    <span class="hljs-string">"apple"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a red fruit."</span>
        ;;
    <span class="hljs-string">"banana"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a yellow fruit."</span>
        ;;
    <span class="hljs-string">"orange"</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is an orange fruit."</span>
        ;;
    *)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Unknown fruit."</span>
        ;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>In this example, since the value of <code>fruit</code> is <code>apple</code>, the first pattern matches, and the block of code that echoes <code>This is a red fruit.</code> is executed. If the value of <code>fruit</code> were instead <code>banana</code>, the second pattern would match and the block of code that echoes <code>This is a yellow fruit.</code> would execute, and so on.</p>
<p>If the value of <code>fruit</code> does not match any of the specified patterns, the default case is executed, which echoes <code>Unknown fruit.</code></p>
<h2 id="heading-part-7-managing-software-packages-in-linux">Part 7: Managing Software Packages in Linux</h2>
<p>Linux comes with several built-in programs. But you might need to install new programs based on your needs. You might also need to upgrade the existing applications.</p>
<h3 id="heading-71-packages-and-package-management">7.1. Packages and Package Management</h3>
<h4 id="heading-what-is-a-package">What is a package?</h4>
<p>A package is a collection of files that are bundled together. These files are essential for a particular program to run. These files contain the program's executable files, libraries, and other resources.</p>
<p>In addition to the files required for the program to run, packages also contain installation scripts, which copy the files to where they are needed. A program may contain many files and dependencies. With packages, it is easier to manage all the files and dependencies at once.</p>
<h4 id="heading-what-is-the-difference-between-source-and-binary">What is the difference between source and binary?</h4>
<p>Programmers write source code in a programming language. This source code is then compiled into machine code that the computer can understand. The compiled code is called binary code.</p>
<p>When you download a package, you can either get the <em>source code</em> or the <em>binary code.</em> The source code is the human-readable code that can be compiled into binary code. The binary code is the compiled code that the computer can understand.</p>
<p>Source packages can be used with any type of machine if the source code is compiled properly. Binary, on the other hand, is compiled code that is specific to a particular type of machine or architecture.</p>
<p>You can find the architecture of your machine using the <code>uname -m</code> command.</p>
<pre><code class="lang-bash">uname -m
<span class="hljs-comment"># output</span>
x86_64
</code></pre>
<h4 id="heading-package-dependencies">Package dependencies</h4>
<p>Programs often share files. Instead of including these files in each package, a separate package can provide them for all programs.</p>
<p>To install a program that needs these files, you must also install the package containing them. This is called a package dependency. Specifying dependencies makes packages smaller and simpler by reducing duplicates.</p>
<p>When you install a program, its dependencies must also be installed. Most required dependencies are usually already installed, but a few extra ones might be needed. So, don't be surprised if several other packages are installed along with your chosen package. These are the necessary dependencies.</p>
<h4 id="heading-package-managers">Package managers</h4>
<p>Linux offers a comprehensive package management system for installing, upgrading, configuring, and removing software.</p>
<p>With package management, you can get access to an organized base of thousands of software packages along with having the ability to resolve dependencies and check for software updates.</p>
<p>Packages can be managed using either command-line utilities that can be easily automated by system administrators, or through a graphical interface.</p>
<h4 id="heading-software-channelsrepositories">Software channels/repositories</h4>
<p>⚠️ Package management is different for different distros. Here, we are using Ubuntu.</p>
<p>Installing software is a bit different in Linux as compared to Windows and Mac.</p>
<p>Linux uses repositories to store software packages. A repository is a collection of software packages that are available for installation via a package manager.</p>
<p>A package manager also stores an index of all of the packages available from a repo. Sometimes the index is rebuilt to ensure that it is up to date and to know which packages have been upgraded or added to the channel since it last checked.</p>
<p>The generic process of downloading software from a repo looks something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313472889/f4961606-b9c4-4ed7-8edc-61e0fc6908e4.png" alt="Rrocess of downloading software from a remote repo" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If we talk specifically about Ubuntu,</p>
<ol>
<li><p>Index is fetched using <code>apt update.</code> (<code>apt</code> is explained in next section).</p>
</li>
<li><p>Required files/ dependencies requested according to index using <code>apt install</code></p>
</li>
<li><p>Packages and dependencies installed locally.</p>
</li>
<li><p>Update dependencies and packages when required using <code>apt update</code> and <code>apt upgrade</code></p>
</li>
</ol>
<p>On Debian-based distros, you can file the list of repos (repositories) in <code>/etc/apt/sources.list</code>.</p>
<h3 id="heading-72-installing-a-package-via-command-line">7.2. Installing a Package via Command Line</h3>
<p>The <code>apt</code> command is a powerful command-line tool, which works with Ubuntu’s "Advanced Packaging Tool (APT)".</p>
<p><code>apt</code>, along with the commands bundled with it, provides the means to install new software packages, upgrade existing software packages, update the package list index, and even upgrade the entire Ubuntu system.</p>
<p>To view the logs of the installation using <code>apt</code>, you can view the <code>/var/log/dpkg.log</code> file.</p>
<p>Following are the uses of the <code>apt</code> command:</p>
<h4 id="heading-installing-packages">Installing packages</h4>
<p>For example, to install the <code>htop</code> package, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt install htop
</code></pre>
<h4 id="heading-updating-the-package-list-index">Updating the package list index</h4>
<p>The package list index is a list of all the packages available in the repositories. To update the local package list index, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt update
</code></pre>
<h4 id="heading-upgrading-the-packages">Upgrading the packages</h4>
<p>Installed packages on your system can get updates containing bug fixes, security patches, and new features.</p>
<p>To upgrade the packages, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt upgrade
</code></pre>
<h4 id="heading-removing-packages">Removing packages</h4>
<p>To remove a package, like <code>htop</code>, you can use the following command:</p>
<pre><code class="lang-bash">sudo apt remove htop
</code></pre>
<h3 id="heading-73-installing-a-package-via-an-advanced-graphical-method-synaptic">7.3. Installing a Package via an Advanced Graphical Method – Synaptic</h3>
<p>If you are not comfortable with the command line, you can use a GUI application to install packages. You can achieve the same results as the command line, but with a graphical interface.</p>
<p>Synaptic is a GUI package management application that helps in listing the installed packages, their status, pending updates, and so on. It offers custom filters to help you narrow down the search results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313599636/0f362ed7-c371-4a58-96c2-c359178cdbd9.png" alt="0f362ed7-c371-4a58-96c2-c359178cdbd9" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>You can also right-click on a package and view further details like the dependencies, maintainer, size, and the installed files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719313607397/33b7ad76-2492-4805-8133-35c8cd3c4a0a.png" alt="View a package's detail" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-74-installing-downloaded-packages-from-a-website">7.4. Installing downloaded packages from a website</h3>
<p>You may want to install a package you have downloaded from a website, rather than from a software repository. These packages are called <code>.deb</code> files.</p>
<p><strong>Using</strong><code>dpkg</code><strong>to install packages:</strong><code>dpkg</code> is a command-line tool used to install packages. To install a package with <strong>dpkg</strong>, open the Terminal and type the following:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> directory
sudo dpkg -i package_name.deb
</code></pre>
<p>Note: Replace "directory" with the directory where the package is stored and "package_name" with the filename of the package.</p>
<p>Alternatively, you can right-click, select "Open With Other Application," and choose a GUI app of your choice.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719322161581/f16d83ac-ca9a-4502-a80c-e6a25dee5c68.png" alt="Installing a software using an app" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> In Ubuntu, you can see a list of installed packages with <code>dpkg --list</code>.</p>
<h2 id="heading-part-8-advanced-linux-topics">Part 8: Advanced Linux Topics</h2>
<h3 id="heading-81-user-management">8.1. User Management</h3>
<p>There can be multiple users with varying levels of access in a system. In Linux, the root user has the highest level of access and can perform any operation on the system. Regular users have limited access and can only perform operations they have been granted permission to do.</p>
<h4 id="heading-what-is-a-user">What is a user?</h4>
<p>A user account provides separation between different people and programs that can run commands.</p>
<p>Humans identify users by a name, as names are easy to work with. But the system identifies users by a unique number called the user ID (UID).</p>
<p>When human users log in using the provided username, they have to use a password to authorize themselves.</p>
<p>User accounts form the foundations of system security. File ownership is also associated with user accounts and it enforces access control to the files. Every process has an associated user account that provides a layer of control for the admins.</p>
<p>There are three main types of user accounts:</p>
<ol>
<li><p><strong>Superuser</strong>: The superuser has complete access to the system. The name of the superuser is <code>root</code>. It has a <code>UID</code> of 0.</p>
</li>
<li><p><strong>System user</strong>: The system user has user accounts that are used to run system services. These accounts are used to run system services and are not meant for human interaction.</p>
</li>
<li><p><strong>Regular user</strong>: Regular users are human users who have access to the system.</p>
</li>
</ol>
<p>The <code>id</code> command displays the user ID and group ID of the current user.</p>
<pre><code class="lang-bash">id
uid=1000(john) gid=1000(john) groups=1000(john),4(adm),24(cdrom),27(sudo),30(dip)... output truncated
</code></pre>
<p>To view the basic information of another user, pass the username as an argument to the <code>id</code> command.</p>
<pre><code class="lang-bash">id username
</code></pre>
<p>To view user-related information for processes, use the <code>ps</code> command with the <code>-u</code> flag.</p>
<pre><code class="lang-bash">ps -u
<span class="hljs-comment"># Output</span>
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1  16968  3920 ?        Ss   18:45   0:00 /sbin/init splash
root         2  0.0  0.0      0     0 ?        S    18:45   0:00 [kthreadd]
</code></pre>
<p>By default, systems use the <code>/etc/passwd</code> file to store user information.</p>
<p>Here is a line from the <code>/etc/passwd</code> file:</p>
<pre><code class="lang-bash">root:x:0:0:root:/root:/bin/bash
</code></pre>
<p>The <code>/etc/passwd</code> file contains the following information about each user:</p>
<ol>
<li><p>Username: <code>root</code> – The username of the user account.</p>
</li>
<li><p>Password: <code>x</code> – The password in encrypted format for the user account that is stored in the <code>/etc/shadow</code> file for security reasons.</p>
</li>
<li><p>User ID (UID): <code>0</code> – The unique numerical identifier for the user account.</p>
</li>
<li><p>Group ID (GID): <code>0</code> – The primary group identifier for the user account.</p>
</li>
<li><p>User Info: <code>root</code> – The real name for the user account.</p>
</li>
<li><p>Home directory: <code>/root</code> – The home directory for the user account.</p>
</li>
<li><p>Shell: <code>/bin/bash</code> – The default shell for the user account. A system user might use <code>/sbin/nologin</code> if interactive logins are not allowed for that user.</p>
</li>
</ol>
<h4 id="heading-what-is-a-group">What is a group?</h4>
<p>A group is a collection of user accounts that share access and resources. Groups have group names to identify them. The system identifies groups by a unique number called the group ID (GID).</p>
<p>By default, the information about groups is stored in the <code>/etc/group</code> file.</p>
<p>Here is an entry from the <code>/etc/group</code> file:</p>
<pre><code class="lang-bash">adm:x:4:syslog,john
</code></pre>
<p>Here is the breakdown of the fields in the given entry:</p>
<ol>
<li><p>Group name: <code>adm</code> – The name of the group.</p>
</li>
<li><p>Password: <code>x</code> – The password for the group is stored in the <code>/etc/gshadow</code> file for security reasons. The password is optional and appears empty if not set.</p>
</li>
<li><p>Group ID (GID): <code>4</code> – The unique numerical identifier for the group.</p>
</li>
<li><p>Group members: <code>syslog,john</code> – The list of usernames that are members of the group. In this case, the group <code>adm</code> has two members: <code>syslog</code> and <code>john</code>.</p>
</li>
</ol>
<p>In this specific entry, the group name is <code>adm</code>, the group ID is <code>4</code>, and the group has two members: <code>syslog</code> and <code>john</code>. The password field is typically set to <code>x</code> to indicate that the group password is stored in the <code>/etc/gshadow</code> file.</p>
<p>The groups are further divided into '<em>primary'</em> and '<em>supplementary'</em> groups.</p>
<ul>
<li><p>Primary Group: Each user is assigned one primary group by default. This group usually has the same name as the user and is created when the user account is made. Files and directories created by the user are typically owned by this primary group.</p>
</li>
<li><p>Supplementary Groups: These are extra groups a user can belong to in addition to their primary group. Users can be members of multiple supplementary groups. These groups let a user have permissions for resources shared among those groups. They help provide access to shared resources without affecting the system’s file permissions and keeping the security intact. While a user must belong to one primary group, belonging to supplementary groups is optional.</p>
</li>
</ul>
<h4 id="heading-access-control-finding-and-understanding-file-permission">Access control: finding and understanding file permission</h4>
<p>File ownership can be viewed using the <code>ls -l</code> command. The first column in the output of the <code>ls -l</code> command shows the permissions of the file. Other columns show the owner of the file and the group that the file belongs to.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-146.png" alt="Detailed output of ls -l" width="600" height="400" loading="lazy"></p>
<p>Let's have a closer look into the <code>mode</code> column:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-147.png" alt="Permission classes and file types" width="600" height="400" loading="lazy"></p>
<p><strong>Mode</strong> defines two things:</p>
<ul>
<li><p><strong>File type:</strong> File type defines the type of the file. For regular files that contain simple data it is blank <code>-</code>. For other special file types the symbol is different. For a directory which is a special file, it is <code>d</code>. Special files are treated differently by the OS.</p>
</li>
<li><p><strong>Permission classes:</strong> The next set of characters define the permissions for user, group, and others respectively.<br>  – <strong>User</strong>: This is the owner of a file and owner of the file belongs to this class.<br>  – <strong>Group</strong>: The members of the file’s group belong to this class<br>  – <strong>Other</strong>: Any users that are not part of the user or group classes belong to this class.</p>
</li>
</ul>
<p>💡<strong>Tip:</strong> Directory ownership can be viewed using the <code>ls -ld</code> command.</p>
<h5 id="heading-how-to-read-symbolic-permissions-or-the-rwx-permissions">How to Read Symbolic Permissions or the <code>rwx</code> permissions</h5>
<p>The <code>rwx</code> representation is known as the Symbolic representation of permissions. In the set of permissions,</p>
<ul>
<li><p><code>r</code> stands for <strong>read</strong>. It is indicated in the first character of the triad.</p>
</li>
<li><p><code>w</code> stands for <strong>write</strong>. It is indicated in the second character of the triad.</p>
</li>
<li><p><code>x</code> stands for <strong>execution</strong>. It is indicated in the third character of the triad.</p>
</li>
</ul>
<p><strong>Read:</strong></p>
<p>For regular files, read permissions allow the file to be opened and read only. Users can't modify the file.</p>
<p>Similarly for directories, read permissions allow the listing of directory content without any modification in the directory.</p>
<p><strong>Write:</strong></p>
<p>When files have write permissions, the user can modify (edit, delete) the file and save it.</p>
<p>For folders, write permissions enable a user to modify its contents (create, delete, and rename the files inside it), and modify the contents of files that the user has write permissions to.</p>
<p><strong>Examples of permissions in Linux</strong></p>
<p>Now that we know how to read permissions, let's see some examples.</p>
<ul>
<li><p><code>-rwx------</code>: A file that is only accessible and executable by its owner.</p>
<p>  <code>-rw-rw-r--</code>: A file that is open to modification by its owner and group but not by others.</p>
</li>
<li><p><code>drwxrwx---</code>: A directory that can be modified by its owner and group.</p>
</li>
</ul>
<p><strong>Execute:</strong></p>
<p>For files, execute permissions allows the user to run an executable script. For directories, the user can access them, and access details about files in the directory.</p>
<h5 id="heading-how-to-change-file-permissions-and-ownership-in-linux-using-chmod-and-chown">How to Change File Permissions and Ownership in Linux using <code>chmod</code> and <code>chown</code></h5>
<p>Now that we know the basics of ownerships and permissions, let's see how we can modify permissions using the <code>chmod</code> command.</p>
<p><strong>Syntax of</strong><code>chmod</code>:</p>
<pre><code class="lang-bash">chmod permissions filename
</code></pre>
<p>Where,</p>
<ul>
<li><p><code>permissions</code> can be read, write, execute or a combination of them.</p>
</li>
<li><p><code>filename</code> is the name of the file for which the permissions need to change. This parameter can also be a list if files to change permissions in bulk.</p>
</li>
</ul>
<p>We can change permissions using two modes:</p>
<ol>
<li><p><strong>Symbolic mode</strong>: this method uses symbols like <code>u</code>, <code>g</code>, <code>o</code> to represent users, groups, and others. Permissions are represented as  <code>r, w, x</code> for read, write, and execute, respectively. You can modify permissions using +, - and =.</p>
</li>
<li><p><strong>Absolute mode</strong>: this method represents permissions as 3-digit octal numbers ranging from 0-7.</p>
</li>
</ol>
<p>Now, let's see them in detail.</p>
<h5 id="heading-how-to-change-permissions-using-symbolic-mode">How to Change Permissions using Symbolic Mode</h5>
<p>The table below summarize the user representation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>USER REPRESENTATION</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>u</td><td>user/owner</td></tr>
<tr>
<td>g</td><td>group</td></tr>
<tr>
<td>o</td><td>other</td></tr>
</tbody>
</table>
</div><p>We can use mathematical operators to add, remove, and assign permissions. The table below shows the summary:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>OPERATOR</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>+</td><td>Adds a permission to a file or directory</td></tr>
<tr>
<td>–</td><td>Removes the permission</td></tr>
<tr>
<td>\=</td><td>Sets the permission if not present before. Also overrides the permissions if set earlier.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<p>Suppose I have a script and I want to make it executable for the owner of the file <code>zaira</code>.</p>
<p>Current file permissions are as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-161.png" alt="image-161" width="600" height="400" loading="lazy"></p>
<p>Let's split the permissions like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-160.png" alt="Splitting file permissions" width="600" height="400" loading="lazy"></p>
<p>To add execution rights (<code>x</code>) to owner (<code>u</code>) using symbolic mode, we can use the command below:</p>
<pre><code class="lang-bash">chmod u+x mymotd.sh
</code></pre>
<p><strong>Output:</strong></p>
<p>Now, we can see that the execution permissions have been added for owner <code>zaira</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-162.png" alt="Permission updated" width="600" height="400" loading="lazy"></p>
<p><strong>Additional examples for changing permissions via symbolic method:</strong></p>
<ul>
<li><p>Removing <code>read</code> and <code>write</code> permission for <code>group</code> and <code>others</code>: <code>chmod go-rw</code>.</p>
</li>
<li><p>Removing <code>read</code> permissions for <code>others</code>: <code>chmod o-r</code>.</p>
</li>
<li><p>Assigning <code>write</code> permission to <code>group</code> and overriding existing permission: <code>chmod g=w</code>.</p>
</li>
</ul>
<h5 id="heading-how-to-change-permissions-using-absolute-mode">How to Change Permissions using Absolute Mode</h5>
<p>Absolute mode uses numbers to represent permissions and mathematical operators to modify them.</p>
<p>The below table shows how we can assign relevant permissions:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>PROVIDE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>add 4</td></tr>
<tr>
<td>write</td><td>add 2</td></tr>
<tr>
<td>execute</td><td>add 1</td></tr>
</tbody>
</table>
</div><p>Permissions can be revoked using subtraction. The below table shows how you can remove relevant permissions.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>PERMISSION</strong></td><td><strong>REVOKE PERMISSION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>read</td><td>subtract 4</td></tr>
<tr>
<td>write</td><td>subtract 2</td></tr>
<tr>
<td>execute</td><td>subtract 1</td></tr>
</tbody>
</table>
</div><p><strong>Example</strong>:</p>
<ul>
<li>Set <code>read</code> (add 4) for <code>user</code>, <code>read</code> (add 4) and <code>execute</code> (add 1) for group, and only <code>execute</code> (add 1) for others.</li>
</ul>
<p><code>chmod 451 file-name</code></p>
<p>This is how we performed the calculation:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-163.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<p>Note that this is the same as <code>r--r-x--x</code>.</p>
<ul>
<li>Remove <code>execution</code> rights from <code>other</code> and <code>group</code>.</li>
</ul>
<p>To remove execution from <code>other</code> and <code>group</code>, subtract 1 from the execute part of last 2 octets.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-164.png" alt="Calculation breakdown for removing permissions" width="600" height="400" loading="lazy"></p>
<ul>
<li>Assign <code>read</code>, <code>write</code> and <code>execute</code> to <code>user</code>, <code>read</code> and <code>execute</code> to <code>group</code> and only <code>read</code> to others.</li>
</ul>
<p>This would be the same as <code>rwxr-xr--</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-165.png" alt="Calculation breakdown for adding permissions" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-ownership-using-the-chown-command">How to Change Ownership using the <code>chown</code> Command</h5>
<p>Next, we will learn how to change the ownership of a file. You can change the ownership of a file or folder using the <code>chown</code> command. In some cases, changing ownership requires <code>sudo</code> permissions.</p>
<p>Syntax of <code>chown</code>:</p>
<pre><code class="lang-bash">chown user filename
</code></pre>
<h5 id="heading-how-to-change-user-ownership-with-chown">How to change user ownership with <code>chown</code></h5>
<p>Let's transfer the ownership from user <code>zaira</code> to user <code>news</code>.</p>
<p><code>chown news mymotd.sh</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-167.png" alt="view current owner" width="600" height="400" loading="lazy"></p>
<p>Command to change ownership: <code>sudo chown news mymotd.sh</code>.</p>
<p><strong>Output:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-168.png" alt="Ownership changed" width="600" height="400" loading="lazy"></p>
<h5 id="heading-how-to-change-user-and-group-ownership-simultaneously">How to change user and group ownership simultaneously</h5>
<p>We can also use <code>chown</code> to change user and group simultaneously.</p>
<pre><code class="lang-bash">chown user:group filename
</code></pre>
<h5 id="heading-how-to-change-directory-ownership">How to change directory ownership</h5>
<p>You can change ownership recursively for contents in a directory. The example below changes the ownership of the <code>/opt/script</code> folder to allow user <code>admin</code>.</p>
<pre><code class="lang-bash">chown -R admin /opt/script
</code></pre>
<h5 id="heading-how-to-change-group-ownership">How to change group ownership</h5>
<p>In case we only need to change the group owner, we can use <code>chown</code> by preceding the group name by a colon <code>:</code></p>
<pre><code class="lang-bash">chown :admins /opt/script
</code></pre>
<h5 id="heading-how-to-switch-between-users">How to switch between users</h5>
<p>You can switch between users using the <code>su</code> command.</p>
<pre><code class="lang-bash">[user01@host ~]$ su user02
Password:
[user02@host ~]$
</code></pre>
<h5 id="heading-how-to-gain-superuser-access">How to gain superuser access</h5>
<p>The superuser or the root user has the highest level of access on a Linux system. The root user can perform any operation on the system. The root user can access all files and directories, install and remove software, and modify or override system configurations.</p>
<p>With great power comes great responsibility. If the root user is compromised, someone can gain complete control over the system. It is advised to use the root user account only when necessary.</p>
<p>If you omit the username, the <code>su</code> command switches to the root user account by default.</p>
<pre><code class="lang-bash">[user01@host ~]$ su
Password:
[root@host ~]<span class="hljs-comment">#</span>
</code></pre>
<p>Another variation of the <code>su</code> command is <code>su -</code>. The <code>su</code> command switches to the root user account but does not change the environment variables. The <code>su -</code> command switches to the root user account and changes the environment variables to those of the target user.</p>
<h5 id="heading-running-commands-with-sudo">Running commands with sudo</h5>
<p>To run commands as the <code>root</code> user without switching to the <code>root</code> user account, you can use the <code>sudo</code> command. The <code>sudo</code> command allows you to run commands with elevated privileges.</p>
<p>Running commands with <code>sudo</code> is a safer option rather than running the commands as the <code>root</code> user. This is because, only a specific set of users can be granted permission to run commands with <code>sudo</code>. This is defined in the <code>/etc/sudoers</code> file.</p>
<p>Also, <code>sudo</code> logs all commands that are run with it, providing an audit trail of who ran which commands and when.</p>
<p>In Ubuntu, you can find the audit logs here:</p>
<pre><code class="lang-bash">cat /var/<span class="hljs-built_in">log</span>/auth.log | grep sudo
</code></pre>
<p>For a user that does not have access to <code>sudo</code>, it gets flagged in logs and prompts a message like this:</p>
<pre><code class="lang-bash">user01 is not <span class="hljs-keyword">in</span> the sudoers file.  This incident will be reported.
</code></pre>
<h4 id="heading-managing-local-user-accounts">Managing local user accounts</h4>
<h5 id="heading-creating-users-from-the-command-line">Creating users from the command line</h5>
<p>The command used to add a new user is:</p>
<pre><code class="lang-bash">sudo useradd username
</code></pre>
<p>This command sets up a user's home directory and creates a private group designated by the user's username. Currently, the account lacks a valid password, preventing the user from logging in until a password is created.</p>
<h5 id="heading-modifying-existing-users">Modifying existing users</h5>
<p>The <code>usermod</code> command is used to modify existing users. Here are some of the common options used with the <code>usermod</code> command:</p>
<p>Here are some examples of the <code>usermod</code> command in Linux:</p>
<ol>
<li><p><strong>Change a user's login name:</strong></p>
<pre><code class="lang-bash"> sudo usermod -l newusername oldusername
</code></pre>
</li>
<li><p><strong>Change a user's home directory:</strong></p>
<pre><code class="lang-bash"> sudo usermod -d /new/home/directory -m username
</code></pre>
</li>
<li><p><strong>Add a user to a supplementary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -aG groupname username
</code></pre>
</li>
<li><p><strong>Change a user's shell:</strong></p>
<pre><code class="lang-bash"> sudo usermod -s /bin/bash username
</code></pre>
</li>
<li><p><strong>Lock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -L username
</code></pre>
</li>
<li><p><strong>Unlock a user's account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -U username
</code></pre>
</li>
<li><p><strong>Set an expiration date for a user account:</strong></p>
<pre><code class="lang-bash"> sudo usermod -e YYYY-MM-DD username
</code></pre>
</li>
<li><p><strong>Change a user's user ID (UID):</strong></p>
<pre><code class="lang-bash"> sudo usermod -u newUID username
</code></pre>
</li>
<li><p><strong>Change a user's primary group:</strong></p>
<pre><code class="lang-bash"> sudo usermod -g newgroup username
</code></pre>
</li>
<li><p><strong>Remove a user from a supplementary group:</strong></p>
<pre><code class="lang-bash">sudo gpasswd -d username groupname
</code></pre>
</li>
</ol>
<h5 id="heading-deleting-users">Deleting users</h5>
<p>The <code>userdel</code> command is used to delete a user account and related files from the system.</p>
<ul>
<li><p><code>sudo userdel username</code>: removes the user's details from <code>/etc/passwd</code> but keeps the user's home directory.</p>
</li>
<li><p>The <code>sudo userdel -r username</code> command removes the user's details from <code>/etc/passwd</code> and also deletes the user's home directory.</p>
</li>
</ul>
<h5 id="heading-changing-user-passwords">Changing user passwords</h5>
<p>The <code>passwd</code> command is used to change a user's password.</p>
<ul>
<li><code>sudo passwd username</code>: sets the initial password or changes the existing password of username. It is also used to change the password of the currently logged in user.</li>
</ul>
<h3 id="heading-82-connecting-to-remote-servers-via-ssh">8.2 Connecting to Remote Servers via SSH</h3>
<p>Accessing remote servers is one of the essential tasks for system administrators. You can connect to different servers or access databases through your local machine and execute commands, all using SSH.</p>
<p><strong>What is the SSH protocol?</strong></p>
<p>SSH stands for Secure Shell. It is a cryptographic network protocol that allows secure communication between two systems.</p>
<p>The default port for SSH is <code>22</code>.</p>
<p>The two participants while communicating via SSH are:</p>
<ul>
<li><p>The server: the machine that you want access to.</p>
</li>
<li><p>The client: The system that you are accessing the server from.</p>
</li>
</ul>
<p>Connection to a server follows these steps:</p>
<ol>
<li><p>Initiate Connection: The client sends a connection request to the server.</p>
</li>
<li><p>Exchange of Keys: The server sends its public key to the client. Both agree on the encryption methods to use.</p>
</li>
<li><p>Session Key Generation: The client and server use the Diffie-Hellman key exchange to create a shared session key.</p>
</li>
<li><p>Client Authentication: The client logs in to the server using a password, private key, or another method.</p>
</li>
<li><p>Secure Communication: After authentication, the client and server communicate securely with encryption.</p>
</li>
</ol>
<p><strong>How to connect to a remote server using SSH?</strong></p>
<p>The <code>ssh</code> command is a built-in utility in Linux and also the default one. It makes accessing servers quite easy and secure.</p>
<p>Here, we are talking about how the client would make a connection to the server.</p>
<p>Prior to connecting to a server, you need to have the following information:</p>
<ul>
<li><p>The IP address or the domain name of the server.</p>
</li>
<li><p>The username and password of the server.</p>
</li>
<li><p>The port number that you have access to in the server.</p>
</li>
</ul>
<p>The basic syntax of the <code>ssh</code> command is:</p>
<pre><code class="lang-bash">ssh username@server_ip
</code></pre>
<p>For example, if your username is <code>john</code> and the server IP is <code>192.168.1.10</code>, the command would be:</p>
<pre><code class="lang-bash">ssh john@192.168.1.10
</code></pre>
<p>After that, you'll be prompted to enter the secret password. Your screen will look similar to this:</p>
<pre><code class="lang-bash">john@192.168.1.10<span class="hljs-string">'s password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Jun  5 10:17:32 UTC 2024

  System load:  0.08               Processes:           122
  Usage of /:   12.3% of 19.56GB   Users logged in:     1
  Memory usage: 53%                IP address for eth0: 192.168.1.10
  Swap usage:   0%

Last login: Fri Jun  5 09:34:56 2024 from 192.168.1.2
john@hostname:~$ # start entering commands</span>
</code></pre>
<p>Now you can execute the relevant commands on the server <code>192.168.1.10</code>.</p>
<p>⚠️ The default port for ssh is <code>22</code> but it is also vulnerable, as hackers will likely attempt here first. Your server can expose another port and share the access with you. To connect to a different port, use the <code>-p</code> flag.</p>
<pre><code class="lang-bash">ssh -p port_number username@server_ip
</code></pre>
<h3 id="heading-83-advanced-log-parsing-and-analysis">8.3. Advanced Log Parsing and Analysis</h3>
<p>Log files, when configured, are generated by your system for a variety of useful reasons. They can be used to track system events, monitor system performance, and troubleshoot issues. They are specifically useful for system administrators where they can track application errors, network events, and user activity.</p>
<p>Here is an example of a log file:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sample log file</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 DEBUG Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 WARN Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 DEBUG API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
</code></pre>
<p>A log file usually contains the following columns:</p>
<ul>
<li><p>Timestamp: The date and time when the event occurred.</p>
</li>
<li><p>Log Level: The severity of the event (INFO, DEBUG, WARN, ERROR).</p>
</li>
<li><p>Component: The component of the system that generated the event (Startup, Config, Database, User, Security, Network, Email, API, Session, Shutdown).</p>
</li>
<li><p>Message: A description of the event that occurred.</p>
</li>
<li><p>Additional Information: Additional information related to the event.</p>
</li>
</ul>
<p>In real-time systems, log files tend to be thousands of lines long and are generated every second. They can be very wordy depending on the configuration. Every column in a log file is a piece of information that can be used to track down issues. This makes log files difficult to read and understand manually.</p>
<p>This is where log parsing comes in. Log parsing is the process of extracting useful information from log files. It involves breaking down the log files into smaller, more manageable pieces, and extracting the relevant information.</p>
<p>The filtered information can also be useful for creating alerts, reports, and dashboards.</p>
<p>In this section, you will explore some techniques for parsing log files in Linux.</p>
<h4 id="heading-text-extraction-using-grep">Text extraction using <code>grep</code></h4>
<p>Grep is a built-in bash utility. It stands for "global regular expression print". Grep is used to match strings in files.</p>
<p>Here are some common uses of <code>grep</code>:</p>
<ol>
<li><p><strong>Search for a specific string in a file:</strong></p>
<pre><code class="lang-bash"> grep <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command searches for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search recursively in directories:</strong></p>
<pre><code class="lang-bash"> grep -r <span class="hljs-string">"search_string"</span> /path/to/directory
</code></pre>
<p> This command searches for "<code>search_string"</code> in all files within the specified directory and its subdirectories.</p>
</li>
<li><p><strong>Ignore case while searching:</strong></p>
<pre><code class="lang-bash"> grep -i <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command performs a case-insensitive search for "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Display line numbers with matching lines:</strong></p>
<pre><code class="lang-bash"> grep -n <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command shows the line numbers along with the matching lines in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Count the number of matching lines:</strong></p>
<pre><code class="lang-bash"> grep -c <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command counts the number of lines that contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Invert match to display lines that do not match:</strong></p>
<pre><code class="lang-bash"> grep -v <span class="hljs-string">"search_string"</span> filename
</code></pre>
<p> This command displays all lines that do not contain "search_string" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Search for a whole word:</strong></p>
<pre><code class="lang-bash"> grep -w <span class="hljs-string">"word"</span> filename
</code></pre>
<p> This command searches for the whole word "word" in the file named <code>filename</code>.</p>
</li>
<li><p><strong>Use extended regular expressions:</strong></p>
<pre><code class="lang-bash"> grep -E <span class="hljs-string">"pattern"</span> filename
</code></pre>
<p> This command allows the use of extended regular expressions for more complex pattern matching in the file named <code>filename</code>.</p>
</li>
</ol>
<p><strong>💡 Tip:</strong> If there are multiple files in a folder, you can use the below command to find the list of files containing the desired strings.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># find the list of files containing the desired strings</span>
grep -l <span class="hljs-string">"String to Match"</span> /path/to/directory
</code></pre>
<h4 id="heading-text-extraction-using-sed">Text extraction using <code>sed</code></h4>
<p><code>sed</code> stands for "stream editor". It processes data stream-wise, meaning it reads data one line at a time. <code>sed</code> allows you to search for patterns and perform actions on the lines that match those patterns.</p>
<p><strong>Basic syntax of</strong><code>sed</code>:</p>
<p>The basic syntax of <code>sed</code> is as follows:</p>
<pre><code class="lang-bash">sed [options] <span class="hljs-string">'command'</span> file_name
</code></pre>
<p>Here, <code>command</code> is used to perform operations like substitution, deletion, insertion, and so on, on the text data. The filename is the name of the file you want to process.</p>
<p><code>sed</code><strong>usage:</strong></p>
<p><strong>1. Substitution:</strong></p>
<p>The <code>s</code> flag is used to replace text. The <code>old-text</code> is replaced with <code>new-text</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/old-text/new-text/'</span> filename
</code></pre>
<p>For example, to change all instances of "error" to "warning" in the log file <code>system.log</code>:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'s/error/warning/'</span> system.log
</code></pre>
<p><strong>2. Printing lines containing a specific pattern:</strong></p>
<p>Using <code>sed</code> to filter and display lines that match a specific pattern:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/pattern/p'</span> filename
</code></pre>
<p>For instance, to find all lines containing "ERROR":</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'/ERROR/p'</span> system.log
</code></pre>
<p><strong>3. Deleting lines containing a specific pattern:</strong></p>
<p>You can delete lines from the output that match a specific pattern:</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/pattern/d'</span> filename
</code></pre>
<p>For example, to remove all lines containing "DEBUG":</p>
<pre><code class="lang-bash">sed <span class="hljs-string">'/DEBUG/d'</span> system.log
</code></pre>
<p><strong>4. Extracting specific fields from a log line:</strong></p>
<p>You can use regular expressions to extract parts of lines. Suppose each log line starts with a date in the format "YYYY-MM-DD". You could extract just the date from each line:</p>
<pre><code class="lang-bash">sed -n <span class="hljs-string">'s/^\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\).*/\1/p'</span> system.log
</code></pre>
<h4 id="heading-text-parsing-with-awk">Text parsing with <code>awk</code></h4>
<p><code>awk</code> has the ability to easily split each line into fields. It's well-suited for processing structured text like log files.</p>
<p><strong>Basic syntax of</strong><code>awk</code></p>
<p>The basic syntax of <code>awk</code> is:</p>
<pre><code class="lang-bash">awk <span class="hljs-string">'pattern { action }'</span> file_name
</code></pre>
<p>Here, <code>pattern</code> is a condition that must be met for the <code>action</code> to be performed. If the pattern is omitted, the action is performed on every line.</p>
<p>In the coming examples, you'll use this log file as an example:</p>
<pre><code class="lang-bash">2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<ul>
<li><strong>Accessing columns using</strong><code>awk</code></li>
</ul>
<p>The fields in <code>awk</code> (separated by spaces by default) can be accessed using <code>$1</code>, <code>$2</code>, <code>$3</code>, and so on.</p>
<pre><code class="lang-bash">zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $1 }'</span> sample.log
<span class="hljs-comment"># output</span>
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25
2024-04-25

zaira@zaira-ThinkPad:~$ awk <span class="hljs-string">'{ print $2 }'</span> sample.log
<span class="hljs-comment"># output</span>
09:00:00
09:01:00
09:02:00
09:03:00
09:04:00
09:05:00
09:06:00
09:07:00
09:08:00
09:09:00
</code></pre>
<ul>
<li><strong>Print lines containing a specific pattern (for example, ERROR)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'/ERROR/ { print $0 }'</span> logfile.log

<span class="hljs-comment"># output</span>
2024-04-25 09:05:00 ERROR Network: Network timeout on request (ReqID: 456)
</code></pre>
<p>This prints all lines that contain "ERROR".</p>
<ul>
<li><strong>Extract the first field (Date and Time)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ print $1, $2 }'</span> logfile.log
<span class="hljs-comment"># output</span>
2024-04-25 09:00:00
2024-04-25 09:01:00
2024-04-25 09:02:00
2024-04-25 09:03:00
2024-04-25 09:04:00
2024-04-25 09:05:00
2024-04-25 09:06:00
2024-04-25 09:07:00
2024-04-25 09:08:007
2024-04-25 09:09:00
</code></pre>
<p>This will extract the first two fields from each line, which in this case would be the date and time.</p>
<ul>
<li><strong>Summarize occurrences of each log level</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ count[$3]++ } END { for (level in count) print level, count[level] }'</span> logfile.log

<span class="hljs-comment"># output</span>
 1
WARN 1
ERROR 1
DEBUG 2
INFO 6
</code></pre>
<p>The output will be a summary of the number of occurrences of each log level.</p>
<ul>
<li><strong>Filter out specific fields (for example, where the 3rd field is INFO)</strong></li>
</ul>
<pre><code class="lang-bash">awk <span class="hljs-string">'{ $3="INFO"; print }'</span> sample.log

<span class="hljs-comment"># output</span>
2024-04-25 09:00:00 INFO Startup: Application starting
2024-04-25 09:01:00 INFO Config: Configuration loaded successfully
2024-04-25 09:02:00 INFO Database: Database connection established
2024-04-25 09:03:00 INFO User: New user registered (UserID: 1001)
2024-04-25 09:04:00 INFO Security: Attempted login with incorrect credentials (UserID: 1001)
2024-04-25 09:05:00 INFO Network: Network timeout on request (ReqID: 456)
2024-04-25 09:06:00 INFO Email: Notification email sent (UserID: 1001)
2024-04-25 09:07:00 INFO API: API call with response time over threshold (Duration: 350ms)
2024-04-25 09:08:00 INFO Session: User session ended (UserID: 1001)
2024-04-25 09:09:00 INFO Shutdown: Application shutdown initiated
  INFO
</code></pre>
<p>This command will extract all lines where the 3rd field is "INFO".</p>
<p>💡 <strong>Tip:</strong> The default separator in <code>awk</code> is a space. If your log file uses a different separator, you can specify it using the <code>-F</code> option. For example, if your log file uses a colon as a separator, you can use <code>awk -F: '{ print $1 }' logfile.log</code> to extract the first field.</p>
<h4 id="heading-parsing-log-files-with-cut">Parsing log files with <code>cut</code></h4>
<p>The <code>cut</code> command is a simple yet powerful command used to extract sections of text from each line of input. As log files are structured and each field is delimited by a specific character, such as a space, tab, or a custom delimiter, <code>cut</code> does a very good job of extracting those specific fields.</p>
<p>The basic syntax of the cut command is:</p>
<pre><code class="lang-bash">cut [options] [file]
</code></pre>
<p>Some commonly used options for the cut command:</p>
<ul>
<li><p><code>-d</code> : Specifies a delimiter used as the field separator.</p>
</li>
<li><p><code>-f</code> : Selects the fields to be displayed.</p>
</li>
<li><p><code>-c</code> : Specifies character positions.</p>
</li>
</ul>
<p>For example, the command below would extract the first field (separated by a space) from each line of the log file:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1 logfile.log
</code></pre>
<p><strong>Examples of using</strong><code>cut</code><strong>for log parsing</strong></p>
<p>Assume you have a log file structured as follows, where fields are space-separated:</p>
<pre><code class="lang-bash">2024-04-25 08:23:01 INFO 192.168.1.10 User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 08:24:15 WARNING 192.168.1.10 Disk usage exceeds 90%.
2024-04-25 08:25:02 ERROR 10.0.0.5 Connection timed out.
...
</code></pre>
<p><code>cut</code> can be used in the following ways:</p>
<ol>
<li><strong>Extracting the time from each log entry</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 2 system.log

<span class="hljs-comment"># Output</span>
08:23:01
08:24:15
08:25:02
...
</code></pre>
<p>This command uses a space as a delimiter and selects the second field, which is the time component of each log entry.</p>
<ol start="2">
<li><strong>Extracting the IP addresses from the logs</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 4 system.log

<span class="hljs-comment"># Output</span>
192.168.1.10
192.168.1.10
10.0.0.5
</code></pre>
<p>This command extracts the fourth field, which is the IP address from each log entry.</p>
<ol start="3">
<li><strong>Extracting log levels (INFO, WARNING, ERROR)</strong>:</li>
</ol>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 3 system.log

<span class="hljs-comment"># Output</span>
INFO
WARNING
ERROR
</code></pre>
<p>This extracts the third field which contains the log level.</p>
<ol start="4">
<li><strong>Combining</strong><code>cut</code><strong>with other commands:</strong></li>
</ol>
<p>The output of other commands can be piped to the <code>cut</code> command. Let's say you want to filter logs before cutting. You can use <code>grep</code> to extract lines containing "ERROR" and then use <code>cut</code> to get specific information from those lines:</p>
<pre><code class="lang-bash">grep <span class="hljs-string">"ERROR"</span> system.log | cut -d <span class="hljs-string">' '</span> -f 1,2 

<span class="hljs-comment"># Output</span>
2024-04-25 08:25:02
</code></pre>
<p>This command first filters lines that include "ERROR", then extracts the date and time from these lines.</p>
<ol start="5">
<li><strong>Extracting multiple fields</strong>:</li>
</ol>
<p>It is possible to extract multiple fields at once by specifying a range or a comma-separated list of fields:</p>
<pre><code class="lang-bash">cut -d <span class="hljs-string">' '</span> -f 1,2,3 system.log` 

<span class="hljs-comment"># Output</span>
2024-04-25 08:23:01 INFO
2024-04-25 08:24:15 WARNING
2024-04-25 08:25:02 ERROR
...
</code></pre>
<p>The above command extracts the first three fields from each log entry that are date, time, and log level.</p>
<h4 id="heading-parsing-log-files-with-sort-and-uniq">Parsing log files with <code>sort</code> and <code>uniq</code></h4>
<p>Sorting and removing duplicates are common operations when working with log files. The <code>sort</code> and <code>uniq</code> commands are powerful commands used to sort and remove duplicates from the input, respectively.</p>
<p><strong>Basic syntax of sort</strong></p>
<p>The <code>sort</code> command organizes lines of text alphabetically or numerically.</p>
<pre><code class="lang-bash">sort [options] [file]
</code></pre>
<p>Some key options for the sort command:</p>
<ul>
<li><p><code>-n</code>: Sorts the file assuming the contents are numerical.</p>
</li>
<li><p><code>-r</code>: Reverses the order of sort.</p>
</li>
<li><p><code>-k</code>: Specifies a key or column number to sort on.</p>
</li>
<li><p><code>-u</code>: Sorts and removes duplicate lines.</p>
</li>
</ul>
<p>The <code>uniq</code> command is used to filter or count and report repeated lines in a file.</p>
<p>The syntax of <code>uniq</code> is:</p>
<pre><code class="lang-bash">uniq [options] [input_file] [output_file]
</code></pre>
<p>Some key options for the <code>uniq</code> command are:</p>
<ul>
<li><p><code>-c</code>: Prefixes lines by the number of occurrences.</p>
</li>
<li><p><code>-d</code>: Only prints duplicate lines.</p>
</li>
<li><p><code>-u</code>: Only prints unique lines.</p>
</li>
</ul>
<h4 id="heading-examples-of-using-sort-and-uniq-together-for-log-parsing">Examples of using <code>sort</code> and <code>uniq</code> together for log parsing</h4>
<p>Let's assume the following example log entries for these demonstrations:</p>
<pre><code class="lang-bash">2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-26 ERROR Connection timed out.
</code></pre>
<ol>
<li><strong>Sorting log entries by date</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This sorts the log entries alphabetically, which effectively sorts them by date if the date is the first field.</p>
<ol>
<li><strong>Sorting and removing duplicates</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq

<span class="hljs-comment"># Output</span>
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 ERROR Connection timed out.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command sorts the log file and pipes it to <code>uniq</code>, removing duplicate lines.</p>
<ol>
<li><strong>Counting occurrences of each line</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -c

<span class="hljs-comment"># Output</span>
2 2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
1 2024-04-25 WARNING Disk usage exceeds 90%.
2 2024-04-26 ERROR Connection timed out.
1 2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>Sorts the log entries and then counts each unique line. According to the output, the line <code>'2024-04-25 INFO User logged in successfully.'</code> appeared 2 times in the file.</p>
<ol>
<li><strong>Identifying unique log entries</strong>:</li>
</ol>
<pre><code class="lang-bash">sort system.log | uniq -u

<span class="hljs-comment"># Output</span>

2024-04-25 WARNING Disk usage exceeds 90%.
2024-04-26 INFO Scheduled maintenance.
</code></pre>
<p>This command shows lines that are unique.</p>
<ol start="2">
<li><strong>Sorting by log level</strong>:</li>
</ol>
<pre><code class="lang-bash">sort -k2 system.log

<span class="hljs-comment"># Output</span>
2024-04-26 ERROR Connection timed out.
2024-04-26 ERROR Connection timed out.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-25 INFO User logged <span class="hljs-keyword">in</span> successfully.
2024-04-26 INFO Scheduled maintenance.
2024-04-25 WARNING Disk usage exceeds 90%.
</code></pre>
<p>Sorts the entries based on the second field, which is the log level.</p>
<h3 id="heading-84-managing-linux-processes-via-command-line">8.4. Managing Linux Processes via Command Line</h3>
<p>A process is a running instance of a program. A process consists of:</p>
<ul>
<li><p>An address space of the allocated memory.</p>
</li>
<li><p>Process states.</p>
</li>
<li><p>Properties such as ownership, security attributes, and resource usage.</p>
</li>
</ul>
<p>A process also has an environment that consists of:</p>
<ul>
<li><p>Local and global variables</p>
</li>
<li><p>The current scheduling context</p>
</li>
<li><p>Allocated system resources, such as network ports or file descriptors.</p>
</li>
</ul>
<p>When you run the <code>ls -l</code> command, the operating system creates a new process to execute the command. The process has an ID, a state, and runs until the command completes.</p>
<h4 id="heading-understanding-process-creation-and-lifecycle">Understanding process creation and lifecycle</h4>
<p>In Ubuntu, all processes originate from the initial system process called <code>systemd</code>, which is the first process started by the kernel during boot.</p>
<p>The <code>systemd</code> process has a process ID (PID) of <code>1</code> and is responsible for initializing the system, starting and managing other processes, and handling system services. All other processes on the system are descendants of <code>systemd</code>.</p>
<p>A parent process duplicates its own address space (fork) to create a new (child) process structure. Each new process is assigned a unique process ID (PID) for tracking and security purposes. The PID and the parent's process ID (PPID) are part of the new process environment. Any process can create a child process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584071059/f24fac4b-18f3-4a39-8659-93d32c533256.png" alt="Process and its initialization to parent and child" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Through the fork routine, a child process inherits security identities, previous and current file descriptors, port and resource privileges, environment variables, and program code. A child process may then execute its own program code.</p>
<p>Typically, a parent process sleeps while the child process runs, setting a request (wait) to be notified when the child completes.</p>
<p>Upon exiting, the child process has already closed or discarded its resources and environment. The only remaining resource, known as a zombie, is an entry in the process table. The parent, signaled awake when the child exits, cleans the process table of the child's entry, thus freeing the last resource of the child process. The parent process then continues executing its own program code.</p>
<h4 id="heading-understanding-process-states">Understanding process states</h4>
<p>Processes in Linux assume different states during their lifecycle. The state of a process indicates what the process is currently doing and how it is interacting with the system. The processes transition between states based on their execution status and the system's scheduling algorithm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719584116150/3054dfe2-c42c-4d62-9e12-e3aec479d53a.png" alt="Linux process states and transitions" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The processes in a Linux system can be in one of the following states:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>(new)</strong></td><td>Initial state when a process is created via a fork system call.</td></tr>
<tr>
<td><strong>Runnable (ready) (R)</strong></td><td>Process is ready to run and waiting to be scheduled on a CPU.</td></tr>
<tr>
<td><strong>Running (user) (R)</strong></td><td>Process is executing in user mode, running user applications.</td></tr>
<tr>
<td><strong>Running (kernel) (R)</strong></td><td>Process is executing in kernel mode, handling system calls or hardware interrupts.</td></tr>
<tr>
<td><strong>Sleeping (S)</strong></td><td>Process is waiting for an event (for example, I/O operation) to complete and can be easily awakened.</td></tr>
<tr>
<td><strong>Sleeping (uninterruptible) (D)</strong></td><td>Process is in an uninterruptible sleep state, waiting for a specific condition (usually I/O) to complete, and cannot be interrupted by signals.</td></tr>
<tr>
<td><strong>Sleeping (disk sleep) (K)</strong></td><td>Process is waiting for disk I/O operations to complete.</td></tr>
<tr>
<td><strong>Sleeping (idle) (I)</strong></td><td>Process is idle, not doing any work, and waiting for an event to occur.</td></tr>
<tr>
<td><strong>Stopped (T)</strong></td><td>Process execution has been stopped, typically by a signal, and can be resumed later.</td></tr>
<tr>
<td><strong>Zombie (Z)</strong></td><td>Process has completed execution but still has an entry in the process table, waiting for its parent to read its exit status.</td></tr>
</tbody>
</table>
</div><p>The processes transition between these states in the following ways:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Transition</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Fork</strong></td><td>Creates a new process from a parent process, transitioning from (new) to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Schedule</strong></td><td>Scheduler selects a runnable process, transitioning it to Running (user) or Running (kernel) state.</td></tr>
<tr>
<td><strong>Run</strong></td><td>Process transitions from Runnable (ready) (R) to Running (kernel) (R) when scheduled for execution.</td></tr>
<tr>
<td><strong>Preempt or Reschedule</strong></td><td>Process can be preempted or rescheduled, moving it back to Runnable (ready) (R) state.</td></tr>
<tr>
<td><strong>Syscall</strong></td><td>Process makes a system call, transitioning from Running (user) (R) to Running (kernel) (R).</td></tr>
<tr>
<td><strong>Return</strong></td><td>Process completes a system call and returns to Running (user) (R).</td></tr>
<tr>
<td><strong>Wait</strong></td><td>Process waits for an event, transitioning from Running (kernel) (R) to one of the Sleeping states (S, D, K, or I).</td></tr>
<tr>
<td><strong>Event or Signal</strong></td><td>Process is awakened by an event or signal, moving it from a Sleeping state back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Suspend</strong></td><td>Process is suspended, transitioning from Running (kernel) or Runnable (ready) to Stopped (T).</td></tr>
<tr>
<td><strong>Resume</strong></td><td>Process is resumed, moving from Stopped (T) back to Runnable (ready) (R).</td></tr>
<tr>
<td><strong>Exit</strong></td><td>Process terminates, transitioning from Running (user) or Running (kernel) to Zombie (Z).</td></tr>
<tr>
<td><strong>Reap</strong></td><td>Parent process reads the exit status of the zombie process, removing it from the process table.</td></tr>
</tbody>
</table>
</div><h4 id="heading-how-to-view-processes">How to view processes</h4>
<p>You can use the <code>ps</code> command along with a combination of options to view processes on a Linux system. The <code>ps</code> command is used to display information about a selection of active processes. For example, <code>ps aux</code> displays all processes running on the system.</p>
<pre><code class="lang-bash">zaira@zaira:~$ ps aux
<span class="hljs-comment"># Output</span>
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0 168140 11352 ?        Ss   May21   0:18 /sbin/init splash
root           2  0.0  0.0      0     0 ?        S    May21   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [rcu_par_gp]
root           5  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [slub_flushwq]
root           6  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [netns]
root          11  0.0  0.0      0     0 ?        I&lt;   May21   0:00 [mm_percpu_wq]
root          12  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_kthread]
root          13  0.0  0.0      0     0 ?        I    May21   0:00 [rcu_tasks_rude_kthread]
*... output truncated ....*
</code></pre>
<p>The output above shows a snapshot of the currently running processes on the system. Each row represents a process with the following columns:</p>
<ol>
<li><p><code>USER</code>: The user who owns the process.</p>
</li>
<li><p><code>PID</code>: The process ID.</p>
</li>
<li><p><code>%CPU</code>: The CPU usage of the process.</p>
</li>
<li><p><code>%MEM</code>: The memory usage of the process.</p>
</li>
<li><p><code>VSZ</code>: The virtual memory size of the process.</p>
</li>
<li><p><code>RSS</code>: The resident set size, that is the non-swapped physical memory that a task has used.</p>
</li>
<li><p><code>TTY</code>: The controlling terminal of the process. A <code>?</code> indicates no controlling terminal.</p>
</li>
<li><p><code>STAT</code>: The process state.</p>
<ul>
<li><p><code>R</code>: Running</p>
</li>
<li><p><code>I</code> or <code>S</code>: Interruptible sleep (waiting for an event to complete)</p>
</li>
<li><p><code>D</code>: Uninterruptible sleep (usually IO)</p>
</li>
<li><p><code>T</code>: Stopped (either by a job control signal or because it is being traced)</p>
</li>
<li><p><code>Z</code>: Zombie (terminated but not reaped by its parent)</p>
</li>
<li><p><code>Ss</code>: Session leader. This is a process that has started a session, and it is a leader of a group of processes and can control terminal signals. The first <code>S</code> indicates the sleeping state, and the second <code>s</code> indicates it is a session leader.</p>
</li>
</ul>
</li>
<li><p><code>START</code>: The starting time or date of the process.</p>
</li>
<li><p><code>TIME</code>: The cumulative CPU time.</p>
</li>
<li><p><code>COMMAND</code>: The command that started the process.</p>
</li>
</ol>
<h4 id="heading-background-and-foreground-processes">Background and foreground processes</h4>
<p>In this section, you'll learn how you can control jobs by running them in the background or foreground.</p>
<p>A job is a process that is started by a shell. When you run a command in the terminal, it is considered a job. A job can run in the foreground or the background.</p>
<p>To demonstrate control, you'll first create 3 processes and then run them in the background. After that, you'll list the processes and alternate them between the foreground and background. You'll see how to put them to sleep or exit completely.</p>
<ol>
<li>Create Three Processes</li>
</ol>
<p>Open a terminal and start three long-running processes. Use the <code>sleep</code> command, that keeps the process running for a specified number of seconds.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># run sleep command for 300, 400, and 500 seconds</span>
sleep 300 &amp;
sleep 400 &amp;
sleep 500 &amp;
</code></pre>
<p>The <code>&amp;</code> at the end of each command moves the process to the background.</p>
<ol start="2">
<li>Display Background Jobs</li>
</ol>
<p>Use the <code>jobs</code> command to display the list of background jobs.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
</code></pre>
<p>The output should look something like this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<ol start="3">
<li>Bring a Background Job to the Foreground</li>
</ol>
<p>To bring a background job to the foreground, use the <code>fg</code> command followed by the job number. For example, to bring the first job (<code>sleep 300</code>) to the foreground:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">fg</span> %1
</code></pre>
<p>This will bring job <code>1</code> to the foreground.</p>
<ol start="4">
<li>Move the Foreground Job Back to the Background</li>
</ol>
<p>While the job is running in the foreground, you can suspend it and move it back to the background by pressing <code>Ctrl+Z</code> to suspend the job.</p>
<p>A suspended job will look like this:</p>
<pre><code class="lang-bash">zaira@zaira:~$ <span class="hljs-built_in">fg</span> %1
sleep 300

^Z
[1]+  Stopped                 sleep 300

zaira@zaira:~$ <span class="hljs-built_in">jobs</span>
<span class="hljs-comment"># suspended job </span>
[1]+  Stopped                 sleep 300
[2]   Running                 sleep 400 &amp;
[3]-  Running                 sleep 500 &amp;
</code></pre>
<p>Now use the <code>bg</code> command to resume the job with ID 1 in the background.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Press Ctrl+Z to suspend the foreground job</span>
<span class="hljs-comment"># Then, resume it in the background</span>
<span class="hljs-built_in">bg</span> %1
</code></pre>
<ol start="5">
<li>Display the jobs again</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">jobs</span>
[1]   Running                 sleep 300 &amp;
[2]-  Running                 sleep 400 &amp;
[3]+  Running                 sleep 500 &amp;
</code></pre>
<p>In this exercise, you:</p>
<ul>
<li><p>Started three background processes using sleep commands.</p>
</li>
<li><p>Used jobs to display the list of background jobs.</p>
</li>
<li><p>Brought a job to the foreground with <code>fg %job_number</code>.</p>
</li>
<li><p>Suspended the job with <code>Ctrl+Z</code> and moved it back to the background with <code>bg %job_number</code>.</p>
</li>
<li><p>Used jobs again to verify the status of the background jobs.</p>
</li>
</ul>
<p>Now you know how to control jobs.</p>
<h4 id="heading-killing-processes">Killing processes</h4>
<p>It is possible to terminate an unresponsive or unwanted process using the <code>kill</code> command. The <code>kill</code> command sends a signal to a process ID, asking it to terminate.</p>
<p>A number of options are available with the <code>kill</code> command.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Options available with kill</span>

<span class="hljs-built_in">kill</span> -l
 1) SIGHUP     2) SIGINT     3) SIGQUIT     4) SIGILL     5) SIGTRAP
 6) SIGABRT     7) SIGBUS     8) SIGFPE     9) SIGKILL    10) SIGUSR1
11) SIGSEGV    12) SIGUSR2    13) SIGPIPE    14) SIGALRM    15) SIGTERM
16) SIGSTKFLT    17) SIGCHLD    18) SIGCONT    19) SIGSTOP    20) SIGTSTP
21) SIGTTIN    22) SIGTTOU    23) SIGURG    24) 
...terminated
</code></pre>
<p>Here are some examples of the <code>kill</code> command in Linux:</p>
<ol>
<li><p><strong>Kill a process by PID (Process ID):</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> 1234
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to the process with PID 1234, requesting it to terminate.</p>
</li>
<li><p><strong>Kill a process by name:</strong></p>
<pre><code class="lang-bash"> pkill process_name
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes with the specified name.</p>
</li>
<li><p><strong>Forcefully kill a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -9 1234
</code></pre>
<p> This command sends the <code>SIGKILL</code> signal to the process with PID 1234, forcefully terminating it.</p>
</li>
<li><p><strong>Send a specific signal to a process:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">kill</span> -s SIGSTOP 1234
</code></pre>
<p> This command sends the <code>SIGSTOP</code> signal to the process with PID 1234, stopping it.</p>
</li>
<li><p><strong>Kill all processes owned by a specific user:</strong></p>
<pre><code class="lang-bash"> pkill -u username
</code></pre>
<p> This command sends the default <code>SIGTERM</code> signal to all processes owned by the specified user.</p>
</li>
</ol>
<p>These examples demonstrate various ways to use the <code>kill</code> command to manage processes in a Linux environment.</p>
<p>Here is the information about the <code>kill</code> command options and signals in a tabular form: This table summarizes the most common <code>kill</code> command options and signals used in Linux for managing processes.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command / Option</td><td>Signal</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>kill &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Requests the process to terminate gracefully (default signal).</td></tr>
<tr>
<td><code>kill -9 &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -SIGKILL &lt;pid&gt;</code></td><td><code>SIGKILL</code></td><td>Forces the process to terminate immediately without cleanup.</td></tr>
<tr>
<td><code>kill -15 &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -SIGTERM &lt;pid&gt;</code></td><td><code>SIGTERM</code></td><td>Explicitly sends the <code>SIGTERM</code> signal to request graceful termination.</td></tr>
<tr>
<td><code>kill -1 &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -SIGHUP &lt;pid&gt;</code></td><td><code>SIGHUP</code></td><td>Traditionally means "hang up"; can be used to reload configuration files.</td></tr>
<tr>
<td><code>kill -2 &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -SIGINT &lt;pid&gt;</code></td><td><code>SIGINT</code></td><td>Requests the process to terminate (same as pressing <code>Ctrl+C</code> in terminal).</td></tr>
<tr>
<td><code>kill -3 &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -SIGQUIT &lt;pid&gt;</code></td><td><code>SIGQUIT</code></td><td>Causes the process to terminate and produce a core dump for debugging.</td></tr>
<tr>
<td><code>kill -19 &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -SIGSTOP &lt;pid&gt;</code></td><td><code>SIGSTOP</code></td><td>Pauses the process.</td></tr>
<tr>
<td><code>kill -18 &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>kill -SIGCONT &lt;pid&gt;</code></td><td><code>SIGCONT</code></td><td>Resumes a paused process.</td></tr>
<tr>
<td><code>killall &lt;name&gt;</code></td><td>Varies</td><td>Sends a signal to all processes with the given name.</td></tr>
<tr>
<td><code>killall -9 &lt;name&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes with the given name.</td></tr>
<tr>
<td><code>pkill &lt;pattern&gt;</code></td><td>Varies</td><td>Sends a signal to processes based on a pattern match.</td></tr>
<tr>
<td><code>pkill -9 &lt;pattern&gt;</code></td><td><code>SIGKILL</code></td><td>Force kills all processes matching the pattern.</td></tr>
<tr>
<td><code>xkill</code></td><td><code>SIGKILL</code></td><td>Graphical utility that allows clicking on a window to kill the corresponding process.</td></tr>
</tbody>
</table>
</div><h3 id="heading-85-standard-input-and-output-streams-in-linux">8.5. Standard Input and Output Streams in Linux</h3>
<p>Reading an input and writing an output is an essential part of understanding the command line and shell scripting. In Linux, every process has three default streams:</p>
<ol>
<li><p>Standard Input (<code>stdin</code>): This stream is used for input, typically from the keyboard. When a program reads from <code>stdin</code>, it receives data entered by the user or redirected from a file. A file descriptor is a unique identifier that the operating system assigns to an open file in order to keep track of open files.</p>
<p> The file descriptor for <code>stdin</code> is <code>0</code>.</p>
</li>
<li><p>Standard Output (<code>stdout</code>): This is the default output stream where a process writes its output. By default, the standard output is the terminal. The output can also be redirected to a file or another program. The file descriptor for <code>stdout</code> is <code>1</code>.</p>
</li>
<li><p>Standard Error (<code>stderr</code>): This is the default error stream where a process writes its error messages. By default, the standard error is the terminal, allowing error messages to be seen even if <code>stdout</code> is redirected. The file descriptor for <code>stderr</code> is <code>2</code>.</p>
</li>
</ol>
<h4 id="heading-redirection-and-pipelines">Redirection and Pipelines</h4>
<p><strong>Redirection:</strong> You can redirect the error and output streams to files or other commands. For example:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirecting stdout to a file</span>
ls &gt; output.txt

<span class="hljs-comment"># Redirecting stderr to a file</span>
ls non_existent_directory 2&gt; error.txt

<span class="hljs-comment"># Redirecting both stdout and stderr to a file</span>
ls non_existent_directory &gt; all_output.txt 2&gt;&amp;1
</code></pre>
<p>In the last command,</p>
<ul>
<li><p><code>ls non_existent_directory</code>: lists the contents of a directory named non_existent_directory. Since this directory does not exist, <code>ls</code> will generate an error message.</p>
</li>
<li><p><code>&gt; all_output.txt</code>: The <code>&gt;</code> operator redirects the standard output (<code>stdout</code>) of the <code>ls</code> command to the file <code>all_output.txt</code>. If the file does not exist, it will be created. If it does exist, its contents will be overwritten.</p>
</li>
<li><p><code>2&gt;&amp;1:</code>: Here, <code>2</code> represents the file descriptor for standard error (<code>stderr</code>). <code>&amp;1</code> represents the file descriptor for standard output (<code>stdout</code>). The <code>&amp;</code> character is used to specify that <code>1</code> is not the file name but a file descriptor.</p>
</li>
</ul>
<p>So, <code>2&gt;&amp;1</code> means "redirect stderr (2) to wherever stdout (1) is currently going," which in this case is the file <code>all_output.txt</code>. Therefore, both the output (if there were any) and the error message from <code>ls</code> will be written to <code>all_output.txt</code>.</p>
<p><strong>Pipelines:</strong></p>
<p>You can use pipes (<code>|</code>) to pass the output of one command as the input to another:</p>
<pre><code class="lang-bash">ls | grep image
<span class="hljs-comment"># Output</span>
image-10.png
image-11.png
image-12.png
image-13.png
... Output truncated ...
</code></pre>
<h3 id="heading-86-automation-in-linux-automate-tasks-with-cron-jobs">8.6 Automation in Linux – Automate Tasks with Cron Jobs</h3>
<p>Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or other specific time basis. The automation capabilities provided by cron play a crucial role in Linux system administration.</p>
<p>The <code>crond</code> daemon (a type of computer program that runs in the background) enables cron functionality. The cron reads the <strong>crontab</strong> (cron tables) for running predefined scripts.</p>
<p>By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.</p>
<p><strong>What are cron jobs in Linux?</strong></p>
<p>Any task that you schedule through crons is called a cron job.</p>
<p>Now, let's see how cron jobs work.</p>
<h4 id="heading-how-to-control-access-to-crons">How to control access to crons</h4>
<p>In order to use cron jobs, an admin needs to allow cron jobs to be added for users in the <code>/etc/cron.allow</code> file.</p>
<p>If you get a prompt like this, it means you don't have permission to use cron.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-51.png" alt="Cron job addition denied for user John." width="600" height="400" loading="lazy"></p>
<p>To allow John to use crons, include his name in <code>/etc/cron.allow</code>. Create the file if it doesn't exist. This will allow John to create and edit cron jobs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-52.png" alt="Allowing John in file cron.allow" width="600" height="400" loading="lazy"></p>
<p>Users can also be denied access to cron job access by entering their usernames in the file <code>/etc/cron.d/cron.deny</code>.</p>
<h4 id="heading-how-to-add-cron-jobs-in-linux">How to add cron jobs in Linux</h4>
<p>First, to use cron jobs, you'll need to check the status of the cron service. If cron is not installed, you can easily download it through the package manager. Just use this to check:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Check cron service on Linux system</span>
sudo systemctl status cron.service
</code></pre>
<h4 id="heading-cron-job-syntax">Cron job syntax</h4>
<p>Crontabs use the following flags for adding and listing cron jobs:</p>
<ul>
<li><p><code>crontab -e</code>: edits crontab entries to add, delete, or edit cron jobs.</p>
</li>
<li><p><code>crontab -l</code>: list all the cron jobs for the current user.</p>
</li>
<li><p><code>crontab -u username -l</code>: list another user's crons.</p>
</li>
<li><p><code>crontab -u username -e</code>: edit another user's crons.</p>
</li>
</ul>
<p>When you list crons and they exist, you'll see something like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Cron job example</span>
* * * * * sh /path/to/script.sh
</code></pre>
<p>In the above example,</p>
<ul>
<li><code>*</code> represents minute(s) hour(s) day(s) month(s) weekday(s), respectively. See details of these values below:</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td><strong>VALUE</strong></td><td><strong>DESCRIPTION</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Minutes</td><td>0-59</td><td>Command will be executed at the specific minute.</td></tr>
<tr>
<td>Hours</td><td>0-23</td><td>Command will be executed at the specific hour.</td></tr>
<tr>
<td>Days</td><td>1-31</td><td>Commands will be executed in these days of the months.</td></tr>
<tr>
<td>Months</td><td>1-12</td><td>The month in which tasks need to be executed.</td></tr>
<tr>
<td>Weekdays</td><td>0-6</td><td>Days of the week where commands will run. Here, 0 is Sunday.</td></tr>
</tbody>
</table>
</div><ul>
<li><p><code>sh</code> represents that the script is a bash script and should be run from <code>/bin/bash</code>.</p>
</li>
<li><p><code>/path/to/script.sh</code> specifies the path to the script.</p>
</li>
</ul>
<p>Below is a summary of the cron job syntax:</p>
<pre><code class="lang-markdown"><span class="hljs-bullet">*</span>   <span class="hljs-emphasis">*   *</span>   <span class="hljs-emphasis">*   *</span>  sh /path/to/script/script.sh
|   |   |   |   |              |
|   |   |   |   |      Command or Script to Execute        
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |
|   |   |   | Day of the Week(0-6)
|   |   |   |
|   |   | Month of the Year(1-12)
|   |   |
|   | Day of the Month(1-31)  
|   |
| Hour(0-23)  
|
Min(0-59)
</code></pre>
<h4 id="heading-cron-job-examples">Cron job examples</h4>
<p>Below are some examples of scheduling cron jobs.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>SCHEDULE</strong></td><td><strong>SCHEDULED VALUE</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>5 0 * 8 *</code></td><td>At 00:05 in August.</td></tr>
<tr>
<td><code>5 4 * * 6</code></td><td>At 04:05 on Saturday.</td></tr>
<tr>
<td><code>0 22 * * 1-5</code></td><td>At 22:00 on every day-of-week from Monday through Friday.</td></tr>
</tbody>
</table>
</div><p>It's okay if you are unable to grasp this all at once. You can practice and generate cron schedules with the <a target="_blank" href="https://crontab.guru/">crontab guru</a> website.</p>
<h4 id="heading-how-to-set-up-a-cron-job">How to set up a cron job</h4>
<p>In this section, we will look at an example of how to schedule a simple script with a cron job.</p>
<ol>
<li>Create a script called <code>date-script.sh</code> which prints the system date and time and appends it to a file. The script is shown below:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">echo</span> `date` &gt;&gt; date-out.txt
</code></pre>
<p>2.  Make the script executable by giving it execution rights.</p>
<pre><code class="lang-bash">chmod 775 date-script.sh
</code></pre>
<p>3.  Add the script in the crontab using <code>crontab -e</code>.</p>
<p>Here, we have scheduled it to run per minute.</p>
<pre><code class="lang-bash">*/1 * * * * /bin/sh /root/date-script.sh
</code></pre>
<p>4.  Check the output of the file <code>date-out.txt</code>. According to the script, the system date should be printed to this file every minute.</p>
<pre><code class="lang-bash">cat date-out.txt
<span class="hljs-comment"># output</span>
Wed 26 Jun 16:59:33 PKT 2024
Wed 26 Jun 17:00:01 PKT 2024
Wed 26 Jun 17:01:01 PKT 2024
Wed 26 Jun 17:02:01 PKT 2024
Wed 26 Jun 17:03:01 PKT 2024
Wed 26 Jun 17:04:01 PKT 2024
Wed 26 Jun 17:05:01 PKT 2024
Wed 26 Jun 17:06:01 PKT 2024
Wed 26 Jun 17:07:01 PKT 2024
</code></pre>
<p><strong>How to troubleshoot crons</strong></p>
<p>Crons are really helpful, but they might not always work as intended. Fortunately, there are some effective methods you can use to troubleshoot them.</p>
<p><strong>1. Check the schedule.</strong></p>
<p>First, you can try verifying the schedule that's set for the cron. You can do that with the syntax you saw in the above sections.</p>
<p><strong>2</strong>. <strong>Check cron logs.</strong></p>
<p>First, you need to check if the cron has run at the intended time or not. In Ubuntu, you can verify this from the cron logs located at <code>/var/log/syslog</code>.</p>
<p>If there is an entry in these logs at the correct time, it means the cron has run according to the schedule you set.</p>
<p>Below are the logs of our cron job example. Note the first column which shows the timestamp. The path of the script is also mentioned at the end of the line. Line #1, 3, and 5 show that the script ran as intended.</p>
<pre><code class="lang-bash">1 Jun 26 17:02:01 zaira-ThinkPad CRON[27834]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
2 Jun 26 17:02:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
3 Jun 26 17:03:01 zaira-ThinkPad CRON[28255]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
4 Jun 26 17:03:02 zaira-ThinkPad systemd[2094]: Started Tracker metadata extractor.
5 Jun 26 17:04:01 zaira-ThinkPad CRON[28538]: (zaira) CMD (/bin/sh /home/zaira/date-script.sh)
</code></pre>
<p><strong>3. Redirect cron output to a file.</strong></p>
<p>You can redirect a cron's output to a file and check the file for any possible errors.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Redirect cron output to a file</span>
* * * * * sh /path/to/script.sh &amp;&gt; log_file.log
</code></pre>
<h3 id="heading-87-linux-networking-basics">8.7. Linux Networking Basics</h3>
<p>Linux offers a number of commands to view network related information. In this section we will briefly discuss some of the commands.</p>
<h4 id="heading-view-network-interfaces-with-ifconfig">View network interfaces with <code>ifconfig</code></h4>
<p>The <code>ifconfig</code> command gives information about network interfaces. Here is an example output:</p>
<pre><code class="lang-bash">ifconfig

<span class="hljs-comment"># Output</span>
eth0: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt;  mtu 1500
        inet 192.168.1.100  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::a00:27ff:fe4e:66a1  prefixlen 64  scopeid 0x20&lt;link&gt;
        ether 08:00:27:4e:66:a1  txqueuelen 1000  (Ethernet)
        RX packets 1024  bytes 654321 (654.3 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 512  bytes 123456 (123.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73&lt;UP,LOOPBACK,RUNNING&gt;  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10&lt;host&gt;
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 256  bytes 20480 (20.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 256  bytes 20480 (20.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code></pre>
<p>The output of the <code>ifconfig</code> command shows the network interfaces configured on the system, along with details such as IP addresses, MAC addresses, packet statistics, and more.</p>
<p>These interfaces can be physical or virtual devices.</p>
<p>To extract IPv4 and IPv6 addresses, you can use <code>ip -4 addr</code> and <code>ip -6 addr</code>, respectively.</p>
<p><strong>View network activity with</strong><code>netstat</code></p>
<p>The <code>netstat</code> command shows network activity and stats by giving the following information:</p>
<p>Here are some examples of using the <code>netstat</code> command in the command line:</p>
<ol>
<li><p><strong>Display all listening and non-listening sockets:</strong></p>
<pre><code class="lang-bash"> netstat -a
</code></pre>
</li>
<li><p><strong>Show only listening ports:</strong></p>
<pre><code class="lang-bash"> netstat -l
</code></pre>
</li>
<li><p><strong>Display network statistics:</strong></p>
<pre><code class="lang-bash"> netstat -s
</code></pre>
</li>
<li><p><strong>Show routing table:</strong></p>
<pre><code class="lang-bash"> netstat -r
</code></pre>
</li>
<li><p><strong>Display TCP connections:</strong></p>
<pre><code class="lang-bash"> netstat -t
</code></pre>
</li>
<li><p><strong>Display UDP connections:</strong></p>
<pre><code class="lang-bash"> netstat -u
</code></pre>
</li>
<li><p><strong>Show network interfaces:</strong></p>
<pre><code class="lang-bash"> netstat -i
</code></pre>
</li>
<li><p><strong>Display PID and program names for connections:</strong></p>
<pre><code class="lang-bash"> netstat -p
</code></pre>
</li>
<li><p><strong>Show statistics for a specific protocol (for example, TCP):</strong></p>
<pre><code class="lang-bash"> netstat -st
</code></pre>
</li>
<li><p><strong>Display extended information:</strong></p>
<pre><code class="lang-bash">netstat -e
</code></pre>
</li>
</ol>
<h4 id="heading-check-network-connectivity-between-two-devices-using-ping">Check network connectivity between two devices using <code>ping</code></h4>
<p><code>ping</code> is used to test network connectivity between two devices. It sends ICMP packets to the target device and waits for a response.</p>
<pre><code class="lang-bash">ping google.com
</code></pre>
<p><code>ping</code> tests if you get a response back without getting a timeout.</p>
<pre><code class="lang-bash">ping google.com
PING google.com (142.250.181.46) 56(84) bytes of data.
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=1 ttl=60 time=78.3 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=2 ttl=60 time=141 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=3 ttl=60 time=205 ms
64 bytes from fjr04s06-in-f14.1e100.net (142.250.181.46): icmp_seq=4 ttl=60 time=100 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 78.308/131.053/204.783/48.152 ms
</code></pre>
<p>You can stop the response with <code>Ctrl + C</code>.</p>
<h4 id="heading-testing-endpoints-with-the-curl-command">Testing endpoints with the <code>curl</code> command</h4>
<p>The <code>curl</code> command stands for "client URL". It is used to transfer data to or from a server. It can also be used to test API endpoints that helps in troubleshooting system and application errors.</p>
<p>As an example, you can use <a target="_blank" href="http://www.official-joke-api.appspot.com/"><code>http://www.official-joke-api.appspot.com/</code></a> to experiment with the <code>curl</code> command.</p>
<ul>
<li>The <code>curl</code> command without any options uses the GET method by default.</li>
</ul>
<pre><code class="lang-bash">curl http://www.official-joke-api.appspot.com/random_joke
{<span class="hljs-string">"type"</span>:<span class="hljs-string">"general"</span>,
<span class="hljs-string">"setup"</span>:<span class="hljs-string">"What did the fish say when it hit the wall?"</span>,<span class="hljs-string">"punchline"</span>:<span class="hljs-string">"Dam."</span>,<span class="hljs-string">"id"</span>:1}
</code></pre>
<ul>
<li><code>curl -o</code> saves the output to the mentioned file.</li>
</ul>
<pre><code class="lang-bash">curl -o random_joke.json http://www.official-joke-api.appspot.com/random_joke
<span class="hljs-comment"># saves the output to random_joke.json</span>
</code></pre>
<ul>
<li><code>curl -I</code> fetches only the headers.</li>
</ul>
<pre><code class="lang-bash">curl -I http://www.official-joke-api.appspot.com/random_joke
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Vary: Accept-Encoding
X-Powered-By: Express
Access-Control-Allow-Origin: *
ETag: W/<span class="hljs-string">"71-NaOSpKuq8ChoxdHD24M0lrA+JXA"</span>
X-Cloud-Trace-Context: 2653a86b36b8b131df37716f8b2dd44f
Content-Length: 113
Date: Thu, 06 Jun 2024 10:11:50 GMT
Server: Google Frontend
</code></pre>
<h3 id="heading-88-linux-troubleshooting-tools-and-techniques">8.8. Linux Troubleshooting: Tools and Techniques</h3>
<h4 id="heading-system-activity-report-with-sar">System activity report with <code>sar</code></h4>
<p>The <code>sar</code> command in Linux is a powerful tool for collecting, reporting, and saving system activity information. It's part of the <code>sysstat</code> package and is widely used for monitoring system performance over time.</p>
<p>To use <code>sar</code> you first need to install <code>syssstat</code> using <code>sudo apt install sysstat</code>.</p>
<p>Once installed, start the service with <code>sudo systemctl start sysstat</code>.</p>
<p>Verify the status with <code>sudo systemctl status sysstat</code>.</p>
<p>Once the status is active, the system will start collecting various stats that you can use to access and analyze historical data. We'll see that in detail soon.</p>
<p>The syntax of the <code>sar</code> command is as follows:</p>
<pre><code class="lang-bash">sar [options] [interval] [count]
</code></pre>
<p>For example, <code>sar -u 1 3</code> will display CPU utilization statistics every second for three times.</p>
<pre><code class="lang-bash">sar -u 1 3
<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:09:26        CPU     %user     %nice   %system   %iowait    %steal     %idle
19:09:27        all      3.78      0.00      2.18      0.08      0.00     93.96
19:09:28        all      4.02      0.00      2.01      0.08      0.00     93.89
19:09:29        all      6.89      0.00      2.10      0.00      0.00     91.01
Average:        all      4.89      0.00      2.10      0.06      0.00     92.95
</code></pre>
<p>Here are some common use cases and examples of how to use the <code>sar</code> command.</p>
<p><code>sar</code> can be used for a variety of purposes:</p>
<h5 id="heading-1-memory-usage">1. Memory usage</h5>
<p>To check memory usage (free and used), use:</p>
<pre><code class="lang-bash">sar -r 1 3

Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:10:46    kbmemfree   kbavail kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact   kbdirty
19:10:47      4600104   8934352   5502124     36.32    375844   4158352  15532012     65.99   6830564   2481260       264
19:10:48      4644668   8978940   5450252     35.98    375852   4165648  15549184     66.06   6776388   2481284        36
19:10:49      4646548   8980860   5448328     35.97    375860   4165648  15549224     66.06   6774368   2481292       116
Average:      4630440   8964717   5466901     36.09    375852   4163216  15543473     66.04   6793773   2481279       139
</code></pre>
<p>This command displays memory statistics every second three times.</p>
<h5 id="heading-2-swap-space-utilization">2. Swap space utilization</h5>
<p>To view swap space utilization statistics, use:</p>
<pre><code class="lang-bash">sar -S 1 3

sar -S 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:11:20    kbswpfree kbswpused  %swpused  kbswpcad   %swpcad
19:11:21      8388604         0      0.00         0      0.00
19:11:22      8388604         0      0.00         0      0.00
19:11:23      8388604         0      0.00         0      0.00
Average:      8388604         0      0.00         0      0.00
</code></pre>
<p>This command helps monitor the swap usage, which is crucial for systems running out of physical memory.</p>
<h5 id="heading-3-io-devices-load">3. I/O devices load</h5>
<p>To report activity for block devices and block device partitions:</p>
<pre><code class="lang-bash">sar -d 1 3
</code></pre>
<p>This command provides detailed stats about data transfers to and from block devices, and is useful for diagnosing I/O bottlenecks.</p>
<h5 id="heading-5-network-statistics">5. Network statistics</h5>
<p>To view network statistics, like number of packets received (transmitted) by the network interface:</p>
<pre><code class="lang-bash">sar -n DEV 1 3
<span class="hljs-comment"># -n DEV tells sar to report network device interfaces</span>
sar -n DEV 1 3
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:12:47        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
19:12:48           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
19:12:48       wlp3s0     10.00      3.00      1.83      0.37      0.00      0.00      0.00      0.00
19:12:48    br-5129d04f972f      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
.
.
.

Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
Average:           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Average:       enp2s0      0.00      0.00      0.00      0.00      0.00      0.00      0.00      0.00
...output truncated...
</code></pre>
<p>This displays network statistics every second for three seconds, helping in monitoring network traffic.</p>
<h5 id="heading-6-historical-data">6. Historical data</h5>
<p>Recall that previously we installed the <code>sysstat</code> package and ran the service. Follow the steps below to enable and access historical data.</p>
<ol>
<li><p><strong>Enable data collection:</strong> Edit the <code>sysstat</code> configuration file to enable data collection.</p>
<pre><code class="lang-bash"> sudo nano /etc/default/sysstat
</code></pre>
<p> Change <code>ENABLED="false"</code> to <code>ENABLED="true"</code>.</p>
<pre><code class="lang-bash"> vim /etc/default/sysstat
 <span class="hljs-comment">#</span>
 <span class="hljs-comment"># Default settings for /etc/init.d/sysstat, /etc/cron.d/sysstat</span>
 <span class="hljs-comment"># and /etc/cron.daily/sysstat files</span>
 <span class="hljs-comment">#</span>

 <span class="hljs-comment"># Should sadc collect system activity informations? Valid values</span>
 <span class="hljs-comment"># are "true" and "false". Please do not put other values, they</span>
 <span class="hljs-comment"># will be overwritten by debconf!</span>
 ENABLED=<span class="hljs-string">"true"</span>
</code></pre>
</li>
<li><p><strong>Configure data collection interval:</strong> Edit the cron job configuration to set the data collection interval.</p>
<pre><code class="lang-bash"> sudo nano /etc/cron.d/sysstat
</code></pre>
<p> By default, it collects data every 10 minutes. You can adjust the interval by modifying the cron job schedule. The relevant files will go to the <code>/var/log/sysstat</code> folder.</p>
</li>
<li><p><strong>View historical data:</strong> Use the <code>sar</code> command to view historical data. For example, to view CPU usage for the current day:</p>
<pre><code class="lang-bash"> sar -u
</code></pre>
<p> To view data from a specific date:</p>
<pre><code class="lang-bash"> sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa&lt;DD&gt;
</code></pre>
<p> Replace <code>&lt;DD&gt;</code> with the day of the month for which you want to view the data.</p>
<p> In the below command, <code>/var/log/sysstat/sa04</code> gives stats for the 4th day of the current month.</p>
</li>
</ol>
<pre><code class="lang-bash">sar -u -f /var/<span class="hljs-built_in">log</span>/sysstat/sa04
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

15:20:49     LINUX RESTART    (12 CPU)

16:13:30     LINUX RESTART    (12 CPU)

18:16:00        CPU     %user     %nice   %system   %iowait    %steal     %idle
18:16:01        all      0.25      0.00      0.67      0.08      0.00     99.00
Average:        all      0.25      0.00      0.67      0.08      0.00     99.00
</code></pre>
<h5 id="heading-7-real-time-cpu-interruptions">7. Real-Time CPU Interruptions</h5>
<p>To observe real-time interrupts per second served by the CPU, use this command:</p>
<pre><code class="lang-bash">sar -I SUM 1 3

<span class="hljs-comment"># Output</span>
Linux 6.5.0-28-generic (zaira-ThinkPad)     04/06/24     _x86_64_    (12 CPU)

19:14:22         INTR    intr/s
19:14:23          sum   5784.00
19:14:24          sum   5694.00
19:14:25          sum   5795.00
Average:          sum   5757.67
</code></pre>
<p>This command helps in monitoring how frequently the CPU is handling interrupts, which can be crucial for real-time performance tuning.</p>
<p>These examples illustrate how you can use <code>sar</code> to monitor various aspects of system performance. Regular use of <code>sar</code> can help in identifying system bottlenecks and ensuring that applications keep running efficiently.</p>
<h3 id="heading-89-general-troubleshooting-strategy-for-servers">8.9. General Troubleshooting Strategy for Servers</h3>
<p><strong>Why do we need to understand monitoring?</strong></p>
<p>System monitoring is an important aspect of system administration. Critical applications demand a high level of proactiveness to prevent failure and reduce the outage impact.</p>
<p>Linux offers very powerful tools to gauge system health. In this section, you'll learn about the various methods available to check your system's health and identify the bottlenecks.</p>
<h4 id="heading-find-load-average-and-system-uptime">Find load average and system uptime</h4>
<p>System reboots may occur which can sometimes mess up some configurations. To check how long the machine has been up, use the command: <code>uptime</code>. In addition to the uptime, the command also displays load average.</p>
<pre><code class="lang-bash">[user@host ~]$ uptime 19:15:00 up 1:04, 0 users, load average: 2.92, 4.48, 5.20
</code></pre>
<p>Load average is the system load over the last 1, 5, and 15 minutes. A quick glance indicates whether the system load appears to be increasing or decreasing over time.</p>
<p>Note: Ideal CPU queue is <code>0</code>. This is only possible when there are no waiting queues for the CPU.</p>
<p>Per-CPU load can be calculated by dividing load average with the total number of CPUs available.</p>
<p>To find the number of CPUs, use the command <code>lscpu.</code></p>
<pre><code class="lang-bash">lscpu
<span class="hljs-comment"># output</span>
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         48 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  12
  On-line CPU(s) list:   0-11
.
.
.
output omitted
</code></pre>
<p>If the load average seems to increase and does not come down, the CPUs are overloaded. There is some process that is stuck or there is a memory leakage.</p>
<h4 id="heading-calculating-free-memory">Calculating free memory</h4>
<p>Sometimes, high memory utilization might be causing problems. To check the available memory and the memory in use, use the <code>free</code> command.</p>
<pre><code class="lang-bash">free -mh
<span class="hljs-comment"># output</span>
               total        used        free      shared  buff/cache   available
Mem:            14Gi       3.5Gi       7.7Gi       109Mi       3.2Gi        10Gi
Swap:          8.0Gi          0B       8.0Gi
</code></pre>
<h4 id="heading-calculating-disk-space">Calculating disk space</h4>
<p>To ensure the system is healthy, don't forget about the disk space. To list all the available mount points and their respective used percentage, use the below command. Ideally, utilized disk spaces should not exceed 80%.</p>
<p>The <code>df</code> command provides detailed disk spaces.</p>
<pre><code class="lang-bash">df -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           1.5G  2.4M  1.5G   1% /run
/dev/nvme0n1p2  103G   34G   65G  35% /
tmpfs           7.3G   42M  7.2G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
efivarfs        246K   93K  149K  39% /sys/firmware/efi/efivars
/dev/nvme0n1p3  130G   47G   77G  39% /home
/dev/nvme0n1p1  511M  6.1M  505M   2% /boot/efi
tmpfs           1.5G  140K  1.5G   1% /run/user/1000
</code></pre>
<h4 id="heading-determining-process-states">Determining process states</h4>
<p>Process states can be monitored to see any stuck process with a high memory or CPU usage.</p>
<p>We saw previously that the <code>ps</code> command gives useful information about a process. Have a look at the <code>CPU</code> and <code>MEM</code> columns.</p>
<pre><code class="lang-bash">[user@host ~]$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
 runner         1  0.1  0.0 1535464 15576 ?       S  19:18   0:00 /inject/init
 runner        14  0.0  0.0  21484  3836 pts/0    S   19:21   0:00 bash --norc
 runner        22  0.0  0.0  37380  3176 pts/0    R+   19:23   0:00 ps aux
</code></pre>
<h4 id="heading-real-time-system-monitoring">Real-time system monitoring</h4>
<p>Real time monitoring gives a window into the realtime system state.</p>
<p>One utility you can use to do this is the <code>top</code> command.</p>
<p>The top command displays a dynamic view of the system's processes, displaying a summary header followed by a process or thread list. Unlike its static counterpart <code>ps</code>, <code>top</code> continuously refreshes the system stats.</p>
<p>With <code>top</code>, you can see well-organised details in a compact window. There a number of flags, shortcuts, and highlighting methods that come along with <code>top</code>.</p>
<p>You can also kill processes using <code>top</code>. For that, press <code>k</code> and then enter the process id.</p>
<h4 id="heading-interpreting-logs">Interpreting logs</h4>
<p>System and application logs carry tons of information about what the system is going through. They contain useful information and error codes that point towards errors. If you search for error codes in logs, issue identification and rectification time can be greatly reduced.</p>
<h4 id="heading-network-ports-analysis">Network ports analysis</h4>
<p>The network aspect should not be ignored as network glitches are common and may impact the system and traffic flows. Common network issues include port exhaustion, port choking, unreleased resources, and so on.</p>
<p>To identify such issues, we need to understand port states.</p>
<p>Some of the port states are explained briefly here:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>State</strong></td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td>LISTEN</td><td>Represents ports that are waiting for a connection request from any remote TCP and port.</td></tr>
<tr>
<td>ESTABLISHED</td><td>Represents connections that are open and data received can be delivered to the destination.</td></tr>
<tr>
<td>TIME WAIT</td><td>Represents waiting time to ensure acknowledgment of its connection termination request.</td></tr>
<tr>
<td>FIN WAIT2</td><td>Represents waiting for a connection termination request from the remote TCP.</td></tr>
</tbody>
</table>
</div><p>Let's explore how we can analyze port-related information in Linux.</p>
<p><strong>Port ranges:</strong> Port ranges are defined in the system, and range can be increased/decreased accordingly. In the below snippet, the range is from <code>15000</code> to <code>65000</code>, which makes a total of <code>50000</code> (65000 - 15000) available ports. If utilized ports are reaching or exceeding this limit, then there is an issue.</p>
<pre><code class="lang-bash">[user@host ~]$ /sbin/sysctl net.ipv4.ip_local_port_range
net.ipv4.ip_local_port_range = 15000    65000
</code></pre>
<p>The error reported in logs in such cases can be <code>Failed to bind to port</code> or <code>Too many connections</code>.</p>
<h4 id="heading-identifying-packet-loss">Identifying packet loss</h4>
<p>In system monitoring, we need to ensure that the outgoing and incoming communication is intact.</p>
<p>One helpful command is <code>ping</code>. <code>ping</code> hits the destination system and brings the response back. Note the last few lines of statistics that show packet loss percentage and time.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># ping destination IP</span>
[user@host ~]$ ping 10.13.6.113
 PING 10.13.6.141 (10.13.6.141) 56(84) bytes of data.
 64 bytes from 10.13.6.113: icmp_seq=1 ttl=128 time=0.652 ms
 64 bytes from 10.13.6.113: icmp_seq=2 ttl=128 time=0.593 ms
 64 bytes from 10.13.6.113: icmp_seq=3 ttl=128 time=0.478 ms
 64 bytes from 10.13.6.113: icmp_seq=4 ttl=128 time=0.384 ms
 64 bytes from 10.13.6.113: icmp_seq=5 ttl=128 time=0.432 ms
 64 bytes from 10.13.6.113: icmp_seq=6 ttl=128 time=0.747 ms
 64 bytes from 10.13.6.113: icmp_seq=7 ttl=128 time=0.379 ms
 ^C
 --- 10.13.6.113 ping statistics ---
 7 packets transmitted, 7 received,0% packet loss, time 6001ms
 rtt min/avg/max/mdev = 0.379/0.523/0.747/0.134 ms
</code></pre>
<p>Packets can also be captured at runtime using <code>tcpdump</code>. We'll look into it later.</p>
<h4 id="heading-gathering-stats-for-issue-post-mortem">Gathering stats for issue post mortem</h4>
<p>It is always a good practice to gather certain stats that would be useful for identifying the root cause later. Usually, after system reboot or services restart, we loose the earlier system snapshot and logs.</p>
<p>Below are some of the methods to capture system snapshot.</p>
<ul>
<li><strong>Logs Backup</strong></li>
</ul>
<p>Before making any changes, copy log files to another location. This is crucial for understanding what condition the system was in during time of issue. Sometimes log files are the only window to look into past system states as other runtime stats are lost.</p>
<ul>
<li><strong>TCP Dump</strong></li>
</ul>
<p>Tcpdump is a command-line utility that allows you to capture and analyze incoming and outgoing network traffic. It is mostly used to help troubleshoot network issues. If you feel that system traffic is being impacted, take <code>tcpdump</code> as follows:</p>
<pre><code class="lang-bash">sudo tcpdump -i any -w

<span class="hljs-comment"># Where,</span>
<span class="hljs-comment"># -i any captures traffic from all interfaces</span>
<span class="hljs-comment"># -w specifies the output filename</span>

<span class="hljs-comment"># Stop the command after a few mins as the file size may increase</span>
<span class="hljs-comment"># use file extension as .pcap</span>
</code></pre>
<p>Once <code>tcpdump</code> is captured, you can use tools like Wireshark to visually analyze the traffic.</p>
<h2 id="heading-810-diagnosing-hardware-problems">8.10 <strong>Diagnosing Hardware Problems</strong></h2>
<p>Troubleshooting unexpected issues is a part of the learning process. Sometimes, you may notice frequent segmentation faults (<code>SIGSEGV</code>), overheating, or random crashes across unrelated applications. The issue could either be software or hardware related. While software-related issues depend on the specific application itself, hardware issues can be diagnosed with some standard steps.</p>
<p>In this section, we will discuss how to diagnose and rule out hardware issues related to memory, CPU, system sensors, power supply, and more.</p>
<h3 id="heading-8101-analyzing-memory-performance"><strong>8.10.1 Analyzing Memory Performance</strong></h3>
<p><strong>Determine Available RAM</strong></p>
<p>If you feel your system is getting slow and taking longer to finish tasks, check your system's available memory. This will ensure there is enough available memory including the swap memory.</p>
<p>The command to check available memory is <code>free -mh</code>, where <code>-h</code> is for human-readable output and <code>-m</code> is for displaying memory in MB.</p>
<pre><code class="lang-bash">free -mh
               total        used        free      shared  buff/cache   available
Mem:            14Gi       5.1Gi       2.4Gi        77Mi       7.3Gi       9.3Gi
Swap:          4.0Gi          0B       4.0Gi
</code></pre>
<p>In the above output, look at the "available" column in the "Mem" row. This shows how much RAM is free for use.</p>
<p>Another way to check the memory in real time is to use the <code>top</code> command. There are 2 ways to do this:</p>
<ul>
<li><p>When you are in <code>top</code>, press <code>Shift + M</code> to sort the processes by memory usage.</p>
</li>
<li><p>Alternately, press <code>m</code> to see the memory usage in a progress bar like format:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739275886121/f1695a67-13d6-4222-b71c-07176a52acb8.png" alt="f1695a67-13d6-4222-b71c-07176a52acb8" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If you see the memory consumed near to <code>100%</code>, you might want to consider identifying the process that is consuming the memory and take necessary action. You might also want to consider adding more memory to your system.</p>
<p><strong>Run a stress test on your hardware</strong></p>
<p>The <code>memtester</code> command is a utility used for diagnosing memory-related issues by stressing the memory and checking for faults. It is often used in situations where you suspect faulty RAM might be causing system instability or crashes.</p>
<p>Here's how to use it effectively:</p>
<ul>
<li><p>First, install <code>memtester</code>.</p>
<pre><code class="lang-bash">  sudo apt install memtester
</code></pre>
</li>
<li><p>Determine the amount of RAM to test and the number of passes you’d like your RAM to go through. In the command below, <code>1G</code> is the amount of RAM to test (1 GB), and <code>5</code> is the number of test passes:</p>
<pre><code class="lang-bash">  sudo memtester 1G 5
</code></pre>
</li>
</ul>
<p>If all tests pass, your RAM is likely error-free. If errors are reported, your RAM might be faulty and could require replacement or further inspection. You can always run the test again with a different amount of RAM or test passes.</p>
<p>Note that, you shouldn't test too much memory at once, as your system also needs memory for running processes. If you have more RAM than can be tested at once, test in smaller segments sequentially.</p>
<p>Below is a snippet of the <code>memtester</code> output if all tests pass. Notice the <code>”ok”</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : ok
  Random Value        : ok
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : ok
  Block Sequential    : ok
  Checkerboard        : ok
  Bit Spread          : ok
  Bit Flip            : ok
  Walking Ones        : ok
  Walking Zeroes      : ok
  8-bit Writes        : ok
  16-bit Writes       : ok
.
.
.
</code></pre>
<p>Below is a snippet of the output if a test fails. Notice the <code>FAILURE</code> status for each test.</p>
<pre><code class="lang-bash">memtester version 4.5.1 (64-bit)
Copyright (C) 2001-2020 Charles Cazabon.
Licensed under the GNU General Public License version 2 (only).

pagesize is 4096
pagesizemask is 0xfffffffffffff000
want 1024MB (1073741824 bytes)
got  1024MB (1073741824 bytes), trying mlock ...locked.
Loop 1/5:
  Stuck Address       : testing   1FAILURE: possible bad address line at offset 0x25378a58.
Skipping to next <span class="hljs-built_in">test</span>...
  Random Value        : FAILURE: 0x4df704aaafdf8848 != 0x4df704aaafdfc848 at offset 0x05379a48.
  Compare XOR         : ok
  Compare SUB         : ok
  Compare MUL         : ok
  Compare DIV         : ok
  Compare OR          : ok
  Compare AND         : ok
  Sequential Increment: ok
  Solid Bits          : testing   6FAILURE: 0x00000000 != 0x00004000 at offset 0x05379a48.
  Block Sequential    : testing   3FAILURE: 0x303030303030303 != 0x303030303034303 at offset 0x05379a48.
  Checkerboard        : testing   0FAILURE: 0xaaaaaaaaaaaaaaaa != 0xaaaaaaaaaaaaeaaa at offset 0x05379a48.
  Bit Spread          : testing  12FAILURE: 0xffffffffffffafff != 0xffffffffffffefff at offset 0x05379a48.
  Bit Flip            : testing   0FAILURE: 0x00000001 != 0x00004001 at offset 0x05379a48.
  Walking Ones        : ok
  Walking Zeroes      : testing   0FAILURE: 0x00000001 != 0x00001001 at offset 0x053af9f8.
  8-bit Writes        : -FAILURE: 0x57c7c8ba7d6f5b3b != 0x57c7c8ba7d6f1b3b at offset 0x0537da28.
  16-bit Writes       : -FAILURE: 0xd7768894fbf79099 != 0xd7768894fbf7d099 at offset 0x05379a48.
FAILURE: 0xfffc5633ffefca5d != 0xfffc5633ffefda5d at offset 0x053a5a38.
.
.
.
</code></pre>
<p>If errors persist across all test loops, it strongly suggests hardware issues, not transient software glitches.</p>
<h3 id="heading-8102-identifying-overheating-issues"><strong>8.10.2 Identifying Overheating Issues</strong></h3>
<p>Overheating can cause unexpected errors and crashes. To diagnose overheating issues, you can use a command line utility <code>lm-sensors</code>.</p>
<p><code>lm-sensors</code> allow syou monitor hardware health by reading data from various sensors. It provides information about system temperatures, voltages, and fan speeds.</p>
<p>Here's how you can identify and monitor your system temperature using <code>lm-sensors</code>:</p>
<ul>
<li><p>First, install <code>lm-sensors</code>:</p>
<pre><code class="lang-bash">  sudo apt install lm-sensors
</code></pre>
</li>
<li><p>Detect the available sensors on your system:</p>
<pre><code class="lang-bash">  sudo sensors-detect
</code></pre>
<p>  Follow the prompts and answer “YES” to detect the available sensors on your system.</p>
</li>
<li><p>Once the available sensors are detected, you can view the temperature of your system using the <code>sensors</code> command:</p>
<pre><code class="lang-bash">  sensors
</code></pre>
<p>  In the output below, you can see the temperature reading at the edge of the GPU, which is 41.0 degrees Celsius. You can also see other pieces of information like voltage supplied, power consumption and voltage supplied.</p>
<pre><code class="lang-bash">  amdgpu-pci-0400
  Adapter: PCI adapter
  vddgfx:      731.00 mV 
  vddnb:       687.00 mV 
  edge:         +41.0°C  
  PPT:           7.00 W
</code></pre>
<p>  Using <code>lm-sensors</code> ensures that the system is operating within safe parameters. It helps to detect potential hardware problems early and take corrective actions to prevent hardware damage.</p>
</li>
</ul>
<h3 id="heading-8103-evaluating-hard-drive-health"><strong>8.10.3 Evaluating Hard Drive Health</strong></h3>
<p>Disk errors can also cause application crashes. To identify disk issues, you can run disk check using <code>smartmontools</code>:</p>
<ul>
<li><p>First, install <code>smartmontools</code>:</p>
<pre><code class="lang-bash">  sudo apt install smartmontools
</code></pre>
</li>
<li><p>Run a quick health check using the command below and replace <code>/dev/sdX</code> with your disk name (check with <code>lsblk</code>).</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/sdX
</code></pre>
</li>
<li><p>Here is the result I got when I ran the command on my disk <code>/dev/nvme0n1</code>:</p>
<pre><code class="lang-bash">  sudo smartctl -H /dev/nvme0n1
  smartctl 7.4 2023-08-01 r5530 [x86_64-linux-6.8.0-52-generic] (<span class="hljs-built_in">local</span> build)
  Copyright (C) 2002-23, Bruce Allen, Christian Franke, www.smartmontools.org

  === START OF SMART DATA SECTION ===
  SMART overall-health self-assessment <span class="hljs-built_in">test</span> result: PASSED
</code></pre>
</li>
<li><p>You can also run a detailed test:</p>
<pre><code class="lang-bash">  sudo smartctl -a /dev/nvme0n1
</code></pre>
</li>
</ul>
<p>The detailed test provides a full report, including:</p>
<ul>
<li><p>Temperature</p>
</li>
<li><p>Power-on hours</p>
</li>
<li><p>Error counts</p>
</li>
<li><p>Wear leveling (for SSDs), and more.</p>
</li>
</ul>
<h3 id="heading-8104-conducting-a-cpu-stress-test"><strong>8.10.4 Conducting a CPU Stress Test</strong></h3>
<p>Faulty CPUs can also lead to a number of performance issues. To test your CPU, you can use the <code>stress-ng</code> utility:</p>
<ul>
<li><p>Install <code>stress-ng</code>:</p>
<pre><code class="lang-bash">  sudo apt install stress-ng
</code></pre>
</li>
<li><p>Run a CPU stress test:</p>
<pre><code class="lang-bash">  stress-ng --cpu 4 --timeout 60
</code></pre>
</li>
</ul>
<p>In the above command, <code>4</code> is the number of CPU cores you’d like to test and <code>60</code> is the duration in seconds. The command will stress all 4 CPU cores for 60 seconds. Notice the CPU is at <code>100%</code> load during the test:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739277374316/9ab475c2-7f09-4c40-989b-e474e334935c.png" alt="9ab475c2-7f09-4c40-989b-e474e334935c" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If the system crashes during this test, the CPU may be faulty.</p>
<h3 id="heading-8105-examining-system-logs-for-errors"><strong>8.10.5 Examining System Logs for Errors</strong></h3>
<p><code>systemd</code> is a Linux system manager responsible for booting the system, managing system processes, and handling system services.</p>
<p><code>journalctl</code> is a command to query the <code>systemd</code> journal logs. It provides detailed logging for system processes, kernel events, user applications, and more.</p>
<p>You can check system logs for hardware-related errors using the command: <code>journalctl -k | grep -iE "error|fault|panic"</code>.</p>
<p>In the logs, look for messages about:</p>
<ul>
<li><p>Memory faults.</p>
</li>
<li><p>I/O errors.</p>
</li>
<li><p>Hardware timeouts.</p>
</li>
</ul>
<p>Here is what errors in the log file can look like:</p>
<pre><code class="lang-bash">Feb 11 10:15:32 hostname kernel: [Hardware Error]: CPU 0: Machine Check: 0 Bank 4: b200000000070f0f
Feb 11 10:15:32 hostname kernel: [Hardware Error]: TSC 0 ADDR fef1c000 MISC 38a0000086 
Feb 11 10:15:32 hostname kernel: [Hardware Error]: PROCESSOR 0:306a9 TIME 1613045732 SOCKET 0 APIC 0 microcode 1f
Feb 11 10:16:45 hostname kernel: EXT4-fs error (device sda1): ext4_find_entry:1453: inode <span class="hljs-comment">#2: comm ls: reading directory lblock 0</span>
Feb 11 10:17:12 hostname kernel: [drm:drm_atomic_helper_commit_cleanup_done [drm_kms_helper]] *ERROR* [CRTC:36:pipe A] flip_done timed out
Feb 11 10:18:05 hostname kernel: Kernel panic - not syncing: Fatal exception
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Thank you for reading the book until the end. If you found it helpful, consider sharing it with others.</p>
<p>This book doesn't end here, though. I will continue to improve it and add new materials in the future. If you found any issues or if you would like to suggest any improvements, <a target="_blank" href="https://github.com/zairahira/Mastering-Linux-Handbook">feel free to open a PR/ Issue.</a></p>
<p><strong>Stay Connected and Continue Your Learning Journey!</strong></p>
<p>Your journey with Linux doesn't have to end here. Stay connected and take your skills to the next level:</p>
<ol>
<li><p><strong>Follow Me on Social Media</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/hira_zaira">X</a>: I share useful short form content there. My DMs are always open.</p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/zaira-hira/">LinkedIn</a>: I share articles and posts on tech there. Leave a recommendation on LinkedIn and endorse me on relevant skills.</p>
</li>
</ul>
</li>
<li><p><strong>Get access to exclusive content</strong>: For one-on-one help and exclusive content go <a target="_blank" href="https://buymeacoffee.com/zairah/extras">here</a>.</p>
</li>
</ol>
<p>My <a target="_blank" href="https://www.freecodecamp.org/news/author/zaira/">articles</a> and books, like this one, are part of my mission to increase accessibility to quality content for everyone. This book will also be open to translation in other languages. Each piece takes a lot of time and effort to write. This book will be free, forever. If you've enjoyed my work and want to keep me motivated, consider <a target="_blank" href="https://buymeacoffee.com/zairah">buying me a coffee</a>.</p>
<p>Thank you once again and happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Hello World in Rust – Example Program ]]>
                </title>
                <description>
                    <![CDATA[ Starting with a new programming language is like taking your first step into a whole new world. One of the very first things you'll do is write a simple program that says "Hello World!". Rust, known for being fast and safe, is no exception. Let's jum... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/hello-world-in-rust/</link>
                <guid isPermaLink="false">66bb8809c32849d18c5cdc9d</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sahil ]]>
                </dc:creator>
                <pubDate>Mon, 08 Apr 2024 09:21:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Neon-Green-Motivational.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Starting with a new programming language is like taking your first step into a whole new world. One of the very first things you'll do is write a simple program that says "Hello World!".</p>
<p>Rust, known for being fast and safe, is no exception. Let's jump right in and create our very first Rust program together!</p>
<h2 id="heading-how-to-write-a-hello-world-program-in-rust">How to Write a Hello World Program in Rust</h2>
<p>First, create a file named <code>main.rs</code>. Every Rust program contains <code>.rs</code> as its file extension.</p>
<p>Then write the following code in the file:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// main.rs</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello World!"</span>);
}
</code></pre>
<p>In the code above, we are trying to print <code>Hello World!</code> in the console or terminal.</p>
<h2 id="heading-how-to-compile-rust-code">How to Compile Rust Code</h2>
<p>In Rust, compiling and running the code are two separate processes.</p>
<p>First, you need to compile the Rust program. To compile it, write the following in the terminal (make sure in the terminal is at at the same directory where the Rust file lives):</p>
<pre><code class="lang-bash">rustc main.rs
</code></pre>
<p>For now, you won't see any output because the code was just compiled. But one thing you can see in the current directory is that a new executable file has been added with the same name as the Rust file.</p>
<h2 id="heading-how-to-run-the-executable-file">How to Run the Executable File</h2>
<p>Now you can run the executable file that gets generated after you successfully compiled the Rust code.</p>
<p>To run the executable file, write the following in your terminal:</p>
<pre><code class="lang-bash">./main
</code></pre>
<p>You should see an output like this:</p>
<pre><code class="lang-bash">Hello World!
</code></pre>
<h2 id="heading-understanding-the-hello-world-code-in-depth">Understanding the Hello World Code in Depth</h2>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {

}
</code></pre>
<p>The program starts with a function called <code>main()</code>. Every Rust executable code starts execution from the main function. </p>
<p>The main function can have some parameters inside the <code>()</code> parenthesis, but we have no need for them in the code so we left that empty.</p>
<p>Everything that is between the curly braces <code>{}</code> is the body of the function. It is necessary to have braces for the body otherwise it'll throw an error.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello World!"</span>);
}
</code></pre>
<p>This line does the work of printing the "Hello World!" text to the terminal or console.</p>
<p>Here, <code>println!</code> is not a function unlike other languages like C, Python, and so on. It is a macro – if there's an <code>!</code> symbol at the end of a keyword, then it's a macro.</p>
<p>Finally, we passed the string as argument to the macro and it prints the string to the terminal.</p>
<p>To end the statement in Rust, you must use <code>;</code>.If you don't provide the semi-colon at the end of every statement, then it'll throw an error.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And there we have it – your first Rust program! By printing out "Hello World!" you've dipped your toes into the world of Rust. </p>
<p>This simple program has given you a taste of Rust's syntax and how it compiles. As you keep going, you'll discover more about Rust's cool features and find out just how powerful it can be. </p>
<p>Ready to dive deeper? Let's keep exploring!</p>
<p>If you have any feedback, then feel free to DM me on <a target="_blank" href="https://twitter.com/introvertedbot">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/sahil-mahapatra/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Git and GitHub – a Guide for Beginners and Experienced Developers ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to Git and GitHub for Beginners! This comprehensive guide is tailored to help you navigate the world of version control and collaboration.  Whether you're a newbie just starting out or an experienced developer looking to brush up on your skil... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/guide-to-git-github-for-beginners-and-experienced-devs/</link>
                <guid isPermaLink="false">66bb56fe0da5b03e481107c4</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Sat, 06 Apr 2024 01:38:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Attractive.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to Git and GitHub for Beginners! This comprehensive guide is tailored to help you navigate the world of version control and collaboration. </p>
<p>Whether you're a newbie just starting out or an experienced developer looking to brush up on your skills, this guide offers a step-by-step approach to understanding and effectively using Git and GitHub.</p>
<p>By the end of this journey, you'll have a solid foundation in Git and GitHub. You'll be equipped with practical knowledge to streamline your coding workflow, collaborate seamlessly with teams, and contribute to open-source projects. </p>
<p>So, let's dive in and get started on your Git and GitHub adventure!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-who-is-this-guide-for">Who is this guide for?</a></li>
<li><a class="post-section-overview" href="#heading-technologies">Technologies</a></li>
<li><a class="post-section-overview" href="#heading-terms">Terms</a></li>
<li><a class="post-section-overview" href="#heading-what-is-github">What is GitHub?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-github-used-for">What is GitHub used for?</a></li>
<li><a class="post-section-overview" href="#heading-common-tasks-youll-perform-with-git">Common tasks you'll perform with Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-git">How to install Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-git">How to configure Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-the-default-editor">How to set the default editor</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-repository-using-the-github-website">How to create a repository using the Github website</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-repository-using-the-git-command-line">How to create a repository using the Git command line</a></li>
<li><a class="post-section-overview" href="#heading-how-to-connect-a-local-repository-to-a-remote-repository-on-github">How to connect a local repository to a remote repository on GitHub</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pull-changes-from-a-remote-repository-to-a-local-repository">How to pull changes from a remote repository to a local repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-git-commands">How to work with Git commands</a></li>
<li><a class="post-section-overview" href="#heading-how-to-make-changes-to-a-file">How to make changes to a file</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-the-status-of-the-current-branch">How to check the status of the current branch</a></li>
<li><a class="post-section-overview" href="#heading-how-to-stage-changes">How to stage changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-commit-changes">How to commit changes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-push-changes-to-a-remote-repository">How to push changes to a remote repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-branch">How to create a branch</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-pull-request">How to create a pull request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-merge-a-pull-requset">How to merge a pull request</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<h2 id="who-is-this-guide-for">Who is This Guide For?</h2>

<p>This guide is for everyone who wants to level up their coding skills and become proficient in using Git and GitHub. </p>
<p>Whether you're:</p>
<ul>
<li>just starting your tech career and need to learn the basics of version control.</li>
<li>an aspiring developer eager to integrate <code>Git</code> into your workflow.</li>
<li>an experienced programmer looking to refresh your knowledge or discover new features.</li>
<li>a team lead or manager interested in fostering a culture of collaboration and efficient code management.</li>
</ul>
<p>Regardless of your background or experience, this guide is designed to empower you with the tools and knowledge you need to excel in your coding endeavors.</p>
<h2 id="technologies">Technologies</h2>

<p>Before you start, make sure:</p>
<ul>
<li>You have a <a target="_blank" href="https://github.com/">GitHub account</a></li>
<li><a target="_blank" href="https://git-scm.com/">Git</a> is installed on your machine</li>
<li>You have a text editor, such as <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> installed</li>
<li><a target="_blank" href="https://nodejs.org/en/">Node.js</a> is installed on your machine</li>
</ul>
<h2 id="terms">Terms</h2>

<p>They are a lot of terms around Git and Github that you may meet when you're working with version control. Let me break it down for you before we start:</p>
<ul>
<li><strong>Branch</strong>: A version of the codebase that diverges from the main branch to isolate changes for specific features, fixes, or experiments.</li>
<li><strong>Commit</strong>: A snapshot of your changes, saved to your local repository. Each commit is uniquely identified by a checksum.</li>
<li><strong>Stage</strong>: The area where Git tracks changes that are ready to be included in the next commit. Files in the staging area are prepared (staged) for the next commit.</li>
<li><strong>Merge</strong>: The process of integrating changes from one branch into another, typically the main branch.</li>
<li><strong>Pull Request</strong>: A proposal to merge changes from one branch into another, often used in collaborative environments to review and discuss changes before they are merged.</li>
<li><strong>Fork</strong>: A personal copy of someone else's project that lives on your GitHub account.</li>
<li><strong>Clone</strong>: The act of downloading a repository from a remote source to your local machine.</li>
<li><strong>Remote</strong>: A common repository that all team members use to exchange their changes.</li>
<li><strong>Origin</strong>: The default name Git gives to the server from which you cloned.</li>
<li><strong>Upstream</strong>: The original repository that was cloned.</li>
<li><strong>Master</strong>: The default branch name given to a repository when it is created. In modern practice, it is often replaced with <code>main</code>.</li>
<li><strong>Repository</strong>: A storage location where your project lives, containing all the files and revision history.</li>
<li><strong>Working Directory</strong>: The directory on your computer where you are making changes to your project.</li>
<li><strong>Staging Area</strong>: Also known as the "Index," it's an area where Git tracks changes that are ready to be committed.</li>
<li><strong>Index</strong>: Another name for the staging area, where Git tracks changes that are ready to be committed.</li>
<li><strong>HEAD</strong>: A reference to the last commit in the currently checked-out branch.</li>
<li><strong>Checkout</strong>: The action of switching from one branch to another or to a specific commit.</li>
<li><strong>Push</strong>: The action of sending your commits to a remote repository.</li>
<li><strong>Pull</strong>: The action of fetching changes from a remote repository and merging them into your current branch.</li>
<li><strong>Fetch</strong>: The action of retrieving updates from a remote repository without merging them into your current branch.</li>
</ul>
<h2 id="what-is-github">What is GitHub?</h2>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/GitHub-1.png" alt="GitHub-1" width="600" height="400" loading="lazy"></p>
<p>GitHub is a platform that hosts code, providing version control and collaboration features. It enables you and others to work together on projects from anywhere in the world. </p>
<p>This guide will introduce you to essential GitHub concepts such as <code>repositories</code>, <code>branches</code>, <code>commits</code>, and <code>Pull Requests</code>. You will learn how to create your own 'Hello World' repository and understand GitHub's Pull Request workflow, a widely-used method for creating and reviewing code. </p>
<p>By the end of this guide, you'll be equipped with the knowledge and skills to collaborate effectively on GitHub.</p>
<h2 id="what-is-github-used-for">What is GitHub Used For?</h2>

<p>GitHub is more than just a code hosting platform. It's a tool that allows for seamless collaboration and version control. Here are some of its uses:</p>
<ul>
<li>Hosting and sharing your code with others.</li>
<li>Tracking and assigning issues to maintain an organized workflow.</li>
<li>Managing pull requests to review and incorporate changes into your project.</li>
<li>Creating your own website using GitHub Pages, a static site hosting service.</li>
<li>Collaborating with others on projects, making it an excellent tool for open-source contributions.</li>
</ul>
<h2 id="what-is-git">What is Git?</h2>

<p>Git is a free and open-source distributed version control system. It's designed to handle everything from small to very large projects with speed and efficiency</p>
<p>Git is easy to learn and has a tiny footprint with lightning-fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows</p>
<p>Git was initially designed and developed by Linus Torvalds for Linux kernel development.</p>
<p>Some features/benefits of Git:</p>
<ul>
<li>Allows you to track changes to your code over time.</li>
<li>Enables you to collaborate with others on the same codebase.</li>
<li>You can easily revert to a previous version of your code or experiment with new features without affecting the main codebase.</li>
<li>Provides a record of all changes made to your code, including who made them and when which can be useful for auditing and debugging.</li>
</ul>
<h2 id="common-tasks-youll-perform-with-git"> Common Tasks You'll Perform with Git </h2>

<ul>
<li>Create a repository</li>
<li>Create a branch</li>
<li>Make changes to a file</li>
<li>Stage changes</li>
<li>Commit changes</li>
<li>Push changes to a remote repository</li>
<li>Merge changes</li>
<li>Revert changes</li>
<li>Delete a branch</li>
</ul>
<h2 id="how-to-install-git">  How to Install Git </h2>

<p>To install Git on your local machine, you need to follow these steps:</p>
<ol>
<li><p>Download Git from the official website: <a target="_blank" href="https://git-scm.com/downloads">Git Downloads</a></p>
</li>
<li><p>Install Git on your local machine by following the instructions provided on the official website: <a target="_blank" href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Installing Git</a></p>
</li>
</ol>
<p><em>Congratulations!</em> You have successfully installed Git on your local machine. You are now ready to start using Git for your projects.</p>
<h2 id="how-to-configure-git">  How to Configure Git </h2>

<p>Git offers a variety of configurations that can streamline your workflow. In this section, I will guide you through the process of setting up Git on your local machine. Let's get started.</p>
<p>Configuring your <code>name</code> and <code>email</code> address on your local machine is an essential step in setting up Git. These details are attached to each commit you make, providing context and ownership. Let's learn how to use the <code>git config --global</code> command to set your name and email globally on your local machine.</p>
<p>To set up your name, you need to type the following command in your terminal:</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Set a name that is identifiable for credit when reviewing version history</span>

$ git config --global user.name <span class="hljs-string">"Your Name"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/userNameEmail.png" alt="userNameEmail" width="600" height="400" loading="lazy"></p>
<p>As you can see in the image above, I have entered my name.</p>
<p>After entering your name, press <code>Enter</code> to save it. You won't receive any response, but rest assured, your name has been stored successfully.</p>
<p>Just like we set up the user name, we also need to set up the user email. This email will be associated with each commit you make. Let's learn how to use the <code>git config --global</code> command to set your email globally on your local machine.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Set an email address that will be associated with each history marker</span>
$ git config --global user.email <span class="hljs-string">"your-email@example.com"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Email.png" alt="Email" width="600" height="400" loading="lazy"></p>
<p>Make sure to replace this with your actual email used in your GitHub account.</p>
<p>Now that we have finished setting up your username and email for Git and GitHub, let's verify that everything is configured correctly.</p>
<p>To do this, use the following command:</p>
<pre><code class="lang-bash">git config --global --list
</code></pre>
<p>This command will list the username and email being used in the console for you to see.</p>
<p>You should see some information displayed in your terminal.</p>
<h2 id="how-to-set-the-default-editor"> How to Set the Default Editor</h2>

<p>In modern development, having a code editor can significantly simplify your workflow, especially when you're focused on coding.</p>
<p>Now, let's see how to configure Git to use a default editor by using this command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Set the default editor for Git</span>
$ git config --global core.editor <span class="hljs-string">"code --wait"</span>
</code></pre>
<p><em>Congratulations!</em> You have successfully configured Git on your local machine. You are now ready to start using Git for your projects.</p>
<h2 id="how-to-create-a-repository-using-the-github-website">  How to Create a Repository Using the Github Website </h2>

<p>Creating a repository is the first step in using Git. A repository is a storage location where your projects live, containing all the files and revision history. </p>
<p>In this section, I will guide you through the process of creating a repository on GitHub. </p>
<p>There are two ways to create a repository: using the <code>GitHub website</code> or the command line. Let's get started. In this section, we'll focus on creating a repository using the GitHub website and the command line.</p>
<p>After logging into your GitHub account, you can create a new repository by following these steps:</p>
<ol>
<li>Click on the <code>+</code> sign in the top right corner of the page and select <code>New Repository</code> from the dropdown menu.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Github-create-repo.png" alt="Github-create-repo" width="600" height="400" loading="lazy"></p>
<p>Above is an image of the new repository button on GitHub.</p>
<ol start="2">
<li><p>You will be directed to a new page where you can fill in the details of your new repository. You will need to enter the following information:</p>
</li>
<li><p><code>Repository name</code>: This is the name of your repository. It should be unique and descriptive.</p>
</li>
<li><code>Description</code>: A brief description of your repository.</li>
<li><code>Public or Private</code>: You can choose to make your repository public or private. Public repositories are visible to everyone, while private repositories are only visible to you and the people you share them with.</li>
<li><code>Initialize</code> this repository with a README: You can choose to initialize your repository with a README file. This is useful if you want to provide information about your project or instructions on how to use it.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-repo-infor.png" alt="github-repo-infor" width="600" height="400" loading="lazy"></p>
<p>The image above shows the form where you'll fill in the details of your new repository.</p>
<ol start="3">
<li>Once you have filled in the details, click on the <code>Create Repository</code> button to create your new repository.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-create-repo-button.png" alt="github-create-repo-button" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Create Repository</code> button_.</p>
<p><em>Congratulations!</em> You have successfully created a new repository on GitHub. You can now start adding files and making changes to your repository.</p>
<p>You should see a page like the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-new-repo.png" alt="github-new-repo" width="600" height="400" loading="lazy"></p>
<p>Now let's create a repository using the command line.</p>
<h2 id="how-to-create-a-repository-using-the-git-command-line">  How to Create a Repository Using the Git Command Line </h2>


<p>To create a new <code>repository</code> using the command line, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory where you want to create your new repository.</p>
</li>
<li><p>Use the <code>git init</code> command to create a new repository. This command will create a new directory called <code>.git</code> in your current directory, which will contain all the necessary files for your repository.</p>
</li>
</ol>
<pre><code class="lang-bash">
<span class="hljs-comment"># initialize a new repository called my-project</span>

$ git init my-project
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-init.png" alt="terminal-init" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to initialize a new repository called <code>my-project</code>.</p>
<ol start="3">
<li>Once you have created your new repository, you can start adding files and making changes to it. You can also connect your local repository to a remote repository on GitHub by following the instructions provided on the GitHub website.</li>
</ol>
<p><em>Congratulations!</em> You have successfully created a new repository using the command line. </p>
<p>Now we have successfully created a repository using the GitHub website and the command line – but how do we connect them? Now let's learn how to connect a local repository to a remote repository on GitHub.</p>
<h2 id="how-to-connect-a-local-repository-to-a-remote-repository-on-github">  How to Connect a Local Repository to a Remote Repository on GitHub </h2>

<p>To connect your local repository to a remote repository on GitHub, you need to follow these steps:</p>
<ol>
<li><p>On GitHub, navigate to the main page of the repository you created earlier.</p>
</li>
<li><p>Click on the <code>Code</code> button to copy the URL of your repository.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Github-code-url-cope.png" alt="Github-code-url-cope" width="600" height="400" loading="lazy"></p>
<p>The image above shows the code button to copy the URL of your repository.</p>
<ol start="3">
<li><p>In your terminal, navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git remote add origin</code> command to connect your local repository to the remote repository on GitHub. Replace repository-URL with the URL of your repository.</p>
</li>
</ol>
<pre><code class="lang-bash">$ git remote add origin repository-url
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-remote-add-origin.png" alt="terminal-remote-add-origin" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to connect your local repository to the remote repository on GitHub.</p>
<ol start="5">
<li>Once you have connected your local repository to the remote repository on GitHub, you can start pushing your changes to the remote repository using the <code>git push</code> command.</li>
</ol>
<p><em>Congratulations!</em> You have successfully connected your local repository to the remote repository on GitHub.</p>
<h2 id="how-to-pull-changes-from-a-remote-repository-to-a-local-repository">   How to Pull Changes from a Remote Repository to a Local Repository </h2>

<p>To pull changes from the remote repository to the local repository, you need to follow these steps:</p>
<ol>
<li><p>In your terminal, navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git pull</code> command to pull changes from the remote repository to the local repository.</p>
</li>
</ol>
<pre><code class="lang-bash">
$ git pull origin main
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-git-pull.png" alt="terminal-git-pull" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to pull changes from the remote repository to the local repository.</p>
<p>After that, navigate the main branch by using the following command:</p>
<pre><code class="lang-bash">
$ git checkout main
</code></pre>
<p><em>Congratulations!</em> You have successfully pulled changes from a remote repository to a local repository. Your local repository is now up-to-date with the remote repository on GitHub*.</p>
<h2 id="how-to-work-with-git-commands"> How to Work with Git Commands </h2>

<p>In this section, we will cover some of the most commonly used Git commands and their functions. These commands will help you navigate your way through the Git workflow in your GitHub repository. Let's get started. </p>
<p>First, I will add some files so that we can start using the Git commands.</p>
<h2 id="how-to-make-changes-to-a-file"> How to Make Changes to a File </h2>

<p>To make changes to a file in Git, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory of your local repository.</p>
</li>
<li><p>Use a text editor to make changes to the file. For example, you can use the <code>code</code> command to open the file in Visual Studio Code.</p>
</li>
</ol>
<pre><code class="lang-bash">
$ code file-name  <span class="hljs-comment"># For example, code index.html</span>
</code></pre>
<ol start="3">
<li>Once you have made your changes, save the file and close the text editor.</li>
</ol>
<p><em>Congratulations!</em> You have successfully made changes to a file in your local repository. Next, let's proceed to the next step: staging changes.</p>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/file-cahnge-added.png" alt="file-cahnge-added" width="600" height="400" loading="lazy"></p>
<p>The image above shows the new file I added which is a React and TypeScript app.</p>
<p>Visual Studio Code (VS Code) includes a source control feature that allows you to interact directly with your GitHub repository. This feature supports a variety of operations, including staging, committing, pushing, and pulling changes. </p>
<p>In addition to the source control feature, you can also use the integrated terminal in VS Code to interact with your GitHub repository. </p>
<p>Currently, if you look at the source control section in VS Code, you'll see the file we added listed under changes. </p>
<p>Next, let's explore how to use the terminal to interact with our GitHub repository.</p>
<p>Open your terminal and navigate to the directory of your local repository.</p>
<p>Now, let's use the <code>git status</code> command to check the status of the current branch.</p>
<h2 id="how-to-check-the-status-of-the-current-branch">  How to Check the Status of the Current Branch </h2>

<p>The <code>git status</code> command shows the status of the current branch, including any changes that have been made to the files in the repository. It provides information about which files have been modified, which files have been staged, and which files are untracked. </p>
<p>This command is useful for understanding the current state of your repository and determining which files need to be staged and committed.</p>
<pre><code class="lang-bash"><span class="hljs-comment">#  Check the status of the current branch</span>

$ git status  <span class="hljs-comment"># On branch master</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/terminal-git-status.png" alt="terminal-git-status" width="600" height="400" loading="lazy"></p>
<p>The image above shows the command to check the status of the current branch.</p>
<p>You may notice that parts of the file are highlighted in different colors. The <code>red</code> color indicates that the file has been modified, while the <code>green</code> color signifies that the file has been added to the staging area. </p>
<p>Currently, all files should be highlighted in <code>red</code> because we have not yet added any files to the staging area.</p>
<p>Let's add the file to the staging area using the <code>git add</code> command.</p>
<h2 id="how-to-stage-changes">  How to Stage Changes </h2>

<p>The <code>git add</code> command adds files to the staging area, preparing them for the next commit. You can add all the files in the current directory to the staging area using the <code>git add .</code> command. </p>
<p>If you want to add a specific file, use the <code>git add &lt;file-name&gt;</code> command, replacing <code>&lt;file-name&gt;</code> with the name of your file. This process is known as staging, which prepares files for the next commit.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Add files to the staging area</span>

$ git add .  <span class="hljs-comment"># Changes to be committed:</span>

or 

$ git add file-name  <span class="hljs-comment"># Changes to be committed:</span>
</code></pre>
<p>Think of it like this: getting into the car is like adding files to the staging area, and driving the car is like making a commit. </p>
<p>Now, let's use the <code>git commit</code> command to commit the changes to the current branch.</p>
<h2 id="how-to-commit-changes">  How to Commit Changes </h2>

<p>The <code>git commit</code> command commits the changes to the current branch. You can use the <code>-m</code> flag to add a message to your commit. This message should provide a brief summary of the changes you've made.</p>
<p>For instance, "Initial commit" could be your commit message. This command is used to save the changes to the local repository.</p>
<pre><code class="lang-bash">

<span class="hljs-comment"># Commit changes to the current branch</span>

$ git commit -m <span class="hljs-string">"Commit message"</span>   <span class="hljs-comment"># For example, git commit -m "Initial commit"</span>
</code></pre>
<p>We've successfully committed the changes to the current branch. Next, we'll push these changes to the remote repository on GitHub using the <code>git push</code> command.</p>
<h2 id="how-to-push-changes-to-a-remote-repository">  How to Push Changes to a Remote Repository </h2>

<p>The <code>git push</code> command pushes changes from your local repository to a remote repository on GitHub. You can use the <code>git push</code> command to push changes from your local repository to the remote repository on GitHub. This process is essential for updating the remote repository with the changes you've made locally.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Push changes to a remote repository</span>

$ git push origin main  <span class="hljs-comment"># For example, git push origin master</span>
</code></pre>
<p><em>Congratulations!</em> You have successfully pushed your changes to the remote repository on GitHub. You can now view your changes on the GitHub website.  </p>
<p>Now that we've successfully pushed our changes to the remote repository on GitHub, let's proceed to the next step: creating a branch. </p>
<p>Depending on your PC environment, your local repository may have a default branch named either <code>main</code> or <code>master</code>. In this guide, we'll use <code>main</code> as the default branch name, aligning with GitHub's recent change from <code>master</code> to <code>main</code>.</p>
<p>Before we start adding files, let's ensure our local repository is up-to-date with the remote repository by pulling any changes. </p>
<p>If the term <code>branch</code> seems unfamiliar, don't worry. In the next section, we'll cover how to create a branch and how to pull changes from the remote repository to the local repository.</p>
<h2 id="how-to-create-a-branch">  How to Create a Branch </h2>

<p>Branching is a fundamental concept in Git. It allows you to diverge from the main line of development and continue working without impacting the main codebase. </p>
<p>In this section, I'll guide you through the process of creating a new branch using the <code>git branch</code> command. This command creates a new branch but does not switch to it. In the following steps, we'll also cover how to switch to your newly created branch using the <code>git checkout</code> command. Let's dive in.</p>
<p>To create a new branch, you need to follow these steps:</p>
<ol>
<li><p>Open your terminal and navigate to the directory of your local repository.</p>
</li>
<li><p>Use the <code>git branch</code> command to create a new branch. Replace <code>&lt;branch-name&gt;</code> with the name of your new branch.</p>
</li>
</ol>
<pre><code class="lang-bash">
<span class="hljs-comment"># Create a new branch</span>

$ git branch &lt;branch-name&gt;  <span class="hljs-comment"># For example, git branch feature-branch</span>
</code></pre>
<p>The <code>git branch</code> command creates a new branch but does not switch to it. To switch to your newly created branch, use the <code>git checkout</code> command.</p>
<pre><code class="lang-bash">
<span class="hljs-comment"># Switch to the newly created branch</span>

$ git checkout &lt;branch-name&gt;  <span class="hljs-comment"># For example, git checkout feature-branch</span>
</code></pre>
<p>The <code>git checkout</code> command is used to switch from one branch to another. Replace <code>&lt;branch-name&gt;</code> with the name of your new branch. In this case, we're switching to the <code>feature-branch</code> branch. But we if want to delete the branch, we can use the following command:</p>
<pre><code class="lang-bash">

<span class="hljs-comment"># Delete a branch</span>

$ git branch -d &lt;branch-name&gt;  <span class="hljs-comment"># For example, git branch -d feature-branch</span>
</code></pre>
<p>The <code>git branch -d</code> command is used to delete a branch. Replace <code>&lt;branch-name&gt;</code> with the name of the branch you want to delete. In this case, we're deleting the <code>feature-branch</code> branch.</p>
<p><em>Congratulations!</em> You have successfully created a new branch and switched to it. You can now start adding files and making changes to your new branch.</p>
<p>Now you know how to create GitHub repository, connect a local repository to a remote repository on GitHub, pull changes from a remote repository to a local repository, work with Git commands, and create a branch. </p>
<p>Let's proceed to the next section, where we'll cover how to create a pull request. This is a crucial step in the collaborative workflow, as it allows you to propose changes and request a review from other collaborators.</p>
 <h2 id="how-to-create-a-pull-request"> How to Create a Pull Request  </h2>

<p>A pull request is a proposal to merge changes from one branch into another. It's a widely-used method for creating and reviewing code. In this section, I'll guide you through the process of creating a pull request using the GitHub website. </p>
<p>For instance, let's say you have a branch named <code>feature-branch</code> and you want to merge it into the <code>main</code> branch. We'll walk you through how to create a pull request for this scenario. Let's get started.</p>
<p>First, let's make a change to our feature branch by adding a file to it:</p>
<pre><code class="lang-bash">
$ git checkout feature-branch
</code></pre>
<p>You should see something like this in your terminal:</p>
<pre><code class="lang-bash">
git checkout feature-branch
Switched to a new branch <span class="hljs-string">'feature-branch'</span>
branch <span class="hljs-string">'feature-branch'</span> <span class="hljs-built_in">set</span> up to track <span class="hljs-string">'origin/feature-branch'</span>.
</code></pre>
<p>Now, let's add a file to the feature branch. </p>
<pre><code class="lang-bash">
$ touch feature-branch-file.txt
</code></pre>
<p>After running the command, you should see a new file called <code>feature-branch-file.txt</code> in your directory.</p>
<p>The <code>touch</code> command is used to create a new file. Replace <code>feature-branch-file.txt</code> with the name of your file. In this case, we're creating a new file called <code>feature-branch-file.txt</code>.</p>
<p>Now, let's add some content to the file.</p>
<pre><code class="lang-bash">
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">"This is a file in the feature branch"</span> &gt;&gt; feature-branch-file.txt
</code></pre>
<p>This command adds the text "This is a file in the feature branch" to the <code>feature-branch-file.txt</code> file.</p>
<p>The <code>echo</code> command is used to add content to a file. In this case, we're adding the text "This is a file in the feature branch" to the <code>feature-branch-file.txt</code> file.</p>
<p>Now that we have some text in the file, let's stage and commit the changes to the feature branch.</p>
<pre><code class="lang-bash">
$ git add .
</code></pre>
<p>The <code>git add .</code> command stages all the changes in the current directory.</p>
<pre><code class="lang-bash">

$ git commit -m <span class="hljs-string">"Add file to feature branch"</span>
</code></pre>
<p>The <code>git commit -m</code> command commits the changes to the current branch. Replace <code>Add file to feature branch</code> with your own descriptive message. This message should provide a brief summary of the changes you've made. In this case, we're committing the changes to the feature branch.</p>
<p>Now, let's push the changes to the remote repository on GitHub.</p>
<pre><code class="lang-bash">
$ git push origin feature-branch
</code></pre>
<p>The <code>git push</code> command is used to push changes from your local repository to the remote repository on GitHub. Replace <code>feature-branch</code> with the name of your branch. In this case, we're pushing the changes to the <code>feature-branch</code> branch.</p>
<p><em>Congratulations!</em> You have successfully pushed your changes to the remote repository on GitHub. You can now view your changes on the GitHub website.</p>
<p>Now when you open your GitHub repository, you should see a message indicating that you recently pushed a new branch. You can click on the <code>Compare &amp; pull request</code> button to create a pull request for the <code>feature-branch</code> branch. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-compare-pull-request.png" alt="github-compare-pull-request" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Compare &amp; pull request</code> button on GitHub.</p>
<p>After clicking on the <code>Compare &amp; pull request</code> button, you will be directed to a new page where you can fill in the details of your pull request. </p>
<p>You will need to enter the following information:</p>
<ul>
<li>Title: a brief summary of your pull request.</li>
<li>Description: a detailed description of your pull request, including information about the changes you've made and why you've made them.</li>
<li>Reviewers: you can choose to request a review from specific collaborators.</li>
<li>Assignees: you can choose to assign your pull request to specific collaborators.</li>
<li>Labels: you can choose to add labels to your pull request to categorize it.</li>
<li>Projects: you can choose to add your pull request to a project board.</li>
<li>Milestone: you can choose to add your pull request to a milestone.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-form.png" alt="github-pull-request-form" width="600" height="400" loading="lazy"></p>
<p>The image above shows the form to fill in the details of your pull request.</p>
<p>You can decide to file the details of your pull request or create the pull request. After creating the pull request, you can view it on the GitHub website. You can also request a review from specific collaborators and make changes to your pull request if necessary. </p>
<p>Once your pull request has been reviewed and approved, you can merge it into the <code>main</code> branch. In our case we not going to file the form but we are going to create the pull request.</p>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-created.png" alt="github-pull-request-created" width="600" height="400" loading="lazy"></p>
<p>The image above shows the pull request created on GitHub.</p>
<p>Now that we have created a pull request, let's proceed to the next section, where we'll cover how to merge a pull request. This is the final step in the collaborative workflow, as it allows you to incorporate changes into the main codebase.</p>
<h2 id="how-to-merge-a-pull-request">How to Merge a Pull Requset  </h2>

<p>Merging a pull request signifies the integration of changes from one branch into another, often the main branch. This step is pivotal in collaborative workflows, enabling the assimilation of modifications into the primary codebase. </p>
<p>In this section, we'll navigate the process of merging a pull request via the GitHub website. </p>
<p>After creating a pull request, you can merge it into the <code>main</code> branch by following these steps:</p>
<ol>
<li><p>On GitHub, navigate to the main page of the repository where you created the pull request.</p>
</li>
<li><p>Click on the <code>Pull requests</code> tab to view the list of pull requests.</p>
</li>
</ol>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-tab.png" alt="github-pull-request-tab" width="600" height="400" loading="lazy"></p>
<p>The image above shows the <code>Pull requests</code> tab on GitHub.</p>
<ol start="3">
<li><p>Click on the pull request you want to merge.</p>
</li>
<li><p>Click on the <code>Merge pull request</code> button to merge the pull request into the <code>main</code> branch.</p>
</li>
<li><p>Click on the <code>Confirm merge</code> button to confirm the merge.</p>
</li>
</ol>
<p>After that you should see a message indicating that the pull request has been successfully merged. You can also delete the branch after merging the pull request.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/github-pull-request-merged.png" alt="github-pull-request-merged" width="600" height="400" loading="lazy"></p>
<p>Now you have successfully merged the pull request into the <code>main</code> branch. You can now delete the <code>feature-branch</code> branch, as it is no longer needed.  </p>
 <h2 id="wrapping-up"> Wrapping Up </h2>

<p>Throughout this guide, we've delved into the core concepts of Git and GitHub, equipping you with a robust understanding of version control and collaborative practices. </p>
<p>We've navigated the essential Git operations, including setting up a repository, linking the local repository to its remote counterpart on GitHub, synchronizing changes between the local and remote repositories, executing Git commands, branching, initiating pull requests, and merging those requests. </p>
<p>Mastering these principles will significantly enhance your coding workflow, facilitate seamless team collaboration, and enable meaningful contributions to open-source projects. </p>
<p>I trust that this guide has instilled in you the knowledge and confidence to excel in your programming journey and start contributing to open source projects. Here's to your success in coding!</p>
<p>You can contact me on <a target="_blank" href="https://twitter.com/Clifftech_Dev">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/isaiah-clifford-opoku/">LinkedIn</a> for any questions or feedback. I'd love to hear from you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Git Fundamentals – A Handbook on Day-to-Day Development Tasks ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development.  Whether you're a seasoned developer or just starting your journey in programming, und... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-git-basics/</link>
                <guid isPermaLink="false">66c7218e55df43f1418b5b2c</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Wed, 03 Apr 2024 03:57:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Learn-Git-Basics-Cover-3--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to my comprehensive guide on Git, the distributed version control system that has revolutionized collaboration and code management in software development. </p>
<p>Whether you're a seasoned developer or just starting your journey in programming, understanding Git is essential to gain proper control over your code, efficiently managing your projects and collaborating with others. </p>
<p>In this tutorial, I'll take you through the fundamentals of Git, covering everything from its basic workflow to advanced branching strategies and rebasing techniques. </p>
<p>By the end of this guide, you'll have a solid understanding of Git's core concepts and be confident and well equipped with the skills to effectively use it in your development workflow.</p>
<h2 id="heading-prerequisites">Prerequisites:</h2>
<p>All you need to bring to the table is a curious and eager-to-learn mindset. This guide is crafted with beginners in mind, so no prior knowledge of version control systems or programming is required. Whether you're a complete novice or have some experience with coding, you'll find this tutorial accessible and easy to follow.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents:</strong></h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-git">What is Git?</a><br>– <a class="post-section-overview" href="#heading-what-makes-git-different-from-other-version-control-systems">Difference from other version control systems</a><br>– <a class="post-section-overview" href="#heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</a></li>
<li><a class="post-section-overview" href="#heading-first-time-git-setup">First-Time Git Setup</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-help-in-git">Get Help in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-a-git-repository">How to Get a Git Repository</a><br>– <a class="post-section-overview" href="#heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">Initialize a Repository in an Existing Directory</a><br>– <a class="post-section-overview" href="#heading-2-how-to-clone-an-existing-repository-in-git">Clone an Existing Repository in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</a></li>
<li><a class="post-section-overview" href="#heading-how-to-view-commit-history-in-git">View Commit History in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-undo-things-in-git">Undo Things in Git</a></li>
<li><a class="post-section-overview" href="#how-to-work-with-remote-repositories-in-git">Remote Repositories in Git</a></li>
<li><a class="post-section-overview" href="#heading-tagging-in-git">Tagging in Git</a></li>
<li><a class="post-section-overview" href="#heading-git-aliases">Git Aliases</a></li>
<li><a class="post-section-overview" href="#heading-git-branching">Git Branching</a><br>– <a class="post-section-overview" href="#heading-how-to-create-a-new-branch-in-git">Create a New Branch in Git</a><br>– <a class="post-section-overview" href="#heading-understanding-branches">Understanding Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-switch-to-another-branch-in-git">Switch to Another Branch in Git</a><br>– <a class="post-section-overview" href="#how-to-visualise-branches-in-git-">Visualise Branches in Git</a></li>
<li><a class="post-section-overview" href="#heading-how-to-manage-branches-in-git">How to Manage Branches in Git</a><br>– <a class="post-section-overview" href="#heading-how-to-manage-merged-branches">Managing Merged Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-rename-branches">Renaming Branches</a><br>– <a class="post-section-overview" href="#heading-how-to-change-the-default-branch-name">Changing the Default Branch Name</a></li>
<li><a class="post-section-overview" href="#heading-branching-workflow">Branching Workflow</a></li>
<li><a class="post-section-overview" href="#heading-rebasing-in-git">Rebasing in Git</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-git">What is Git?</h2>
<p>Git is a distributed version control system that helps you and your team collaborate effectively while keeping your project's history safe. It's like having a time machine for your code!</p>
<h3 id="heading-what-makes-git-different-from-other-version-control-systems">What makes Git different from other Version Control Systems?</h3>
<h4 id="heading-conceptual-difference">Conceptual Difference:</h4>
<p>The big thing that sets Git apart from other tools is how it thinks about data. Instead of storing changes to files, Git thinks of its data as a series of snapshots of your project, means, every time you make a change and save it (commit), Git takes a snapshot of all your files at that moment. If a file hasn't changed, Git just keeps a link to the previous identical file.</p>
<h4 id="heading-local-operations">Local Operations:</h4>
<p>With Git, most things you do don't need a connection to a server. Because you have the entire project history on your computer, operations are super fast. You can browse project history or see changes between versions without waiting for a server.</p>
<h4 id="heading-data-integrity">Data Integrity:</h4>
<p>Git makes sure nothing gets lost or corrupted. Every file and directory is checksummed, and Git knows if anything changes. </p>
<p>Git uses a SHA-1 hash, a unique code for each version of a file. If any changes are made to the content, even a single character, it will result in a different SHA-1 hash.</p>
<h4 id="heading-append-only-model">Append-Only Model:</h4>
<p>In Git, almost everything adds data to the project, making it hard to accidentally lose information. Once you commit changes, they are safely stored. Experimenting is less risky with Git.</p>
<h3 id="heading-the-three-states-and-basic-git-workflow">The Three States and Basic Git Workflow</h3>
<p>Understanding Git's three states—modified, staged, and committed—is essential for effective version control:</p>
<ul>
<li><strong>Modified</strong>: Changes made to files in your <strong>Working tree</strong> that are not yet committed.</li>
<li><strong>Staged</strong>: Modifications marked for the next commit in the <strong>Staging area</strong> to be included in next commit.</li>
<li><strong>Committed</strong>: Changes permanently stored in the local <strong>Git directory</strong>.</li>
</ul>
<p><strong>Basic Git Workflow</strong>:</p>
<ol>
<li><strong>Modify files</strong> in your working tree.</li>
<li><strong>Stage changes</strong> you want to include in the next commit.</li>
<li><strong>Commit changes</strong>, which permanently saves snapshots to the Git directory.</li>
</ol>
<h2 id="heading-first-time-git-setup">First-Time Git Setup</h2>
<p>Setting up Git for the first time involves customizing your Git environment to suit your preferences. But first, you'll need to download Git from <a target="_blank" href="https://git-scm.com/download/win">Git - Downloads</a> or use the Chocolatey package. Then just follow the installation instructions and you should be good to go.</p>
<h3 id="heading-git-configuration">Git Configuration</h3>
<p>We use the <code>git config</code> tool to customize our Git environment. This tool allows us to both retrieve and set configuration variables that dictate how Git operates. These variables can be stored in three different locations:</p>
<ol>
<li><strong>System-wide Configuration:</strong><br>Stored in the <code>/etc/gitconfig</code> file, these settings apply to all users on the system and all repositories. We can interact with this file using the <code>--system</code> option with <code>git config</code>.</li>
<li><strong>User-specific Configuration:</strong><br>Stored in <code>~/.gitconfig</code> or <code>~/.config/git/config</code>, these values are specific to you as a user. We can interact with this file using the <code>--global</code> option with <code>git config</code>, affecting all repositories you work with on your system.</li>
<li><strong>Repository-specific Configuration:</strong><br>Stored in the <code>.git/config</code> file within a specific repository, these settings override global configurations and apply only to that repository.</li>
</ol>
<p>Each level of configuration overrides values from the previous level. For instance, values in <code>.git/config</code> will override those in <code>~/.gitconfig</code>.</p>
<p>To view all configuration settings and their sources/origins:</p>
<pre><code class="lang-bash">$ git config --list --show-origin
</code></pre>
<h4 id="heading-how-to-configure-your-identity-in-git">How to Configure your identity in Git:</h4>
<p>Identity in Git is used for attributing commits properly. Let's set up your user name and email address.</p>
<pre><code class="lang-bash">$ git config --global user.name <span class="hljs-string">"Your Name"</span>
$ git config --global user.email <span class="hljs-string">"your.email@example.com"</span>
</code></pre>
<p>If you need to override this for specific projects, you can omit the <code>--global</code> option when setting the values, and they'll only apply to that particular repository.</p>
<h4 id="heading-how-to-configure-your-default-text-editor">How to Configure Your Default Text Editor</h4>
<p>After configuring your identity, it's important to set up your default text editor in Git. This text editor will be used when Git needs you to input messages, such as when writing commit messages or resolving merge conflicts.</p>
<p>By default, Git uses your system's default text editor. However, if you prefer to use a different text editor, such as Emacs, you can set it up like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"emacs"</span>
</code></pre>
<p>On Windows systems, setting up a different text editor requires specifying the full path to its executable file. For example, if you want to use Notepad++, you might use a command like this:</p>
<pre><code class="lang-bash">$ git config --global core.editor <span class="hljs-string">"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"</span>
</code></pre>
<p>Make sure you provide the correct path to the executable file of your text editor.</p>
<p>By the way, these – <code>"-multiInst -notabbar -nosession -noPlugin"</code> – are options used to customize the behavior of Notepad++ when it is launched by Git.</p>
<h4 id="heading-how-to-change-default-branch-name-in-git-optional">How to Change default branch name in Git (optional):</h4>
<p>By default, when you initialize a new repository with <code>git init</code>, Git creates a branch named <code>master</code>. But from Git version 2.28 onwards, you have the option to set a different name for the initial branch.</p>
<pre><code class="lang-bash">$ git config --global init.defaultBranch main
</code></pre>
<h4 id="heading-how-to-check-configurationsettings-in-git">How to Check Configuration/settings in Git:</h4>
<p>You can view your Git configuration using:</p>
<pre><code class="lang-bash">$ git config --list
$ git config user.name  <span class="hljs-comment"># To check a specific setting (e.g., user name):</span>
</code></pre>
<p>The <code>git config --list</code> command lists all the configuration settings Git can find at that moment.</p>
<h2 id="heading-how-to-get-help-in-git">How to Get Help in Git</h2>
<p>There are three equivalent ways to get detailed help for any Git command:</p>
<ol>
<li>Git Help Command: <code>$ git help &lt;verb&gt;</code></li>
<li>Using the <code>--help</code> Option: <code>$ git &lt;verb&gt; --help</code></li>
<li>Manual pages (manpages): <code>$ man git-&lt;verb&gt;</code></li>
</ol>
<p>Replace the <code>&lt;verb&gt;</code> with whatever command you need help with. For example, to get help for the <code>config</code> command, you can type:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">help</span> config
or
$ man git-config
</code></pre>
<p>These commands work offline as well, which is handy.</p>
<p>If you need quick, concise information about the available options for a Git command, you can use the <code>-h</code> option:</p>
<pre><code class="lang-bash">$ git add -h    <span class="hljs-comment"># This will display options available for the add command</span>
</code></pre>
<h2 id="heading-how-to-get-a-git-repository">How to Get a Git Repository</h2>
<p>To start using Git, you typically obtain a Git repository. There are essentially two main ways to get started:</p>
<h3 id="heading-1-how-to-initialize-a-repository-in-an-existing-directory-in-git">1. How to Initialize a Repository in an Existing Directory in Git</h3>
<p>Open a terminal or command prompt. Use the <code>cd</code> command to change the directory to your project's location: <code>cd /path/to/your/project</code>.</p>
<p>Once you're in your project directory, initialize a Git repository by running:</p>
<pre><code class="lang-bash">$ git init
</code></pre>
<p>This command creates a new subdirectory named <code>.git</code> where Git stores all the necessary files for your Git repository. At this point, none of your project files are being tracked yet.</p>
<p>Now, Suppose you have certain files that you want Git to start tracking:</p>
<pre><code class="lang-bash">$ git add *.py        <span class="hljs-comment"># Add all Python files</span>
$ git add README.md   <span class="hljs-comment"># Add README file</span>
$ git commit -m <span class="hljs-string">'Initial commit'</span>
</code></pre>
<p><code>git add</code> adds files to the staging area indicating that you want to include them in the next commit, and then commit the changes. The <code>-m</code> flag allows you to add a descriptive message to the commit.</p>
<h3 id="heading-2-how-to-clone-an-existing-repository-in-git">2. How to Clone an Existing Repository in Git:</h3>
<p>The second way to obtain a Git repository is by cloning an existing one. This is useful when you want to work on a project that already exists elsewhere (for example, a project you'd like to contribute to).</p>
<p><strong>Note:</strong> When you clone a repository, Git retrieves a full copy of nearly all data that the server has. This includes every version of every file for the history of the project. This means you'll have a complete copy of the repository's history on your local machine.</p>
<p>To clone a repo, Use the <code>git clone</code> command followed by the URL of the repo you want to clone. For example, to clone the grok-1 repository, you can use:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git
</code></pre>
<p>This creates a directory named grok-1, initializes a <code>.git</code> directory inside it, and pulls down all the data for that repository.</p>
<p>BTW, <code>.git</code> is just a convention to signify that the URL points to a Git repository. You can use it or not, it doesn't matter.</p>
<p>If you want to clone into a directory with a different name, you can specify it. To clone the grok-1 repo into a directory named "chatgpt" instead of "grok-1", do this:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/xai-org/grok-1.git chatgpt
</code></pre>
<p>Git provides various transfer protocols you can use for cloning repos. The example above uses the <code>https://</code> protocol, but you may also see <code>git://</code> or <code>user@server:path/to/repo.git</code>, which uses the SSH transfer protocol.</p>
<h2 id="heading-how-to-record-changes-to-the-repository">How to Record Changes to the Repository</h2>
<p>Now that you have a Git repository set up, you'll often need to make changes and record those changes in your repository. The process involves tracking files, staging changes, and committing snapshots. Let's explore the steps involved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/lifecycle.png" alt="Image" width="600" height="400" loading="lazy">
<em>pic credit - https://git-scm.com/</em></p>
<h3 id="heading-1-how-to-check-the-status-of-your-files-in-git">1. How to Check the Status of Your Files in Git:</h3>
<p>When working with a Git repository, it's crucial to understand the status of your files. </p>
<p>Git categorizes files into two types: tracked and untracked. Tracked files are those that Git recognizes, either because they were part of the last snapshot (commit) or have been staged. Untracked files are everything else—files that Git is not currently monitoring. To check the status of your repository:</p>
<pre><code class="lang-bash">$ git status
</code></pre>
<p>This command provides comprehensive information about the current branch, its synchronization status, and the status of your files. </p>
<p><code>git status</code> also suggests actions you can take. For instance, when files are modified but not staged for commit, <code>git status</code> suggests using <code>git add &lt;file&gt;</code> to stage them. It also suggests using <code>git checkout -- &lt;file&gt;</code> to discard changes in the working directory. These suggestions streamline your workflow by providing quick access to relevant Git commands.</p>
<p>Also, <code>git status</code> offers a Short Status mode (<code>git status -s</code>), which presents a more concise view of your changes using symbols like M (modified), A (added), and ?? (untracked) to represent file statuses.</p>
<h3 id="heading-2-how-to-track-new-files-in-git">2. How to Track New Files in Git</h3>
<p>When you create a new file in your project, Git initially considers it untracked. To start tracking a new file, you need to add it to the staging area using the <code>git add</code> command.</p>
<p>For instance, let's create a new file called <code>index.html</code> for our project and add it to the staging area:</p>
<pre><code class="lang-bash">$ touch index.html
$ git add index.html
</code></pre>
<p>After adding, running <code>git status</code> again will show that the <code>index.html</code> file is now tracked and staged for commit.</p>
<h3 id="heading-3-how-to-stage-modified-files-in-git">3. How to Stage Modified Files in Git</h3>
<p>If you modify an existing tracked file, you need to stage the changes using <code>git add</code>. Let's say we modify an existing file called <code>styles.css</code></p>
<pre><code class="lang-bash">$ vim styles.css
</code></pre>
<p>After making changes, stage the file:</p>
<pre><code class="lang-bash">$ git add styles.css
</code></pre>
<p>Now, when you check the status, you'll see both the modified file and the new file staged for commit.</p>
<h3 id="heading-4-how-to-ignore-files-in-git">4. How to Ignore Files in Git</h3>
<p>Often, there are files or directories within a project that aren't intended for Git tracking. These might include log files, build artifacts, or sensitive information like local environment settings (such as *.env or config.json). You can specify these files to be ignored using a <code>.gitignore</code> file.</p>
<p>Create a <code>.gitignore</code> file :</p>
<pre><code class="lang-bash">$ nano .gitignore
</code></pre>
<p>List the patterns of files or directories you want to ignore.:</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'*.log'</span> &gt;&gt; .gitignore
$ <span class="hljs-built_in">echo</span> <span class="hljs-string">'build/'</span> &gt;&gt; .gitignore
</code></pre>
<p>Here, we're telling Git to ignore all files with a <code>.log</code> extension and the <code>build/</code> directory.</p>
<p><strong>Note:</strong> Files already tracked by Git before being added to the <code>.gitignore</code> file will remain tracked. To remove them, you'll need to manually untrack them using Git commands. </p>
<p>Here are some patterns you can use to work more effectively in Git.</p>
<ul>
<li><strong>Target individual files or file extensions precisely:</strong> For example, <code>test.txt</code> ignores only that specific file, while <code>*.log</code> ignores all files ending with <code>.log</code>.</li>
<li><strong>Wildcards for broader matches:</strong> The asterisk (<code>*</code>) wildcard matches any number of characters. For example, <code>*.doc</code> ignores all files with the <code>.doc</code> extension, regardless of their name.</li>
</ul>
<h3 id="heading-5-how-to-view-changes-in-git">5. How to View Changes in Git:</h3>
<p>If you want to see the exact changes you've made to your files before committing, you can use the <code>git diff</code> command.</p>
<p>To see unstaged changes:</p>
<pre><code class="lang-bash">$ git diff
</code></pre>
<p>And to see staged changes:</p>
<pre><code class="lang-bash">$ git diff --cached README.md
</code></pre>
<p><code>git diff</code> provides a detailed view of the actual modifications. Use <code>git diff &lt;filename&gt;</code> to focus on changes within a particular file.</p>
<h3 id="heading-6-how-to-commit-changes">6. How to Commit Changes:</h3>
<p>When you are ready to commit your changes, use the <code>git commit</code> command. This opens your text editor for you to provide a commit message. Alternatively, you can use the <code>-m</code> flag to add a commit message directly:</p>
<p>Once you have staged the changes you want to include in the commit, you can commit them using <code>git commit</code></p>
<pre><code class="lang-bash">$ git commit -m <span class="hljs-string">"Your commit message here"</span>
</code></pre>
<h3 id="heading-7-how-to-remove-files-in-git">7. How to Remove Files in Git:</h3>
<p>If you need to remove a file from Git's tracking, you can use <code>git rm</code>. It remove the file from both the repository and working directory. Suppose you want to remove a file named <code>temp.txt</code>:</p>
<pre><code class="lang-bash">$ git rm temp.txt
</code></pre>
<p>If you only want to remove it from the repository but keep it in the working directory, use the <code>--cached</code> option:</p>
<pre><code class="lang-bash">$ git rm --cached temp.txt
</code></pre>
<h3 id="heading-8-how-to-move-or-rename-files-in-git">8. How to Move (or Rename) Files in Git:</h3>
<p>Git doesn't explicitly track file movements. But you can use <code>git mv</code> to rename or move files within your repository. For example, to rename <code>old_file.txt</code> to <code>new_file.txt</code>:</p>
<pre><code class="lang-bash">$ git mv old_file.txt new_file.txt
</code></pre>
<p>It is equivalent to manually moving the file, followed by using <code>git rm</code> to remove the old file, and then <code>git add</code> to add the new file. <code>git mv</code> basically consolidates these steps into a single command.</p>
<p>These commands form the basic workflow for making changes, staging them, and committing them to your Git repository.</p>
<h2 id="heading-how-to-view-commit-history-in-git">How to View Commit History in Git</h2>
<p>After creating multiple commits or cloning a repository, the <code>git log</code> command allows you to examine the commit history. </p>
<p>By default, it lists commits in reverse chronological order, displaying each commit with its SHA-1 checksum, author's name and email, date, and commit message.<br>Now let's see how can we enhance this output:</p>
<h3 id="heading-how-to-view-commit-differences-in-git">How to View Commit Differences in Git:</h3>
<p>To view the difference introduced in each commit, you can use the <code>-p</code> or <code>--patch</code> option:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> -p -2    <span class="hljs-comment"># -2 is used to view the differences introduced in each of the last two commits</span>
</code></pre>
<h3 id="heading-how-to-display-statistics-in-git">How to Display Statistics in Git:</h3>
<p>The <code>--stat</code> option provides summarized statistics for each commit, including the modified files, lines added/deleted, and a summary.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --<span class="hljs-built_in">stat</span>
</code></pre>
<h3 id="heading-how-to-customize-git-log-output-format">How to Customize Git Log Output Format:</h3>
<p>The <code>--pretty</code> option allows you to alter the log output format. Various options are available for different formats:</p>
<ul>
<li><code>oneline</code>: Concise, single-line summary of each commit. </li>
<li><code>short</code>: Default format with author, date, and message. </li>
<li><code>full</code>: Detailed format with commit hash, author, date, message, and diff.</li>
<li><code>fuller</code>: More detailed format, including full file paths. </li>
<li><code>format</code>: Customize the output using format specifiers.</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=oneline
</code></pre>
<p><strong>Useful format specifiers for</strong> <code>--pretty=format</code>:</p>
<ul>
<li><code>%h:</code> Abbreviated commit hash</li>
<li><code>%an:</code> Author name</li>
<li><code>%ae:</code> Author email</li>
<li><code>%ad:</code> Author date</li>
<li><code>%s:</code> Subject (commit message)</li>
</ul>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %an %ad %s"</span>
</code></pre>
<p><strong>ASCII Graph</strong>:</p>
<p>Using <code>--graph</code>, you can also visualize branch and merge history.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --pretty=format:<span class="hljs-string">"%h %s"</span> --graph
</code></pre>
<h3 id="heading-how-to-limit-git-log-output">How to Limit Git Log Output:</h3>
<p>In addition to formatting options, <code>git log</code> offers various limiting options to refine the displayed commit history.</p>
<ul>
<li><code>-&lt;n&gt;:</code> Shows only the last n commits.</li>
<li><code>--since, --until:</code> Limits commits to those made after/before the specified date.</li>
<li><code>--author:</code> Shows commits only by a specific author.</li>
<li><code>--grep:</code> Filters commits by a keyword in the commit messages.</li>
<li><code>-S:</code> Shows commits changing</li>
</ul>
<p><strong>Example Usage:</strong> View the last 3 commits by author Abbey since a certain date, with patch details:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --author=<span class="hljs-string">"Abbey"</span> --since=<span class="hljs-string">"2024-01-01"</span> -p -3
</code></pre>
<h2 id="heading-how-to-undo-things-in-git">How to Undo Things in Git</h2>
<p>Undoing changes is a common need in Git, and several options are available for this purpose.</p>
<h3 id="heading-how-to-undo-a-commit-in-git">How to Undo a Commit in Git</h3>
<p>If you've committed too early or need to make additional changes to the last commit, use this command:</p>
<pre><code class="lang-bash">$ git commit --amend
</code></pre>
<p>This opens the commit message editor allowing you to modify the message. If no changes were made since the last commit, it simply allows you to edit the commit message.</p>
<p><strong>Note</strong>: Only amend commits that are still local and haven't been pushed yet to avoid issues for collaborators.</p>
<h3 id="heading-how-to-unstage-a-staged-file-with-git-reset">How to Unstage a Staged File with <code>git reset</code></h3>
<p>To unstage a file that was accidentally included, you can use the <code>git reset HEAD &lt;file&gt;</code> command. For example:</p>
<pre><code class="lang-bash">$ git reset HEAD CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, allowing you to make further changes without committing the unintended ones.</p>
<h3 id="heading-how-to-unmodify-a-modified-file-with-git-checkout">How to Unmodify a Modified File with <code>git checkout</code></h3>
<p>Suppose you made some modifications to files that you later realize you don't want to keep. Use <code>git checkout -- &lt;file&gt;</code> to discard the changes made to a file and revert it back to its previous state.</p>
<pre><code class="lang-bash">$ git checkout -- CONTRIBUTING.md
</code></pre>
<p>This will replace the modified file with the last staged or committed version. </p>
<h3 id="heading-undoing-things-with-git-restore">Undoing Things with <code>git restore</code></h3>
<p>Let's explore the alternatives introduced by Git version 2.23.0, <code>git restore</code>, which serves as an alternative to <code>git reset</code> for many undo operations.</p>
<h4 id="heading-how-to-unstage-a-staged-file-with-git-restore">How to unstage a staged file with <code>git restore</code></h4>
<p>If you accidentally stage a file that you didn't intend to commit, you can use <code>git restore --staged &lt;file&gt;</code> to unstage it.</p>
<pre><code class="lang-bash">$ git restore --staged CONTRIBUTING.md
</code></pre>
<p>The file is unstaged, similar to <code>git reset HEAD &lt;file&gt;</code>, allowing you to make further changes without committing the unintended ones.</p>
<h4 id="heading-how-to-unmodify-a-modified-file-with-git-restore">How to unmodify a modified file with <code>git restore</code></h4>
<p>To discard changes made to a file in the working directory, use <code>git restore &lt;file&gt;</code>:</p>
<pre><code class="lang-bash">$ git restore CONTRIBUTING.md
</code></pre>
<p>Similar to <code>git checkout -- &lt;file&gt;</code>, this command discard the changes made to the specified file, reverting it back to the state it was in at the last commit.</p>
<p><strong>Important Note:</strong> Use commands like <code>git reset</code>, <code>git checkout --</code>,<code>git restore</code> cautiously as they can discard local changes permanently. Use these commands when you're certain that the changes are not needed and you don't have any unsaved local changes. </p>
<p><strong>Alternatives:</strong> Stashing and branching are alternative methods to temporarily set aside changes without discarding them entirely. These methods are safer if you're unsure about discarding changes.</p>
<h2 id="heading-how-to-work-with-remotes-in-git">How to Work with Remotes in Git</h2>
<p>Remote repositories are versions of your project hosted on the internet or a network. Collaborating with others involves managing these remote repositories, including adding, removing, and inspecting them. Let's learn how to manage them effectively.</p>
<h3 id="heading-how-to-show-your-remotes-in-git">How to Show Your Remotes in Git</h3>
<p>To start, let's see which remote servers are configured for our project using:</p>
<pre><code class="lang-bash">$ git remote
</code></pre>
<p>This command lists the shortnames of all remote handles we've specified. For instance, if we've cloned a repository, we'll typically see <code>origin</code>, the default name Git assigns to the server we cloned from.</p>
<p>Adding the <code>-v</code> option provides additional details, such as the URLs associated with each remote.</p>
<pre><code class="lang-bash">$ git remote -v
</code></pre>
<p>This displays both the fetch and push URLs for each remote, allowing us to understand where our project is hosted and how we interact with it.</p>
<h3 id="heading-how-to-add-remote-repositories-in-git">How to Add Remote Repositories in Git</h3>
<p>To explicitly add a new remote repository, use <code>git remote add &lt;shortname&gt; &lt;url&gt;</code>:</p>
<pre><code class="lang-bash">$ git remote add example https://github.com/example/example.git
</code></pre>
<p>Here, we've added a remote named <code>example</code> with the specified URL. This allows us to reference this remote repository using the shortname <code>example</code> in our commands.</p>
<h3 id="heading-how-to-fetch-and-pull-from-remotes-in-git">How to Fetch and Pull from Remotes in Git</h3>
<p>To fetch data from a remote repository, we use the <code>git fetch</code> command followed by the remote name:</p>
<pre><code class="lang-bash">$ git fetch origin // Here we are not specifying any particular branch.
</code></pre>
<p>It downloads any new changes from the <code>origin</code> remote repository to our local repository, allowing us to stay up-to-date with the latest developments. </p>
<p>Alternatively, if we want to fetch and merge changes from a remote branch into our current branch in a single step, we use the <code>git pull</code> command:</p>
<pre><code class="lang-bash">$ git pull origin master
</code></pre>
<p>Here, we're specifically pulling changes from the <code>master</code> branch of the <code>origin</code> remote repository into our current branch.</p>
<h3 id="heading-how-to-push-changes-to-remotes-in-git">How to Push Changes to Remotes in Git</h3>
<p>To share our work with others, we push our changes to a remote repository using:</p>
<pre><code class="lang-bash">$ git push origin main
</code></pre>
<p>In this example, we're pushing our local changes to the <code>main</code> branch of the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-inspect-a-remote-in-git">How to Inspect a Remote in Git</h3>
<p>Lastly, we can inspect a remote repository to gather more information about it using:</p>
<pre><code class="lang-bash">$ git remote show origin
</code></pre>
<p>This command displays details such as the fetch and push URLs, the tracked branches, and local branch configurations associated with the <code>origin</code> remote repository.</p>
<h3 id="heading-how-to-rename-remotes-in-git">How to Rename Remotes in Git</h3>
<p>Now Suppose we want to rename a remote's shortname from <code>example</code> to <code>new-example</code>:</p>
<pre><code class="lang-bash">$ git remote rename example new-example
</code></pre>
<h3 id="heading-how-to-remove-remotes-in-git">How to Remove Remotes in Git</h3>
<p>If, for some reason, we no longer need a remote repository and want to remove it from our project:</p>
<pre><code class="lang-bash">$ git remote remove new-example
or
$ git remote rm new-example
</code></pre>
<p>After removal, the remote-tracking branches and associated configuration settings are also deleted.</p>
<h2 id="heading-tagging-in-git">Tagging in Git</h2>
<p>Tagging in Git is a fundamental feature allowing developers to mark specific points in a repository's history as significant. Typically, tags are used to denote release points, such as v1.0, v2.0, and so forth.</p>
<h3 id="heading-how-to-list-existing-tags-in-git">How to List Existing Tags in Git</h3>
<p>Imagine you're working on a project with multiple release versions. To list existing tags:</p>
<pre><code class="lang-bash">$ git tag
</code></pre>
<p>Also, you can search for tags matching a specific pattern using the <code>-l</code> or <code>--list</code> option. For Example:</p>
<pre><code class="lang-bash">$ git tag -l <span class="hljs-string">"v2.0*"</span>
</code></pre>
<p>This command will list tags like <code>v2.0</code>, <code>v2.0-beta</code>, and so on, matching the specified pattern.</p>
<h3 id="heading-how-to-create-tags-in-git">How to Create Tags in Git</h3>
<p>Git supports two types of tags: lightweight and annotated.</p>
<h4 id="heading-lightweight-tags">Lightweight Tags</h4>
<p>Use lightweight tags when you want to mark a specific commit without adding any additional information. Example:</p>
<pre><code class="lang-bash">$ git tag v1.1-lw
</code></pre>
<p>To view commit information associated with this tag, use:</p>
<pre><code class="lang-bash">$ git show v1.1-lw
</code></pre>
<h4 id="heading-annotated-tags">Annotated Tags</h4>
<p>Annotated tags, on the other hand, contain additional info such as tagger information, date, and a tagging message.</p>
<p>Creating an annotated tag involves using the <code>-a</code> option with the <code>git tag</code> command, along with a tagging message. e.g:</p>
<pre><code class="lang-bash">$ git tag -a v2.0 -m <span class="hljs-string">"Release version 2.0"</span>
</code></pre>
<p>To view detailed information about this tag, including the commit it points to and the tagging message, use:</p>
<pre><code class="lang-bash">$ git show v2.0
</code></pre>
<h3 id="heading-how-to-tag-an-older-commit-in-git">How to tag an older commit in Git</h3>
<p>Sometimes, you might forget to tag a specific commit. Not to worry, you can tag it later by specifying the commit checksum</p>
<p>Example: suppose you forgot to tag a commit with ID <code>abcdefg</code>. You can tag it as follows:</p>
<pre><code class="lang-bash">$ git tag -a v1.2 abcdefg
</code></pre>
<h4 id="heading-how-to-push-tag-to-a-remote-repo-in-git">How to Push Tag to a Remote repo in Git</h4>
<p>To push a specific tag to a remote server, you can use:</p>
<pre><code class="lang-bash">$ git push origin &lt;tagname&gt;
</code></pre>
<p>If you have multiple tags and want to push them all at once, you can use the <code>--tags</code> option:</p>
<pre><code class="lang-bash">$ git push origin --tags
</code></pre>
<h4 id="heading-how-to-delete-tags-in-git">How to Delete Tags in Git</h4>
<p>To delete a tag locally (removing from local repo):</p>
<pre><code class="lang-bash">$ git tag -d &lt;tagname&gt;
</code></pre>
<p>For Example, to delete a lightweight tag named <code>v1.4-lw</code>:</p>
<pre><code class="lang-bash">$ git tag -d v1.4-lw
</code></pre>
<p>On the other hand, you can delete a tag from a remote server in two ways:</p>
<ol>
<li>Using the <code>git push</code> command with a refspec:</li>
</ol>
<pre><code class="lang-bash">$ git push origin :refs/tags/v1.1-lw
</code></pre>
<ol start="2">
<li>Using the <code>--delete</code> option with <code>git push</code>:</li>
</ol>
<pre><code class="lang-bash">$ git push origin --delete v1.1-lw
</code></pre>
<h4 id="heading-how-to-check-out-tags-in-git">How to Check Out Tags in Git</h4>
<p>To view the state of files at a specific tag, you can check out that tag:</p>
<pre><code class="lang-bash">$ git checkout v2.0
</code></pre>
<p>This command puts your repository in a "detached HEAD" state, where you can view files but cannot make changes directly.</p>
<p>If you need to work on files at that tag, it's better to create a new branch:</p>
<pre><code class="lang-bash">$ git checkout -b v2.0-branch v2.0
</code></pre>
<p>Now you can make changes and commits without altering the original tag.</p>
<h2 id="heading-git-aliases">Git Aliases</h2>
<p>Git aliases are shortcuts or custom commands that you can create to simplify and streamline your Git workflow.  </p>
<p>To create a Git alias, you use the <code>git config</code> command with the <code>--global</code> flag to make the alias available across all your Git repositories. </p>
<h3 id="heading-basic-aliases-for-common-commands">Basic Aliases for Common Commands</h3>
<p>You can create aliases for frequently used Git commands to make them easier to remember and type. For example:</p>
<pre><code class="lang-bash">$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
</code></pre>
<p>Now, instead of typing out the full commands, you can use shorter aliases like <code>git co</code>, <code>git br</code>, and <code>git ci</code> respectively.</p>
<p>You can also <strong>create custom aliases for actions you frequently perform</strong> or for improving command readability. Example:</p>
<pre><code class="lang-bash">$ git config --global alias.unstage <span class="hljs-string">'reset HEAD --'</span>
</code></pre>
<p>Now, you can use <code>git unstage &lt;file&gt;</code> instead of <code>git reset HEAD -- &lt;file&gt;</code> to unstage a file.</p>
<h4 id="heading-how-to-combine-multiple-commands-in-git">How to Combine Multiple Commands in Git</h4>
<p>Aliases can also be used to combine multiple Git commands into a single alias. For example, let's create an alias to stage all changes and then commit them with a single command:</p>
<pre><code class="lang-bash">$ git config --global alias.commitall <span class="hljs-string">'!git add -A &amp;&amp; git commit'</span>
</code></pre>
<p>Now, running <code>git commitall</code> will stage all changes (<code>git add -A</code>) and then commit them, saving you time and keystrokes.</p>
<h2 id="heading-git-branching">Git Branching</h2>
<p>Branches in Git provide a powerful way to manage your project's codebase, allowing for parallel development and experimentation without affecting the main codebase.</p>
<p>Git branching allows you to diverge from the main line of development, work on features or fixes, and then merge your changes back. Unlike many other version control systems, Git's branching model is lightweight and efficient, making branching operations nearly instantaneous.</p>
<h3 id="heading-what-are-branches-in-git">What are Branches in Git?</h3>
<p>A branch is a lightweight, movable pointer to a commit. The default branch name is often "master," but it's not special – it's like any other branch.</p>
<p>Creating and switching between branches allows you to work on different features simultaneously.</p>
<h3 id="heading-how-to-create-a-new-branch-in-git">How to Create a New Branch in Git:</h3>
<p>When you want to start working on a new feature or experiment with an idea, you can create a new branch in Git. This new branch serves as a separate line of development, allowing you to make changes without affecting the main branch.</p>
<pre><code class="lang-bash">$ git branch new_feature
</code></pre>
<p>This command creates a new branch named 'new-feature' pointing to the same commit as the current branch. Branches can coexist, and Git keeps a special pointer called <code>HEAD</code> to indicate the current branch.</p>
<h3 id="heading-understanding-branches">Understanding Branches</h3>
<p>Firstly, let's grasp the basics of branches in Git. When you initialize a Git repository, you start with a default branch, usually named 'master' or 'main'. Branches are essentially pointers to commits, enabling you to work on different features or fixes independently. </p>
<p>To view all branches in your repository, use the command:</p>
<pre><code class="lang-bash">$ git branch
</code></pre>
<p>This will display a list of branches with an asterisk (*) indicating the currently checked out branch. For additional information like the last commit on each branch, utilize:</p>
<pre><code class="lang-bash">$ git branch -v
</code></pre>
<h3 id="heading-how-to-switch-to-another-branch-in-git">How to Switch to Another Branch in Git:</h3>
<p>To switch to an existing different branch, use <code>git checkout</code>. </p>
<pre><code class="lang-bash">$ git checkout new_feature
</code></pre>
<p>This command switches the 'HEAD' pointer to the 'new-feature' branch, making it the currently active branch.</p>
<p>To create and switch to a new branch in one operation:</p>
<pre><code class="lang-bash">$ git checkout -b &lt;newbranchname&gt;
</code></pre>
<p>In Git version 2.23 onwards, you can use <code>git switch</code> instead of <code>git checkout</code>.</p>
<ul>
<li>Switch to an existing branch: <code>git switch existing-branch</code>.</li>
<li>Create and switch to new branch: <code>git switch -c new-branch</code>.</li>
</ul>
<h3 id="heading-how-to-visualize-branches-in-git">How to Visualize Branches in Git:</h3>
<p>After creating and switching branches, you can visualize the branch structure using:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">log</span> --oneline --decorate --graph --all
</code></pre>
<p>This command displays a concise and graphical representation of the commit history and branch pointers, allowing you to see how branches diverge and merge over time.</p>
<h2 id="heading-how-to-manage-branches-in-git">How to Manage Branches in Git</h2>
<h3 id="heading-how-to-manage-merged-branches">How to Manage Merged Branches</h3>
<p>As your project evolves, you'll merge branches back into the main branch once their changes are finalized. To identify merged branches, execute:</p>
<pre><code class="lang-bash">$ git branch --merged
</code></pre>
<p>This command lists branches that have been successfully merged into the current branch. These branches are generally safe to delete using:</p>
<pre><code class="lang-bash">$ git branch -d branch_name
</code></pre>
<p>However, for branches containing unmerged work, use:</p>
<pre><code class="lang-bash">$ git branch --no-merged
</code></pre>
<p>Deleting such branches requires the '-D' flag:</p>
<pre><code class="lang-bash">$ git branch -D branch_name
</code></pre>
<p>This ensures that you don't inadvertently lose any unmerged changes.</p>
<h3 id="heading-how-to-rename-branches">How to Rename Branches</h3>
<p>To rename a local branch:</p>
<pre><code class="lang-bash">$ git branch --move old_branch_name new_branch_name
</code></pre>
<p>This command updates the branch name locally. To reflect the change on the remote repository, push the renamed branch:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin new_branch_name
</code></pre>
<p>Verify the changes using: </p>
<pre><code class="lang-bash">$ git branch --all
</code></pre>
<p>Ensure to delete the old branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete old_branch_name
</code></pre>
<p>This ensures uniformity across local and remote repositories.</p>
<h3 id="heading-how-to-change-the-default-branch-name">How to Change the Default Branch Name</h3>
<p>Renaming the default branch, often 'master', requires caution and coordination, as it impacts project integrations and collaborators.</p>
<pre><code class="lang-bash">$ git branch --move master main
</code></pre>
<p>Once renamed, push the updated branch to the remote repo:</p>
<pre><code class="lang-bash">$ git push --set-upstream origin main
</code></pre>
<p>Make sure you remember to update references and configurations across dependencies, tests, scripts, and repository hosts. Once done, delete the old master branch on the remote:</p>
<pre><code class="lang-bash">$ git push origin --delete master
</code></pre>
<p>This is <strong>different from <code>$ git config --global init.defaultBranch main</code></strong> that we discussed in the configuration part in the following ways:</p>
<ul>
<li><code>$ git branch --move master main</code>: This command renames the existing branch named "master" to "main" within the current repository. It is a sort of local operation that affects only the repository.</li>
<li><code>$ git config --global init.defaultBranch main</code>: This command sets the default branch name for new repositories globally. It does not rename existing branches but ensures that any new repositories created thereafter will use "main" as the default branch name instead of "master".</li>
</ul>
<p><strong>Additional Resource</strong>: Consider checking out this official Git <a target="_blank" href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches">resource</a> for its informative visuals and diagrams which can provide you more clarity on remote branches and branch management concepts.</p>
<h2 id="heading-branching-workflow">Branching Workflow</h2>
<p>Let's understand branches in more detail and look at a common branching workflow that is used in large projects.</p>
<h3 id="heading-long-running-branches">Long-Running Branches:</h3>
<p>In Git, long-running branches are branches that remain open over an extended period. </p>
<h3 id="heading-topic-branches">Topic Branches:</h3>
<p><code>Topic</code>/<code>Feature</code> branches are short-lived branches created for specific features or pieces of work. Unlike long-running branches, which persist over time, topic branches are created, used, and often deleted once the work is complete. </p>
<p><strong>Example:</strong> Let's consider a scenario where a team maintains two long-running branches: <code>master</code> and <code>develop</code>.</p>
<ul>
<li>The <code>master</code> branch contains only stable code, possibly what has been released or will be released.</li>
<li>The <code>develop</code> branch acts as a staging area for ongoing development. While it might not always be stable, it serves as a testing ground for new features.</li>
</ul>
<p>Developers merge changes from feature branches into the <code>develop</code> branch for testing. Once features are thoroughly tested and stable, they are merged into <code>master</code>.</p>
<p>Note how changes progress through different levels of stability, moving from the least stable (feature branches) to more stable ones (such as the develop branch), as they undergo testing and refinement, and are finally merged into the most stable main/master branch. </p>
<p>This maintains a clear separation between stable and development code, ensuring that only thoroughly tested features make their way into the stable release.</p>
<h3 id="heading-branching-best-practices">Branching Best Practices</h3>
<ol>
<li><strong>Create Descriptive Branch Names</strong>: Use meaningful branch names that reflect the purpose or feature being developed.</li>
<li><strong>Delete Unused Branches</strong>: Once a branch has served its purpose and its changes have been merged into the main branch, consider deleting it to keep the repository clean and manageable.</li>
</ol>
<h2 id="heading-rebasing-in-git">Rebasing in Git</h2>
<p>In Git, when you're working with branches, there are two primary ways to integrate changes from one branch into another: merging and rebasing. </p>
<p>Unlike merging, which can create a cluttered history with multiple merge commits, rebasing produces a linear history, making it easier to understand the sequence of changes made over time. </p>
<h3 id="heading-basic-rebase-example">Basic Rebase Example:</h3>
<p>Imagine you're working on a project with two branches: "feature" and "master". You've made some commits on the "feature" branch and now want to integrate these changes into the "master" branch using rebasing.</p>
<p>First, you switch to your "feature" branch:</p>
<pre><code class="lang-bash">$ git checkout feature
</code></pre>
<p>Then, you rebase your feature branch onto the master branch: </p>
<pre><code class="lang-bash">$ git rebase master
</code></pre>
<p>This command takes all the commits/changes you made on your "feature" branch and applies them on top of the latest commits in the "master" branch, and replays the commits one by one.</p>
<p>Not only master branch, you can also rebase a topic branch onto another topic branch. Example:</p>
<p>Suppose you're working on a project with two feature branches: "frontend" and "backend". You made some commits on the "frontend" branch and now want to integrate these changes into the "backend" branch.</p>
<p>Let's use a different approach this time -<br>use <code>--onto</code> option of <code>git rebase</code> to rebase the "frontend" branch onto the "backend" branch:</p>
<pre><code class="lang-bash">$ git rebase --onto backend frontend
</code></pre>
<p>After rebasing, switch back to the "backend" branch and perform a fast-forward merge:</p>
<pre><code class="lang-bash">$ git checkout backend
$ git merge frontend
</code></pre>
<p>Now, your project history appears linear, reflecting the sequential integration of changes from the "frontend" branch into the "backend" branch.</p>
<h3 id="heading-rebasing-vs-merging-which-is-better">Rebasing vs Merging: Which is Better?</h3>
<h4 id="heading-rebasing-use-cases">Rebasing Use Cases:</h4>
<ul>
<li>Suitable for feature branches that need a clean integration into the mainline branch.</li>
<li>Preferred for open-source contributions where a clean commit history is valued.</li>
</ul>
<h4 id="heading-merging-use-cases">Merging Use Cases:</h4>
<ul>
<li>Appropriate for collaborative environments where transparency in the project's development process is crucial.</li>
<li>Useful for projects where maintaining an accurate historical record is a priority.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This handbook serves as a comprehensive guide to understanding and utilizing Git, a powerful version control system widely used in software development. </p>
<p>From basic workflows to setting up a repository, tagging, and branching remote repositories, we have learnt a comprehensive suite of features that will help streamlining the development process.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn React – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React. Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-for-beginners-handbook/</link>
                <guid isPermaLink="false">66bd919d1bb54b9103c678c0</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 01 Mar 2024 00:34:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Learn-React-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React.</p>
<p>Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks of the library. You'll learn about JSX, components, props, states, event handlers, creating forms, and running network requests.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-requirements">Requirements</a></li>
<li><a class="post-section-overview" href="#heading-chapter-1-introduction">Chapter 1: Introduction</a><ul>
<li><a class="post-section-overview" href="#heading-computer-setup">Computer Setup</a></li>
<li><a class="post-section-overview" href="#heading-your-first-react-application">Your First React Application</a></li>
<li><a class="post-section-overview" href="#heading-explaining-the-source-code">Explaining the Source Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</a></li>
<li><a class="post-section-overview" href="#heading-how-to-render-to-the-screen">How to Render to the Screen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-comments-in-react">How to Write Comments in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-the-class-attribute">How to Add the Class Attribute</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-4-props-and-states">Chapter 4: Props and States</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</a></li>
<li><a class="post-section-overview" href="#heading-props-are-immutable">Props are Immutable</a></li>
<li><a class="post-section-overview" href="#heading-state-in-react">State in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</a><ul>
<li><a class="post-section-overview" href="#heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the &amp;&amp; Operator</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-change-the-ui-by-handling-events">How to Change the UI by Handling Events</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-7-css-in-react">Chapter 7: CSS in React</a><ul>
<li><a class="post-section-overview" href="#heading-react-inline-styling">React Inline Styling</a></li>
<li><a class="post-section-overview" href="#heading-css-files">CSS Files</a></li>
<li><a class="post-section-overview" href="#heading-css-modules">CSS Modules</a></li>
<li><a class="post-section-overview" href="#heading-tailwind-css">Tailwind CSS</a></li>
<li><a class="post-section-overview" href="#heading-which-one-should-you-use">Which One Should You Use?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-input">How to Handle Form Input</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-submission">How to Handle Form Submission</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-validation">How to Handle Form Validation</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</a><ul>
<li><a class="post-section-overview" href="#heading-the-useeffect-hook">The useEffect Hook</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<p>By covering these concepts, you'll be equipped to dive further into advanced React topics.</p>
<h2 id="heading-requirements">Requirements</h2>
<p>To get the full benefit of this handbook, you should have basic knowledge of HTML, CSS, and JavaScript. No previous knowledge about React is needed, as we will start from the very basics.</p>
<p>If you need a JavaScript refresher, you can <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">get my JavaScript book here</a>.</p>
<h2 id="heading-chapter-1-introduction">Chapter 1: Introduction</h2>
<p>React is a very popular JavaScript front-end library. It's received lots of love from developers around the world for its <strong>simplicity</strong> and <strong>fast performance</strong>.</p>
<p>React was initially developed by Facebook as a solution to front end problems they were facing:</p>
<ul>
<li>DOM manipulation is an expensive operation and should be minimized</li>
<li>No library specialized in handling front-end development at the time (there is Angular, but it's an ENTIRE framework.)</li>
<li>Using a lot of vanilla JavaScript can turn a web application into a mess that's hard to maintain.</li>
</ul>
<p>Why do developers love React? As a software developer myself, I can think of a few reasons why I love it:</p>
<ul>
<li><strong>It's minimalist</strong>. React takes care of only ONE thing: the user interface and how it changes according to the data you feed into it. React makes your interface dynamic with minimal code.</li>
<li><strong>It has a low learning curve</strong>. The core concepts of React are relatively easy to learn, and you don't need months or 40 hours of video lectures to learn the basics.</li>
<li><strong>It's unopinionated</strong>. React can be integrated with lots of different technologies. On the front-end, you can use different libraries to handle Ajax calls (Axios, Superagent, or just plain Fetch.) On the back-end, you can use PHP/ Ruby/ Go/ Python or whatever language you prefer.</li>
<li><strong>It has strong community support</strong>. To enhance React's capabilities, open source contributors have built an amazing ecosystem of libraries that enables you to make even more powerful applications. But most open source libraries for React are optional. You don't need to learn them until you've mastered React fundamentals.</li>
</ul>
<p>The bottom line is that with a low learning curve, React gives you incredible power in making your UI flexible, reusable, and spaghetti-free.</p>
<p>Learning React opens tremendous opportunities if you want to work as a web developer.</p>
<h3 id="heading-computer-setup">Computer Setup</h3>
<p>To start programming with React, you'll need to have three things:</p>
<ol>
<li>A web browser</li>
<li>A code editor</li>
<li>Node.js</li>
</ol>
<p>We're going to use the Chrome browser to run our JavaScript code, so if you don't have it, <a target="_blank" href="https://www.google.com/chrome/">you can download it here</a>.</p>
<p>The browser is available for all major operating systems. Once the download is complete, install the browser on your computer.</p>
<p>Next, you'll need to install a code editor if you don't already have one. There are several free code editors available on the Internet, such as Sublime Text, Visual Studio Code, and Notepad++.</p>
<p>Out of these editors, my favorite is Visual Studio Code, because it's fast and easy to use.</p>
<h4 id="heading-how-to-install-visual-studio-code">How to install Visual Studio Code</h4>
<p>Visual Studio Code, or VSCode for short, is an application created for the purpose of writing code. Aside from being free, VSCode is fast and available on all major operating systems.</p>
<p>You can <a target="_blank" href="https://code.visualstudio.com/">download Visual Studio Code here</a>.</p>
<p>When you open the link above, there should be a button showing the version compatible with your operating system as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-installvscode-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Downloading Visual Studio Code</em></p>
<p>Click the button to download VSCode, and install it on your computer.</p>
<p>Now that you have a code editor installed, the next step is to install Node.js</p>
<h4 id="heading-how-to-install-nodejs">How to install Node.js</h4>
<p>Node.js is a JavaScript runtime application that enables you to run JavaScript outside of the browser. You need to install this application on your computer to install packages required in React development.</p>
<p>You can download and install Node.js from <a target="_blank" href="https://nodejs.org/">https://nodejs.org</a>. Pick the recommended LTS version because it has long-term support. The installation process is pretty straightforward.</p>
<p>To check if Node has been properly installed, type the command below on your command line (Command Prompt on Windows or Terminal on Mac):</p>
<pre><code class="lang-sh">node -v
</code></pre>
<p>The command line should respond with the version of the Node.js you have on your computer.</p>
<h3 id="heading-your-first-react-application">Your First React Application</h3>
<p>It's time to run your first React application. First, create a folder on your computer that will be used to store all files related to this book. You can name the folder 'beginning_react'.</p>
<p>The next step is to open your terminal and run the npm command to create a new React application using Vite.</p>
<p>Vite (pronounced 'veet') is a build tool that you can use to bootstrap a new React project. Inside the 'beginning_react' folder, you need to run the following command to create a new React project with Vite:</p>
<pre><code class="lang-sh">npm create vite@5.1.0 my-react-app -- --template react
</code></pre>
<p>You should see npm asking to install a new package (create-vite) as shown below. Proceed by typing 'y' and pressing Enter:</p>
<pre><code class="lang-txt">Need to install the following packages:
  create-vite@5.1.0
Ok to proceed? (y) y
</code></pre>
<p>Then Vite will create a new React project named 'my-react-app' as follows:</p>
<pre><code class="lang-txt">Scaffolding project in /dev/beginning_react/my-react-app...

Done. Now run:

  cd my-react-app
  npm install
  npm run dev
</code></pre>
<p>When you're done, follow the next steps you see in the output above. Use the <code>cd</code> command to change the working directory to the application you've just created, and then run <code>npm install</code> to install the packages required by the application.</p>
<p>Then, you need to run the <code>npm run dev</code> command to start your application:</p>
<pre><code class="lang-txt">$ npm run dev

&gt; my-react-app@0.0.0 dev
&gt; vite


  VITE v5.0.10  ready in 509 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
</code></pre>
<p>Now you can view the running application from the browser, at the designated localhost address:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-demo.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Home Page</em></p>
<p>This means you have successfully created your first React app. Congratulations!</p>
<h3 id="heading-explaining-the-source-code">Explaining the Source Code</h3>
<p>Now that you've successfully run a React application, let's take a look at the source code generated by Vite to understand how things work.</p>
<p>Run the Visual Studio Code you've installed in the previous section, and open the 'my-react-app' folder inside VSCode.</p>
<p>Here, you should see several folders and files that make up the React application as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-app.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Application Structure</em></p>
<p>The <code>vite.config.js</code> is a configuration file that instructs Vite on how to run the application. Because we have a React application, you'll see the React plugin imported inside:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  <span class="hljs-attr">plugins</span>: [react()],
})
</code></pre>
<p>When you run the <code>npm run dev</code> command, Vite will look into this file to know how to run the program.</p>
<p>The <code>package.json</code> file stores the information about the project, including the packages required to run the project without any issues. The <code>package-lock.json</code> file keeps track of the installed package versions.</p>
<p>The <code>.eslintrc.cjs</code> file contains ESLint rules. ESLint is a code analysis tool that can identify problematic code in your project without needing to run the project. It will report any errors and warnings in VSCode.</p>
<p>The <code>index.html</code> file is a static HTML document that's going to be used when running the React application, and the <code>README.md</code> file contains an introduction to the project.</p>
<p>You don't need to modify any of these files. Instead, let's go to the <code>src/</code> folder where the React application code is written.</p>
<pre><code class="lang-txt">src
├── App.css
├── App.jsx
├── assets
│   └── react.svg
├── index.css
└── main.jsx
</code></pre>
<p>First, the <code>App.css</code> file contains the CSS rules applied to the <code>App.jsx</code> file, which is the main React application code.</p>
<p>The <code>assets/</code> folder contains the assets required for this project. In this case, it's the React icon, which you had seen in the browser.</p>
<p>The <code>index.css</code> file is the root CSS file applied globally to the application, and the <code>main.jsx</code> file is the root file that access the <code>index.html</code> file to render the React application. Here's the content of <code>main.jsx</code> file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.jsx'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the ReactDOM library creates a root at the <code>&lt;div&gt;</code> element that contains the <code>root</code> ID, then renders the whole React application to that element.</p>
<p>You can open the <code>App.jsx</code> file to view the React code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> reactLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'./assets/react.svg'</span>
<span class="hljs-keyword">import</span> viteLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'/vite.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://vitejs.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{viteLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Vite logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://react.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{reactLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo react"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"React logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount((count) =&gt; count + 1)}&gt;
          count is {count}
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.jsx<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to test HMR
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"read-the-docs"</span>&gt;</span>
        Click on the Vite and React logos to learn more
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>In this file, a single component named <code>App</code> is defined. The Vite and React logos are rendered with a link to the respective library, and there's a counter button that will increment the counter by 1 when you click on it.</p>
<p>This file is where we will be exploring the fundamentals of React. Let's delete everything in this file, and write a simple <code>App</code> component that renders a <code>&lt;h1&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Next, delete the <code>index.css</code>, <code>app.css</code>, and <code>assets/</code> folder. You also need to delete the <code>import './index.css'</code> statement in your <code>main.jsx</code> file.</p>
<p>If you open the browser again, you should see a single heading rendered as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-react-hello-world.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Output From Code Changes</em></p>
<p>Alright! Now you're ready to learn the fundamentals of React. We'll start your first lesson in the next chapter.</p>
<h2 id="heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</h2>
<p>In React, a component is a single independent unit of a user interface (UI). What you write inside a component will determine what should appear on the browser screen at a given time.</p>
<p>In the previous chapter, we created an <code>App</code> component that returns a heading element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>A component is made up of a function that returns a single UI element.</p>
<p>When you want a component to render nothing, you can return a <code>null</code> or <code>false</code> instead of an element.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}
</code></pre>
<p>All React components are saved under the <code>.jsx</code> file extension. As you can see in this project, you have <code>main.jsx</code> and <code>App.jsx</code>.</p>
<p>What is JSX? It's an extension of JavaScript that produces JavaScript-powered HTML elements. We're going to learn about it later.</p>
<h3 id="heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</h3>
<p>A component must always return a single element. When you need to return multiple elements, you need to wrap all of them in a single element like a <code>&lt;div&gt;</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But this will make your application render one extra <code>&lt;div&gt;</code> element in the browser. To avoid cluttering your application, you can render an empty tag <code>&lt;&gt;</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>The empty tag above is a React feature called a Fragment. By using a Fragment, your component won't render an extra element to the screen.</p>
<p>You can also import the <code>Fragment</code> module from React to make it explicit as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Fragment } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But you don't need to explicitly state the <code>Fragment</code> tag. Using an empty tag <code>&lt;&gt;</code> is enough.</p>
<h3 id="heading-how-to-render-to-the-screen">How to Render to the Screen</h3>
<p>To render a React component into the browser, you need to create a root React component using the ReactDOM library, which you've seen previously when viewing the <code>main.jsx</code> file.</p>
<p>You need to have an HTML file as the source from which your React component is rendered. </p>
<p>Usually, a very basic HTML document with a <code>&lt;div&gt;</code> is enough, as you can see in the <code>index.html</code> file:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/src/main.jsx"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Next, you render the component into the <code>&lt;div&gt;</code> element. </p>
<p>Notice how ReactDOM is imported from <code>react-dom</code> package, and the <code>document.getElementById('root')</code> is used to select the <code>&lt;div&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the <code>App</code> component is placed in the same file as the ReactDOM library. You can do this if you want to remove the <code>App.jsx</code> file, so you have only a single <code>main.jsx</code> file as the source for your React application.</p>
<p>But it's confusing to have multiple components in one file, so let's not do this.</p>
<h3 id="heading-how-to-write-comments-in-react">How to Write Comments in React</h3>
<p>Writing comments in React components is similar to how you comment in regular JavaScript code. You can use the double forward slash syntax <code>//</code> to comment any code.</p>
<p>The following example shows how to comment the <code>export</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-comment">// export default App</span>
</code></pre>
<p>When you want to comment the code inside the <code>return</code> statement, you need to use the curly brackets, forward slash, and asterisk format <code>{/* comment here */}</code> as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {/* <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span> */}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>It may seem very annoying that you need to remember two different ways of commenting when writing React applications. But don't worry, because a modern tool like VSCode knows how to generate the right comment syntax.</p>
<p>You only need to press the comment shortcut, which is <code>CTRL + /</code> for Windows/ Linux or <code>Command + /</code> for macOS.</p>
<h3 id="heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</h3>
<p>Up until this point, you've only rendered a single <code>App</code> component to the browser. But applications built using React can be composed of tens or hundreds of components.</p>
<p><strong>Composing components</strong> is the process of forming the user interface by using loosely coupled components. It's kind of like making a house out of Lego blocks, as I will show you in the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">UserComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ProfileComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">FeedComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> User Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProfileComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Profile Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FeedComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Feed Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>From the example above, you can see how the <code>&lt;ParentComponent&gt;</code> renders three children components:</p>
<ul>
<li><code>&lt;UserComponent&gt;</code></li>
<li><code>&lt;ProfileComponent&gt;</code></li>
<li><code>&lt;FeedComponent&gt;</code></li>
</ul>
<p>The composition of many components will form a single tree of React components in a top-down approach.</p>
<p>The tree will then be rendered into the DOM through the <code>ReactDOM.render()</code> method:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/2-react-tree.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Component Tree Illustrated</em></p>
<p>By composing multiple components, you can split the user interface into independent, reusable pieces, and develop each piece in isolation.</p>
<h2 id="heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</h2>
<p>In the previous chapter, you learned that a component must always have a <code>return</code> statement that contains elements to render on the screen:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The tag <code>&lt;h1&gt;</code> looks like a regular HTML tag, but it's actually a special template language included in React called JSX.</p>
<p>JSX is a syntax extension that produces JavaScript powered HTML elements. It can be assigned to JavaScript variables and can be returned from function calls. For example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myElement = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  <span class="hljs-keyword">return</span> myElement
}
</code></pre>
<p>Because of JSX, you can also embed JavaScript expressions inside an element by using curly brackets <code>{}</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> lowercaseClass = <span class="hljs-string">'text-lowercase'</span>;
<span class="hljs-keyword">const</span> text = <span class="hljs-string">'Hello World!'</span>;
<span class="hljs-keyword">const</span> App = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{lowercaseClass}</span>&gt;</span>{text}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
</code></pre>
<p>This is what makes React elements different from HTML elements. You can't embed JavaScript directly by using curly braces in HTML.</p>
<p>Instead of creating a whole new templating language, you just need to use JavaScript functions to control what is being displayed on the screen.</p>
<h3 id="heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</h3>
<p>For example, let's say you have an array of users that you'd like to show:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
]
</code></pre>
<p>You can use the <code>map()</code> function to loop over the array:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> users = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
  ]

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The currently active users list:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {
        users.map(function(user){
          // returns Nathan, then John, then Jane
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> {user.name} as the {user.role} <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          )
        })
      }
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Inside React, you don't need to store the return value of the <code>map()</code> function in a variable. The example above will return a <code>&lt;li&gt;</code> element for each array value into the component.</p>
<p>While the above code is already complete, React will trigger an error in the console, saying that you need to put a "key" prop in each child of a list (the element that you return from <code>map()</code> function):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/3-react-array-warning.png" alt="Image" width="600" height="400" loading="lazy">
<em>React 'key' Warning on Browser Console</em></p>
<p>A prop (short for property) is an input that you can pass to a component when rendering that component. The <code>key</code> prop is a special prop that React will use to determine which child element has been changed, added, or removed from the list.</p>
<p>You won't use it actively in any part of your array rendering code, but React will ask for one when you render a list.</p>
<p>It is recommended that you put the unique identifier of your data as the key value. In the example above, you can use the <code>user.id</code> data. Here's how you pass a <code>key</code> prop for each <code>&lt;li&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span> 
    {user.name} as the {user.role} 
  <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
)
</code></pre>
<p>When you don't have any unique identifiers for your list, you can use the array <code>index</code> value as the last resort:</p>
<pre><code class="lang-jsx">users.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user, index</span>)</span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
      {user.name} as the {user.role}
    <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  )
})
</code></pre>
<p>Props are one of the ingredients that make a React component powerful. You're going to learn more about it in the next chapter.</p>
<h3 id="heading-how-to-add-the-class-attribute">How to Add the Class Attribute</h3>
<p>You can add the <code>class</code> attribute to your elements by using the <code>className</code> keyword:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-lowercase'</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The keyword <code>class</code> is reserved for JavaScript classes, so you need to use <code>className</code> instead.</p>
<h2 id="heading-chapter-4-props-and-states">Chapter 4: Props and States</h2>
<p>Props and states are used to pass data inside React components. Props (or properties) are inputs passed down from a parent component to its child component.</p>
<p>On the other hand, states are variables defined and managed inside the components.</p>
<p>Let's start by understanding props. Suppose you have a <code>ParentComponent</code> that renders a <code>ChildComponent</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> /&gt;</span></span>
}
</code></pre>
<p>You can pass a prop from <code>ParentComponent</code> into <code>ChildComponent</code> by adding a new attribute after the component name.</p>
<p>In the code below, the <code>name</code> prop with the value 'John' is passed to the <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span> /&gt;</span></span>
}
</code></pre>
<p>When the component is rendered on the browser, the <code>ChildComponent</code> will receive the name prop into the component.</p>
<p>You can access the <code>props</code> object by defining it in the function component's argument:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>The <code>props</code> parameter will always be an object, and any prop you define when rendering the component will be passed as a property to the object.</p>
<h3 id="heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</h3>
<p>You can pass as many props as you want into a single child component. Just add the props when using the component as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span>
      <span class="hljs-attr">name</span>=<span class="hljs-string">"John"</span>
      <span class="hljs-attr">age</span>=<span class="hljs-string">{29}</span>
      <span class="hljs-attr">hobbies</span>=<span class="hljs-string">{[</span>"<span class="hljs-attr">read</span> <span class="hljs-attr">books</span>", "<span class="hljs-attr">drink</span> <span class="hljs-attr">coffee</span>"]}
      <span class="hljs-attr">occupation</span>=<span class="hljs-string">"Software Engineer"</span>
    /&gt;</span></span>
  )
}
</code></pre>
<p>All the props above will be passed to the ChildComponent's <code>props</code> parameter.</p>
<p>You can even pass a function into props like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello World'</span>
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">greetings</span>=<span class="hljs-string">{greetings}</span> /&gt;</span></span>
}
</code></pre>
<p>In the child component, you can call the function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.greetings()}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>Note that if you pass anything other than a string as a prop value, you need to put the value in curly brackets (numbers, functions, arrays, objects, and so on)</p>
<p>This is because JavaScript expressions can't be processed by JSX unless you put the expression inside curly brackets.</p>
<h3 id="heading-props-are-immutable">Props are Immutable</h3>
<p>Immutable means that a prop's value can't be changed no matter what happens.</p>
<p>In the code below, the <code>ChildComponent</code> tries to change the value of <code>props.name</code> property:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  props.name = <span class="hljs-string">'Mark'</span>;
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span>/&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>But you'll get an error in the console as follows:</p>
<pre><code class="lang-txt">Uncaught TypeError: Cannot assign to read only property 'name' of object '#&lt;Object&gt;'
</code></pre>
<p>As you can see, React props can't be changed once you declare them. But what if your data needs to change as a user interacts with your application? This is where state comes to the rescue.</p>
<h3 id="heading-state-in-react">State in React</h3>
<p>In React, states are arbitrary data that you can declare and manage in your components. To create a state in React, you need to call the <code>useState</code> hook as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>In React, hooks are functions that allow you to tap into the features provided by React. The <code>useState</code> hook is a function that enables you to put value into the state mechanism.</p>
<p>When calling the <code>useState()</code> function, you can pass an argument that will serve as the initial value of the state. The function then returns an array with two elements.</p>
<p>The first element holds the state value, and the second element is a function that allows you to change the state value. You need to use the destructuring array syntax to receive both elements as shown above</p>
<p>You can give any names to the variables returned by <code>useState</code>, but it's recommended to use <code>[something, setSomething]</code>.</p>
<p>To render the state value, you can embed it into JSX as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>If you want to change the value of the <code>name</code> variable, you need to use the provided <code>setName()</code> function.</p>
<p>But you can't call <code>setName()</code> in the component's body, because React will refresh itself anytime you change the state value.</p>
<p>Instead, you can create a button that will change the value of name when you click it:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In the code above, we create a <code>&lt;button&gt;</code> element and add the <code>onClick</code> prop, which gets executed anytime we click on the button.</p>
<p>Inside the prop, we pass a function that simply calls the <code>setName()</code> function, changing the state value.</p>
<h3 id="heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</h3>
<p>You can pass the state into any child component. When you need to update the state from a child component, you need to pass the <code>setSomething</code> function received from the <code>useState</code> hook.</p>
<p>Here's an example of passing a state from <code>ParentComponent</code> to <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">setName</span>=<span class="hljs-string">{setName}</span> /&gt;</span></span>
}
</code></pre>
<p>In the <code>ChildComponent</code>, you can call the <code>setName()</code> function from <code>props</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> props.setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When the button on the <code>ChildComponent</code> is clicked, the value of the <code>name</code> state will change. Internally, React will refresh the application and reflect the changes in the user interface.</p>
<h3 id="heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</h3>
<p>To help ease your development, you can install the React Developer Tools (DevTools for short) to inspect the current state and props value of your components. </p>
<p>You can <a target="_blank" href="https://chromewebstore.google.com/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">install React DevTool for Chrome here</a>.</p>
<p>Once installed, open the developer tool and you should have two extra tabs called <em>Components</em> and <em>Profiler</em> as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-chrome.png" alt="Image" width="600" height="400" loading="lazy">
<em>Opening React DevTool</em></p>
<p>Similar to how you can inspect CSS rules applied to HTML elements, you can inspect the state and props of React components using the developer tools. Click the <em>Components</em> tab, and inspect one of the two components we created earlier.</p>
<p>Below, you can see the props and state of the <code>ParentComponent</code>, as well as other details:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-inspect.png" alt="Image" width="600" height="400" loading="lazy">
<em>Inspecting Components With React DevTool</em></p>
<p>When you click on the button, the state value will change accordingly. You can inspect the <code>ChildComponent</code> to view its details. These DevTools will come in handy when you develop React applications.</p>
<h2 id="heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</h2>
<p>You can control what output is being rendered by a component by implementing conditional rendering in your JSX code.</p>
<p>For example, let's say you want to switch between rendering the login and logout buttons, depending on the availability of the <code>user</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">if</span> (user) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>You don't need to add an <code>else</code> statement in the component because React will stop further processes once it reaches a <code>return</code> statement.</p>
<p>In the example above, React will render the logout button when the <code>user</code> value is truthy, and the login button when <code>user</code> is falsy.</p>
<h3 id="heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</h3>
<p>When developing with React, there will be cases where you want to render a part of your UI dynamically in a component.</p>
<p>In the example below, the JSX element is stored in a variable called <code>button</code>, and that variable is used again in the <code>return</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">let</span> button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>

  <span class="hljs-keyword">if</span> (user) {
    button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {button}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of writing two return statements, you store the dynamic UI element inside a variable and use that variable in the <code>return</code> statement.</p>
<p>This way, you can have a component that has static and dynamic elements.</p>
<h3 id="heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the <code>&amp;&amp;</code> Operator</h3>
<p>It's possible to render a component only if a certain condition is met and render null otherwise.</p>
<p>For example, let's say you want to render a dynamic message for users when they have new emails in their inbox:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> newEmails = <span class="hljs-number">2</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {newEmails &gt; 0 &amp;&amp;
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
          You have {newEmails} new emails in your inbox.
        <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In this example, the <code>&lt;h2&gt;</code> element only gets rendered when the <code>newEmails</code> count is greater than 0.</p>
<h3 id="heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</h3>
<p>It's also possible to use a ternary operator in order to render the UI dynamically.</p>
<p>Take a look at the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      { user? <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of using a variable to hold the <code>&lt;button&gt;</code> element, you can simply use the ternary operator on the <code>user</code> value and render 'Logout' or 'Login' button according to the variable's value.</p>
<h2 id="heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</h2>
<p>Under the hood, React has an internal event handler that connects to the native DOM event.</p>
<p>This is why we can add the <code>onClick</code> prop to buttons in the previous chapters, which gets executed in response to a click event.</p>
<p>When you call a function in response to events, the <code>event</code> object will be passed to the callback function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
    <span class="hljs-built_in">console</span>.log(event);
  }
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>
      Click me
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  )
}
</code></pre>
<p>When you click on the button above, the <code>event</code> variable will be logged as a <code>SyntheticBaseEvent</code> object in your console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/8-react-synthetic-event.png" alt="Image" width="600" height="400" loading="lazy">
<em>React's SyntheticBaseEvent Log</em></p>
<p>The <code>SyntheticBaseEvent</code> object is a built-in React object used to interact with the native DOM events. Different browsers have different implementations of the DOM event object, so the <code>SyntheticBaseEvent</code> makes React compatible with these browsers.</p>
<p>Whenever a DOM event is triggered, that synthetic event will be handled by React so that you can decide what to do with that event.</p>
<p>The use case for this Synthetic event is the same as the native DOM event. Three of the most common event handlers you're going to use are:</p>
<ul>
<li><code>onChange</code></li>
<li><code>onClick</code></li>
<li><code>onSubmit</code></li>
</ul>
<p>You can respond to user interactions like clicking, hovering, focusing or typing on a form input, submitting a form, and so on.</p>
<h3 id="heading-how-to-change-the-ui-by-handling-events">How to Change the UI By Handling Events</h3>
<p>In the previous chapter, you saw how conditional logic can be used to render different outputs.</p>
<p>By combining conditional logic with state, props, and event handlers, you can create a dynamic component that renders different outputs based on the data it currently holds.</p>
<p>For example, suppose you want to show or hide a <code>&lt;div&gt;</code> element with a button click. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// State to hold the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> [isParagraphVisible, setIsParagraphVisible] = useState(<span class="hljs-literal">true</span>);

  <span class="hljs-comment">// Function to toggle the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> toggleStatus = <span class="hljs-function">() =&gt;</span> {
    setIsParagraphVisible(!isParagraphVisible);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Change UI based on click<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {isParagraphVisible &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This paragraph will be shown/hidden on click<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleStatus}</span>&gt;</span>
        {isParagraphVisible ? 'Hide' : 'Show'} Paragraph
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>First, you create a state to hold the visibility status of the paragraph using the <code>useState</code> hook. The default value of the state is <code>true</code>.</p>
<p>Next, a function named <code>toogleStatus()</code> is defined. This function will change the <code>status</code> value from <code>true</code> to <code>false</code> and vice versa.</p>
<p>Finally, a <code>return</code> statement is added to render the elements to the screen. When the button is clicked, the <code>toogleStatus()</code> function will be executed. This will show or hide the paragraph depending on the current status.</p>
<p>By using states, props, and event handlers, the code you write becomes a description of what the user interface should look like. React then takes that description and renders it on the browser.</p>
<h2 id="heading-chapter-7-css-in-react">Chapter 7: CSS in React</h2>
<p>There are 4 common ways you can add CSS in a React application:</p>
<ol>
<li>Inline styling</li>
<li>CSS files</li>
<li>CSS modules</li>
<li>Tailwind CSS</li>
</ol>
<p>This chapter will explore these 4 different ways to write CSS in React components, and which one you should use when starting a React application.</p>
<h3 id="heading-react-inline-styling">React Inline Styling</h3>
<p>React components are composed of JSX elements. But just because you're not writing regular HTML elements doesn't mean you can't use the old inline style method.</p>
<p>The only difference with JSX is that inline styles must be written as an object instead of a string. See the example below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> '<span class="hljs-attr">red</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>In the style attribute above, the first set of curly brackets is used to write JavaScript expressions. The second set of curly brackets initializes a JavaScript object.</p>
<p>Style property names that have more than one word are written in camelCase instead of using the traditional hyphenated style. For example, the usual <code>text-align</code> property is written as <code>textAlign</code> in JSX:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>Because the style attribute is an object, you can also separate the style by writing it as a constant. This way, you can reuse the style in other elements as needed:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>The weather is sunny today.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>If you need to extend your paragraph style further down the line, you can use the spread operator.</p>
<p>This will let you add inline styles to your already declared style object. See the <code>&lt;p&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...pStyle</span>, <span class="hljs-attr">color:</span> '<span class="hljs-attr">green</span>', <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">right</span>' }}&gt;</span>
      When you go to work, bring your umbrella with you!
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  )
}
</code></pre>
<p>JSX inline styles allow you to write CSS directly into your component.</p>
<p>One of the benefits of using the inline style approach is that you will have a simple component-focused styling technique. When using an object for styling, you can extend your style by spreading the object.</p>
<p>But in a big and complex project where you have hundreds of React components to manage, this might not be the best choice for you.</p>
<p>You can't specify pseudo classes using inline styles. That means you can't define rules like <code>:hover</code>, <code>:focus</code>, <code>:active</code>, and so on.</p>
<p>Also, you can't specify media queries for responsive styling. Let's consider another way to style your React app.</p>
<h3 id="heading-css-files">CSS Files</h3>
<p>Another way to add CSS in React is to use <code>.css</code> files. Vite already knows how to handle a <code>.css</code> file, so all you need to do is import the CSS file into your JSX file and add the right <code>className</code> prop to your component.</p>
<p>Let's create a <code>style.css</code> file in your project folder with the following content:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* style.css */</span>
<span class="hljs-selector-class">.paragraph-text</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff0000</span>;
}
</code></pre>
<p>Now, let's import the CSS file into the <code>App.jsx</code> file and add the class prop to the component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"paragraph-text"</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  );
}
</code></pre>
<p>This way, the CSS will be separated from your JavaScript files, and you can just write CSS syntax as usual.</p>
<p>You can even include a CSS framework such as Bootstrap in React with this approach. All you need to do is import the CSS file in your root component.</p>
<p>This method will enable you to use all CSS features, including pseudo classes and media queries.</p>
<h3 id="heading-css-modules">CSS Modules</h3>
<p>A CSS module is a regular CSS file with all of its class and animation names scoped locally by default.</p>
<p>When applying this method, each React component will have its own CSS file, and you need to import that CSS file into your component.</p>
<p>To let React know you're using CSS modules, name your CSS file using the <code>[name].module.css</code> convention.</p>
<p>Here's an example:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* App.module.css */</span>
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>Then import it to your component file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./App.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.BlueParagraph}</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.GreenParagraph}</span>&gt;</span>
        Still, don't forget to bring your umbrella!
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When you build your app, Vite will automatically look for CSS files that have the <code>.module.css</code> name and process the class names to a new localized name.</p>
<p>Using CSS Modules ensures that your CSS classes are scoped locally, preventing CSS rules from colliding with each other.</p>
<p>Another advantage of using CSS Modules is that you can compose a new class by inheriting from other classes that you've written. This way, you'll be able to reuse CSS code that you've written previously, like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.MediumParagraph</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
}
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>But we're not going to explore every single feature of CSS modules here, only enough to get you familiar with them.</p>
<h3 id="heading-tailwind-css">Tailwind CSS</h3>
<p>Tailwind CSS is a modern utility-first CSS framework that allows you to style elements by combining a bunch of classes together.</p>
<p>CSS frameworks like Bootstrap and Bulma provide you with high-level components that you can immediately use in your project. When you need to style a button, you just need to apply the classes that contain the desired CSS properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn btn-primary"</span>&gt;</span>Subscribe<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>When using Bootstrap, the <code>btn</code> class provides a combination of CSS properties such as padding, color, opacity, font weight, and so on.</p>
<p>On the other hand, Tailwind gives you utility classes where each class has only one or two properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'px-5 py-2 text-white bg-blue-500 border-2'</span>&gt;</span>
  Subscribe
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the example above, the <code>px-5</code> is short for padding <code>padding-left</code> and <code>padding-right</code>, while 5 is a specific size for the paddings. The <code>text-white</code> applies <code>color: white</code>, the <code>bg-blue-500</code> applies the <code>background-color</code> property, and <code>border</code> applies <code>border-width</code>.</p>
<h3 id="heading-which-one-should-you-use">Which One Should You Use?</h3>
<p>It depends on the method you feel comfortable with the most. If you're working with a team, you need to discuss and agree on the method you want to apply, because mixing the styles makes it hard to develop and maintain the application.</p>
<p>Remember: Always use only one way to style React components in a specific project to avoid confusion.</p>
<h2 id="heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</h2>
<p>One of the most common interfaces you're going to build as a web developer is a form. In React, you can create a form by using state as the single source of that form's data.</p>
<p>In this chapter, I will show you how to handle form input, form submission, and form validation using React.</p>
<h3 id="heading-how-to-handle-form-input">How to Handle Form Input</h3>
<p>For example, suppose you want to create a form with a single text input and a button.</p>
<p>You can first set up the state that will serve as the input value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
}
</code></pre>
<p>Next, add the <code>return</code> statement and define the form. On the <code>&lt;input&gt;</code> element, assign the <code>username</code> state as the <code>value</code> prop:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'username'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Next, add the <code>onChange</code> prop to the <code>&lt;input&gt;</code> element. In that prop, assign the <code>value</code> of the text input as the value of the <code>username</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>The <code>e</code> or <code>event</code> object is passed by the <code>onChange</code> prop to the callback function. From that object, we can get the value of the text input at <code>event.target.value</code> property.</p>
<p>Now whenever the input value changes, the state will be updated to reflect the changes.</p>
<h3 id="heading-how-to-handle-form-submission">How to Handle Form Submission</h3>
<p>The next step is to submit the form. Let's create a function that handles the submit event called <code>handleSubmit()</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    alert(username);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the <code>handleSubmit()</code> function will stop the default form submission behavior, which will trigger a refresh, and then create an alert box to display the <code>username</code> value.</p>
<p>The function then gets passed to the <code>onSubmit</code> prop of the <code>&lt;form&gt;</code> element. A <code>&lt;button&gt;</code> is also added so that the user can submit the form.</p>
<h3 id="heading-how-to-handle-form-validation">How to Handle Form Validation</h3>
<p>To handle form validation, you need to create another state that will store the error message. You can name this state <code>usernameError</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();
</code></pre>
<p>Next, create a <code>handleUsername()</code> function that will run when the <code>username</code> input changes.</p>
<p>Inside this function, you can call the <code>setUsername()</code> function to update the state, and then write logic to validate the input value.</p>
<p>For example, suppose the <code>username</code> length must be longer than 6. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { value } = e.target;
  setUsername(value);

  <span class="hljs-comment">// Validate username value:</span>
  <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
    setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
  } <span class="hljs-keyword">else</span> {
    setUsernameError();
  }
};
</code></pre>
<p>Now that you have some validation logic, you need to set the <code>handleUsername()</code> function as the <code>onChange</code> prop handler.</p>
<p>Also, add a paragraph below the <code>&lt;input&gt;</code> element that will show the error message as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
    Username:
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
);
</code></pre>
<p>Inside the <code>handleSubmit()</code> function, you can check if there's an error on the form by checking the <code>usernameError</code> state, then prevent the form from being submitted when there is an error:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">if</span>(usernameError){
    alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
  } <span class="hljs-keyword">else</span> {
    alert(username);
  }
}
</code></pre>
<p>This way, the form won't be submitted until the error is fixed.</p>
<p>Here's the full source code of the form if you want to try it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    <span class="hljs-keyword">if</span>(usernameError){
      alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
    } <span class="hljs-keyword">else</span> {
      alert(username);
    }
  }

  <span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> { value } = e.target;
    setUsername(value);

    <span class="hljs-comment">// Validate username value:</span>
    <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
      setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
    } <span class="hljs-keyword">else</span> {
      setUsernameError();
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span>
      /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>A form can be as complex or as simple as required, but you'll use the pattern you see here no matter what form you build:</p>
<ul>
<li>State values are used as the source of form data and validation</li>
<li><code>onChange</code> prop as a way to update the state</li>
<li>Validations are triggered by user inputs</li>
<li>A <code>handleSubmit()</code> function is executed when the form is submitted</li>
</ul>
<p>Using these building blocks, you can build any form required by your application.</p>
<h2 id="heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</h2>
<p>Modern web applications tend to have a modular architecture, where the back end is separated from the front end. The front end app will need to send an HTTP network request to a remote endpoint.</p>
<p>React doesn't tell you how you should send network requests. The library only focuses on rendering UI with data management using props and states.</p>
<p>To fetch data using React, you can use any valid JavaScript library like Axios, Superagent, and even the native Fetch API.</p>
<p>In this chapter, we're going to see how to do network requests using Fetch in React.</p>
<h3 id="heading-the-useeffect-hook">The useEffect Hook</h3>
<p>When you create a React application that needs to synchronize with a system outside of React, you need to use the <code>useEffect</code> hook.</p>
<p>This hook allows you to run some code after rendering so that you can synchronize your component with some system outside of React.</p>
<p>When the hook has finished performing the data request, you can set the response into your component states and render the appropriate components based on the state values.</p>
<p>To show you an example, let's fetch data from <a target="_blank" href="https://jsonplaceholder.typicode.com/todos/1">https://jsonplaceholder.typicode.com/todos/1</a> which is a dummy end point:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    getData();
  }, []);

  <span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> task = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(task)
    setTitle(task.title);
  };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>In the code above, we create an <code>App</code> component that has a state called <code>title</code>, and we run the Fetch API to get a todo task from the API.</p>
<p>When a response is received, we parse the JSON string into a JavaScript object, log the object, and then set the <code>title</code> state to the <code>task.title</code> property value.</p>
<p>The response is as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/9-useeffect-log.png" alt="Image" width="600" height="400" loading="lazy">
<em>React useEffect Log</em></p>
<p>Here, you can see that the <code>console.log()</code> is called twice. This is because the <code>&lt;React.StrictMode&gt;</code> wrapper always runs a <code>useEffect</code> hook twice to help you in development.</p>
<p>If you remove the <code>&lt;React.StrictMode&gt;</code> wrapper in <code>main.jsx</code>, the <code>useEffect</code> hook will run only once.</p>
<p>The <code>useEffect</code> hook itself is a function that accepts two arguments:</p>
<ul>
<li>A callback function to run on every render</li>
<li>An array of state variables to watch for changes. <code>useEffect</code> will be skipped if none of the variables are updated.</li>
</ul>
<p>When you want to run <code>useEffect</code> only once, you can pass an empty array as the second argument to the function, as shown in the example above.</p>
<p>By using the <code>useEffect</code> hook, React can send HTTP requests and fetch data from any external system, then store that data in the component state.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Congratulations on finishing this handbook! I hope you found it useful and now feel that learning React is not impossible or confusing at all. All you need is a step-by-step guide that reveals the key concepts of React one by one.</p>
<p>If you're eager to dive deeper into React and expand your skills, I encourage you to check out my new book called <em>Beginning React</em> here:</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-react"><img src="https://www.freecodecamp.org/news/content/images/2024/02/beginning-react-promo.png" alt="Beginning React Book" width="600" height="400" loading="lazy"></a></p>
<p>The goal of this book is to help you see how to build an application using React. There are two projects included in this book that will give you the "experience" of building a web application using React.</p>
<p>You will see how React concepts like components, JSX, props, states, hooks, and Context API are used to create a dynamic front-end application.</p>
<p>Here's my promise: <em>You will actually feel confident building web applications from scratch using React.</em></p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Python Basics – A Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Are you eager to dive into the world of programming but unsure where to begin? Look no further – Python is an excellent starting point for both newcomers and seasoned developers.  In this guide, I'll take you through the basics so you can get started... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-python-basics/</link>
                <guid isPermaLink="false">66ba15982bddfbcfd2178948</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chepkirui Dorothy ]]>
                </dc:creator>
                <pubDate>Tue, 20 Feb 2024 19:04:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/learn-python-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you eager to dive into the world of programming but unsure where to begin? Look no further – Python is an excellent starting point for both newcomers and seasoned developers. </p>
<p>In this guide, I'll take you through the basics so you can get started on your Python journey.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
    <li><a href="#prerequisites">Prerequisites</a></li>
    <li><a href="#why-learn-python">Why Learn Python?</a></li>
    <li><a href="#key-characteristics-of-python">Key Characteristics of Python</a></li>
    <li><a href="#practical-uses-of-python">Practical Uses of Python</a></li>
    <li><a href="#how-to-write-hello-world-in-python">How to Write "Hello, World" in Python</a></li>
    <li><a href="#python-variables-and-data-types">Python Variables and Data Types</a>
        <ul>
            <li><a href="#primitive-fundamental-data-types-">Primitive (Fundamental) Data Types</a>
                <ul>
                    <li><a href="#characteristics-of-primitive-data-types-">Characteristics of Primitive Data Types</a></li>
                    <li><a href="#use-cases-for-primitive-data-types-">Use Cases for Primitive Data Types</a></li>
                </ul>
            </li>
            <li><a href="#non-primitive-composite-data-types-in-python">Non-Primitive (Composite) Data Types in Python</a>
                <ul>
                    <li><a href="#characteristics-of-non-primitive-data-types-">Characteristics of Non-Primitive Data Types</a></li>
                    <li><a href="#use-cases-for-non-primitive-data-types-">Use Cases for Non-Primitive Data Types</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#operators-in-python">Operators in Python</a>
        <ul>
            <li><a href="#arithmetic-operators-">Arithmetic Operators</a></li>
            <li><a href="#comparison-operators">Comparison Operators</a></li>
        </ul>
    </li>
    <li><a href="#statements-in-python">Statements in Python</a>
        <ul>
            <li><a href="#assignment-statements">Assignment Statements</a> </li>

             <li><a href="#print-statement">Print Statement</a></li>


            <li><a href="#conditional-statements-if-elif-else-">Conditional Statements (if, elif, else)</a>

                    </li><li><a href="#loops-for-and-while-">Loops (for and while)</a>
                        <ul>
                            <li><a href="#for-loop-">For Loop</a></li>
                            <li><a href="#while-loop-">While Loop</a></li>

                    </ul></li></ul> </li>
                    <li><a href="#break-and-continue-statements">Break and Continue Statements</a></li>


        </ul>
    
    <li><a href="#functions-in-python">Functions in Python</a></li>
    <li><a href="#conclusion">Conclusion</a></li>



<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Before you embark on this coding adventure, make sure you have the following:</p>
<ul>
<li><a target="_blank" href="https://www.python.org/downloads/">Python installed</a>.</li>
<li>A code editor like <a target="_blank" href="https://code.visualstudio.com/download">VSCode</a>, <a target="_blank" href="https://www.vim.org/download.php">Vim</a>, or <a target="_blank" href="https://www.sublimetext.com/3">Sublime</a>.</li>
</ul>
<p>Now, let's explore the advantages of using Python.</p>
<h2 id="heading-why-learn-python">Why Learn Python?</h2>
<p>If you're wondering why Python is an excellent choice for beginners and seasoned developers alike, here are some of the reasons:</p>
<ul>
<li><strong>Readability and Simplicity:</strong> Python's clean syntax enhances code readability, reducing development time and making it beginner-friendly.</li>
<li><strong>Versatility:</strong> You can use Python to build a diverse range of applications, from web development to data science and AI. It also has an extensive standard library and many helpful third-party packages.</li>
<li><strong>Community and Documentation:</strong> Python has a robust community and comprehensive documentation that provides ample support, fostering the language's popularity and growth.</li>
<li><strong>Cross-Platform Compatibility:</strong> Ensures seamless execution across Windows, macOS, and Linux.</li>
<li><strong>Extensive Libraries and Frameworks:</strong> A rich ecosystem simplifies complex tasks, saving time and effort for developers.</li>
</ul>
<p>Hopefully, you're intrigued by Python's perks – so let's delve into its key characteristics.</p>
<h2 id="heading-key-characteristics-of-python">Key Characteristics of Python</h2>
<p>Understanding the key characteristics of Python will give you insights into its strengths and why it's a popular choice among developers:</p>
<ul>
<li><strong>Interpreted Language:</strong> Your code is not directly translated by the target machine. Instead, a special program called the interpreter reads and executes the code, allowing for cross-platform execution of your code.</li>
<li><strong>Dynamically Typed:</strong> Dynamic typing eliminates the need for explicit data type declarations, enhancing simplicity and flexibility.</li>
<li><strong>Object-Oriented:</strong> Python supports object-oriented principles, promoting code modularity and reusability.</li>
<li><strong>Indentation-based Syntax:</strong> Indentation-based syntax enforces code readability and maintains a consistent coding style.</li>
<li><strong>Memory Management:</strong> Automatic memory management through garbage collection simplifies memory handling for developers.</li>
</ul>
<h2 id="heading-practical-uses-of-python">Practical Uses of Python</h2>
<p>Python's versatility and readability make it suitable for a wide array of applications. Here are some practical uses:</p>
<ul>
<li><strong>Web Development:</strong> Python, with frameworks like Django and Flask, powers back-end development for robust web applications.</li>
<li><strong>Data Science and Machine Learning:</strong> Widely used in data science, Python's libraries like NumPy and Pandas support data analysis and machine learning.</li>
<li><strong>Automation and Scripting:</strong> Python excels in automating tasks and scripting, simplifying repetitive operations.</li>
<li><strong>AI and NLP:</strong> Python, with libraries like TensorFlow, dominates in AI and natural language processing applications.</li>
<li><strong>Game Development:</strong> Python, combined with Pygame, facilitates 2D game development for hobbyists and indie developers.</li>
<li><strong>Scientific Computing:</strong> Python is a valuable tool in scientific computing, chosen by scientists and researchers for its extensive libraries.</li>
</ul>
<p>Python is pre-installed in most Linux distributions. Follow <a target="_blank" href="https://www.datacamp.com/blog/how-to-install-python">this article</a> on how to install Python on Windows and MacOS.</p>
<h2 id="heading-how-to-write-hello-world-in-python">How to Write "Hello, World" in Python</h2>
<p>This is usually the first achievement when starting to code in any language: having your code say 'Hello world'. Open any code editor of your choice, and create a file named <code>project.py</code>. Inside the file, type the following:</p>
<pre><code class="lang-python">     print(<span class="hljs-string">"Hello, World!"</span>)
</code></pre>
<p>To run this code, open the command line interface (CLI). Follow <a target="_blank" href="https://www.freecodecamp.org/news/command-line-for-beginners/">this article</a> to understand more about CLI.</p>
<p>Make sure to open the directory where the file is saved, and run the following:</p>
<pre><code class="lang-bash"> python3 project.py
</code></pre>
<p>When you run this program, you'll see the timeless greeting displayed in your command line interface.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-30-11-59-12.png" alt="Image" width="600" height="400" loading="lazy">
<em>hello world displayed in the CLI</em></p>
<p>‌Congratulations! You've just executed your first Python script. Now that you've printed a simple message, let's dive deeper into Python.</p>
<h2 id="heading-python-variables-and-data-types"><strong>Python Variables and Data Types</strong></h2>
<p>The primary purpose of computers is to process data into useful information, for that to happen, the data needs to be stored in its memory. This is achieved using a programming language's variables and data types.</p>
<p>Data types in Python are particular kinds of data items, as defined by the value they can take. Variables, on the other hand, are like labeled containers that store this data. They enable you to manage and modify information using specific identifiers.</p>
<p>Data types are generally classified into two types:</p>
<h3 id="heading-primitive-fundamental-data-types">Primitive (Fundamental) Data Types:</h3>
<p>Primitive data types represent simple values. These data types are the most basic and essential units used to store and manipulate information in a program. They translate directly into low-level machine code. </p>
<p>Primitive data types include:</p>
<ul>
<li><strong>String (<code>str</code>):</strong> Represents sequences of characters. Should be enclosed in quotes. Example: <code>"Hello, Python!"</code></li>
<li><strong>Integer (<code>int</code>):</strong> Represents whole numbers without decimals. Example: <code>42</code></li>
<li><strong>Float (<code>float</code>):</strong> Represents numbers with decimals. Example: <code>3.14</code></li>
<li><strong>Boolean (<code>bool</code>):</strong> Represents either <code>True</code> or <code>False</code>.</li>
</ul>
<h4 id="heading-characteristics-of-primitive-data-types">Characteristics of Primitive Data Types:</h4>
<ul>
<li><strong>Immutability:</strong> Primitive data types are immutable, meaning their values cannot be changed after they are created. Any operation that appears to modify a primitive value creates a new value.</li>
<li><strong>Direct Representation:</strong> Each primitive data type directly corresponds to a specific low-level machine code representation.</li>
<li><strong>Atomic Values:</strong> Primitive data types represent individual, atomic values. They are not composed of other types or structures.</li>
</ul>
<h4 id="heading-use-cases-for-primitive-data-types">Use Cases for Primitive Data Types:</h4>
<ul>
<li>Strings are used for text manipulation and representation.</li>
<li>Integers and floats are essential for numerical calculations.</li>
<li>Booleans are employed in logical operations and decision-making.</li>
</ul>
<p>Let's see how these work by continuing to write some Python code.</p>
<p>Modify your <code>project.py</code> file to include the following:</p>
<pre><code class="lang-python"><span class="hljs-comment"># String Example </span>
name = <span class="hljs-string">"John"</span>
<span class="hljs-comment"># Integer Example</span>
age = <span class="hljs-number">25</span> 
<span class="hljs-comment"># Float Example </span>
height = <span class="hljs-number">1.75</span> 
<span class="hljs-comment"># Boolean Example</span>
is_student = <span class="hljs-literal">True</span>
<span class="hljs-comment"># Print variable values </span>
print(<span class="hljs-string">"Name:"</span>, name) 
print(<span class="hljs-string">"Age:"</span>, age) 
print(<span class="hljs-string">"Height:"</span>, height)
print(<span class="hljs-string">"Is student?"</span>, is_student)
</code></pre>
<p>In this snippet, you've introduced variables with different data types. Run the program and observe how Python handles these data types.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-30-12-02-11.png" alt="Image" width="600" height="400" loading="lazy">
<em>primitive data types</em></p>
<p>The output reveals the values assigned to the variables in the Python script. The <code>print</code> statements display the contents of the <code>name</code>, <code>age</code>, <code>height</code>, and <code>is_student</code> variables. </p>
<h3 id="heading-non-primitive-composite-data-types-in-python">‌‌Non-Primitive (Composite) Data Types in Python</h3>
<p>Non-primitive data types are structures that can hold multiple values and are composed of other data types, including both primitive and other composite types. Unlike primitive data types, non-primitive types allow for more complex and structured representations of data.</p>
<p>Non-primitive data types include:</p>
<ul>
<li><strong>List (<code>list</code>):</strong> Represents an ordered and mutable collection of values. Example: <code>fruits = ["apple", "banana", "cherry"]</code></li>
<li><strong>Tuple (<code>tuple</code>):</strong> Represents an ordered and immutable collection of values. Example: <code>coordinates = (3, 7)</code></li>
<li><strong>Dictionary (<code>dict</code>):</strong> Represents an unordered collection of key-value pairs. Example: <code>person = {"name": "Alice", "age": 25, "is_student": True}</code></li>
</ul>
<h4 id="heading-characteristics-of-non-primitive-data-types">Characteristics of Non-Primitive Data Types:</h4>
<ul>
<li><strong>Mutability:</strong> Lists are mutable, meaning their elements can be modified after creation. Tuples, on the other hand, are immutable – their elements cannot be changed. Dictionaries are mutable – you can add, modify, or remove key-value pairs.</li>
<li><strong>Collection of Values:</strong> Non-primitive data types allow the grouping of multiple values into a single structure, enabling the creation of more sophisticated data representations.</li>
<li><strong>Ordered (Lists and Tuples):</strong> Lists and tuples maintain the order of elements, allowing for predictable indexing.</li>
<li><strong>Key-Value Mapping (Dictionary):</strong> Dictionaries map keys to values, providing a way to organize and retrieve data based on specific identifiers.</li>
</ul>
<h4 id="heading-use-cases-for-non-primitive-data-types">Use Cases for Non-Primitive Data Types:</h4>
<ul>
<li><strong>Lists:</strong> Useful when you need a collection that can be altered during the program's execution, such as maintaining a list of items that may change over time.</li>
<li><strong>Tuples:</strong> Suitable when you want to ensure that the data remains constant and cannot be accidentally modified. Often used for representing fixed sets of values.</li>
<li><strong>Dictionaries:</strong> Ideal for scenarios where data needs to be associated with specific labels or keys. They offer efficient data retrieval based on these identifiers.</li>
</ul>
<p>Alright, continuing with our Python code – modify the <code>project.py</code> file as shown below:</p>
<pre><code class="lang-python"><span class="hljs-comment"># List Example</span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
print(<span class="hljs-string">"List Example:"</span>, fruits)

<span class="hljs-comment"># Tuple Example</span>
coordinates = (<span class="hljs-number">3</span>, <span class="hljs-number">7</span>)
print(<span class="hljs-string">"Tuple Example:"</span>, coordinates)

<span class="hljs-comment"># Dictionary Example</span>
person = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>, <span class="hljs-string">"is_student"</span>: <span class="hljs-literal">True</span>}
print(<span class="hljs-string">"Dictionary Example:"</span>, person)
</code></pre>
<p>Run the program to see how lists and tuples allow you to organize and store data. In this code snippet:</p>
<ul>
<li>The <code>fruits</code> variable is a list containing strings representing different fruits.</li>
<li>The <code>coordinates</code> variable is a tuple with two integers representing coordinates.</li>
<li>The <code>person</code> variable is a dictionary associating keys ("name," "age," "is_student") with corresponding values.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-01-31-11-19-39.png" alt="Image" width="600" height="400" loading="lazy">
<em>non-primitive data types</em></p>
<p>You can perform various operations on these structures, such as adding elements to a list or accessing individual items in a tuple.</p>
<p>Data types are crucial for several reasons:</p>
<ul>
<li><strong>Memory Allocation:</strong> Different data types require different amounts of memory. Knowing the data type allows the computer to allocate the appropriate amount of memory for a variable.</li>
<li><strong>Operations:</strong> Each data type supports specific operations. For example, you can add two <code>integer</code> numbers, concatenate two <code>strings</code>, or compare two <code>boolean</code> values.</li>
<li><strong>Error Prevention:</strong> Using the wrong data type in an operation can lead to errors. Data types help prevent unintended consequences by enforcing rules on how different types can interact.</li>
</ul>
<h2 id="heading-operators-in-python">Operators in Python</h2>
<p>Operators in Python are symbols that perform operations on variables and values.<br>An operand refers to the inputs or objects on which an operation is performed.</p>
<p>Let's explore some of the essential operators in Python:</p>
<h3 id="heading-arithmetic-operators">Arithmetic Operators:</h3>
<p>Arithmetic operators are fundamental components of any programming language, allowing developers to perform basic mathematical operations on numerical values. </p>
<p>In Python, several arithmetic operators enable you to carry out calculations efficiently. Let's explore these operators:</p>
<ul>
<li>Addition (+): Adds two operands.</li>
<li>Subtraction (-): Subtracts the right operand from the left operand.</li>
<li>Multiplication (*): Multiplies two operands.</li>
<li>Division (/): Divides the left operand by the right operand (always returns a float).</li>
<li>Modulus (%): Returns the remainder of the division of the left operand by the right operand.</li>
<li>Exponentiation (**): Raises the left operand to the power of the right operand.</li>
</ul>
<p>Modify your <code>project.py</code> file to include examples of these operators:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Arithmetic Operators</span>
 num1 = <span class="hljs-number">10</span> 
 num2 = <span class="hljs-number">3</span> 
 add_result = num1 + num2 
 sub_result = num1 - num2 
 mul_result = num1 * num2 
 div_result = num1 / num2 
 mod_result = num1 % num2 
 exp_result = num1 ** num2 
 print(<span class="hljs-string">"Addition:"</span>, add_result) 
 print(<span class="hljs-string">"Subtraction:"</span>, sub_result)
 print(<span class="hljs-string">"Multiplication:"</span>, mul_result) 
 print(<span class="hljs-string">"Division:"</span>, div_result) 
 print(<span class="hljs-string">"Modulus:"</span>, mod_result) 
 print(<span class="hljs-string">"Exponentiation:"</span>, exp_result)
</code></pre>
<p>The code above initializes two variables, <code>num1</code> and <code>num2</code>, with the values <code>10</code> and <code>3</code> respectively, representing two numerical operands.</p>
<p>Then, arithmetic operations are performed using these operands:</p>
<ul>
<li><code>add_result</code> stores the result of adding <code>num1</code> and <code>num2</code>.</li>
<li><code>sub_result</code> stores the result of subtracting <code>num2</code> from <code>num1</code>.</li>
<li><code>mul_result</code> stores the result of multiplying <code>num1</code> and <code>num2</code>.</li>
<li><code>div_result</code> stores the result of dividing <code>num1</code> by <code>num2</code>.</li>
<li><code>mod_result</code> stores the remainder of dividing <code>num1</code> by <code>num2</code>.</li>
<li><code>exp_result</code> stores the result of raising <code>num1</code> to the power of <code>num2</code>.</li>
</ul>
<p>Finally, the results of these arithmetic operations are printed using <code>print()</code> statements, each labeled appropriately, such as "Addition:", "Subtraction:", and so on, followed by the corresponding result.</p>
<p> Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/arithmetic.png" alt="Image" width="600" height="400" loading="lazy">
<em>arithmetic operations</em></p>
<h3 id="heading-comparison-operators">Comparison Operators</h3>
<p>Comparison operators in Python are essential tools for evaluating and comparing values. They enable you to express conditions and make decisions based on the relationship between different values.  They return either <code>True</code> or <code>False</code> based on the comparison result.</p>
<p>Here are the common comparison operators:</p>
<ul>
<li>Equal to (==): Checks if two operands are equal.</li>
<li>Not equal to (!=): Checks if two operands are not equal.</li>
<li>Greater than (&gt;): Checks if the left operand is greater than the right operand.</li>
<li>Less than (&lt;): Checks if the left operand is less than the right operand.</li>
<li>Greater than or equal to (&gt;=): Checks if the left operand is greater than or equal to the right operand.</li>
<li>Less than or equal to (&lt;=): Checks if the left operand is less than or equal to the right operand.</li>
</ul>
<p>Extend your <code>project.py</code> file to include examples of comparison operators:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Comparison Operators </span>
 age = <span class="hljs-number">25</span>
 is_adult = age &gt;= <span class="hljs-number">18</span>
 is_teenager = age &gt;= <span class="hljs-number">13</span> <span class="hljs-keyword">and</span> age &lt; <span class="hljs-number">18</span>
 print(<span class="hljs-string">"Is adult?"</span>, is_adult)
 print(<span class="hljs-string">"Is teenager?"</span>, is_teenager)
</code></pre>
<p>The variable <code>age</code> is initialized with the value <code>25</code>, representing a person's age.</p>
<p>Then, the comparison operator <code>&gt;=</code> is used to evaluate whether <code>age</code> is greater than or equal to <code>18</code>. The result of this comparison determines the boolean value stored in the variable <code>is_adult</code>. If the age is <code>18</code> or older, <code>is_adult</code> will be <code>True</code>, indicating adulthood.</p>
<p>Then the logical operator <code>and</code> is utilized to combine two comparison operations. The first comparison, <code>age &gt;= 13</code>, checks if the age is <code>13</code> or older. The second comparison, <code>age &lt; 18</code>, ensures the age is less than <code>18</code>. If both conditions are true, <code>is_teenager</code> will be <code>True</code>, signifying teenage years.</p>
<p>Finally, the results are printed using <code>print()</code> statements, indicating whether the person is classified as an adult (<code>True</code> or <code>False</code>) and whether they are identified as a teenager (<code>True</code> or <code>False</code>).</p>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/is-adult.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-statements-in-python">Statements in Python</h2>
<p>Statements instruct the interpreter to perform specific actions or operations. These actions can range from simple assignments of values to variables to more complex control flow structures and iterations. </p>
<p>Understanding different types of statements is essential for writing effective and expressive Python code.</p>
<h3 id="heading-assignment-statements">Assignment Statements</h3>
<p>Assignment statements are the most basic type of statement in Python. They are used to assign values to variables, creating a named reference to data. </p>
<p>Here's an example:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span> 
name = <span class="hljs-string">"Alice"</span>
</code></pre>
<p>In this snippet, <code>x</code> is assigned the integer value <code>10</code>, and the <code>name</code> is assigned the string <code>"Alice"</code>. These assignments create variables that can be used throughout the program.</p>
<h3 id="heading-print-statement">Print Statement</h3>
<p>The print statement is used to display output in the console. It is a crucial tool for debugging and providing information to users. Example:</p>
<pre><code class="lang-python">print(<span class="hljs-string">"Hello, Python!"</span>)
</code></pre>
<p>This code prints the string "Hello, Python!" to the console.</p>
<h3 id="heading-conditional-statements-if-elif-else">Conditional Statements (if, elif, else)</h3>
<p>Conditional statements are used when you want to execute different blocks of code based on certain conditions. </p>
<p>Suppose you wanted to determine if a person has reached the legal age for drinking.  Modify the <code>project.py</code> file with the following code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Conditional Statement Example </span>
age = <span class="hljs-number">20</span>
<span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span>:
    print(<span class="hljs-string">"You are a minor."</span>)
<span class="hljs-keyword">elif</span> <span class="hljs-number">18</span> &lt;= age &lt; <span class="hljs-number">21</span>:
    print(<span class="hljs-string">"You are an adult, but not yet allowed to drink."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"You are a legal adult."</span>)
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>if</code> statement checks if <code>age</code> is less than 18.</li>
<li>The <code>elif</code> statement (shorthand for else if) checks if <code>age</code> is between 18 (inclusive) and 21 (exclusive).</li>
<li>The <code>else</code> statement is executed if none of the above conditions are met.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/drinking.png" alt="Image" width="600" height="400" loading="lazy">
<em>if else statement</em></p>
<p>A person aged 20 is not allowed to drink.</p>
<h3 id="heading-loops-for-and-while">Loops (for and while)</h3>
<p>Loops are used to repeat a block of code multiple times. There are two main types of loops in Python: <code>for</code> loops and <code>while</code> loops.</p>
<h4 id="heading-for-loop">For Loop:</h4>
<p>A <code>for</code> loop is used when you know the number of iterations in advance. Suppose you had a list containing the names of fruits, and you wanted to print each fruit. In this case, a <code>for</code> loop is an ideal choice for iterating over the elements of the list. </p>
<p>Here's an example using Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># for loop Example </span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
<span class="hljs-keyword">for</span> fruit <span class="hljs-keyword">in</span> fruits:
    print(fruit)
</code></pre>
<p>‌In this example, the <code>for</code> loop iterates over each element in the <code>fruits</code> list and prints each fruit.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/apple.png" alt="Image" width="600" height="400" loading="lazy">
<em>list of fruits in the for loop</em></p>
<h4 id="heading-while-loop">While Loop:</h4>
<p>A <code>while</code> statement is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition is true.  </p>
<p>Suppose you want to simulate counting until a certain threshold is reached. Modify your <code>project.py</code> and add the following code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># While Loop Example </span>
count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> count &lt; <span class="hljs-number">5</span>:
    print(<span class="hljs-string">"Count:"</span>, count)
    count += <span class="hljs-number">1</span>
</code></pre>
<p>In this scenario, the <code>while</code> loop continues executing as long as the <code>count</code> variable is less than 5. The code inside the loop increments the count and prints the current count in each iteration. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/count.png" alt="Image" width="600" height="400" loading="lazy">
<em>output of while loop</em></p>
<h3 id="heading-break-and-continue-statements">Break and Continue Statements</h3>
<p>Break and continue statements are used within loops.</p>
<ul>
<li><code>break</code>: Exits the loop.</li>
<li><p><code>continue</code>: Skips the rest of the code inside the loop for the current iteration, then continues the loop.</p>
<p>Examples:</p>
</li>
</ul>
<pre><code class="lang-python">‌<span class="hljs-comment"># Break Statement Example </span>
print(<span class="hljs-string">"Output with 'break':"</span>)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    <span class="hljs-keyword">if</span> i == <span class="hljs-number">3</span>:
        print(<span class="hljs-string">f"Encountered 'break' at i=<span class="hljs-subst">{i}</span>"</span>) 
        <span class="hljs-keyword">break</span>
    print(i)

<span class="hljs-comment"># Continue Statement Example </span>
print(<span class="hljs-string">"\nOutput with 'continue':"</span>)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    <span class="hljs-keyword">if</span> i == <span class="hljs-number">2</span>:
        print(<span class="hljs-string">f"Skipped iteration with 'continue' at i=<span class="hljs-subst">{i}</span>"</span>)
        <span class="hljs-keyword">continue</span>
    print(i)
</code></pre>
<p>‌In the <code>break</code> example, the loop stops when <code>i</code> is equal to 3, and the numbers 0, 1, and 2 are printed. </p>
<p>In the <code>continue</code> example, when <code>i</code> is equal to 2, the <code>continue</code> statement skips the <code>print(i)</code> statement for that iteration, resulting in the omission of the number 2 from the output.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/break1.png" alt="Image" width="600" height="400" loading="lazy">
<em>break and continue statements output</em></p>
<h2 id="heading-functions-in-python">Functions in Python</h2>
<p>Functions are reusable blocks of code, enhancing modularity by enclosing functionality into separate, organized units. This approach helps avoid code duplication and significantly improves code readability. </p>
<p>Inside the <code>project.py</code> file, write the following code:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)

<span class="hljs-comment"># Call the function to execute</span>
greet()
</code></pre>
<p>The code above contains a simple Python function called <code>greet()</code>. When 'called' or 'invoked', this function prints "Hello, World!" to the console. It's a basic example illustrating how functions work in Python.</p>
<p>You can take this a step further by including parameters. Parameters serve as placeholders for values passed to a function during its invocation, allowing functions to accept input and perform operations based on that input.</p>
<p>Modify the previous example on <code>if elif else</code> statement to include functions:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_age</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">18</span>:
        print(<span class="hljs-string">"You are a minor."</span>)
    <span class="hljs-keyword">elif</span> <span class="hljs-number">18</span> &lt;= age &lt; <span class="hljs-number">21</span>:
        print(<span class="hljs-string">"You are an adult, but not yet allowed to drink."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"You are a legal adult."</span>)

<span class="hljs-comment"># Call the function with a specific age</span>
check_age(<span class="hljs-number">20</span>)
</code></pre>
<p>In this example, the <code>check_age</code> function takes an <code>age</code> parameter and performs the same conditional check as the original code. The function allows you to reuse this logic for different age values by simply calling the function with the desired age.</p>
<p>You can call <code>check_age</code> function with any age value, and it will print the appropriate message based on the age provided.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-from-2024-02-07-13-03-23.png" alt="Image" width="600" height="400" loading="lazy">
<em>functions</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>‌‌‌‌Embarking on your Python learning journey, this guide introduces the benefits of learning Python, its key characteristics, and practical use cases. </p>
<p>Starting with the iconic "Hello, World!" and progressing through variables, data types, statements, and functions, you've gained some hands-on experience with basic Python. We also talked about primitive and non-primitive data types, conditional statements, and loops.</p>
<p>As your journey progresses, delve into advanced topics like object-oriented programming, file handling, and real-world projects. Armed with foundational knowledge, you can now embrace coding challenges that come your way. Stay curious, and relish the rewarding process of coding with Python. Happy coding!</p>
<p>‌‌</p>
<p>‌‌</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn the C# Programming Language – Full Book for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ C# version 1 was released in January 2002. It is a modern, general purpose programming language designed and developed from the ground up by the renowned Danish software engineer, Anders Heijleberg and his team at Microsoft. I’ve heard Anders Heijlsb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-csharp-book/</link>
                <guid isPermaLink="false">66b0c58dece58de64f5e1dc9</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gavin Lon ]]>
                </dc:creator>
                <pubDate>Tue, 06 Feb 2024 22:35:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/The-C--Handbook---Version-4-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C# version 1 was released in January 2002. It is a modern, general purpose programming language designed and developed from the ground up by the renowned Danish software engineer, Anders Heijleberg and his team at Microsoft.</p>
<p>I’ve heard Anders Heijlsberg say in an interview that with C# the goal was to provide the power and expressiveness of C++ and the RAD (Rapid Application Development) capabilities of Visual Basic.</p>
<p>C# is similar to Java in the sense that it runs within its own environment. Java runs within an environment known as the JRE (Java Runtime Environment) whereas C# runs in an environment known as .NET. Both the JRE and .NET run on top of the relevant operating system.</p>
<p>The first version of .NET is known as the .NET Framework which needs to be deployed to the target computer in its entirely and can only run on Windows platforms. But now, .NET has evolved into an environment that can run on multiple platforms like Windows, Mac OS, Linux, IOS, Android and more.</p>
<p>The .NET environment became fragmented in 2016 with the release of .NET Core, which enabled .NET to be cross platform and agile in the sense that only your application’s base class library dependencies need to be deployed to the target computer with your application.</p>
<p>Then in 2020, .NET became unified with the release of NET 5, which meant that the confusion created by having two strands of .NET, namely .NET Framework and .NET Core, was alleviated.</p>
<p>The latest stable release of C# is a highly evolved, sophisticated programming language that allows you to create almost any kind of application that can run on multiple platforms. You can create a single code base that can run on multiple platforms, for example Linux, Mac OS, Android, IOS, in the Cloud, of course Windows operating systems and more.</p>
<p>You are able to write and build your C# applications using free tools like Visual Studio 2022 Community edition or the cross platform, light weight tool, Visual Studio Code. Visual Studio Code can run on Windows, Mac OS, and Linux platforms.</p>
<p>C# is a highly versatile programming language. You can build many types of applications, such as web-based applications using ASP .NET, cross platform mobile and desktop applications using the .Net MAUI framework, Internet of things applications, AI applications using ML.NET, cloud native applications, games and more.</p>
<p>C# has a huge support base, backed by Microsoft, and is constantly evolving. A new version of .NET is shipped every November, which always contains many improvements and enhancements. This means that .NET is forever evolving, improving, and keeping up with the latest trends in technology.</p>
<p>C# is a well designed, modern, general purpose programming language that will be a great addition to your developer toolkit. So let's dive in.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-net">Introduction to .NET</a></li>
<li><a class="post-section-overview" href="#heading-free-tools-available-for-creating-c-applications">Free Tools Available for Creating C# Applications</a><ul>
<li><a class="post-section-overview" href="#heading-create-a-basic-console-app-using-visual-studio-community-edition">Create a Basic Console App using Visual Studio Community Edition</a><ul>
<li><a class="post-section-overview" href="#heading-the-main-method-application-entry-point">The Main Method (Application Entry Point)</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-basic-console-app-using-visual-studio-code">Creating a Basic Console App using Visual Studio Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-data-types">C# Data Types</a><ul>
<li><a class="post-section-overview" href="#heading-value-types-and-reference-types">Value Types and Reference Types</a></li>
<li><a class="post-section-overview" href="#heading-c-built-in-value-types">C# Built-in Value Types</a></li>
<li><a class="post-section-overview" href="#heading-c-built-in-reference-types">C# Built-in Reference Types</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-strings">C# Strings</a><ul>
<li><a class="post-section-overview" href="#heading-immutability-of-c-strings">Immutability of C# Strings</a></li>
<li><a class="post-section-overview" href="#heading-quoted-string-literals-verbatim-string-literals-and-raw-string-literals">Quoted String Literals, Verbatim String Literals and Raw String Literals</a><ul>
<li><a class="post-section-overview" href="#heading-quoted-string-literals">Quoted String Literals</a></li>
<li><a class="post-section-overview" href="#heading-verbatum-string-literals">Verbatum String Literals</a></li>
<li><a class="post-section-overview" href="#heading-raw-string-literals">Raw String Literals</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-useful-c-built-in-string-methods">Useful C# Built-in String Methods</a><ul>
<li><a class="post-section-overview" href="#heading-the-indexof-built-in-method">The IndexOf Built-in Method</a></li>
<li><a class="post-section-overview" href="#heading-the-replace-built-in-method">The Replace Built-in Method</a></li>
<li><a class="post-section-overview" href="#heading-the-substring-built-in-method">The Substring Built-in Method</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-data-type-conversion">C# Data Type Conversion</a><ul>
<li><a class="post-section-overview" href="#heading-implicit-vs-explicit-data-type-conversion">Implicit vs Explicit Data Type Conversion</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-operators">C# Operators</a><ul>
<li><a class="post-section-overview" href="#heading-types-of-c-operators">Types of C# Operators</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-constants-and-read-only-variables">Constants and Read-only Variables</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-constants">Introduction to Constants</a></li>
<li><a class="post-section-overview" href="#heading-introduction-to-read-only-variables">Introduction to Read-only Variables</a></li>
<li><a class="post-section-overview" href="#heading-code-example-using-a-const">Code Example Using a Const</a></li>
<li><a class="post-section-overview" href="#heading-code-example-using-a-read-only-variable">Code Example Using a Read-only Variable</a></li>
<li><a class="post-section-overview" href="#heading-code-example-of-the-incorrect-use-of-a-read-only-variable">Code Example of the Incorrect Use of a Read-only Variable</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-if-else-if-else-statements">C# if / else if / else Statements</a><ul>
<li><a class="post-section-overview" href="#heading-basic-ifelse-conditional-logic">Basic if/else Conditional Logic</a></li>
<li><a class="post-section-overview" href="#heading-implementing-ifelse-ifelse-conditional-logic">Implementing if/else if/else Conditional Logic</a></li>
<li><a class="post-section-overview" href="#heading-nested-if-statements">Nested if Statements</a></li>
<li><a class="post-section-overview" href="#heading-more-complex-conditional-expressions">More Complex Conditional Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-the-ampamp-operator">The &amp;&amp; Operator</a></li>
<li><a class="post-section-overview" href="#heading-the-operator">The || Operator</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-loops">C# Loops</a><ul>
<li><a class="post-section-overview" href="#heading-the-for-loop">The for Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-while-loop">The while Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-do-while-loop">The do-while Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-foreach-loop">The foreach Loop</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-arrays">C# Arrays</a><ul>
<li><a class="post-section-overview" href="#heading-one-dimensional-arrays">One-dimensional Arrays</a></li>
<li><a class="post-section-overview" href="#heading-multi-dimensional-arrays">Multi-dimensional Arrays</a><ul>
<li><a class="post-section-overview" href="#heading-two-dimensional-arrays">Two-dimensional Arrays</a></li>
<li><a class="post-section-overview" href="#heading-three-dimensional-arrays">Three-dimensional Arrays</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-jagged-arrays">Jagged Arrays</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-methods">C# Methods</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-methods-in-c">Introduction to Methods</a></li>
<li><a class="post-section-overview" href="#heading-the-main-method">The Main Method</a></li>
<li><a class="post-section-overview" href="#heading-the-structure-of-methods">The Structure of Methods</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-classes">C# Classes</a><ul>
<li><a class="post-section-overview" href="#heading-the-class-keyword">The 'class' Keyword</a></li>
<li><a class="post-section-overview" href="#heading-the-public-access-modifier">Public Access Modifier</a></li>
<li><a class="post-section-overview" href="#heading-the-private-member-variable">Private Member Variable</a></li>
<li><a class="post-section-overview" href="#heading-the-constructor">The Constructor</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-structs">C# Structs</a><ul>
<li><a class="post-section-overview" href="#heading-key-differences-between-a-class-and-a-struct">Key Differences Between a Class and a Struct</a></li>
<li><a class="post-section-overview" href="#heading-use-a-struct-in-code">Use a Struct in Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-enums-and-switch-statements">Enums and Switch Statements</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-enums">Introduction to Enums</a></li>
<li><a class="post-section-overview" href="#heading-use-an-enum-in-code">Use an Enum in Code</a></li>
<li><a class="post-section-overview" href="#heading-using-a-switch-statement-in-code-with-an-enum">Using a switch Statement in Code with an enum</a></li>
<li><a class="post-section-overview" href="#heading-associating-one-code-block-with-more-than-one-case">Associating One Code Block with More than One Case</a></li>
<li><a class="post-section-overview" href="#heading-using-strings-in-switch-statements">Using Strings in switch Statements</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-inheritance-in-c">Inheritance in C#</a></li>
<li><a class="post-section-overview" href="#heading-abstraction-in-c">Abstraction in C#</a></li>
<li><a class="post-section-overview" href="#heading-c-exception-handling">C# Exceptions</a></li>
<li><a class="post-section-overview" href="#heading-c-delegates">C# Delegates</a></li>
<li><a class="post-section-overview" href="#heading-c-events">C# Events</a></li>
<li><a class="post-section-overview" href="#heading-c-generics">C# Generics</a></li>
<li><a class="post-section-overview" href="#heading-linq">LINQ</a></li>
<li><a class="post-section-overview" href="#heading-c-attributes">C# Attributes</a></li>
<li><a class="post-section-overview" href="#heading-reflection-in-c">Reflection</a></li>
<li><a class="post-section-overview" href="#heading-video-on-asynchronous-programming-in-c">Video on Asynchronous Programming in C#</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-net">Introduction to .NET</h2>
<p>As we briefly discussed in the introductory section, .NET provides an environment in which your C# applications run.</p>
<p>An essential feature of .NET is what can be described as a virtual machine known as the CoreCLR or Core Common Language Runtime.</p>
<p>The Core Common Language Runtime provides services like Just-in-time compilation, memory management, garbage collection, security and exception handling. Also provided with .NET is a variety of base class libraries, that provide generic functionality that can be leveraged by your C# code.</p>
<p>The first version of .NET was the .NET Framework which was released in 2002. .NET Framework could only run on certain windows platforms and had to be installed in its entirety on the target computer.</p>
<p>.NET Core was released in 2016 and provided a modular, cross platform version of .NET that is optimized for the cloud. A significant feature of .NET Core was that only the dependencies used by your application needed to be shipped to the target computer, unlike .NET Framework that had to exist in its entirety on the target computer.</p>
<p>The rapid evolution of these two versions of .NET, .NET Framework and .NET Core, resulted in growing fragmentations of .NET.</p>
<p>In order to deal with the continuing fragmentation of .NET, Microsoft created the .NET Standard, where all platforms running .NET had to support .NET Standard. This was the first step in unifying .NET but it was a temporary solution.</p>
<p>Then in November 2020, .NET 5 was released. This version of .NET retained the great features of both .NET Framework and .NET core, but this release was significant in that .NET 5 meant that .NET was now unified under one umbrella (as it were). There is now no more .NET Framework and .NET core – rather just one version of .NET moving forward.</p>
<p>With the release of .NET 6 the following year, in November 2021, came many significant improvements and new features. Perhaps what is most significant about .NET 6, is that it cemented the unification of .NET.</p>
<p>At this point in time, .NET is a cross platform, modular, agile, fast, robust and secure environment in which your C# applications can run. This means C# and .NET have now evolved to a point where you can “write once and run anywhere”.</p>
<p>Here's a video overview about how .NET works in more detail:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/P6lJA3E3Uog" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And for a full video series on the evolution of .NET, you can check this out:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/OkeM7XVwEdA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-free-tools-available-for-creating-c-applications">Free Tools Available for Creating C# Applications</h2>
<p>Microsoft provides two sophisticated free tools that you can use for creating C# applications: Visual Studio Community Edition, which is an IDE (Integrated Development Environment) that can run on Windows platforms, and Visual Studio Code (a light weight code editor) that can run on Windows, Mac OS, and Linux platforms.</p>
<p>You can download and install Visual Studio Community Edition 2022 and the latest version of Visual Studio Code from here: <a target="_blank" href="https://visualstudio.microsoft.com/downloads/">https://visualstudio.microsoft.com/downloads/</a>.</p>
<h3 id="heading-create-a-basic-console-app-using-visual-studio-community-edition">Create a Basic Console App using Visual Studio Community Edition</h3>
<p>The easiest way to create your first C# application is by using the simplest project template made available to you through Visual Studio.</p>
<p>The simplest project template is named “Console App”. To get started building your first C# application using Visual Studio, just follow the instructions below:</p>
<ul>
<li>Launch Visual Studio</li>
<li>From the “Get Started” section on the dialog presented to you, select “Create a new project”.</li>
<li>Find the project template named, “Console App”.</li>
<li>Select the “Console App” project template option and press the “Next” button.</li>
<li>Provide a name for your project and the location on your hard disk drive where you’d like to store the files for your project. Press the “Next” button.</li>
<li>At the time of the creation of this book, the latest stable release of .NET is .NET version 8. If you have this latest version installed on your target computer, it will be selected in the relevant dropdown list for the field marked “Framework”.</li>
<li>Press the ‘Create’ button to generate the files for your C# project.</li>
</ul>
<p>You can check out the YouTube video below for a demonstration of creating a basic "Console App" project using Visual Studio 2022.</p>
<p>In this YouTube video, the first demonstration of creating a basic project shows how to create a "Console App" project that includes top-level statements (that is, the <code>Main</code> method definition is not present by default).</p>
<p>The second demonstration shows the creation of a basic "Console App" project that doesn't include top-level statements. You'll see how the <code>Main</code> method is shown in the default code, whereas in the first demonstration only the body of the <code>Main</code> method is shown, and the actual <code>Main</code> method definition is not present.</p>
<p>Note that the <code>Main</code> method is always the entry point of C# applications. Where top-level-statements are included, the <code>Main</code> method is still there but is not visible by default in your code. The inclusion of top-level-statements results in a reduced amount of boilerplate code needed in order for a developer to get started.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/10QrZCLfuCQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h4 id="heading-the-main-method-application-entry-point">The Main Method (Application Entry Point)</h4>
<p>If you look at the "Program.cs" file, you’ll see the following code:</p>
<pre><code class="lang-csharp">
    Console.WriteLine(“Hello World”);
</code></pre>
<p>You can run this code by pressing the play button on your toolbar. The code for this application is very basic and simply outputs the line, "Hello World" to the console screen.</p>
<p>If you look at the code in the "Program.cs" file, it may seem that there is no real entry point to the application. This is specificially when you have elected to use top-level-statements. If you have written code in previous versions of .NET, the absence of a <code>Main</code> method will be conspicuous.</p>
<p>So in .NET 5, for example, the same code currently in your application would look different because the program class and within it the <code>Main</code> method would be included.</p>
<p>Check out the code depicted in figure 1 for an example of this:</p>
<p>Figure 1.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">CSharpSampleCode</span>
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Hello, World!"</span>);
        }
    }
}
</code></pre>
<p>In .NET 6, a marked effort was made to simplify the amount of boilerplate code needed in your applications. Note that with C# 10, you can simply write the body of the <code>Main</code> method in the "Program.cs" file. You don't need to include a class definition (and within the relevant class, a <code>Main</code> method definition) as is depicted in figure 1.</p>
<p>So the relevant statements do not need to reside within a <code>Main</code> method. The statements can exist as what’s known as top-level-statements.</p>
<p>A <code>Main</code> method does still exist behind the scenes and is still the entry point for all C# applications. But after the release of .NET 6, the <code>Main</code> method does not need to be present within your code because the compiler synthesises a <code>Program</code> class with a <code>Main</code> method and places all your top-level-statements within the <code>Main</code> method.</p>
<p>But this is now done behind the scenes. The term top-level-statements means that you're able to write statements that are not wrapped in a <code>Main</code> method within a class. Behind the scenes the <code>Main</code> method and relevant class are created by the compiler. So you're able to write a lot less code, and the entry point of the application – that used to be explicitly written using the <code>Main</code> method – is now synthesised by the C# compiler.</p>
<p>Figure 2 depicts how you can avoid writing multiple lines of code for the <code>Main</code> method (the entry point for a C# application).</p>
<p>Figure 2.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Hello, World!"</span>); <span class="hljs-comment">//The ‘Main' method is not visible within the code</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2pquQMSYk6c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-how-to-create-a-basic-console-app-using-visual-studio-code">How to Create a Basic Console App using Visual Studio Code</h3>
<p>I'll now walk you through the process of creating a console application using Visual Studio Code.</p>
<p>First, you'll need to launch VS Code. For the best experience coding an application in C#, you should install the C# Dev Kit extension using the Extensions view.</p>
<p>You can bring up the Extensions view by clicking the Activity Bar on the side of Visual Studio Code. You can then search for C# Dev Kit and install this extension.</p>
<p>Next, create a local folder where you’d like to store the files for your C# project anywhere on your computer.</p>
<p>Using the File &gt; Open Folder menu option, open the folder you created in the previous step, from within VS Code.</p>
<p>Then launch the terminal window using the View &gt; Terminal menu option. You can also launch the terminal window by pressing ctrl + `</p>
<p>You’ll need to ensure that you have installed an appropriate version of the .NET SDK. The latest stable release is .NET version 8. You can download the recommended install file from this location, <a target="_blank" href="https://dotnet.microsoft.com/download">https://dotnet.microsoft.com/download</a>.</p>
<p>In order to verify that you have installed the .NET SDK, you can type <code>dotnet —-version</code> within the terminal window and then press the enter key.</p>
<p>To create a project based on the "Console App" project template, you can type this command at your command prompt: <code>dotnet new console</code>. Then press the enter key.</p>
<p>To run the project, type <code>dotnet run</code> at the command prompt and press the enter key.</p>
<p>After you have appropriately updated the code in your 'Program.cs' file, remember to save your changes before running the updated code.</p>
<p>As an exercise, change the the code so that the output is 'Hello C#', then save your code, and then run your code by typing in, <code>dotnet run</code> in the terminal window. Once you press the enter key, 'Hello C#' should be outputted to your console screen.</p>
<p>For a detailed video guide on how to use Visual Studio Code to create C# applications, you can watch the following YouTube video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rab_1cFQUF4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-data-types">C# Data Types</h2>
<p>It's important to note that C# is a statically typed programming language, whereas JavaScript and Python, for example, are both dynamically typed.</p>
<p>This means that in C#, when variables are declared at compile time, the variables must be defined as a specific C# type.</p>
<p>An exception to this rule is made through the use of the <code>dynamic</code> type. The <code>dynamic</code> data type allows you to circumvent the .Net type system. If a variable is declared as the <code>dynamic</code> data type, this is similar to how variables are typed in a dynamically typed language like JavaScript.</p>
<p>In most cases, you should strongly type variables so that you can reap the benefits inherent in a statically typed language. The advantage of strongly typing variables is that potential data type-related errors can be flagged at compiled time and then dealt with appropriately at compile time.</p>
<p>If you create code that is not valid in relation to the type used to define a variable, this can be flagged by the C# compiler at compile time.</p>
<p>If you look at the code example in figure 3, the C# code is invalid because variable <code>a</code> is defined as an integer and in the <code>DoSomething</code> method, the <code>a</code> variable is assigned a string value.</p>
<p>The C# compiler flags the exception at compile time, and the exception is represented within the Visual Studio IDE, where a red squiggly line is drawn under the offending code.</p>
<p>Figure 3.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SomeClass</span>
{
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomething</span>(<span class="hljs-params"></span>)</span>
    {
        a = <span class="hljs-string">"Gavin Lon"</span>; <span class="hljs-comment">// Compile time error stating: "Cannot implicitly convert type 'string' to 'int'"</span>
    }
}
</code></pre>
<p>So the code fails to compile and the cause of the compile time exception is made clear to you through a red squiggly line which appears under the offending code.</p>
<p>This safeguards type-related exceptions from being deployed to a production environment where code that is not appropriately checked at compile time could be prone to runtime errors.</p>
<p>Statically typed languages ensure better code robustness at runtime than dynamically typed languages. C# also performs better than dynamically typed languages like JavaScript or Python because the use of statically typed variables means that the type of the variable is known at compile time. This means that variable types do not need to be determined at runtime, which is what happens with dynamically typed languages.</p>
<p>With dynamically typed languages, the type of a variable is determined at runtime based on the value assigned to the relevant variable. With statically typed languages like C#, the type is known, as it were, at compile time – so the added step of determining the variable's type at runtime is not necessary. This results a performance advantage over dynamically typed code.</p>
<h3 id="heading-value-types-and-reference-types">Value Types and Reference Types</h3>
<p>C# data types can be put into two main classifications: value types and reference types. These main data type classifications denote how data for C# data types are stored in memory.</p>
<p>A value type is stored in a memory location called the stack, where the value assigned to a variable is stored in the relevant memory space on the stack.</p>
<p>A reference type is stored in a memory location known as the heap, where an address of where the actual data is stored resides on the stack and points to the location where the actual data is stored on the heap.</p>
<p>A key difference between data stored on the stack and data stored on the heap is that all data stored on the stack has a fixed size, where data stored on the heap does not have a fixed size. the fixed size for discrete data stored on the stack means more efficiency in the storage and retrieval of such data when compared to the management of data stored on the heap.</p>
<p>A very basic example that highlights the significance of value types and references types is the following:</p>
<p>Let’s say an integer named <code>a</code> is assigned a value of <code>1</code>, and an integer named <code>b</code> is assigned the value stored in <code>a</code>. Then let’s say that the value of <code>3</code> is assigned to variable <code>a</code>. Does this assignment affect the value stored in variable <code>b</code>?</p>
<p>The answer is no. This is because the integer data type is a value type. The <code>a</code> variable’s data and the <code>b</code> variable’s data are stored in completely different memory locations on the stack. So a change to the data stored in variable <code>a</code> will not affect the data stored in variable <code>b</code>, even though the value stored in <code>a</code> was assigned to the <code>b</code> variable.</p>
<p>Figure 4.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">int</span> b = a;
a = <span class="hljs-number">3</span>;
</code></pre>
<p>The object data type in C# is the root type for all data types in C#. An object data type is a reference type, and so all types that inherit directly from the object data type are reference types.</p>
<p>In the example below (in figure 5), variable <code>a</code>, which is defined as the <code>Employee</code> user defined type, is assigned a new <code>Employee</code> object, where the <code>Name</code> property is set to the string value of <code>"Gavin Lon"</code>. Variable <code>b</code>, which is defined as the <code>Employee</code> user defined type, is assigned the value of <code>a</code>.</p>
<p>When the <code>Name</code> property of object variable <code>a</code> is changed to <code>David Hasslehoff</code>, the <code>Name</code> property of object variable <code>b</code> is automatically changed to <code>"David Hasslehof"</code>.</p>
<p>This is because when <code>b</code> is assigned the value stored in <code>a</code>, the data stored in <code>a</code> is not copied to the storage location that stores the data in <code>b</code>. A memory address is copied to <code>b</code>, which contains the memory location of where the data is stored for variable <code>a</code>. The actual data is stored on the heap and only the memory location of where the data is stored on the heap, is stored on the stack.</p>
<p>This means that variable <code>a</code> and variable <code>b</code> reference the same data (stored on the heap) at this point. So when the <code>Name</code> property of object variable <code>a</code> is changed to <code>"David Hasslehof"</code>, this change also affects variable <code>b</code>. So the <code>Name</code> property in variable <code>b</code> will also reflect <code>"David Hasselhof"</code>.</p>
<p>Figure 5.</p>
<pre><code class="lang-csharp">Employee a = <span class="hljs-keyword">new</span> Employee { Id = <span class="hljs-number">1</span>, Name = <span class="hljs-string">"Gavin Lon"</span> };
Employee b = a;
a.Name = <span class="hljs-string">"David Hasslehof"</span>;
Console.WriteLine(b.Name); <span class="hljs-comment">// This code prints out the value of David Hasslehof</span>
</code></pre>
<h3 id="heading-c-built-in-value-types">C# Built-in Value Types</h3>
<p>You can see below, in figure 6, the built-in value type data types in C#. Each item contains a link to an appropriate Microsoft Learn page so that you can read more about the relevant data type.</p>
<p>Figure 6.</p>
<table><thead><tr><th>C# type keyword</th><th>.NET type</th></tr></thead><tbody><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/bool"><code>bool</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.boolean" class="no-loc">System.Boolean</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>byte</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.byte" class="no-loc">System.Byte</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>sbyte</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.sbyte" class="no-loc">System.SByte</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/char"><code>char</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.char" class="no-loc">System.Char</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>decimal</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.decimal" class="no-loc">System.Decimal</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>double</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.double" class="no-loc">System.Double</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>float</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.single" class="no-loc">System.Single</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>int</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int32" class="no-loc">System.Int32</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>uint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint32" class="no-loc">System.UInt32</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>nint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.intptr" class="no-loc">System.IntPtr</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>nuint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uintptr" class="no-loc">System.UIntPtr</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>long</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int64" class="no-loc">System.Int64</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>ulong</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint64" class="no-loc">System.UInt64</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>short</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int16" class="no-loc">System.Int16</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>ushort</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint16" class="no-loc">System.UInt16</a></td></tr></tbody></table>

<h3 id="heading-c-built-in-reference-types">C# Built-in Reference Types</h3>
<p>And you can also see all of the built-in reference type data types in C# in figure 7.</p>
<p>Figure 7.</p>
<table><thead><tr><th>C# type keyword</th><th>.NET type</th></tr></thead><tbody><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-object-type"><code>object</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object" class="no-loc">System.Object</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-string-type"><code>string</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.string" class="no-loc">System.String</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type"><code>dynamic</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object" class="no-loc">System.Object</a></td></tr></tbody></table>

<p>And now you can check out two YouTube videos where C# data types and C# variables are discussed. Code examples are also provided.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/sW-fsSJaFA0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rM9HostBLJ4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-strings">C# Strings</h2>
<p>In C#, you can define a string using the <code>System.String</code> class or using its alias, <code>string</code>. In the example depicted in figure 8, the two lines of code are equivalent:</p>
<p>Figure 8.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> fullName = <span class="hljs-string">"Gavin Lon"</span>;
System.String fullName = <span class="hljs-string">"Gavin Lon"</span>;
</code></pre>
<p>A string is simply a reference to an object in memory that stores text. Internally, a string is an array of char objects.</p>
<p>To create a new string object, the <code>new</code> keyword is not generally used. The <code>new</code> keyword is only used to create a new string when an array of char objects is passed as an argument to the constructor of the relevant string object.</p>
<p>You can see an example of this below in figure 9.</p>
<p>Figure 9.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">char</span>[] nameCharacters = { <span class="hljs-string">'G'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'v'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">' '</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'n'</span> };
<span class="hljs-keyword">string</span> fullName = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>(nameCharacters);
</code></pre>
<h3 id="heading-immutability-of-c-strings">Immutability of C# Strings</h3>
<p>Strings are reference types, which means a numeric reference to a memory address is stored on the stack and points to the actual string data which is stored on the heap.</p>
<p>The difference between the string reference type and other reference types (like, for example, an object instantiated from a class) is that the data for a particular string (stored on the heap) cannot be directly changed in memory. This means that every time, for example, a concatenation operation occurs in code, the memory address stored on the stack is simply amended to point to a new memory location on the heap that stores the new string that has been created as a result of the relevant concatenation operation.</p>
<h3 id="heading-quoted-string-literals-verbatim-string-literals-and-raw-string-literals">Quoted String Literals, Verbatim String Literals and Raw String Literals</h3>
<h4 id="heading-quoted-string-literals">Quoted String Literals</h4>
<p>Quoted string literals are string values defined on one line in code that start with a single double quote character and end with a single double quote character. Quoted string literals are best suited for stings that exist on one line and don’t contain escape sequences.</p>
<p>If you were to include a backslash (<code>\</code>) character in a quoted string literal (like when expressing a directory path, for example), you would need to escape the backslash character with a backslash character directly preceding the backslash character you wish to output as part of the string.</p>
<p>Here's an example of this depicted in figure 11.</p>
<p>Figure 11.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">"C:\\development\\CSharpProjects"</span>;
Console.Write(path);
<span class="hljs-comment">// Output: C:\development\CSharpProjects</span>
</code></pre>
<p>The <code>\</code> character has a special meaning in C#, so it must be escaped with the appropriate escape character – which is the <code>\</code> character. To make it clear that the <code>\</code> character is an escape character used in C# string literals, see the below example (in figure 12) where the <code>\</code> character is used to escape the double quote (<code>"</code>) characters included in a string literal.</p>
<p>Figure 12.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">"\"C:\\development\\CSharpProjects\""</span>;
Console.WriteLine(path);
<span class="hljs-comment">//Output: "C:\development\CSharpProjects"</span>
</code></pre>
<h4 id="heading-verbatum-string-literals">Verbatum String Literals</h4>
<p>Verbatim string literals are recommended where quotations and backslash characters need to be included in the output for string literals. If you precede a string literal with the <code>@</code> symbol, the relevant code can output the relevant string verbatim.</p>
<p>Note how the code in figure 13 outputs the same result as the code depicted in figure 12.</p>
<p>Figure 13.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">@"""C:\development\CSharpProjects"""</span>;
Console.WriteLine(path);
<span class="hljs-comment">// Output: "C:\development\CSharpProjects"</span>
</code></pre>
<p>The output is the same when the same string lateral is represented in code as a quoted string literal and as a verbatim string literal.</p>
<p>But using a verbatim string literal is much easier to read and is cleaner in its representation. So where the backslash and double quote symbols need to be outputted within the string literal, it's better to use a verbatim string literal.</p>
<p>It's also better to use a verbatim string literal for code that outputs multiline text. In figure 14 is a code example where a verbatim string literal is used in code to output multiline text.</p>
<p>Figure 14.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative =
    <span class="hljs-string">@"Humpty Dumpty sat on the wall
Humpty Dumpty had a great fall
all the kings horses and all the kings men
couldn’t put Humpty together again"</span>;
</code></pre>
<p>So the above code example dipicted in figure 14 would output the narrative as it is written in the literal string – that is, the text is outputted on multiple lines as the text appears within the literal string in code.</p>
<h4 id="heading-raw-string-literals">Raw String Literals</h4>
<p>C# 11 introduced raw string literals. These make it even easier to write code to output multiline text.</p>
<p>Raw string literals remove the need to ever use escape sequences within literal strings.</p>
<p>To indicate in code that you are using a raw string literal, you wrap the relevant text in three double quote symbols. So the first 3 characters should be three double quote symbols followed by the literal string, and the last 3 characters must be three double quote symbols.</p>
<p>Note that in this example, the three quotes that wrap the string literal appear on their own line. This is important because in this example the first part of the string literal appears within double quotes.</p>
<p>Note the output of the code below in figure 15.</p>
<p>Figure 15.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> text = <span class="hljs-string">""</span><span class="hljs-string">"
"</span>To be or not to be<span class="hljs-string">" is a quote from Shakespeare's Hamlet.
"</span><span class="hljs-string">""</span>;
Console.WriteLine(text);
<span class="hljs-comment">// Output: "To be or not to be" is a quote from Shakespeare’s Hamlet.</span>
</code></pre>
<p>Note the output of the code example depicted in figure 16.</p>
<p>Figure 16.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">""</span><span class="hljs-string">"C:\development\CSharpProjects"</span><span class="hljs-string">""</span>;
Console.WriteLine(path);
<span class="hljs-comment">// Output: C:\development\CSharpProjects</span>
</code></pre>
<p>You could output the multiline text shown in the code example in figure 17, where the output is displayed to the screen in much the same way as the text is represented over multiple lines in the relevant raw literal string in code.</p>
<p>Note that when using a raw string literal to output multiple lines of text, the three double quote characters that must be used to wrap the relevant multiline text must each be on their own line, as is depicted in the example in figure 17.</p>
<p>Figure 17.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative = <span class="hljs-string">""</span><span class="hljs-string">"
Humpty Dumpty sat on the wall
Humpty Dumpty had a great fall
all the kings horses and all the kings men
couldn’t put Humpty together again
"</span><span class="hljs-string">""</span>;
</code></pre>
<h2 id="heading-useful-c-built-in-string-methods">Useful C# Built-in String Methods</h2>
<p>The C# language has many useful built-in string methods that can, for example, be leveraged for common string-related functionality.</p>
<h3 id="heading-the-indexof-built-in-method">The IndexOf Built-in Method</h3>
<p>One common example is finding a string literal within text stored within a string variable using the <code>IndexOf</code> method. See the code example of this depicted in figure 18.</p>
<p>Figure 18.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;

<span class="hljs-comment">// find freeCodeCamp in the narrative</span>
<span class="hljs-keyword">var</span> indx = narrative.IndexOf(<span class="hljs-string">"freeCodeCamp"</span>);

<span class="hljs-comment">// the value of indx will be 46</span>
<span class="hljs-keyword">if</span> (indx == <span class="hljs-number">-1</span>)
{
    Console.WriteLine(<span class="hljs-string">"\"freeCodeCamp\" could not be found in the narrative"</span>);
}
<span class="hljs-keyword">else</span>
{
    Console.WriteLine(<span class="hljs-string">$"\"freeCodeCamp\" was found at position <span class="hljs-subst">{indx}</span> in the narrative"</span>);
}
indx = narrative.IndexOf(<span class="hljs-string">"Gavin Lon"</span>);

<span class="hljs-comment">// the value of indx will be 0</span>
<span class="hljs-keyword">if</span> (indx == <span class="hljs-number">-1</span>)
{
    Console.WriteLine(<span class="hljs-string">"\"Gavin Lon\" could not be found in the narrative"</span>);
}
<span class="hljs-keyword">else</span>
{
    Console.WriteLine(<span class="hljs-string">$"\"Gavin Lon\" was found at position <span class="hljs-subst">{indx}</span>"</span>);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// "freeCodeCamp" was found at position 46 in the narrative</span>
<span class="hljs-comment">// "Gavin Lon" was found at position 0</span>
</code></pre>
<h3 id="heading-the-replace-built-in-method">The Replace Built-in Method</h3>
<p>Another example of common string related functionality used in C# is finding a specific literal string value within text stored in a variable and replacing the relevant literal string with another literal string value. You can do this in C# using the builtin <code>Replace</code> method.</p>
<p>Check out the code example showing this in figure 19.</p>
<p>Figure 19.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;
<span class="hljs-keyword">var</span> newNarrative = narrative.Replace(<span class="hljs-string">"Gavin Lon"</span>, <span class="hljs-string">"Farhan Hassan Chowdury"</span>);
Console.WriteLine(newNarrative);
<span class="hljs-comment">// Output: Farhan Hassan Chowdury loves to create free courses on the freeCodeCamp YouTube channel.</span>
</code></pre>
<h3 id="heading-the-substring-built-in-method">The Substring Built-in Method</h3>
<p>Another common example is assigning a portion of text stored within a variable to another variable using the builtin <code>Substring</code> method. Here's a code example depicting this in figure 20.</p>
<p>Figure 20.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;
<span class="hljs-keyword">var</span> charityName = narrative.Substring(<span class="hljs-number">46</span>, <span class="hljs-number">12</span>);
Console.WriteLine(charityName);
<span class="hljs-comment">// Output: freeCodeCamp</span>
</code></pre>
<p>You can also watch the YouTube video below for more information and code examples that talk about using and manipulating strings in C#.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tzJjrrOe69c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-data-type-conversion">C# Data Type Conversion</h2>
<p>As we discussed above, in C#, variables are statically typed at compile time. This means that once a variable has been defined as a specific type, you can’t define the variable again and you can’t assign a value of an incompatible data type to a variable.</p>
<p>Have a look at the example depicted in figure 21 that highlights static typing in C#.</p>
<p>Figure 21.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative = <span class="hljs-string">"The cat sat on the mat."</span>;
narrative = <span class="hljs-number">1</span> + <span class="hljs-number">1</span>; <span class="hljs-comment">// Compile time error: "Cannot implicitly convert type 'int' to 'string'"</span>
</code></pre>
<p>Here's an example of what happens if you attempt to define a variable twice in code:</p>
<p>Figure 22.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">string</span> a = <span class="hljs-string">"one"</span>;
<span class="hljs-comment">// The compiler would immediately flag an error and underline the ‘a’ variable, where an attempt to</span>
<span class="hljs-comment">// define variable, a, as string is made.</span>
<span class="hljs-comment">// A compile time error occurs: "A local variable or function named 'a' is already defined in this scope"</span>
</code></pre>
<h3 id="heading-implicit-vs-explicit-data-type-conversion">Implicit vs Explicit Data Type Conversion</h3>
<p>Variables defined as numeric datatypes can be implicitly converted to certain other numeric datatypes – but in other cases an explicit conversion is required.</p>
<p>Implicit data type conversion means that the compiler will automatically convert a variable defined as one data type to another data type, and you don't need to appropriately implement explicit data type conversion code in order for the appropriate data type conversion to occur.</p>
<p>The following code example in figure 23 demonstrates trying to implicitly convert a variable defined as a short integer to the byte data type. Note the commented lines that explain what happens in your code editor.</p>
<p>Figure 23.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">short</span> b = <span class="hljs-number">255</span>;
<span class="hljs-keyword">byte</span> a = b;
<span class="hljs-comment">// The compiler would immediately flag an exception and a red squiggly line would appear under</span>
<span class="hljs-comment">// variable b in the second line of code.</span>
<span class="hljs-comment">// If you hover your mouse pointer over the red squiggly line the following error message is</span>
<span class="hljs-comment">// presented: “Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists (are you missing a cast?)”</span>
</code></pre>
<p>After reading the commented lines in figure 23, you can see that an explicit conversion is required to satisfy the C# compiler.</p>
<p>The code in figure 24 shows how you can use an explicit type conversion in this case to prevent the relevant data type compile time exception from being flagged.</p>
<p>Figure 24.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">short</span> b = <span class="hljs-number">255</span>;
<span class="hljs-keyword">byte</span> a = Convert.ToByte(b);
Console.Write(b);
<span class="hljs-comment">// When this code runs, 255, is printed to the console screen</span>
</code></pre>
<p>It's important to note that an explicit type conversion can result in a runtime error occurring. If you assigned <code>b</code> with a value of <code>256</code> instead of <code>255</code> (as in the code depicted in figure 24), a run time error would occur when the code is run.</p>
<p>So this explicit type conversion is dangerous because, in this case, the erroneous code would not be flagged at compile time – which would have forced you to fix the error at compile time (before the code is released into production). So this code would result in a runtime error occuring.</p>
<p>The error is caused because the byte data type supports storing whole number values in memory from <code>0</code> to <code>255</code>. A value of <code>256</code> is clearly outside of this range, so a runtime error will occur with the following error message, <code>System.OverFlowException: Value was either too large or too small for an unsigned byte.</code>. So a value of <code>256</code> must be stored in a variable defined with a data type that supports a range that is greater than the range supported by the byte data type.</p>
<p>The next data type in C# that supports a greater range than the byte data type for whole number values is the short integer data type (or short data type). The value range that a short data type supports is from <code>-32,768</code> to <code>32,767</code>.</p>
<p>The variable defined as the short data type would be clearly be appropriate for storing a whole number value of <code>256</code>.</p>
<p>The next data type that supports a greater value range for whole numbers (than the short data type) is the int data type. The int data type supports a value range from <code>-2,147,483,648</code> to <code>2,147,483,647</code>.</p>
<p>The data type that supports the greatest value range for whole numbers is the long data type, which supports values from <code>-9,223,372,036,854,775,808</code> to <code>9,223,372,036,854,775,807</code>.</p>
<p>As we have just discussed, the C# language has data types like the byte data type, the short data type, the int data type and the long datatype for defining variables for the purpose of storing whole number values.</p>
<p>In C#, there are built-in data types appropriate for the storage of values that contain fractal values. Three data types that you can use for the definition of variables for the storage of values with fractal parts are the float, double, and decimal data type.</p>
<p>A great example of a type of value where you’d want to use one of these data types to define a variable (for storing a value that contains a fractal part) is the decimal data type used for storing monetary values. You could use the float or the double data type for storing monetary values, but the decimal data type is more appropriate for this scenario. This is because the decimal data type (although supports less magnitude than the float or double data types) supports greater precision.</p>
<p>In a banking application, for example, where monetary value precision is of the utmost importance, accounting for fractions of value is essential. So the decimal data type (that supports the highest precision for values in C#) should be leveraged for storing monetary values.</p>
<p>Keep in mind that data can be lost when converting a value stored in a variable defined as one particular data type to another data type.</p>
<p>For example, if you have a monetary value stored in a variable defined as a decimal data type that contains a fractal part, converting this value to, for e.g. an int data type would result in the loss of the fractal part of the value.</p>
<p>Here's an example of this depicted in figure 25.</p>
<p>Figure 25</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> monetaryValue = <span class="hljs-number">10.34</span>m; <span class="hljs-comment">// note if the ‘m’ suffix is not provided the data type is</span>

<span class="hljs-comment">// assumed to be the double data type.</span>
<span class="hljs-comment">// The ‘m’ suffix explicitly defines the variable as</span>
<span class="hljs-comment">// decimal</span>
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = Decimal.ToInt32(monetaryValue); <span class="hljs-comment">//converts decimal to int</span>
Console.WriteLine(<span class="hljs-keyword">value</span>); <span class="hljs-comment">// this outputs 10 – the value of 0.34 is lost</span>
</code></pre>
<p>So you can see that a value of <code>0.34</code> would be lost as a result of running the data type conversion code depicted in figure 25.</p>
<p>You can check out the YouTube video below for more information on implicit and explicit data type conversions in C#.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NF4lyA1yx8Y" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-operators">C# Operators</h2>
<p>C# operators are made up of one or more symbols that signify to the C# compiler that a particular operation should be performed between relevant operands.</p>
<p>In figure 26, we have a few simple examples of built-in C# operators used to perform mathematical operations.</p>
<p>Figure 26.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">var</span> b = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> r = a + b; <span class="hljs-comment">// the ‘+’ symbol signifies to the compiler to perform an appropriate Addition operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 3 to the screen</span>
r = a * <span class="hljs-number">2</span>; <span class="hljs-comment">//the ‘*’ symbol signifies to the compiler to perform an appropriate multiplication operation</span>
Console.WriteLine(r); <span class="hljs-comment">//prints 2 to the screen</span>
r = b - a; <span class="hljs-comment">//the ‘-’ symbol signifies to the compiler to perform an appropriate subtraction operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 1 to the screen</span>
r = b / <span class="hljs-number">2</span>; <span class="hljs-comment">//the ‘/’ symbol signifies to the compiler to perform an appropriate multiplication operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 1 to the screen</span>
</code></pre>
<p>Typically you are able to overload the default behaviour for built-in operators for numeric data types in C#. So you can change the behaviour of specific operators between two operands defined as specific built-in C# data types.</p>
<p>In the above example, the <code>+</code> operator performs an addition mathematical operation between the relevant operands. You could write code to overload the <code>+</code> operator and change the default addition functionality between two integers.</p>
<p>For example, instead of performing an addition operation between <code>1</code> and <code>2</code> where a value of <code>3</code> is the result of the relevant operation, your operator overload code could return <code>12</code>. So in this case the <code>1</code> and <code>2</code> are simply put together as if a concatenation of two string values was being performed. An integer value of <code>12</code> would be the result of the relevant operation.</p>
<p>Of course, overloading the operator in this way may not be very practical. This example merely illustrates how you could change the behaviour of the <code>+</code> operator between two integer values by overloading the <code>+</code> operator in C#.</p>
<h3 id="heading-types-of-c-operators">Types of C# Operators</h3>
<p>The table below is copied from the Microsoft Learn platform at this URL, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators</a></p>
<table>
<thead>
<tr>
<th>Operators</th>
<th>Category or name</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="member-access-operators#member-access-expression-">x.y</a>, <a href="member-access-operators#invocation-expression-">f(x)</a>, <a href="member-access-operators#indexer-operator-">a[i]</a>, <a href="member-access-operators#null-conditional-operators--and-"><code>x?.y</code></a>, <a href="member-access-operators#null-conditional-operators--and-"><code>x?[y]</code></a>, <a href="arithmetic-operators#increment-operator-">x++</a>, <a href="arithmetic-operators#decrement-operator---">x--</a>, <a href="null-forgiving">x!</a>, <a href="new-operator">new</a>, <a href="type-testing-and-cast#typeof-operator">typeof</a>, <a href="../statements/checked-and-unchecked">checked</a>, <a href="../statements/checked-and-unchecked">unchecked</a>, <a href="default">default</a>, <a href="nameof">nameof</a>, <a href="delegate-operator">delegate</a>, <a href="sizeof">sizeof</a>, <a href="stackalloc">stackalloc</a>, <a href="pointer-related-operators#pointer-member-access-operator--">x-&gt;y</a></td>
<td>Primary</td>
</tr>
<tr>
<td><a href="arithmetic-operators#unary-plus-and-minus-operators">+x</a>, <a href="arithmetic-operators#unary-plus-and-minus-operators">-x</a>, <a href="boolean-logical-operators#logical-negation-operator-">!x</a>, <a href="bitwise-and-shift-operators#bitwise-complement-operator-">~x</a>, <a href="arithmetic-operators#increment-operator-">++x</a>, <a href="arithmetic-operators#decrement-operator---">--x</a>, <a href="member-access-operators#index-from-end-operator-">^x</a>, <a href="type-testing-and-cast#cast-expression">(T)x</a>, <a href="await">await</a>, <a href="pointer-related-operators#address-of-operator-">&amp;x</a>, <a href="pointer-related-operators#pointer-indirection-operator-"><em>x</em></a>, <a href="true-false-operators">true and false</a></td>
<td>Unary</td>
</tr>
<tr>
<td><a href="member-access-operators#range-operator-">x..y</a></td>
<td>Range</td>
</tr>
<tr>
<td><a href="switch-expression">switch</a>, <a href="with-expression">with</a></td>
<td><code>switch</code> and <code>with</code> expressions</td>
</tr>
<tr>
<td><a href="arithmetic-operators#multiplication-operator-">x  y</a>, <a href="arithmetic-operators#division-operator-">x / y</a>, <a href="arithmetic-operators#remainder-operator-">x % y</a></td>
<td>Multiplicative</td>
</tr>
<tr>
<td><a href="arithmetic-operators#addition-operator-">x + y</a>, <a href="arithmetic-operators#subtraction-operator--">x – y</a></td>
<td>Additive</td>
</tr>
<tr>
<td><a href="bitwise-and-shift-operators#left-shift-operator-">x &lt;&lt;  y</a>, <a href="bitwise-and-shift-operators#right-shift-operator-">x &gt;&gt; y</a>, <a href="bitwise-and-shift-operators#unsigned-right-shift-operator-">x &gt;&gt;&gt; y</a></td>
<td>Shift</td>
</tr>
<tr>
<td><a href="comparison-operators#less-than-operator-">x &lt; y</a>, <a href="comparison-operators#greater-than-operator-">x &gt; y</a>, <a href="comparison-operators#less-than-or-equal-operator-">x &lt;= y</a>, <a href="comparison-operators#greater-than-or-equal-operator-">x &gt;= y</a>, <a href="type-testing-and-cast#is-operator">is</a>, <a href="type-testing-and-cast#as-operator">as</a></td>
<td>Relational and type-testing</td>
</tr>
<tr>
<td><a href="equality-operators#equality-operator-">x == y</a>, <a href="equality-operators#inequality-operator-">x != y</a></td>
<td>Equality</td>
</tr>
<tr>
<td><code>x &amp; y</code></td>
<td><a href="boolean-logical-operators#logical-and-operator-">Boolean logical AND</a> or <a href="bitwise-and-shift-operators#logical-and-operator-">bitwise logical AND</a></td>
</tr>
<tr>
<td><code>x ^ y</code></td>
<td><a href="boolean-logical-operators#logical-exclusive-or-operator-">Boolean logical XOR</a> or <a href="bitwise-and-shift-operators#logical-exclusive-or-operator-">bitwise logical XOR</a></td>
</tr>
<tr>
<td><code>x | y</code></td>
<td><a href="boolean-logical-operators#logical-or-operator-">Boolean logical OR</a> or <a href="bitwise-and-shift-operators#logical-or-operator-">bitwise logical OR</a></td>
</tr>
<tr>
<td><a href="boolean-logical-operators#conditional-logical-and-operator-">x &amp;&amp; y</a></td>
<td>Conditional AND</td>
</tr>
<tr>
<td><a href="boolean-logical-operators#conditional-logical-or-operator-">x || y</a></td>
<td>Conditional OR</td>
</tr>
<tr>
<td><a href="null-coalescing-operator">x ?? y</a></td>
<td>Null-coalescing operator</td>
</tr>
<tr>
<td><a href="conditional-operator">c ? t : f</a></td>
<td>Conditional operator</td>
</tr>
<tr>
<td><a href="assignment-operator">x = y</a>, <a href="arithmetic-operators#compound-assignment">x += y</a>, <a href="arithmetic-operators#compound-assignment">x -= y</a>, <a href="arithmetic-operators#compound-assignment">x *= y</a>, <a href="arithmetic-operators#compound-assignment">x /= y</a>, <a href="arithmetic-operators#compound-assignment">x %= y</a>, <a href="boolean-logical-operators#compound-assignment">x &amp;= y</a>, <a href="boolean-logical-operators#compound-assignment">x |= y</a>, <a href="boolean-logical-operators#compound-assignment">x ^= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &lt;&lt;= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &gt;&gt;= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &gt;&gt;&gt;= y</a>, <a href="null-coalescing-operator">x ??= y</a>, <a href="lambda-operator">=&gt;</a></td>
<td>Assignment and lambda declaration</td>
</tr>
</tbody>
</table>


<p>For more information on C# Operators, you can watch the YouTube Video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/qGgwm95FK5M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For instructions on how you can overload operators in C#, check out the following YouTube video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tq3_8GQxM14" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-constants-and-read-only-variables">Constants and Read-only Variables</h2>
<h3 id="heading-introduction-to-constants">Introduction to Constants</h3>
<p>A constant is like a variable in the sense that you can store a value in it by declaring it and assigning it a value. You can then reference that value with a human readable name that denotes the const value in code.</p>
<p>A constant is different from a variable in the sense that it must be assigned a value on the same line in which it is declared. Also, once you have assigned a value to a constant, you cannot assign a new value to that constant at any other point in the code.</p>
<p>You should use constants in your code where they make your code more readable and maintainable. When you appropriately use a const, you don’t have to repeat a value that you assigned to the const in your code. When you need to reference that value in code, you can instead include the human readable name you gave the const in your code that denotes the relevant constant value.</p>
<p>If a const value needs to change, you only need to change the code in one place (that is where the const has been declared). This change will automatically propagate to where the constant is referenced in other lines of code (that are appropriately scoped).</p>
<h3 id="heading-introduction-to-read-only-variables">Introduction to Read-only Variables</h3>
<p>A read-only variable is like a variable in that you can store a value in it by declaring it and assigning it a value. You can then reference that value with a human readable name that denotes the read-only variable.</p>
<p>A read-only variable is different from a variable in that its value can only be changed once in code after it has been declared. Its value can be changed in the constructor of a class, but cannot be changed in other parts of your code.</p>
<p>So if you have assigned a read-only variable with a value in the line where it's declared, you can assign that read-only variable with a different value in the constructor of a class – but you can't then assign that read-only variable a new value in any other code.</p>
<p>So a read-only variable is often referred to as a runtime constant. A constant is declared and assigned its value on the same line of code at compile time, and the value for that const cannot be subsequently changed at compile time (and so also can’t be changed at runtime).</p>
<p>A read-only variable is assigned the value that cannot be subsequently changed at runtime. So with a read-only variable, where it is assigned a value within the constructor of a class, is set once when an object instance is created from that class at runtime. That read-only variable cannot be changed after this assignment is made.</p>
<h3 id="heading-code-example-using-a-const">Code Example Using a Const</h3>
<p>Here's an example of how to use a const depicted in figure 27.</p>
<p>Figure 27.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> SpeedOfLight = <span class="hljs-number">299792458</span>;
Console.WriteLine(<span class="hljs-string">$"The speed of light is <span class="hljs-subst">{SpeedOfLight}</span>"</span>);
<span class="hljs-comment">// The output for this code is:</span>
<span class="hljs-comment">// The speed of light is 299792458</span>
</code></pre>
<h3 id="heading-code-example-using-a-read-only-variable">Code Example Using a Read-only Variable</h3>
<p>And here's an example in figure 28 of how to use a read-only variable:</p>
<p>Figure 28.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"Admin"</span>);
employee.PrintEmployeeRole();
</code></pre>
<p>Notice how the read-only string variable named <code>"RoleName"</code> has been assigned a value twice. It's assigned an empty string when it's first declared at the top of the class. The read-only variable is assigned its final value within the constructor of the <code>Employee</code> class.</p>
<p>Note that you can only change the value of a read-only variable once, and you can only do this within the constructor of a class. Once a read-only variable’s value is assigned within the constructor of a class, you can't change its value in any other part of the code.</p>
<p>In the example below in figure 29, a method named <code>SetRoleName</code> contains code to change the value of the <code>RoleName</code> read-only variable. This is not possible in C#, because the read-only variable can only be assigned its final value within the contructor of a class. You cannot for e.g. assign the read-only variable a value within a method.</p>
<p>This code will result in a compile time error being flagged by the C# compiler. The error message will state the following in your code editor: <code>A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initialiser)</code>.</p>
<h3 id="heading-code-example-of-the-incorrect-use-of-a-read-only-variable">Code Example of the Incorrect Use of a Read-only Variable</h3>
<p>Figure 29.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"Admin"</span>);
employee.PrintEmployeeRole();
</code></pre>
<p>For more information on const and read-only variables, you can watch the YouTube video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/yvOdN5PBY2g" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-if-else-if-else-statements">C# if / else if / else Statements</h2>
<h3 id="heading-basic-ifelse-conditional-logic">Basic if/else Conditional Logic</h3>
<p>If statements allow you to include conditional logic in your code. Let's look at a basic example to see how they work.</p>
<p>Let's say you are working on a shopping cart application and a particular piece of code adds a product to the user's shopping cart. In your code, you only want that item added to the user’s shopping cart if the product is in stock.</p>
<p>When a user tries to add a product that is out of stock, you want a message displayed informing the user that the item they want to add is not in stock. You could also add to this message that they should try to add this item to their shopping cart in a week (i.e. when the item may be in stock).</p>
<p>In C#, to automate this conditional logic, you can implement an <code>if / else</code> statement. The code in figure 30 shows how this might look:</p>
<pre><code class="lang-csharp">Product product = <span class="hljs-keyword">new</span>();
product.Name = <span class="hljs-string">"Ladder"</span>;
product.ItemCount = <span class="hljs-number">10</span>;
<span class="hljs-keyword">if</span> (product.ItemCount == <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">$"<span class="hljs-subst">{product.Name}</span> is currently not in stock. Please try again in a week."</span>);
}
<span class="hljs-keyword">else</span>
{
    AddToShopingCart(product);
    DisplayMessage(<span class="hljs-string">$"A <span class="hljs-subst">{product.Name}</span> has been successfully added to your shopping cart."</span>);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DisplayMessage</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>
{
    Console.WriteLine(message);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddToShopingCart</span>(<span class="hljs-params">Product product</span>)</span>
{
    Console.WriteLine(<span class="hljs-string">"Code runs to add product"</span>);
}

<span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ItemCount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>The <code>if</code> statement contains a boolean expression. A boolean expression returns either <code>true</code> or <code>false</code>. If the product is in stock, this boolean expression, <code>product.ItemCount == 0</code>, will return <code>false</code>. If the product is not in stock, then the boolean expression will return <code>true</code>.</p>
<p>The <code>if</code> statement expression evaluates whether the relevant product is currently in stock. If the relevant product is no longer in stock, the <code>ItemCount</code> property will return <code>0</code>. In the case, where the number of products in stock is equal to <code>0</code>, code runs and tells the user that the product is not in stock and that they should try to add the product to their cart in a week.</p>
<p>If, however, the count of stock for the product is not equal to <code>0</code> (meaning the product is in stock), code will run that adds the product to the user's shopping cart. A message will also appear on the user's screen stating that the product has been successfully added to the user's shopping cart.</p>
<p>You can simply include an <code>if</code> statement on its own – and not include an <code>else</code> block within the relevant conditional logic. For example, let's say you wanted to output a message to people using a banking application. When their account is overdrawn (that is, they've taken out too much money), the code might look like the basic example in figure 31:</p>
<p>Figure 31.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">2000</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>); <span class="hljs-comment">// this message will be displayed to the user</span>
}
</code></pre>
<h3 id="heading-implementing-ifelse-ifelse-conditional-logic">Implementing if/else if/else Conditional Logic</h3>
<p>Let’s say that in addition to the above code logic, we want to add a requirement so that a specific message is displayed to the person if they can successfully make a withdrawal without their account being overdrawn.</p>
<p>In this requirement, we also want to include a message that gets displayed if their withdrawal results in the balance being less than <code>100</code> dollars.</p>
<p>To account for these additional requirements, we can update the relevant conditional logic with an <code>else if</code> block and an <code>else</code> block. The code in figure 32 shows how this code might look.</p>
<p>Figure 32.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">876</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>);
}
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">100</span>)
{
    DisplayMessage(<span class="hljs-string">"You have less than 100 dollars left in your account."</span>);
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">$"You have successfully withdrawn <span class="hljs-subst">{withdrawalAmount}</span> dollars"</span>);
}
</code></pre>
<p>So how does the <code>if/else if/ else</code> code work? The first boolean expression is evaluated which accounts for if the balance is less than <code>0</code>. If this expression returns <code>true</code>, the message, <code>"Your account is overdrawn."</code>, is displayed to the user.</p>
<p>If that expression returns <code>false</code>, the code in the <code>else if</code> block is evaluated, and then the expression is evaluated to check if the balance is less than <code>100</code>. If this expression returns <code>true</code> (that is, if the value of <code>balance</code> is less than <code>100</code>) the message , <code>"You have less than 100 dollars left in your account."</code>&gt;, is displayed to the user.</p>
<p>If however, the expression returns <code>false</code>, this means that the code within the <code>else</code> block is executed. So the message, <code>"You have successfully withdrawn {withdrawalAmount} dollars"</code> is displayed to the screen.</p>
<p>Each expression is evaluated from top to bottom and each section of the <code>if/else if/else</code> code is mutually exclusive. This means that only one of the statements within each of the sections of the <code>if/else if/else</code> logic can be run when the relevant conditional logic is executed.</p>
<p>When this conditional logic is run, only one of the messages will be displayed to the user as a result of them making a withdrawal from their account.</p>
<h3 id="heading-nested-if-statements">Nested if Statements</h3>
<p>You can also include nested if statements within your conditional logic. An example of this is depicted in figure 33.</p>
<p>Figure 33.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">6500</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">-5000</span>)
    {
        DisplayMessage(
            <span class="hljs-string">"You have reached your allowable overdraft limit. You will be charged a penalty amount!"</span>
        );
    }
    <span class="hljs-keyword">else</span>
    {
        DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>);
    }
}
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">100</span>)
{
    DisplayMessage(<span class="hljs-string">"You have less than 100 dollars left in your account."</span>);
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">$"You have successfully withdrawn <span class="hljs-subst">{withdrawalAmount}</span> dollars"</span>);
}
</code></pre>
<p>In the above example, the top <code>if</code> statement first checks to see if the account has been overdrawn. If the account has been overdrawn (that is, the value of <code>balance</code> is less than <code>0</code>), a nested <code>if/else</code> statement runs. A nested <code>if</code> statement is an <code>if</code> statement that resides within another <code>if</code> statement.</p>
<p>The nested <code>if</code> statement only runs if the expression in the <code>if</code>statement in which the nested <code>if</code> statement resides returns <code>true</code>.</p>
<p>The nested <code>if</code> statement depicted in figure 33 further evaluates if the balance is less than <code>-5000</code>. If this expression returns <code>true</code>, then the user sees a message informing them that the amount just drawn from their account has resulted in the account being overdrawn (i.e. in excess of their allowable overdraft amount). It also lets the user know that the user will be charged an additional penalty amount.</p>
<p>The code in the <code>else</code> part of the nested <code>if</code> statement runs if the user’s balance is between <code>-5000</code> and <code>0</code>. This means their account is overdrawn but will not, in this case, result in a penalty amount being charged (because it's within their allowable overdraft limit).</p>
<h3 id="heading-more-complex-conditional-expressions">More Complex Conditional Expressions</h3>
<h4 id="heading-the-ampamp-operator">The &amp;&amp; Operator</h4>
<p>An <code>if</code> statement can include more complex boolean logic as well. For example, you can use the <code>&amp;&amp;</code> operator or the <code>||</code> operator to evaluate multiple boolean expressions on one line. Figure 34 below depicts a code example of using the <code>&amp;&amp;</code> operator in an <code>if</code> statement to evaluate more than one boolean expression on one line.</p>
<p>The <code>&amp;&amp;</code> operator can be translated as "And also". If the first expression on the left side of the <code>&amp;&amp;</code> operator is evaluated as <code>false</code>, this means that the entire boolean expression evaluated by the <code>if</code> statement is deemed <code>false</code>. The boolean expression on the right side of the expression is not evaluated.</p>
<p>In this case, <code>false</code> is returned by the <code>if</code> statement, meaning that the code within the <code>if</code> statements will not be run.</p>
<p>But if, in this example, the condition on the left hand side of the <code>&amp;&amp;</code> operator is <code>true</code>, this means that the expression on the right side of the <code>&amp;&amp;</code> operator must be evaluated. So in this case, if the value of <code>balance</code> is less than <code>-5000</code>, the boolean expression returns <code>false</code>. This means that the entire boolean expression <code>(balance &lt; -4000 &amp;&amp; balance &gt;= -5000)</code> is <code>false</code>. This also means that the message displayed by the code within the <code>if</code> statement will not run.</p>
<p>But if the code on the right side of the <code>&amp;&amp;</code> operator is <code>true</code> (so in this case the balance is greater than or equal to <code>-5000</code>), the entire boolean expression in the <code>if</code> statement is <code>true</code>. This means the message in the <code>if</code> statement will be outputted to the screen. So <code>Your transaction is successful but you are close to your overdraft limit</code> will be outputted to the screen.</p>
<p>Figure 34.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">5500</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
</code></pre>
<h4 id="heading-the-operator">The || Operator</h4>
<p>You can also use the <code>||</code> operator (as shown in figure 35) when appropriate for boolean expressions that consist of more than one boolean expression.</p>
<p>The <code>||</code> operator can be translated as "or-else". When the boolean expression on the left side of the <code>||</code> operator returns <code>true</code>, the boolean expression on the right side of the <code>||</code> operator does not need to be evaluated. This is because only one of the expressions needs to return true for the entire boolean expression to return <code>true</code>.</p>
<p>If the boolean expression on the left of the <code>||</code> operator returns <code>false</code>, then the expression on the right will be evaluated.</p>
<p>If the expression on the right returns <code>false</code>, then the entire expression returns <code>false</code>. If, however, the expression on the right of the <code>||</code> operator returns <code>true</code>, the entire boolean expression returns <code>true</code>.</p>
<p>Figure 35.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">960</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (withdrawalAmount &lt; <span class="hljs-number">50</span> || balance &lt; <span class="hljs-number">-5000</span>)
{
    RollBackTransaction();
    DisplayMessage(
        <span class="hljs-string">"Your transaction failed either because you tried to withdraw less than 50 dollars or your total withdrawal would have resulted in your account having a balance of less than -5000 dollars which exceeds your overdraft limit."</span>
    );
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">"Thank you! Your transaction was successful!"</span>);
    CommitTransaction();
}
</code></pre>
<p>The code in figure 35 evaluates the boolean expression in the <code>if</code> statement as, if the withdrawl amount is less than 50 dollars then rollback the transaction and display the appropriate message. If, however, the withdrawl amount is greater than 50 dollars the expression on the right hand side of the <code>||</code> operator needs to be evaluated because this means that the expression on the left hand side of the <code>||</code> operator has returned <code>false</code>.</p>
<p>So if the expression on the right hand side of the <code>||</code> operator returns <code>true</code> meaning that the customer's <code>balance</code> is less than <code>-5000</code>, the code to rollback the transaction and display the appropriate message must be run.</p>
<p>So the key take away when using the <code>||</code> operator in an <code>if</code> condition is that if one of the expressions on either side of the <code>||</code> operator returns true, this means that the entire condition returns <code>true</code>. In order for the entire condition to return <code>false</code>, both expressions on either side of the <code>||</code> operator must return <code>false</code>.</p>
<p>So if both expressions on either side of the <code>||</code> operator returns <code>false</code>, this means that the customer has made a valid withdrawl, and the customer's transaction proceeds successfully. A message to this effect is displayed to the customer as a result.</p>
<p>Here's a comprehensive explanation of using <code>if</code> statements for conditional logic in C# in the YouTube video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2mChNV9GmpM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-loops">C# Loops</h2>
<h3 id="heading-the-for-loop">The for Loop</h3>
<p>Through the use of loops in code, programmers are able to drastically reduce the lines of code required to perform specific tasks. A very simple example of this is displaying a count from <code>1</code> to <code>10</code> where each value is printed on a new line in the console window. Without using a loop the code could look like the code depicted in figure 36.</p>
<p>Figure 36.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"1"</span>);
Console.WriteLine(<span class="hljs-string">"2"</span>);
Console.WriteLine(<span class="hljs-string">"3"</span>);
Console.WriteLine(<span class="hljs-string">"4"</span>);
Console.WriteLine(<span class="hljs-string">"5"</span>);
Console.WriteLine(<span class="hljs-string">"6"</span>);
Console.WriteLine(<span class="hljs-string">"7"</span>);
Console.WriteLine(<span class="hljs-string">"8"</span>);
Console.WriteLine(<span class="hljs-string">"9"</span>);
Console.WriteLine(<span class="hljs-string">"10"</span>);
</code></pre>
<p>Using a <code>for</code> loop in C# you could reduce 10 lines of code to 3 lines of code as is depicted in figure 37. You could update the code so that the <code>for</code> loop loops 100 times instead of 10 times. To do this you would change the relevant <code>for</code> loop expression from, <code>count&lt;=10</code>, to <code>count &lt;=100</code>. So in the code example depicted in figure 38 you would have reduced 100 lines of code to 3 lines of code by using the <code>for</code> loop to achieve exactly the same output.</p>
<p>Figure 37.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>; count &lt;= <span class="hljs-number">10</span>; count++)
{
    Console.WriteLine(count);
}
</code></pre>
<p>Figure 38.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>; count &lt;= <span class="hljs-number">100</span>; count++)
{
    Console.WriteLine(count);
}
</code></pre>
<p>You could implement the same functionality using a <code>while</code> loop that loops 10 times as is depicted in figure 39.</p>
<h3 id="heading-the-while-loop">The while Loop</h3>
<p>Figure 39.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">1</span>;
</code></pre>
<h3 id="heading-the-do-while-loop">The do-while Loop</h3>
<p>You could implement the same functionality using a <code>do-while</code> loop in C# as is depicted in figure 40.</p>
<p>Figure 40.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">1</span>;
<span class="hljs-keyword">do</span>
{
    Console.WriteLine(count);
    count++;
} <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">10</span>);
</code></pre>
<p>The difference between a <code>while</code> loop and a <code>do-while</code> loop is that a <code>do-while</code> loop will always execute the code within it at least once. With a <code>while</code> loop the boolean conditional expression is at the top of the loop so when this expression returns <code>false</code> (i.e. before code within the <code>while</code> loop has a chance to run), no code within the <code>while</code> loop will run. With the <code>do-while</code> loop, code within the <code>do-while</code> loop is always executed at least once. In the example depicted in Figure 41, the statements within the <code>while</code> block will never run.</p>
<p>Figure 41.</p>
<p>The value of <code>count</code> is equal to <code>11</code> and the boolean conditional expression, <code>(count &lt;= 10)</code>, returns <code>false</code> so the two lines of code within the <code>while</code> loop will not execute. Let's look at a similar example but where a <code>do-while</code> loop is used. This example is depicted in figure 42.</p>
<p>Figure 42.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">11</span>;
<span class="hljs-keyword">do</span>
{
    Console.WriteLine(count);
    count++;
} <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">10</span>);
</code></pre>
<p>The lines of code within the <code>do-while</code> loop will execute one time. So the result of this is the value of <code>11</code> will be printed to the console screen. After the value of <code>11</code> is printed to the console screen, the boolean expression, <code>(count &lt;= 10)</code>, is run. The value of <code>count</code> is <code>11</code> which means the boolean expression at the bottom of the <code>do-while</code> loop returns <code>false</code>, so the loop will be exited.</p>
<h3 id="heading-the-foreach-loop">The foreach Loop</h3>
<p>In C# you can leverage a <code>foreach</code> loop instead of a <code>for</code> loop. One of the advantages of using a <code>foreach</code> loop rather than a <code>for</code> loop is that if the number of traversals that need to occur in order to traverse all of the relevant items in the loop change, the code created for the execution of the loop does not need to change. Consider this example depicted in figure 43 where a <code>foreach</code> loop is used to print each value contained within an array to the console screen.</p>
<p>Figure 43.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span> };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> val <span class="hljs-keyword">in</span> arr)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{val}</span> "</span>);
}
<span class="hljs-comment">// Output:  1 2 3 4 5 6 7 8 9 10</span>
</code></pre>
<p>Consider what happens when the number of items and values in the array are changed. Please see a code example depiciting this in figure 44.</p>
<p>Figure 44.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">12</span> };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> val <span class="hljs-keyword">in</span> arr)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{val}</span> "</span>);
}
<span class="hljs-comment">// Output:  1 2 3 4 5 6 7 8 9 10 11 13 12</span>
</code></pre>
<p>A <code>for</code> loop used to execute the same code would look like the code example depicted in figure 45.</p>
<p>Figure 45.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">12</span> };
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt;= arr.Length - <span class="hljs-number">1</span>; x++)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{arr[x]}</span> "</span>);
}
<span class="hljs-comment">// Output: 10 8 5 1 2 6 7 4 8 9 3 11 13 12</span>
</code></pre>
<p>With the <code>for</code> loop, the length of the array must be included in the code for executing the loop. The index of the array must be included in the code where each item is printed to the screen. You can accomplish the same task using a <code>for</code> loop and a <code>foreach</code> loop in these scenarios but the <code>foreach</code> loop is cleaner and easier to read. So with the <code>foreach</code> loop you don’t have to worry about the index of the elements in the array or the length of the array.</p>
<p>For more details on loops in C# and more code examples, please watch the YouTube video below this paragraph.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/oO0GXIIE56U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-arrays">C# Arrays</h2>
<p>An array is a data structure. You can store multiple values of the same type within an array. You can also store multiple types within an array by defining the array elements as the object data type.</p>
<p>All types in C# inherit from the object data type, so you can store multiple types of data within an array where the elements are defined as objects.</p>
<p>Consider the below example depicted in figure 46 where an integer array is defined that can store 10 integer values.</p>
<p>Figure 46.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arrValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>In this example, the array can only store integer values. If you try to store any other type in this array, an appropriate compile time error will be flagged.</p>
<p>In the next example in figure 47, you can only store string values.</p>
<p>Figure 47.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span>[] arrayStringValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>But in the example depicted in figure 48 below, you can store both string and integer values as well as other types of data in the array. This is because, as discussed, all data types in C# inherit from the object data type. So in the array in the example below, you can store string values, integer values, decimal values, boolean values, char values, user defined typed values, and so on.</p>
<p>Figure 48.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">object</span>[] arrayObjectValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>Storing multiple data types in this way this is known as 'boxing', because, for example, if an integer is stored as an element within an array defined as object, the integer data is first ‘boxed’ within the object type. This means that in order to retrieve the data as its appropriate data type from the array, the value must first be ‘unboxed’. This simply means that the relevant array element is explicitly type cast from an object to its appropriate data type.</p>
<p>It is important to note that when defining an array as an object, you are in effect circumventing the type system of the C# language and losing the benefits of a strongly typed language (like faster performance, as well as increased robustness of runtime code).</p>
<p>The 'unboxing' code that needs to run when retrieving values from the array can potentially cause runtime errors to occur, as well as causes a casting runtime overhead. And this slows down the performance of the code.</p>
<p>So strongly typing the array is recommended to increase runtime performance and runtime robustness. This lets you leverage the benefits of the strong type system supported by the C# language.</p>
<h3 id="heading-one-dimensional-arrays">One-dimensional Arrays</h3>
<p>In C# you have three types of arrays, one dimensional arrays, multi-dimensional arrays, and jagged arrays.</p>
<p>A one dimensional array allows for the storage of data that is one dimensional in nature. An example of this would be an array of grades for a particular student for a particular year.</p>
<p>So for example, let's say that a student received the following grades in 2023: 60, 50, 72, 85, 91. These grades could be stored in a one dimensional integer array like is depicted in figure 49.</p>
<p>Figure 49.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] grades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>]{<span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span>};
</code></pre>
<h3 id="heading-multi-dimensional-arrays">Multi-dimensional Arrays</h3>
<h4 id="heading-two-dimensional-arrays">Two-dimensional Arrays</h4>
<p>An example of using a multi-dimensional array could be an array where more than one student’s grades are stored in the array. This code example is depicted in below figure 50.</p>
<p>So lets say that grades for Sarah, John, and Bob are stored within the two dimensional array. Within the main set of curley brackets, all of the values are included in the two dimensional array. Also within the main set of curly brackets are three sets of curly brackets, one set for each student. And within each of the three sets of curly brackets are 5 grades pertaining to the three students.</p>
<p>So lets say the first set of grades belongs to Sarah, the second set of grades belongs to John, and the third set of grades belongs to Bob.</p>
<p>Figure 50.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">5</span>]
{
    { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
    { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">80</span>, <span class="hljs-number">93</span> },
    { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }
};
</code></pre>
<p>So the first subscript in the array is 3, which in this example represents the number of students. The second subscript in the array represents the number of grades. So you could use a C# nested <code>for</code> loop to loop through the items in this array and print their values to the screen in a two dimensional matrix display.</p>
<p>In figure 51 you'll see an example of looping through a two dimensional array and displaying the results to the console screen in a two dimensional matrix.</p>
<p>Figure 51.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">5</span>]
{
    { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
    { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">80</span>, <span class="hljs-number">93</span> },
    { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }
};
</code></pre>
<h4 id="heading-three-dimensional-arrays">Three-dimensional Arrays</h4>
<p>You could add another dimension to this array – for example, you could split the grades up for each student so the grades relate to a particular time of year.</p>
<p>For simplicity, let's divide the year in half. So for the first half of 2023, Sarah received the following grades: 54, 42, 70, 80, 93. For the second half of the year, Sarah received the these grades: 65, 46, 68, 90, 95.</p>
<p>So in this example (depicted in figure 52), the relevant three dimensional array includes the results for Sarah and two other students (John and bob) where their results include their grades for the first half of 2023 as well as their grades for the second half of 2023.</p>
<p>Figure 52.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>]
{
    {
        { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
        { <span class="hljs-number">65</span>, <span class="hljs-number">46</span>, <span class="hljs-number">68</span>, <span class="hljs-number">90</span>, <span class="hljs-number">95</span> }
    },
    {
        { <span class="hljs-number">45</span>, <span class="hljs-number">40</span>, <span class="hljs-number">64</span>, <span class="hljs-number">70</span>, <span class="hljs-number">90</span> },
        { <span class="hljs-number">55</span>, <span class="hljs-number">50</span>, <span class="hljs-number">73</span>, <span class="hljs-number">90</span>, <span class="hljs-number">95</span> }
    },
    {
        { <span class="hljs-number">46</span>, <span class="hljs-number">60</span>, <span class="hljs-number">88</span>, <span class="hljs-number">55</span>, <span class="hljs-number">89</span> },
        { <span class="hljs-number">50</span>, <span class="hljs-number">56</span>, <span class="hljs-number">92</span>, <span class="hljs-number">59</span>, <span class="hljs-number">85</span> }
    }
};
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; studentGrades.GetLength(<span class="hljs-number">0</span>); i++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; studentGrades.GetLength(<span class="hljs-number">1</span>); j++)
    {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> k = <span class="hljs-number">0</span>; k &lt; studentGrades.GetLength(<span class="hljs-number">2</span>); k++)
        {
            Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{studentGrades[i, j, k]}</span>\t"</span>);
        }
        Console.WriteLine();
    }
    Console.WriteLine();
    Console.WriteLine();
}
</code></pre>
<p>So in figure 52 above, you can see the first student’s data is printed to the console screen where the first line presents the student’s grades for the first half of the year.</p>
<p>This is followed by a line feed and the first student’s grades for the second half of the year are printed on the subsequent line. Two line feeds follow the data printed for the first student. This is followed by the second student’s grades, and so on.</p>
<p>The first dimension of the array is in this case denoted by the three students. The second dimension of the array is in this case denoted by the the parts of the year (in this case the year is divided into 2 parts (or two halves)). The third dimension of the array is denoted by the actual grades for each student (in this case, five grades).</p>
<p>So depicted in Figure 52 is an example of a three dimensional array declared and initialised. The code that follows outputs the values stored in the three dimensional array to the console screen. So the example in figure 52 is a great example of C# code that implements nested for loops to print out the data stored in a 3 dimensional array to the console screen.</p>
<p>So with this example, you are in effect printing out three dimensional data onto a 2 dimensional screen using C#.</p>
<h3 id="heading-jagged-arrays">Jagged Arrays</h3>
<p>Basically a Jagged array is an array of arrays. It allows you to store uneven data (if you like).</p>
<p>So what do I mean by uneven data? If you go back to the 2-dimensional array example depicted in figure 51, you have 5 grades represented for each of the three students.</p>
<p>Let’s say that student number two (John in the example) studies only the first three subjects, so you only have grades for those three subjects for John. But you have five grades pertaining to the first three subjects as well as grades pertaining to the last two subjects for the other two students (Sarah and Bob) completed. You still want to store John’s three grades along with the five grades for Sarah and Bob in the array.</p>
<p>Well, good news - you can store all of the data (without the need to include redundant ‘placeholder’ data for John’s missing two grades) by using a jagged array.</p>
<p>In the example depicted in figure 53, C# code is implemented for storing the relevant grades in a jagged array. The code that follows outputs the grades to the console screen.</p>
<p>Figure 53.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[][] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>][];
studentGrades[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>] { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> }; <span class="hljs-comment">// Sarah’s grades</span>
studentGrades[<span class="hljs-number">1</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>] { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span> }; <span class="hljs-comment">// John’s grades</span>
studentGrades[<span class="hljs-number">2</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>] { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }; <span class="hljs-comment">// Bob’s grades</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; studentGrades.Length; i++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; studentGrades[i].Length; j++)
    {
        Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{studentGrades[i][j]}</span>\t"</span>);
    }
    Console.WriteLine();
}
</code></pre>
<p>You can see by the outputted results, that when compared to the output in the two dimensional array example depicted in figure 51, the shape of the data is jagged (uneven). This is why this data structure is referred to as a jagged array.</p>
<p>You can watch the YouTube video below for more information on arrays in C#, as well as more code examples of how arrays are used in C# code.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/K4wjL7kRJyE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-methods">C# Methods</h2>
<h3 id="heading-introduction-to-methods-in-c">Introduction to Methods in C</h3>
<p>A method is simply a block of code that contains a series of statements. When a program is run and a method is called, the statements within that method are executed.</p>
<p>In C#, every statement is executed in the context of a method. So methods are fundamental to how C# code is structured and executed.</p>
<h3 id="heading-the-main-method">The Main Method</h3>
<p>The <code>Main</code> method is the entry point of all C# applications. So this is the method that is first executed whenever a program coded in C# is run.</p>
<p>The CLR (Common Language Runtime) calls the <code>Main</code> method when a program (coded in C#) is first started. In C# you can create both named methods and anonymous methods. In this part of the C# book, we'll discuss named methods.</p>
<h3 id="heading-the-structure-of-methods">The Structure of Methods</h3>
<p>Methods are used to encapsulate a series of statements that get executed when the method is called in code. In some cases, a method is just a series of statements where (at runtime) the statements are executed in sequence and no value is returned from the relevant method to the calling code.</p>
<p>These methods (that don’t return a value) contain the <code>void</code> keyword in the relevant method declaration to signify that the method does not return a value.</p>
<p>Methods can also be created that contain a list of statements that are executed sequentially. At the end of the list of statements, a value of a specified data type is returned to the calling code.</p>
<p>For methods that return values, the data type denoting the value that must be returned from the method is appropriately included within the method's declaration. At the end of the sequence of statements encapsulated by the method, the <code>return</code> keyword is included, followed by the value that will be returned to the calling code, on the same line as where the <code>return</code> keyword is included.</p>
<p>You can see a simple example of a method that is used for returning the result of a mathematical operation in figure 54.</p>
<p>Figure 54.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> result = AddTwoNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
Console.WriteLine(result);
<span class="hljs-keyword">int</span> result2 = AddTwoNumbers(<span class="hljs-number">300</span>, <span class="hljs-number">400</span>);
Console.WriteLine(result2);
</code></pre>
<p>In the example above, this simple method has a method declaration that contains a <code>private</code> access modifier. This means that the <code>AddTwoNumbers</code> method is only accessible from methods contained within the same class in which the <code>AddTwoNumbers</code> method resides.</p>
<p>The <code>AddTwoNumbers</code> method returns a value that is of type integer. This is denoted by the <code>int</code> alias used in the method declaration.</p>
<p>The method declaration contains two parameters, both of the integer data type. The first line of code within the method executes the addition mathematical operation between two arguments that are appropriately passed to the method’s parameters at runtime. The second line of code within the method uses the <code>return</code> C# keyword followed by the result of the previous statement, to return the result of the relvant mathematical operation to the calling code.</p>
<p>The <code>return</code> keyword denotes returning a value to the calling code, which in this case will be the result of the mathematical operation executed in the first line of code within the <code>AddTwoNumbers</code> method.</p>
<p>In the example below (depicted in figure 55), two statements are contained within the method. A fundamental difference between the <code>AddTwoNumbers</code> method (depicted in figure 54) and the method below (depicted in Figure 55) is that the <code>LogFormulaResultToFile</code> method (depicted in figure 55) does not return a value. This is denoted by the <code>void</code> keyword which is included within the <code>LogFormulaResultToFile</code> method declaration.</p>
<p>Figure 55.</p>
<pre><code class="lang-csharp">LogFormulaResultToFile(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"This is the result: "</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// This is the result:  7</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogFormulaResultToFile</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">string</span> message</span>)</span>
{
    <span class="hljs-keyword">int</span> result = operand1 + operand2;
    LogToFile(<span class="hljs-string">$"<span class="hljs-subst">{message}</span> <span class="hljs-subst">{result}</span>"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogToFile</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>
{
    Console.WriteLine(message); <span class="hljs-comment">// for simplicity print message to screen rather than write to file</span>
}
</code></pre>
<p>The fundamental structure for every method in C# is defined by its method signature. And we’ve discussed that within methods are a series of statements.</p>
<p>The method signature defines what type of value is returned by the method, the name of the method, and the level of access (or scope) associated with the method (for example, <code>private</code> or <code>public</code>). The method signature also includes zero, one, or a list of parameters denoting arguments that can be passed to the method when the method is called at runtime. The method signature can also contain the following keywords, <code>abstract</code>,<code>sealed</code>, or <code>virtual</code>. These keywords are beyond the scope of this handbook.</p>
<p>Methods are declared in a <code>class</code>, <code>struct</code> or <code>interface</code>. Methods in an <code>interface</code> do not contain any implementation (that is, any statements) and only the method signature is defined in an <code>interface</code>.</p>
<p>Note that methods defined within an <code>interface</code> do not include access modifiers. When a <code>class</code> implements an <code>interface</code>, the methods contained within the <code>interface</code> must be appropriately implemented by the <code>class</code> that implements the <code>interface</code>.</p>
<p>On the other hand, when methods are contained within a <code>class</code> or a <code>struct</code>, both the method signatures and code implementations for the methods are included.</p>
<p>The example below (depicted in figure 56) demonstrates the implementation of a <code>public</code> method that can be used to return the factorial of a number.</p>
<p>Figure 56.</p>
<pre><code class="lang-csharp">MathFunctions mathFunctions = <span class="hljs-keyword">new</span> MathFunctions();
<span class="hljs-keyword">var</span> result = mathFunctions.GetFactorial(<span class="hljs-number">6</span>);
Console.WriteLine(result);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 720</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MathFunctions</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">GetFactorial</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> num</span>)</span>
    {
        <span class="hljs-keyword">int</span> fact = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= num; i++)
        {
            fact = fact * i;
        }
        <span class="hljs-keyword">return</span> fact;
    }
}
</code></pre>
<p>In the <code>public</code> method named, <code>GetFactorial</code>, a local variable is declared and initialised to a value of <code>1</code> at the top of the method.</p>
<p>A local variable is a variable that has local scope, meaning that in this case the <code>fact</code> variable is not accessible outside of the <code>GetFactorial</code> method. It is only accessible within the <code>GetFactorial</code> method. This means that the <code>fact</code> variable’s value cannot be changed from outside the method but can only be changed from within the method.</p>
<p>You can see that within the <code>for</code> loop, a statement is run that alters the value of the <code>fact</code> variable with each iteration of the loop. Once the the loop is terminated, a final result is reached and that result is returned (using the C# <code>return</code> keyword) to the calling code.</p>
<p>If for example the <code>GetFactorial</code> method resides within a class named, <code>MathFunctions</code>, the calling code could look like the example below depicted in figure 57.</p>
<p>Figure 57.</p>
<pre><code class="lang-csharp">
MathFunctions mathFunctions = <span class="hljs-keyword">new</span> MathFunctions();
<span class="hljs-keyword">var</span> result = mathFunctions.GetFactorial(<span class="hljs-number">6</span>);
Console.WriteLine(result);
</code></pre>
<p>Below, you'll see an example of a <code>private</code> method that uses C# string manipulation to appropriately concatenate and reformat the string arguments representing the first name and last name of an employee (depicted in figure 58).</p>
<p>So if the employee’s first name is "John" and the employee's last name is "Denver", the relevant method will return the string value, "Denver, J". The method concatenates the last name with a comma followed by the a further concatenation of the first initial of the employee’s first name.</p>
<p>This concatenation operation is presented by the <code>return</code> keyword on the same line, which means the result of the concatenation operation is returned to the calling code.</p>
<p>Figure 58.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">FormatName</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
{
    <span class="hljs-keyword">return</span> lastName + <span class="hljs-string">", "</span> + firstName.Substring(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>).ToUpper();
}
</code></pre>
<p>In figure 59 below, we have a code sample where a class named <code>Employee</code> is included. This class contains a read-only property named, <code>DisplayName</code>. This property exposes the formatted <code>name</code> to the calling code through the use of the <code>public</code> access modifier.</p>
<p>The <code>firstName</code> and <code>lastName</code> string arguments are passed to the constructor of the <code>Employee</code> class when it is instantiated by the calling code. The calling code can then write the relevant employee’s formatted name to the console screen. So the <code>private</code> method, <code>FormatName</code>, is not accessible to the calling code. The formatting of the employee's name is handled within the <code>Employee</code> class.</p>
<p>This is a design decision driven by the requirements.</p>
<p>Figure 59.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> firstName = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> lastName = <span class="hljs-string">""</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
    {
        <span class="hljs-keyword">this</span>.firstName = firstName;
        <span class="hljs-keyword">this</span>.lastName = lastName;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> DisplayName
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> FormatName(<span class="hljs-keyword">this</span>.firstName, <span class="hljs-keyword">this</span>.lastName); }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">FormatName</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
    {
        <span class="hljs-keyword">return</span> lastName + <span class="hljs-string">", "</span> + firstName.Substring(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>).ToUpper();
    }
}
</code></pre>
<p>The calling code could look like the code example depicted in figure 60:</p>
<p>Figure 60.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Denver"</span>);
Console.WriteLine(employee.DisplayName);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Denver, J</span>
</code></pre>
<p>The code example depicted in figure 59 demonstrates the use of the code design concept of encapsulation. The complexity of the <code>FormatName</code> functionality is encapsulated within a <code>private</code> method in the <code>Employee</code> class so the calling code is not concerned with the implementation detail of the formatting functionality of the employee’s name. The calling code only needs to reference the <code>DisplayName</code> property on an object derived from the <code>Employee</code> user defined type (or class). The formatting functionality is handled within the <code>Employee</code> class.</p>
<p>The <code>private</code> access modifier enforces the encapsulation of the formatting functionality. The <code>FormatName</code> method is not accessible from the calling code, but is only accessible from within the <code>Employee</code> class.</p>
<p>This particular design decision is enforced through the use of the <code>private</code> access modifier appropriately contained within the <code>FormatName</code> method declaration.</p>
<h2 id="heading-c-classes">C# Classes</h2>
<p>C# supports object-oriented programming. All data types including user defined types in C# inherit from the <code>object</code> data type, so you could say that everything in C# is an object. So an <code>int</code> is an object, a <code>decimal</code> is an object, a <code>string</code> is an object, a <code>bool</code> is an object etc…</p>
<p>The main difference between an <code>int</code>, <code>decimal</code> and <code>bool</code> when compared to a <code>string</code> data type is that the <code>int</code>, <code>decimal</code> and <code>bool</code> data types inherit from the ValueType abstract class, the ValueType class in turn inserts from the <code>object</code> type. This means that the <code>int</code>, <code>decimal</code> and <code>bool</code> data types are value types. Strings, on the other hand are reference types. The <code>string</code> data type does not inherit from the ValueType abstract class but inherits directly from <code>System.Object</code> class.</p>
<p>Note that <code>int</code>, <code>bool</code> and <code>decimal</code> data types are implemented as structs in C#. Structs are value types and are similar to classes in many ways.</p>
<p>The main difference between a struct and a class in C# is that structs are value types and classes are reference types. The <code>string</code> data type inherits directly form the <code>System.Object</code> type which means the <code>string</code> datatype is a reference type.</p>
<p>In C# you are able to create your own custom classes. When you create a class in C#, behind the scenes your user defined type inherits from the <code>System.Object</code> type. So your user defined class is a reference type.</p>
<p>Note that you can also create user defined structs using the <code>struct</code> keyword, whereas when you create user defined classes, you use the <code>class</code> keyword.</p>
<p>The underlying difference between a class and a struct is the way they are stored in memory. Value types store their data directly in a memory location known as the stack, while reference types store a numeric reference (memory address) on the stack, to an object containing the actual data (where the data is actually stored) known as the heap.</p>
<p>The stack stores data in a more structured way than how data is stored on the heap. Make sure you understand this difference, because it affects how the objects derived from classes or structs are copied and passed around in code, and the efficiency with which data is stored and retreived in memory.</p>
<p>Structs are generally faster than classes, so if you are working with large amounts of data, structs may be a more efficient option because they don’t require the overhead of heap memory. Structs may be the best option when needing to represent a simple data structure that contains  data types like integer, boolean, or decimal datatypes.</p>
<p>Structs also have the benefit of being handled more efficiently in memory, which means when dealing with large amounts of instantiated objects from a particular data structure, a struct may be a better option to represent that data, rather than a class.</p>
<p>Structs and classes are both similar in that they both support concepts like for example constructors, fields, properties and methods.</p>
<p>In figure 61 the <code>Player</code> class is used as a template for an object that represents a game object for a particular game.</p>
<p>Figure 61</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Player</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> name = <span class="hljs-string">""</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Player</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
    {
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Move</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> x, <span class="hljs-keyword">double</span> y</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Moving <span class="hljs-subst">{name}</span> to coordinates where 'x' = <span class="hljs-subst">{x}</span>, and 'y' = <span class="hljs-subst">{y}</span>"</span>);
    }
}
</code></pre>
<p>In the above example (depicted in figure 61), you can see some of the fundamental concepts in C# being expressed, through for example the use of the <code>class</code> keyword, the <code>private</code> and public access modifiers, a constructor that contains one parameter, a method that contains two parameters and a private member variable defined as a string.</p>
<h3 id="heading-the-class-keyword">The class keyword</h3>
<p>The class keyword in C# is used for defining a user defined reference type or class.</p>
<h3 id="heading-the-public-access-modifier">The Public Access Modifier</h3>
<p>Preceding the <code>class</code> keyword is the <code>public</code> access modifier. The use of the <code>public</code> access modifier in this way means that this class can be accessed and instantiated from anywhere within the assembly in which the class resides as well as from outside of the assembly in which the class resides.</p>
<h3 id="heading-the-private-member-variable">The Private Member Variable</h3>
<p>The <code>private</code> member variable named, <code>name</code>, is not directly accessible to code that exists outside of the <code>Player</code> class. The <code>name</code> member variable can only be accessed and used from within a property, constructor or method that resides within the <code>Player</code> class.</p>
<h3 id="heading-the-constructor">The Constructor</h3>
<p>The <code>Player</code> class (depicted in the code example in figure 61) has one constructor. Classes are instantiated into objects at runtime. The Player constructor contains one string parameter named <code>name</code>. When calling code instantiates an object derived from the <code>Player</code> class, the name of the <code>Player</code> can be passed as an argument to the Player objects constructor.</p>
<p>Within the constructor of the ‘Player’ class the private member variable named, <code>name</code> is assigned the value passed in by calling code to the parameterised constructor of the ‘Player’ class. When the calling code subsequently calls the <code>Move</code> method, the <code>name</code> member variable is accessed and utilised by code within the <code>Move</code> method. The constructor is called when the object is derived from the <code>Player</code> class.</p>
<p>The constructor enables the calling code to assign a value for the name of the player pertaining to the relevant object at the point at which the relevant object is instantiated.</p>
<h3 id="heading-the-move-method">The Move Method</h3>
<p>Once the calling code has instantiated an object from the <code>Player</code> class, the calling code is able to execute the code within the Move method by appropriately calling the <code>Move</code> method on the relevant object.</p>
<p>The <code>Move</code> method is accessible to code from outside of the class in which it resides because it has a <code>public</code> access modifier. If the method had, for example, a private access modifier, this method would only be accessible from within the class in which it resides.</p>
<p>When the <code>Move</code> method is executed by calling code, two arguments of type <code>double</code>, must be passed into the move method because the <code>Move</code> method contains two parameters of type <code>double</code>.</p>
<p>Below (in figure 62) is an example of calling code instantiating an object from the <code>Player</code> class and subsequently calling the Move method on the relevant instantiated player object.</p>
<p>Figure 62.</p>
<pre><code class="lang-csharp">Player player = <span class="hljs-keyword">new</span> Player(<span class="hljs-string">"Bob"</span>);
player.Move(<span class="hljs-number">10.54</span>, <span class="hljs-number">18.43</span>);
</code></pre>
<p>For more information on C# Classes please view the video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/6rlUl5T2Sck" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And below you can find a full video series on C# classes:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=6rlUl5T2Sck&amp;list=PL4LFuHwItvKY76WTDhfGAwrpLZaSxF9fS">C# Classes Video Series</a></p>
<h2 id="heading-c-structs">C# Structs</h2>
<p>The <code>struct</code> keyword is used to define a data structure in C# that is a value type. Structs are similar to classes in many respects – for example, you can use both structs and classes to represent data structures that can contain data members and related behavioural functionality expressed within methods.</p>
<h3 id="heading-key-differences-between-a-class-and-a-struct">Key differences between a Class and a Struct.</h3>
<ul>
<li>The main difference is that a class is a reference type and a struct is a value type. Structs implicitly inherit from the <code>System.ValueType</code> abstract class (which in turn inherits from the <code>System.Object</code> class), while reference types inherit directly from the <code>System.Object</code> type.</li>
<li>A struct is a better choice than a class when representing data structures that store small amounts of data. Another good reason to use a struct is if you need to store small amounts of data in the relevant data structure and where a vast number of objects derived from the relevant struct are being dealt with in code.</li>
<li>You can instantiate an object from a struct using the <code>new</code> keyword just like you would when instantiating an object from a class. But the <code>new</code> keyword is not required when declaring and initialising a struct before you can use it in code.</li>
<li>In C# certain value type primitives are represented as structs, for example the <code>int</code> alias represents the <code>System.Int32</code> struct, the <code>bool</code> alias represents the <code>System.Bool</code> struct, and the <code>float</code> alias represents <code>System.Single</code> struct.</li>
</ul>
<h3 id="heading-use-a-struct-in-code">Use a Struct in Code</h3>
<p>Below (depicted in figure 63) is an example of code that uses a struct to store the specifications for a pattern. The pattern is denoted by a circle that is drawn within a square.</p>
<p>The <code>Radius</code> field stores the value that denotes the radius of the circle, which also determines the size of the square. The <code>InnerSymbol</code> field denotes the <code>char</code> value printed to the screen that is used for depicting the inner circle. The <code>OuterSymbol</code> field denotes the <code>char</code> value printed to the screen that is used for depicting the outer square in the overall pattern.</p>
<p>Figure 63.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Please enter the radius of the circle"</span>);
<span class="hljs-keyword">double</span> radius = Convert.ToDouble(Console.ReadLine());

CircleInSquare circleInSquare;
circleInSquare.Radius = radius;
circleInSquare.InnerSymbol = <span class="hljs-string">'0'</span>;
circleInSquare.OuterSymbol = <span class="hljs-string">'1'</span>;
circleInSquare.Draw();

<span class="hljs-comment">//Output</span>

<span class="hljs-comment">// 11111111111111111111111111111111111111111</span>
<span class="hljs-comment">// 11111111111111000000000000011111111111111</span>
<span class="hljs-comment">// 11111111110000000000000000000001111111111</span>
<span class="hljs-comment">// 11111111000000000000000000000000011111111</span>
<span class="hljs-comment">// 11111100000000000000000000000000000111111</span>
<span class="hljs-comment">// 11110000000000000000000000000000000001111</span>
<span class="hljs-comment">// 11100000000000000000000000000000000000111</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11100000000000000000000000000000000000111</span>
<span class="hljs-comment">// 11110000000000000000000000000000000001111</span>
<span class="hljs-comment">// 11111100000000000000000000000000000111111</span>
<span class="hljs-comment">// 11111111000000000000000000000000011111111</span>
<span class="hljs-comment">// 11111111110000000000000000000001111111111</span>
<span class="hljs-comment">// 11111111111111000000000000011111111111111</span>
<span class="hljs-comment">// 11111111111111111111111111111111111111111</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">struct</span> CircleInSquare
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> Radius;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">char</span> InnerSymbol;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">char</span> OuterSymbol;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CircleInSquare</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> radius, <span class="hljs-keyword">char</span> innerSymbol, <span class="hljs-keyword">char</span> outerSymbol</span>)</span>
    {
        Radius = radius;
        InnerSymbol = innerSymbol;
        OuterSymbol = outerSymbol;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">WriteMemberValuesToScreen</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(
            <span class="hljs-string">$"Radius = <span class="hljs-subst">{Radius}</span>, InnerSymbol = '<span class="hljs-subst">{InnerSymbol}</span>', OuterSymbol = '<span class="hljs-subst">{OuterSymbol}</span>'"</span>
        );
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Draw</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">double</span> radiusInner = Radius - <span class="hljs-number">0.5</span>;
        <span class="hljs-keyword">double</span> radiusOuter = Radius + <span class="hljs-number">0.5</span>;

        Console.WriteLine();

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">double</span> y = Radius; y &gt;= -Radius; --y)
        {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">double</span> x = -Radius; x &lt; radiusOuter; x += <span class="hljs-number">0.5</span>)
            {
                <span class="hljs-keyword">double</span> <span class="hljs-keyword">value</span> = x * x + y * y;

                <span class="hljs-keyword">if</span> (<span class="hljs-keyword">value</span> &gt;= radiusInner * radiusInner)
                {
                    Console.Write(OuterSymbol);
                    System.Threading.Thread.Sleep(<span class="hljs-number">50</span>);
                }
                <span class="hljs-keyword">else</span>
                {
                    Console.Write(InnerSymbol);
                }
            }
            Console.WriteLine();
        }
    }
}
</code></pre>
<p>Note that as demonstrated in the example above (in figure 63), the <code>new</code> keyword does not need to be used when instantiating an object from a struct in C#.</p>
<p>A struct is a data structure in C# that is ideal for storing a small amount of values, for example that are needed for objects derived from the <code>CircleInSquare</code> struct.</p>
<p>As discussed above, structs are value types in C# which means they are handled more efficiently in memory, where the relevant data is stored in memory on the stack. If you needed to store a sufficiently large number of instances of objects derived from the <code>CircleInSquare</code> struct in a collection, this is where a performance advantage could be noticeably gained over a scenario where object instances derived from a class version of the <code>CircleInSquare</code> template are stored within a collection.</p>
<p>So for example in a game where perhaps vector information needs to be stored in a large collection to represent the position of a <code>player</code> object, you could use a struct to represent the data rather than a class. This would help the data be managed more efficiently in memory, which brings a performance advantage as well in terms of code execution.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NVKGxzuBe8c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-enums-and-switch-statements">Enums and Switch Statements</h2>
<h3 id="heading-introduction-to-enums">Introduction to Enums</h3>
<p>In C#, an enum, short for enumeration, is a value type that you can use to define a set of named integral constants. Enums are used to create human readable names for a set of related and unique values, making the code more readable.</p>
<h3 id="heading-use-an-enum-in-code">Use an Enum in Code</h3>
<p>To declare an enum, you use the <code>enum</code> C# keyword. In figure 64 is a code example demonstrating the use of an enum. You can see that months of the year are represented by an enum named <code>MonthOfYear</code>. Each of the twelve members of the <code>MonthOfYear</code> enum represents a unique month of the year. Each month’s associated integer value is ordered in ascending order by the chronological order in which they occur for a calendar year.</p>
<p>So <code>Jan</code> is given the value of <code>1</code>, <code>Feb</code> is given the value of <code>2</code>,  <code>Mar</code> is given the value of <code>3</code> and so on, until the last month <code>Dec</code>, which is given a value of <code>12</code> (the twelfth and final month of the calendar year).</p>
<p>A simple method named <code>OutputMonthMainFocus</code> is passed an enum value in order to output an appropriate narrative to the user that displays the user focus for the passed-in month argument.</p>
<p>Figure 64.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, MonthOfYear.Jan);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, MonthOfYear.Mar);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, MonthOfYear.Dec);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus.for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus.for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Spend more time with friends and family</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">OutputMonthMainFocus</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> prependedText, MonthOfYear month</span>)</span>
{
    <span class="hljs-keyword">switch</span> (month)
    {
        <span class="hljs-keyword">case</span> MonthOfYear.Jan:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Feb:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Mar:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Apr:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Getting up earlier"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.May:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Better work organisation"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jun:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Volunteer work"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jul:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Eating more vegetables"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Aug:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Travel to London"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Sep:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learning to cook better"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Oct:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn to. surf"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Nov:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Be more productive"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Dec:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Spend more time with friends and family"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Invalid Month"</span>);
    }
}
</code></pre>
<h3 id="heading-using-a-switch-statement-in-code-with-an-enum">Using a switch Statement in Code with an enum</h3>
<p>You can see that the above <code>switch</code> statement depicted in figure 64 is similar to an <code>if/else</code> statement.</p>
<p>At the top of the <code>switch</code> statement is code that contains the <code>switch</code> keyword. Within the brackets following the <code>switch</code> keyword is the value that the <code>switch</code> operation compares to a series of values that are denoted by each <code>case</code> statement that's encapsulated within the <code>switch</code> code block.</p>
<p>Each <code>case</code> section is comparing the value within the brackets following the <code>switch</code> keyword to a value following each <code>case</code> keyword. When a match between the value within the brackets following the <code>switch</code> keyword and a value following one of the <code>case</code> keywords is found, the statement list within the matched case section is executed.</p>
<p>For example, where the first line in the calling code (that is code that calls the <code>OutputMonthMainFocus</code> method) is called, the statement in the first case section is executed. This is because <code>Month.Jan</code> is passed in as an argument to the <code>OutputMonthMainFocus</code> method and <code>Month.Jan</code> is a match against the value following the <code>case</code> keyword in the first <code>case</code> section.</p>
<p>Note that a <code>break</code> keyword or a <code>return</code> keyword (if appropriate) must be included as the bottom statement of each case section’s statement list.</p>
<p>Each case section is mutually exclusive. This means that in the code example depicted in figure 64 where a <code>break</code> keyword is included as the bottom statement in each <code>case</code> section, when a match occurs, only the statements within that matching <code>case</code> section are run. Once the statements within that <code>case</code> statement are run, the code breaks out of the <code>switch</code> code block. If there is any code below the <code>switch</code> code block, then that code will subsequently be run. No other code within that <code>switch</code> statement will be run after a match occurs.</p>
<p>If no matches are found within any of the <code>case</code> statements, the code within the <code>default</code> section is run.</p>
<p>You can see in the example in figure 64 that the code throws an <code>ArgumentException</code> if no values within the relevant <code>case</code> statements match the value passed into the <code>switch</code> statement.</p>
<h3 id="heading-associating-one-code-block-with-more-than-one-case">Associating One Code Block with More than One Case</h3>
<p>You could alter the <code>switch</code> statement as depicted in figure 65, so that more than one case statement is associated with a block of code (or lines of code). So if, for example, <code>Month.Jan</code> was passed into the <code>switch</code> statement, the code statements within the <code>Month.Mar</code> case section would run.</p>
<p>The same lines of code within the <code>Month.Mar</code> case section would also run where <code>Month.Feb</code> or <code>Month.Mar</code> are passed in as arguments to the <code>switch</code> statement. This happens because there are no lines of coded included within the <code>Month.Jan</code> case section and there are no lines of code included within the <code>Month.Feb</code> section. So if the <code>Month.Jan</code> or <code>Month.Feb</code> sections aren't matched, the code falls through to the <code>Month.Mar</code> case section and the lines of code within the <code>Month.Mar</code> case section are run.</p>
<p>Of course the lines of code within the <code>Month.Mar</code> section will also run if the <code>Month.Mar</code> case section is matched. So the logic for this is the same as the <code>if</code> statement depicted in figure 64b.</p>
<p>Figure 64b.</p>
<pre><code class="lang-csharp">MonthOfYear month = MonthOfYear.Feb;
<span class="hljs-keyword">string</span> prependedText = <span class="hljs-string">"Focus for Feb"</span>;
<span class="hljs-keyword">if</span> (month == MonthOfYear.Jan || month == MonthOfYear.Feb || month == MonthOfYear.Mar)
{
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
}
</code></pre>
<p>Figure 65.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, MonthOfYear.Jan);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, MonthOfYear.Feb);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, MonthOfYear.Mar);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus for Jan: Learn Spanish</span>
<span class="hljs-comment">// Focus for Jan: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Mar: Health and fitness</span>
<span class="hljs-comment">// Focus for Mar: Learn Spanish</span>
<span class="hljs-comment">// Focus for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Health and fitness</span>
<span class="hljs-comment">// Focus for Dec: Learn Spanish</span>
<span class="hljs-comment">// Focus for Dec: Increase knowledge of calculus</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">OutputMonthMainFocus</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> prependedText, MonthOfYear month</span>)</span>
{
    <span class="hljs-keyword">switch</span> (month)
    {
        <span class="hljs-keyword">case</span> MonthOfYear.Jan:
        <span class="hljs-keyword">case</span> MonthOfYear.Feb:
        <span class="hljs-keyword">case</span> MonthOfYear.Mar:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Apr:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Getting up earlier"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.May:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Better work organisation"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jun:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Volunteer work"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jul:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Eating more vegetables"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Aug:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Travel to London"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Sep:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learning to cook better"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Oct:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn to. surf"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Nov:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Be more productive"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Dec:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Spend more time with friends and family"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Invalid Month"</span>);
    }
}
</code></pre>
<h3 id="heading-using-strings-in-switch-statements">Using Strings in switch Statements</h3>
<p>The example depicted in figure 64, specifically deals with the value list within an enum type. You can also, of course, use a <code>switch</code> statement to evaluate the values for any C# data type.</p>
<p>For example, in figure 66, values of the string data type are evaluated instead of the numeric values contained within an enum. figure 66.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, <span class="hljs-string">"JAN"</span>);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, <span class="hljs-string">"MAR"</span>);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, <span class="hljs-string">"DEC"</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Spend more time with friends and family</span>
</code></pre>
<p>Note that you can use <code>if/else if/else</code> conditional logic where appropiate in order to replace a <code>switch</code> statement, however it is better to use a <code>switch</code> statement when there are a large number of logical conditions to evaluate. This is because a <code>switch</code> statement is more readible in this scenario.</p>
<p>You can watch the YouTube videos below to learn more about switch statements and enums.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/XTDEYQUymt8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1248C0V_yHs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-inheritance-in-c">Inheritance in C</h2>
<p>C# is an object-oriented programming language. The principles of object-oriented programming are encapsulation, inheritance, polymorphism, and abstraction.</p>
<p>Inheritance is where one class is based on another class. It is important to note that multiple inheritance is not permitted in C#. A class in C# can inherit from multiple interfaces but not multiple classes at one time. We'll discuss interfaces in the next section of this handbook along with the principle of abstraction.</p>
<p>So if, for example, the <code>ManagingDirector</code> class is based on the <code>Manger</code> class, which in turn is based on the <code>Employee</code> class, in C# you cannot implement the code like in the example below (in figure 67) in order to express this inheritance hierarchy.</p>
<p>Figure 67.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ManagingDirector</span> : <span class="hljs-title">Manager</span>, <span class="hljs-title">Employee</span>
{
    <span class="hljs-comment">// code goes here</span>
}
</code></pre>
<p>In C++, this type of multiple inheritance is permitted. But in C#, only single inheritance is permitted.</p>
<p>In C# you are, however, still able to express that the <code>ManagingDirector</code> class inherits from the <code>Manager</code> class that in turn inherits from the <code>Employee</code> class – but you have to do this in a specific way.</p>
<p>The example below (in figure 68) depicts how this specific inheritance hierarchy can be expressed in C#.</p>
<p>Figure 68.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Manager</span>:<span class="hljs-title">Employee</span>
{
    <span class="hljs-comment">// code goes here</span>
} 
<span class="hljs-keyword">public</span> ManagingDirector:Manager
{    
    <span class="hljs-comment">// code goes here</span>
}
</code></pre>
<p>So C# only supports single inheritance for classes, but you can achieve multiple inheritance by implementing code in a certain way in C#. The example above (in figure 68) shows you how to do this.</p>
<h2 id="heading-abstraction-in-c">Abstraction in C</h2>
<p>Abstraction is another principle of object-oriented programming. It is a concept that is often confused with another one of the principles of object-oriented programming, namely, encapsulation.</p>
<p>Abstraction can be defined as the inclusion of essential design related code but no implementation detail. The implementation detail is denoted by the lines of code within a method, and the abstraction of that method is the method’s method signature.</p>
<p>In the simplified example below (in figure 69), you can see a method named <code>LogData</code> that is responsible for either printing data to the console screen or printing data to a predefined local file.</p>
<p>Figure 69</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
{
    LogToScreen(data);
}
</code></pre>
<p>The abstraction of this method would be the method signature that could be represented inside an interface like in the example below depicted in figure 70:</p>
<p>Figure 70.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>;
}
</code></pre>
<p>The <code>LogData</code> method could reside inside a class named <code>Logging</code> that implements the <code>ILogging</code> interface. When a class implements an interface in C# this means that the class must contain and implement all the methods that are defined within the relevant <code>interface</code>.</p>
<p>See below (in figure 71) an example of the <code>Logging</code> class implementing the <code>ILogging</code> interface.</p>
<p>Figure 71</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Logging</span> : <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
    {
        LogToScreen(data);
    }
}
</code></pre>
<p>The <code>ILogging</code> interface can be described as an abstraction of the <code>Logging</code> class. In C#, the calling code does not need to know (as it were) about the the code implementation of the <code>LogData</code> method. The calling code only needs to know about the type definition. The type definition is the abstraction of the <code>Logging</code> class.</p>
<p>In the example below (in figure 72) you can see an example of calling code instantiating an object from the <code>Logging</code> user defined type. Notice how the type definition can be implemented using the <code>ILogging</code> interface. This means the calling code will know about the <code>LogData</code> method at compile time, but will not know anything about its implementation.</p>
<p>Figure 72.</p>
<pre><code class="lang-csharp">ILogging logging = <span class="hljs-keyword">new</span> Logging();
logging.LogData(<span class="hljs-string">"Data to be logged."</span>);
</code></pre>
<p>Now you could create many logging classes with different implementations of the <code>LogData</code> method.</p>
<p>For example, currently the <code>Logging</code> class contains an implementation of the <code>LogData</code> method that logs data to the console screen. Let’s say a requirement emerges where you want to log the data to the a predefined file. To do this you could simply create a new class that implements the <code>ILogging</code> interface, where the code within the new class contains code that logs the relevant data to a predefined file.</p>
<p>The example below (in figure 73) depicts the new class. For the sake of simplicity let’s name this class <code>Logging2</code>.</p>
<p>Figure 73.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Logging2</span> : <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
    {
        LogToFile(data);
    }
}
<span class="hljs-comment">// Calling code</span>
ILogging logging = <span class="hljs-keyword">new</span> Logging2();
logging.LogData(<span class="hljs-string">"Data to be logged."</span>);
</code></pre>
<p>The calling code that implements the <code>LogData</code> method in the <code>Logging</code> class would look very similar to when the <code>LogData</code> method is called on an object instantiated from the <code>Logging2</code> class.</p>
<p>In fact you could abstract the instantiation of the relevant <code>logging</code> object into its own factory class like you see below in figure 74. So through the use of an interface we are able to further abstract our code, by abstracting the instantiation process of the logging classes.</p>
<p>Figure 74.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">LoggingFactory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ILogging <span class="hljs-title">GetLoggingObject</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> toScreen</span>)</span>
    {
        <span class="hljs-keyword">if</span> (toScreen)
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Logging();
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Logging2();
        }
    }
}
</code></pre>
<p>The calling code could now be implemented as is depicted below in figure 75.</p>
<p>Figure 75.</p>
<pre><code class="lang-csharp">ILogging logging = LoggingFactory.GetLoggingObject(<span class="hljs-literal">true</span>);
logging.LogData(<span class="hljs-string">"Log data to screen"</span>);
</code></pre>
<p>And the calling code could be implemented as is depicted in figure 76 for logging data to a predefined file.</p>
<p>Figure 76.</p>
<pre><code class="lang-csharp">ILogging logging = LoggingFactory.GetLoggingObject(<span class="hljs-literal">false</span>);
logging.LogData(<span class="hljs-string">"Log data to file"</span>);
</code></pre>
<p>We have abstracted away the implementation for both the <code>LogData</code> method as well as the instantiation of the <code>logging</code> object. This is a very basic example of how the principle of abstraction can be implemented using C# in order to create a separation of concerns.</p>
<p>You can of course create many layers of abstraction using similar techniques and various design patterns. Some key driving forces behind how you abstract your code should be better code reuse, better code readability, easier maintenance of code, design extensibility, and to facilitate better unit testing.</p>
<p>In this book, I haven't delved deep into object-oriented principles. For a more detailed explanation of object-oriented programming using C#, you can check out the videos in the playlist link below. In the videos in this playlist the object-orientied principles of encapsulation, inheritance, polymorphism and abstraction are explained and many practicle code eamples are included.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/HcjOcwMS43w" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on object-oriented programming in C#, please visit here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=HcjOcwMS43w&amp;list=PL4LFuHwItvKYD0e60jNOtT6mFKqFMH1u_">Full Video Series on Object-oriented Programming using C#</a></p>
<h2 id="heading-c-exception-handling">C# Exception Handling</h2>
<p>One of your core design criterion when designing an application should be ensuring that your application is as robust as possible.</p>
<p>In order to do this, you'll need to devise and implement a well-designed exception handling strategy. C# makes this fairly easy through the use of <code>try/catch/finally</code> blocks.</p>
<p>Exception handling is used to prevent an application from crashing. As a good rule, you should try as much as possible to prevent exceptions from being thrown through code, and only use built-in C# <code>try/catch</code> blocks to handle exceptions under truly exceptional circumstances.</p>
<p>A<code>try/catch'</code> block allows you to wrap certain code that you know, under certain exceptional circumstances, can result in your application crashing. By understanding the relevant exceptional circumstances that may cause your application to crash, you can implement the appropriate exception handling functionality.</p>
<p>You can catch specific exceptions through the <code>catch</code> section of the <code>try/catch</code> block. Then you can handle the exception appropriately either by handing the exception within the relevant catch block or by throwing the exception up the stack to be handled appropriately at a further point further up the execution stack.</p>
<p>In this very basic calculator application code example (depicted in figure 77), a method named <code>Calculate</code> is implemented to carry out the calculations.</p>
<p>Figure 77.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">try</span>
{
    <span class="hljs-keyword">int</span> result1 = Calculate(<span class="hljs-number">200000</span>, <span class="hljs-number">500000</span>, <span class="hljs-string">'*'</span>); <span class="hljs-comment">// OverFlowException occures</span>
    <span class="hljs-keyword">int</span> result2 = Calculate(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'^'</span>); <span class="hljs-comment">// InvalidOperation exception will occur within the Calculate method</span>
    <span class="hljs-keyword">int</span> result3 = Calculate(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'/'</span>); <span class="hljs-comment">// Attempted to divide by zero</span>
    Console.WriteLine(result1);
}
<span class="hljs-keyword">catch</span> (ArgumentException)
{
    WriteToScreen(<span class="hljs-string">"The operation symbol input is not recognised by this application"</span>);
}
<span class="hljs-keyword">catch</span> (Exception ex)
{
    WriteToScreen(ex.Message);
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Calculate</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">char</span> operatorSymbol</span>)</span>
{
    <span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">switch</span> (operatorSymbol)
        {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'+'</span>:
                result = operand1 + operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'-'</span>:
                result = operand1 - operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'*'</span>:
                <span class="hljs-keyword">checked</span>
                {
                    result = operand1 * operand2;
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'/'</span>:
                result = operand1 / operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException();
        }
    }
    <span class="hljs-keyword">catch</span> (OverflowException)
    {
        WriteToScreen(
            <span class="hljs-string">"The result of the calculation exceeded that max value for the int data type"</span>
        );
    }
    <span class="hljs-keyword">catch</span> (InvalidOperationException ex)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(
            <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(operatorSymbol)}</span> is invalid"</span>,
            <span class="hljs-keyword">nameof</span>(operatorSymbol),
            ex
        );
    }
    <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>With the first call to the <code>Calculate</code> method in the above example, the calculation will yield a result that is too large to be supported by the integer data type. This means that an <code>OverFlowException</code> will be initially flagged by the C# compiler.</p>
<p>Within the <code>OverFlowException</code> catch filter in the code example depicted in figure 77, code is implemented that handles the exception locally within the <code>Calculate</code> method. This means the exception is not thrown up the stack to be handled within the calling method. The exception handling code in the <code>OverFlowException</code> catch block is simply logging a message to a file through a custom <code>LogException</code> method.</p>
<p>With the second call to the <code>Calculate</code> method, an invalid operator (that is <code>^</code>) is passed to the <code>Calculate</code> method. In the default part of the relevant <code>switch</code> statement, the code is throwing an <code>InvalidOperation</code> exception which is an exception type that is built into the C# language. Within the <code>try/catch</code> block is a <code>catch</code> filter for specifically catching this <code>InvalidOperation</code> exception.</p>
<p>Within the <code>catch</code> block, the code is throwing a new <code>ArgumentException</code> exception which is subsequently being handled within the calling method (which in this case is the <code>Main</code> method, the entry point of this application). In the relevant code example top-level-statements are enabled which means the <code>Main</code> is not present in the code but as discussed earlier, the <code>Main</code> method is added behind the scenes and encapsulates the calling code which is expressed in this example as top-level-statements.</p>
<p>The <code>Main</code> method contains an <code>ArgumentException</code> catch section. In this <code>catch</code> section, the exception is being handled by outputting an informative message to the user.</p>
<p>Arguably this type of exception would be best handled in code rather than using <code>try/catch</code> code for this purpose. You could, for example, validate the operator before the <code>Calculate</code> method is called. If the operator is entered by the user incorrectly, output an informative message to them. The user can then alter their input appropriately.</p>
<p>So in order to use validation rather than <code>try/catch</code> code in this scenario, the calling code could be changed to what you see in the example below in figure 78:</p>
<p>Figure 78.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
Console.WriteLine(<span class="hljs-string">"Please enter a whole number value for the first operand"</span>);
<span class="hljs-keyword">int</span> operand1 = <span class="hljs-keyword">int</span>.Parse(Console.ReadLine());
Console.WriteLine(<span class="hljs-string">"Please enter a whole number value for the second operand"</span>);
<span class="hljs-keyword">int</span> operand2 = <span class="hljs-keyword">int</span>.Parse(Console.ReadLine());
Console.WriteLine(<span class="hljs-string">"Please enter a valid operator symbol ('+','-','*','/')"</span>);
<span class="hljs-keyword">char</span> operatorSymbol = <span class="hljs-keyword">char</span>.Parse(Console.ReadLine());

<span class="hljs-keyword">if</span> (
    operatorSymbol != <span class="hljs-string">'+'</span>
    || operatorSymbol != <span class="hljs-string">'-'</span>
    || operatorSymbol != <span class="hljs-string">'*'</span>
    || operatorSymbol != <span class="hljs-string">'/'</span>
)
{
    WriteToScreen(
        <span class="hljs-string">"Incorrect operator input. The operator symbol must be one of the following ('+'’','-','*','/') "</span>
    );
}
<span class="hljs-keyword">else</span>
{
    result = Calculate(operand1, operand2, operatorSymbol);
    WriteToScreen(result.ToString());
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Calculate</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">char</span> operatorSymbol</span>)</span>
{
    <span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">switch</span> (operatorSymbol)
        {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'+'</span>:
                result = operand1 + operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'-'</span>:
                result = operand1 - operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'*'</span>:
                <span class="hljs-keyword">checked</span>
                {
                    result = operand1 * operand2;
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'/'</span>:
                result = operand1 / operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException();
        }
    }
    <span class="hljs-keyword">catch</span> (OverflowException)
    {
        WriteToScreen(
            <span class="hljs-string">"The result of the calculation exceeded that max value for the int data type"</span>
        );
    }
    <span class="hljs-keyword">catch</span> (InvalidOperationException ex)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(
            <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(operatorSymbol)}</span> is invalid"</span>,
            <span class="hljs-keyword">nameof</span>(operatorSymbol),
            ex
        );
    }
}
<span class="hljs-keyword">return</span> result;
</code></pre>
<p>In this case, it's unnecessary to use exception handling, and instead you can use conditional code to validate the operator symbol before the <code>Calculate</code> method is even called.</p>
<p>It is important to note that all <code>Exception</code> types – including the ones that have been used in these code examples – are derived from the <code>Exception</code> type.</p>
<p>The <code>Exception</code> type is built into C#. All <code>Exception</code> types in C# are derived from the base <code>Exception</code> type. An exception inheritance hierarchy has been deliberately designed and implemented in C#. The exceptions I've used in the examples in this section of the book are <code>OverflowException</code>, <code>InvalidOperationException</code> and <code>ArgumentException</code>. These exception types are derived from the base <code>Exception</code> type.</p>
<p>The exception type hierarchy in C# means that when there are multiple exception filters within a <code>try/catch</code> block, the more derived exception types must be included first within the relevant list of catch filters.</p>
<p>For example, in the examples depicted in this section, the <code>ArgumentException</code> appears before the <code>Exception</code> catch filter. If the <code>Exception</code> catch filter appeared before the <code>ArgumentException</code> filter, this would mean that the code within the <code>ArgumentException</code> catch filter would never be called. So it's important that the <code>Exception</code> catch filter appear after the <code>ArgumentException</code> catch filter.</p>
<p>Note that in many cases you'll want to include a <code>finally</code> section in your <code>try/catch</code> code. This <code>finally</code> section is always called when the relevant <code>try/catch</code> code is executed. So the code included in the <code>finally</code> section is run when code within the <code>try</code> section causes an exception to occur (resulting in code within the relevant catch filter being executed) or even if no exceptions occur due to code included within the relevant <code>try</code> section. This makes the <code>finally</code>  section ideal for including clean up code, that is used for cleaning up resources (for example database connection objects) that are no longer needed.</p>
<p>For more detail on exception handling in C#, you can check out the videos in the playlist below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/mpdg6SAaoZ4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on exception handling in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=mpdg6SAaoZ4&amp;list=PL4LFuHwItvKaHOvj1B5DhTnH0MJ1JFJzr">Full Video Series on Exception Handling in C#</a></p>
<p>For a full video series on file handling in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=DHgU_tAC85U&amp;list=PL4LFuHwItvKaqc6w0awyyNGfkzU4ke5fu">Full Video Series on File Handling in C#</a></p>
<h2 id="heading-c-delegates">C# Delegates</h2>
<p>Delegates can be described as type safe function pointers. With a delegate, you can define a method definition that includes a parameter list as well as a return type (if no return type is included in the delegate definition, the <code>void</code> keyword must be included in place of a data type).</p>
<p>Methods that conform (appropriately in terms of their method signatures) to that defined delegate type can be referenced by the compatible delegate type. A variable can be assigned the relevant delegate and you can then use the variable to invoke any appropriate method that is referenced by the delegate.</p>
<p>In the code example depicted in figure 79 below, a delegate is defined and named <code>LogDel</code>. With the declaration of the <code>LogDel</code> delegate, a method definition for a method is declared. The method definition in this case represents any method that accepts a string argument and does not return a value (which is denoted by the <code>void</code> keyword).</p>
<p>The C# <code>void</code> keyword is used in the delegate definition to signify that any method referenced by this delegate must not return a value. Of course you can declare a delegate for a method that does return a value (in which case the delegate definition would include the appropriate data type instead of the <code>void</code> keyword).</p>
<p>In this case, however, a delegate is defined to provide an abstraction for a method that accepts a string argument and does not return a value.</p>
<p>In the code example depicted in figure 79, you can see how a delegate is used to create flexibility where calling code can reuse the <code>LogDel</code> delegate to log text to the console screen or log the text to a text file. Using this delegate definition the calling code can even implement what is known as a multi-cast delegate.</p>
<p>In this case, an instantiation of the <code>LogDel</code> delegate type is used to combine the functionality of a method that logs text to the screen as well as a method that logs text to a file. In the code, the <code>+</code> operator is used in between two delegates and the result is assigned to a delegate named <code>multiLogDel</code>.</p>
<p>When the <code>multiLogDel</code> delegate is invoked, the text is logged both to the console screen as well as to the text file. So delegates can be used to call multiple methods (that are appropriately defined where the method definitions match the delegate definition) through one invocation of the delegate instantiation.</p>
<p>Also, through the delegate, you can invoke functionality for just one of the methods – in this example either <code>LogTextToScreen</code> or <code>LogTextToFile</code>.</p>
<p>So delegates provide a type safe, flexible abstraction over methods that you can use to call one or multiple methods that conform to a specified method definition.</p>
<p>Figure 79.</p>
<pre><code class="lang-csharp">Log log = <span class="hljs-keyword">new</span> Log();
LogDel LogTextToScreenDel,
    LogTextToFileDel;
LogTextToScreenDel = <span class="hljs-keyword">new</span> LogDel(log.LogTextToScreen);
LogTextToFileDel = <span class="hljs-keyword">new</span> LogDel(log.LogTextToFile);
LogDel multiLogDel = LogTextToScreenDel + LogTextToFileDel;
Console.WriteLine(<span class="hljs-string">"Please enter your name"</span>);
<span class="hljs-keyword">var</span> name = Console.ReadLine();
LogText(multiLogDel, name);
Console.ReadKey();
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogText</span>(<span class="hljs-params">LogDel logDel, <span class="hljs-keyword">string</span> text</span>)</span>
{
    logDel(text);
}
<span class="hljs-function"><span class="hljs-keyword">delegate</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogDel</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title">Log</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogTextToScreen</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{DateTime.Now}</span>: <span class="hljs-subst">{text}</span>"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogTextToFile</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>
    {
        <span class="hljs-keyword">using</span> (
            StreamWriter sw = <span class="hljs-keyword">new</span> StreamWriter(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, <span class="hljs-string">"Log.txt"</span>),
                <span class="hljs-literal">true</span>
            )
        )
        {
            sw.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{DateTime.Now}</span>: <span class="hljs-subst">{text}</span>"</span>);
        }
    }
}
</code></pre>
<p>For more detail on delegates, you can watch the videos in the playlist below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/5YTqMe2GC5U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on delegates in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=5YTqMe2GC5U&amp;list=PL4LFuHwItvKZwUnVL2KKvfYxNMVo-TQAB">Full Video Series on C# Delegates</a></p>
<h2 id="heading-c-events">C# Events</h2>
<p>Events can be used in C# to notify other classes or objects when, for example, a condition is met within the class or object in which that event resides. When the condition is met within the class or object that contains the event, the event can be raised. This means that those classes or objects that have elected to receive notifications when the relevant event is raised will receive those notifications.</p>
<p>The classes or objects elect to receive these notifications by subscribing in code to the event that resides in the class or object that contains the event. The class or object that contains the event is known as the publisher, and the classes or objects that have subscribed to recieve notifications when the relevant event is raised are known as the subscribers.</p>
<p>In the example depicted in figure 80 below, the publisher is the class named <code>GuessNumberGame</code>. You can see that an event named <code>GameEvent</code> has been published within this class. In this simple example, the subscription to the <code>GameEvent</code> class is made within the entry point or <code>Main</code> method of the application (shown in this example in the top-level-statements of the application).</p>
<p>Here, this is for the sake of simplicity – but in a real-world application you may have many subscriber classes subscribing to the event within the publisher class.</p>
<p>So within the calling code, a subscription to the <code>GameEvent</code> event is made through the use of the <code>+=</code> operator. This operator is used when a subscription to an event is made in C# code.</p>
<p>On the right hand side of the <code>+=</code> operator is the name of a method that is designated to handle the event when the event is raised. So this event handling method resides within the subscriber code.</p>
<p>We used a built-in C# generic delegate to define the <code>GameEvent</code> event. This in effect defines the the method definition for the method or methods that are designated to handle the event.</p>
<p>The <code>EventHandler</code> delegate provides a definition for a method that contains two parameters. One is defined as <code>object</code>, and the other is defined as a generic type argument that is passed in as an argument to the <code>EventHandler</code> delegate at compile time within the publisher class where the event is declared.</p>
<p>So you can see in the calling code, a method named <code>EventHandlerMethod</code> is defined that contains an argument of type <code>object</code>. There's also an object defined as the data type argument passed into the type parameter for the built-in generic <code>EventHandler</code> delegate, when the <code>GameEvent</code> is declared inside the publisher class.</p>
<p>So when the relevant condition is met within the <code>OnCorrectNumberGuessed</code> method, the <code>GameEvent</code> event is raised. This, in effect, results in the <code>EventHandlerMethod</code> being executed within the calling code, or within the subscriber's code, if you like.</p>
<p>The code in figure 80 is a simple game. The user gets three chances to guess a random number between 1 and 4 (including 4), generated within the <code>GuessNumberGame</code> class.</p>
<p>If the user guesses the correct number, the <code>GameEvent</code> event is raised and the code within the <code>EventHandlerMethod</code> is run. This results in outputted text being displayed to the user, informing them that they have guessed the correct number and have therefore won the game.</p>
<p>So when the user guesses the correct number, the following text is outputted to the console screen: <code>You guessed it!! Well done! :)</code>.</p>
<p>As we discussed before, the <code>+=</code> operator is used for subscribers to subscribe to an event within the publisher class or object. This lets them receive notifications when the event is raised through code within the publisher class or object.</p>
<p>After the <code>while</code> loop code, there's a line of code where the subscriber unsubscribes from the event. This is important, as it prevents possible memory leaks from occurring.</p>
<p>To unsubscribe from the event, you can use the <code>-=</code> C# operator:</p>
<p>Figure 80.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Guess the number of which the computer is thinking. Is it 1,2,3 or 4?"</span>);
Console.WriteLine();
<span class="hljs-keyword">int</span> counter = <span class="hljs-number">0</span>;
<span class="hljs-keyword">bool</span> gameIsWon = <span class="hljs-literal">false</span>;
GuessNumberGame guessNumberGame = <span class="hljs-keyword">new</span> GuessNumberGame();
guessNumberGame.GameEvent += EventHandlerMethod;
<span class="hljs-keyword">do</span>
{
    counter++;
    Console.WriteLine(<span class="hljs-string">"Please input your number choice"</span>);
    <span class="hljs-keyword">int</span> userGuessedNumber = Int32.Parse(Console.ReadLine());
    guessNumberGame.CompareUsersNumber(userGuessedNumber);
} <span class="hljs-keyword">while</span> (gameIsWon == <span class="hljs-literal">false</span> &amp;&amp; counter &lt; <span class="hljs-number">3</span>);
guessNumberGame.GameEvent -= EventHandlerMethod;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">EventHandlerMethod</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> sender, GuessNumberDataEventArgs args</span>)</span>
{
    Console.WriteLine(args.GuessNumberGameOutputMessage);
    gameIsWon = <span class="hljs-literal">true</span>;
}

<span class="hljs-keyword">class</span> <span class="hljs-title">GuessNumberGame</span>
{
    Random rnd = <span class="hljs-keyword">new</span> Random();
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> generatedRandomNumber = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GuessNumberGame</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">this</span>.generatedRandomNumber = rnd.Next(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>);
        Console.WriteLine(<span class="hljs-string">"Computer Gen ="</span> + generatedRandomNumber);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CompareUsersNumber</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> guessedNumber</span>)</span>
    {
        <span class="hljs-keyword">if</span> (guessedNumber == <span class="hljs-keyword">this</span>.generatedRandomNumber)
        {
            OnCorrectNumberGuessed(
                <span class="hljs-keyword">new</span> GuessNumberDataEventArgs
                {
                    GuessNumberGameOutputMessage = <span class="hljs-string">"You guessed it!! Well done! :)"</span>
                }
            );
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnCorrectNumberGuessed</span>(<span class="hljs-params">GuessNumberDataEventArgs e</span>)</span>
    {
        EventHandler &amp; lt;
        GuessNumberDataEventArgs &amp; gt;
        handler = GameEvent;
        <span class="hljs-keyword">if</span> (handler != <span class="hljs-literal">null</span>)
        {
            handler(<span class="hljs-keyword">this</span>, e);
        }
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">event</span> EventHandler&lt;GuessNumberDataEventArgs&gt; GameEvent;

}
</code></pre>
<p>For more details on using C# Events and more code examples, you can check out the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/QJJKMW3ErEw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on events in C#, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=QJJKMW3ErEw&amp;list=PL4LFuHwItvKa3dr0NL732rnnOhcc3aEgG">Full Video Series on C# Events</a></p>
<h2 id="heading-c-generics">C# Generics</h2>
<p>Generics allow C# developers to reuse specific code (like that which exists within a method, class, or collection) in the context of multiple different C# data types.</p>
<p>You determine this data type context at compile time where, for example, you can pass a data type argument to a data type parameter that is contained within the definition of the method, class, or collection type.</p>
<p>A simple code example of this is the C# generic <code>List</code> type, which is a built-in collection you can use. You can strongly type a generic list at compile time with C# built-in data types like <code>int</code>, <code>string</code>, <code>char</code>, <code>bool</code>, <code>decimal</code>, <code>float</code>, <code>double</code> and so on, as well as user defined types, like those that are implemented using a class or a struct.</p>
<p>In the example depicted in figure 82, the generic list type is being used to store the grades of a university student. All of the grades are integers. When you look at the definition for the <code>List</code> generic type that is built into C#, you see the word <code>List</code> followed by angle brackets, with a <code>T</code> included within the angle brackets. So the generic built-in C# <code>List</code> type is defined as is depicted in figure 81.</p>
<p>The <code>T</code> is a placeholder representing the generic data type parameter, which you can use to pass a data type argument to the 'List' type at compile time in order to strongly type the list.</p>
<p>Generics means that type parameters are included in .NET. This makes it possible for you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by calling code.</p>
<p>Figure 81.</p>
<pre><code class="lang-csharp">List&lt;T&gt;
</code></pre>
<p>Figure 82.</p>
<pre><code class="lang-csharp">List&lt;<span class="hljs-keyword">int</span>&gt; grades = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">int</span>&gt;();
grades.Add(<span class="hljs-number">60</span>);
grades.Add(<span class="hljs-number">73</span>);
grades.Add(<span class="hljs-number">85</span>);
grades.Add(<span class="hljs-number">92</span>);
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">int</span> grade <span class="hljs-keyword">in</span> grades)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{grade}</span>, "</span>);
}

<span class="hljs-comment">// Output: 60, 73, 85, 92,</span>
<span class="hljs-comment">// You could also use the generic list to store the subject names pertaining to the grades of the relevant</span>
<span class="hljs-comment">// student.</span>
List&lt;<span class="hljs-keyword">string</span>&gt; subjects = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;();
subjects.Add(<span class="hljs-string">"Observational Astronomy"</span>);
subjects.Add(<span class="hljs-string">"Particle Physics"</span>);
subjects.Add(<span class="hljs-string">"Quantum mechanics"</span>);
subjects.Add(<span class="hljs-string">"Advanced Math"</span>);
</code></pre>
<p>You can also use the same generic list data type to store objects derived from a specific user defined type, implemented, for example, as a class in code.</p>
<p>So in the example in figure 83, the list data type is used to store a collection of 'student' objects:</p>
<p>Figure 83.</p>
<pre><code class="lang-csharp">List&lt;Student&gt; students = <span class="hljs-keyword">new</span> List&lt;Student&gt;();
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">1</span>,
        Name = <span class="hljs-string">"Dale Jones"</span>,
        Grade = <span class="hljs-number">60</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">2</span>,
        Name = <span class="hljs-string">"Gale Davis"</span>,
        Grade = <span class="hljs-number">89</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">3</span>,
        Name = <span class="hljs-string">"Debbie Hill"</span>,
        Grade = <span class="hljs-number">56</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">4</span>,
        Name = <span class="hljs-string">"Dave Brown"</span>,
        Grade = <span class="hljs-number">76</span>
    }
);
<span class="hljs-keyword">foreach</span> (Student student <span class="hljs-keyword">in</span> students)
{
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student.Id}</span> <span class="hljs-subst">{student.Name}</span> <span class="hljs-subst">{student.Grade}</span> "</span>);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 1 Dale Jones 60</span>
<span class="hljs-comment">// 2 Gale Davis 89</span>
<span class="hljs-comment">// 3 Debbie Hill 56</span>
<span class="hljs-comment">// 4 Dave Brown 76</span>
</code></pre>
<p>Through generics, you are able to reuse the functionality in the built-in <code>list</code> data type to store multiple types of data. Any generic list used in your C# code must be strongly typed with one particular data type.</p>
<p>You can strongly type the generic list by passing in the relevant type as an argument when defining and instantiating an object of the <code>List</code> type.</p>
<p>Prior to the generic <code>List</code> type being introduced (in .NET Framework 2.0), you could use an <code>ArrayList</code> to store a collection of heterogeneous data types. You could store multiple different data types within one <code>ArrayList</code>.</p>
<p>The problem with the <code>ArrayList</code> is that any calling code retrieving an item from an <code>ArrayList</code> must first convert that value to its appropriate data type before the value can be of any use.</p>
<p>Every item stored in an <code>ArrayList</code> is ‘boxed' within the <code>object</code> type. This is possible because all C# data types inherit from the <code>object</code> data type, so every data type in C# can be implicitly boxed into an object.</p>
<p>Boxing is simply the process of converting a value type to the <code>object</code> type in C#. When the common language runtime (CLR) boxes a value type, it wraps the value inside a <code>System.Object</code> instance and stores it on the managed heap. So in order to use an item retrieved from an <code>ArrayList</code>, the object must first be converted or 'unboxed' into its original type.</p>
<p>This highlights one of the main advantages of using generics in C#. Through using the generic <code>List</code> to store strongly typed items in a collection, you can avoid 'boxing' and 'unboxing'. This means that with generics, the performance overhead caused through 'boxing' and 'unboxing' is also avoided.</p>
<p>The other main advantage is that you can avoid type-related errors that can occur as a result of explicit type conversions needing to be performed on an item retrieved from an <code>ArrayList</code> at runtime.</p>
<p>So by strongly typing a <code>List</code> at compile time, the compiler is able to check that all data type-related code is correct before it is deployed into production. In this way, data type-related errors are preempted at compile time.</p>
<p>Depicted in figure 84, is an example of using an <code>ArrayList</code>  to store heterogeneous data types.</p>
<p>Figure 84.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Collections;
<span class="hljs-keyword">using</span> System.ComponentModel;

ArrayList studentDetails = <span class="hljs-keyword">new</span> ArrayList();
<span class="hljs-keyword">int</span> grade = <span class="hljs-number">90</span>;
<span class="hljs-keyword">string</span> name = <span class="hljs-string">"Bob Jones"</span>;
studentDetails.Add(<span class="hljs-number">90</span>); <span class="hljs-comment">// int value boxed as object</span>
studentDetails.Add(<span class="hljs-string">"Bob Jones"</span>);
studentDetails.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">1</span>,
        Name = <span class="hljs-string">"Bob Jones"</span>,
        Grade = <span class="hljs-number">90</span>
    }
);
grade = Convert.ToInt32(studentDetails[<span class="hljs-number">0</span>]); <span class="hljs-comment">// runtime performance slowed by unboxing int student = int32.Parse(studentDetails[2]); // This would result in a runtime exception being thrown due to an invalid type conversion operation being performed at runtime</span>
</code></pre>
<p>So you can see that using a generic <code>List</code> to store strongly typed values in a collection (rather than an <code>ArrayList</code> where 'boxing' and 'unboxing' code needs to be performed) results in a performance improvement. It also ensures better robustness at runtime.</p>
<p>The example depicted in figure 85 is a more complicated example of using generics in C#. In this example, the factory pattern is employed where you can reuse the <code>GetInstance</code> method to instantiate objects of different types using the same instantiation functionality enveloped in the <code>GetInstance</code> method.</p>
<p>You can see that <code>K</code> and <code>T</code> are used as placeholders to represent the types that can be passed as arguments to the class at compile time (that is, in order to strongly type the class). The <code>where</code> keyword denotes constraints (which are defined rules) on the type arguments passed to this class.</p>
<p>So these constraints mean that the type passed as an argument to the parameter represented by the <code>T</code> placeholder must be a class. The <code>new</code> keyword followed by open and closed brackets denotes that a new object must be created from the relevant class which is of type <code>K</code>.</p>
<p>Figure 85.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Instantiation of objects from the generic types passed as objects to the FactoryPattern class.</span>
IStudent student = FactoryPattern&lt;IStudent, Student&gt;.GetInstance();
student.Name = <span class="hljs-string">"Bob Jones"</span>;
student.Grade = <span class="hljs-number">78</span>;
student.Subject = <span class="hljs-string">"Math"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student.Name}</span> <span class="hljs-subst">{student.Grade}</span> <span class="hljs-subst">{student.Subject}</span>"</span>);
IStudent student2 = FactoryPattern&lt;IStudent, Student&gt;.GetInstance();
student2.Name = <span class="hljs-string">"Debbie Long"</span>;
student2.Grade = <span class="hljs-number">84</span>;
student2.Subject = <span class="hljs-string">"Science"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student2.Name}</span> <span class="hljs-subst">{student2.Grade}</span> <span class="hljs-subst">{student2.Subject}</span>"</span>);
IProfessor professor = FactoryPattern&lt;IProfessor, Proffessor&gt;.GetInstance();
professor.Name = <span class="hljs-string">"Ron Willis"</span>;
professor.MainSubject = <span class="hljs-string">"Math"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{professor.Name}</span> <span class="hljs-subst">{professor.MainSubject}</span>"</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Bob Jones 78 Math</span>
<span class="hljs-comment">// Debbie Long 84 Science</span>
<span class="hljs-comment">// Ron Willis Math</span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FactoryPattern</span>&lt;<span class="hljs-title">K</span>, <span class="hljs-title">T</span>&gt;
    <span class="hljs-keyword">where</span> <span class="hljs-title">T</span> : <span class="hljs-keyword">class</span>, <span class="hljs-title">K</span>, <span class="hljs-title">new</span>()
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> K <span class="hljs-title">GetInstance</span>(<span class="hljs-params"></span>)</span>
    {
        K objK;
        objK = <span class="hljs-keyword">new</span> T();
        <span class="hljs-keyword">return</span> objK;
    }
}
</code></pre>
<p>So in the example depicted in figure 85, generics is used to create clean, reusable code for the implementation of the factory pattern.</p>
<p>A single code block is used to create instances of objects derived from multiple user defined types. Through generics the amount of code is minimised, and if you have a good knowledge of generics, this code is easy to maintain and reuse. Generics gives you greater design flexibility, and ensures better runtime performance and robustness.</p>
<p>For more information on C# Generics and more code examples, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/UUF8QCf3rpI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on generics in C#, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=UUF8QCf3rpI&amp;list=PL4LFuHwItvKaeSVOur67Lu-0I7sfjf5N3">Full Video Series on C# Generics</a></p>
<h2 id="heading-linq">LINQ</h2>
<p>LINQ stands for Language-Integrated Query and was first introduced to .NET languages with .NET Framework version 3.5 in 2007. It provides .NET developers with a high level query abstraction where, for example, C# code can be used to natively query collections of C# objects. It's similar to the well known relational database management system declarative query language, T-SQL – but the entities being queried with LINQ code are collections of objects rather than rows within database tables.</p>
<p>The code example depicted in figure 86 shows how T-SQL might be used to query a database table named, <code>Employees</code>, in order to bring back all the field values in each row stored in the <code>Employees</code> database table.</p>
<p>Figure 86.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> Employees
</code></pre>
<p>In figure 87, a code example is depicted where LINQ in C# code is leveraged to query a collection of <code>Employee</code> objects.</p>
<p>Figure 87</p>
<pre><code class="lang-csharp">List&lt;Employee&gt; employees = <span class="hljs-keyword">new</span> List&lt;Employee&gt;();
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">1</span>,
        FirstName = <span class="hljs-string">"Gavin"</span>,
        LastName = <span class="hljs-string">"Lon"</span>,
        Salary = <span class="hljs-number">10000</span>
    }
);
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">2</span>,
        FirstName = <span class="hljs-string">"Sandy"</span>,
        LastName = <span class="hljs-string">"James"</span>,
        Salary = <span class="hljs-number">90000</span>
    }
);
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">3</span>,
        FirstName = <span class="hljs-string">"Greg"</span>,
        LastName = <span class="hljs-string">"Jones"</span>,
        Salary = <span class="hljs-number">73000</span>
    }
);
<span class="hljs-keyword">var</span> employeeResults = <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees <span class="hljs-keyword">select</span> e;
<span class="hljs-keyword">foreach</span> (Employee emp <span class="hljs-keyword">in</span> employees)
{
    Console.WriteLine(emp.FirstName);
}
</code></pre>
<p>If for example the <code>Employees</code> database table contained four fields, namely <code>Id</code>, <code>FirstName</code>, <code>LastName</code> and <code>Salary</code>, and you wanted to only bring back the <code>FirstName</code> and <code>LastName</code> fields through your T-SQL query, your query would look like the example in figure 88.</p>
<p>Figure 88.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> FirstName, LastName <span class="hljs-keyword">FROM</span> Employees
</code></pre>
<p>In order to bring back the <code>FirstName</code> and <code>LastName</code> fields from a collection of objects where each object has an <code>Id</code> property, a <code>FirstName</code> property, a <code>LastName</code> property, and a <code>Salary</code> property your LINQ query could be implemented as is shown in the code example in figure 89.</p>
<p>Figure 89.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults =
    <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees
    <span class="hljs-keyword">select</span> <span class="hljs-keyword">new</span> Employee { FirstName = e.FirstName, LastName = e.LastName };
</code></pre>
<p>There are two types of syntax you can leverage to implement LINQ in C#. The type of syntax you've seen so far in this section is known as query syntax. Another way to implement LINQ code is by using method syntax.</p>
<p>To illustrate the use of query syntax vs method syntax, let's look at a slightly more complex example. In the example depicted in figure 90, a T-SQL query is used to bring back the <code>FirstName</code> and <code>LastName</code> fields, for rows pertaining to employees that have a salary higher than <code>50000</code>.</p>
<p>Figure 90.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> FirstName, LastName <span class="hljs-keyword">FROM</span> Employees e <span class="hljs-keyword">WHERE</span> e.Salary &gt; <span class="hljs-number">50000</span>
</code></pre>
<p>Using Query syntax in LINQ to perform the equivalent query against a collection of <code>Employee</code> objects, the code would look like what is depicted in figure 91.</p>
<p>Figure 91.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults =
    <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees
    <span class="hljs-keyword">where</span> e.Salary &gt; <span class="hljs-number">50000</span>
    <span class="hljs-keyword">select</span> <span class="hljs-keyword">new</span> Employee
    {
        FirstName = e.FirstName,
        LastName = e.LastName,
        Salary = e.Salary
    };
</code></pre>
<p>Using method syntax in LINQ, the equivalent query could be implemented with the code depicted in figure 92.</p>
<p>Figure 92.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults = employees
    .Select(e =&gt; <span class="hljs-keyword">new</span> Employee
    {
        FirstName = e.FirstName,
        LastName = e.LastName,
        Salary = e.Salary
    })
    .Where(e =&gt; e.Salary &gt; <span class="hljs-number">50000</span>);
</code></pre>
<p>These LINQ related code examples hopefully give you a sense of how method syntax looks compared to query syntax.</p>
<p>Note that you can't create all LINQ queries using query syntax, so depending on your requirements you may have to use method syntax for performing certain queries using LINQ.</p>
<p>Behind the scenes, the C# compiler converts query syntax to method syntax. Query syntax was introduced in the LINQ technology specifically to improve the readability of your queries.</p>
<p>LINQ is made up of many extension methods that reside within the <code>System.LINQ</code> namespace. In the example in figure 92, the <code>Select</code> and <code>Where</code> LINQ extension methods have been appropriately chained together to create the desired query.</p>
<p>For more detils on LINQ and for more code examples, you can watch the  YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/UfZOmSCCbDY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on LINQ, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=UfZOmSCCbDY&amp;list=PL4LFuHwItvKbzDl6MBp3XY0MrnALSfyub">Full Video Series on Using LINQ in C#</a></p>
<h2 id="heading-c-attributes">C# Attributes</h2>
<p>You can associate metadata with program entities (for example assemblies, types, methods, and properties) through the use of attributes in C#.</p>
<p>Attributes are powerful when combined with reflection (a concept we'll discuss in the next section). Through the use of reflection, the attributes can be queried at runtime and then custom functionality can be executed based on the metadata provided through the use of the relevant attributes.</p>
<p>Attributes in C# are created as objects at runtime. Their properties and methods can be used just like any other object in C#.</p>
<p>There are two broad categories for attributes: predefined attributes and custom attributes. Predefined attributes are built into the base class libraries provided in .NET, and custom attributes allow you to define your own attributes that address your unique application requirements.</p>
<p>An example of a predefined general attribute is the <code>obsolete</code> attribute. You can check out figure 93 for a code example depicting how you can use the <code>obsolete</code> attribute and how it can be useful when you're attempting to consume an obsolete method (or a method marked as obsolete with the <code>obsolete</code> attribute).</p>
<p>In the code example, you can see that the <code>obsolete</code> attribute decorates a method named <code>LogToScreen</code>. A new updated method named <code>LogToFile</code> has been created within the same class to replace the old <code>LogToScreen</code> method. So the creator of the <code>Logging</code> class would prefer the <code>LogToFile</code> method be consumed by developers (when applying logging functionality in calling code) rather than the <code>LogToScreen</code> method.</p>
<p>When the consumer of the class tries to use the older obsolete method (in this example, the <code>LogToScreen</code> method), a predefined warning message can be displayed to the developer from inside their code editor. This warning message is created to warn developers who wish to consume the logging functionality that the <code>LogToFile</code> method should be used for logging and not the obsolete <code>LogToScreen</code> method.</p>
<p>So to ensure that an appropriate message is displayed, you can pass an appropriate custom message as an argument to the <code>obsolete</code> attribute that appropriately decorates the <code>LogToScreen</code> method (which has now been deemed as obsolete). The warning message can for example warn developers that the old method (<code>LogToScreen</code>) is now obsolete and direct them to use the new preferred method (<code>LogToFile</code>) in its place.</p>
<p>Figure 93.</p>
<pre><code class="lang-csharp">Logging logAction = <span class="hljs-keyword">new</span> Logging();
logAction.LogToScreen(<span class="hljs-string">"Start of Code"</span>); <span class="hljs-comment">// This message, "The LogToScreen method is now obsolete. Please use the LogToFile method instead" is flagged by the C# compilerSomeFunction();</span>
logAction.LogToScreen(<span class="hljs-string">"End of Code"</span>); <span class="hljs-comment">// This message, "The LogToScreen method is now obsolete. Please use the LogToFile method instead" is flagged by the C# compiler</span>
</code></pre>
<p>In the example depicted in figure 94, a custom attribute is created through the implementation of a C# class that inherits from the built-in C# class <code>System.Attribute</code>. A general predefined attribute named, <code>AttributeUsage</code> is used to decorate the class in order to enforce the usage rules associated with the <code>Required</code> custom attribute.</p>
<p>The arguments being passed (in this example) to the <code>AttributeUsage</code> attribute establish the rules where the <code>Required</code> attribute can only be associated with field, parameter, and property program elements, and cannot be applied to the same element multiple times.</p>
<p>The <code>Required</code> attribute can only be applied to a particular program element once, and can be applied to fields, parameters, and properties.</p>
<p>In the example depicted in <strong>figure 94</strong>, a very basic use of a custom attribute is implemented where an custom attribute named <code>RequiredAttribute</code> is used to decorate certain properties of a model. Note that when a custom attribute is actually applied, the 'Attribute' part of the custom attribute's name can be omitted. So in <strong>figure 94</strong> you can see that the relevant program elements are decorated with the attribute named,<code>Required</code> and not <code>RequiredAttribute</code>.</p>
<p>The <code>EmployeeModel</code> model class is used to represent an <code>Employee</code> record. The class named, <code>EmployeeModel</code>, provides a template for an employee record. The <code>Required</code> attribute gives you the ability to reuse this custom attribute across properties where <code>Required</code> validation is necessary (that is, where a user must input a value that is subsequently assigned to the property decorated with the <code>Required</code> attribute).</p>
<p>In the calling code, reflection is employed to inspect the property program elements of the <code>EmployeeModel</code> user defined type at runtime to see if there are any attributes applied to its properties.</p>
<p>In this basic example, the code queries the <code>Id</code> property of the <code>EmployeeModel</code> class, and the <code>Required</code> attribute is found to be associated with the <code>Id</code> property. The code then knows to appropriately validate the user's input for the <code>Id</code> property of the <code>EmployeeModel</code> class.</p>
<p>Note that the <code>Required</code> attribute is also applied to the <code>FirstName</code> property. So you can see how an attribute can be applied multiple times in order to address cross cutting concerns.</p>
<p>Figure 94.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Reflection;

Console.WriteLine(<span class="hljs-string">"Please enter an Id for the employee:"</span>);
<span class="hljs-keyword">string</span> id = Console.ReadLine();
Type employeeType = <span class="hljs-keyword">typeof</span>(EmployeeModel);
PropertyInfo prop = employeeType.GetProperty(<span class="hljs-string">"Id"</span>);
Attribute[] attributes = prop.GetCustomAttributes().ToArray();
<span class="hljs-keyword">foreach</span> (Attribute attr <span class="hljs-keyword">in</span> attributes)
{
    <span class="hljs-keyword">if</span> (attr <span class="hljs-keyword">is</span> RequiredAttribute)
    {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(id))
        {
            Console.WriteLine(
                <span class="hljs-string">"The employee’s Id is required. You did not enter the employee’s Id. "</span>
            );
        }
    }
}

<span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeModel</span>
{
    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FirstName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> LastName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}

[<span class="hljs-meta">AttributeUsage(
    AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property,
    AllowMultiple = false
)</span>]
<span class="hljs-keyword">class</span> <span class="hljs-title">RequiredAttribute</span> : <span class="hljs-title">Attribute</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ErrorMessage { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RequiredAttribute</span>(<span class="hljs-params"></span>)</span>
    {
        ErrorMessage = <span class="hljs-string">"You cannot leave field, {0}, empty"</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RequiredAttribute</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> errorMessage</span>)</span>
    {
        ErrorMessage = errorMessage;
    }
}
</code></pre>
<p>You can check out the following video that contains more details and code examples pertaining to C# Attributes.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JOM6zDb9Wa8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-reflection-in-c">Reflection in C</h2>
<p>Reflection is a concept in C#, where the programmer is able to create C# code that can dynamically read the metadata of .NET assemblies at runtime. This gives you a powerful tool where you can create code to dynamically analyse a .NET assembly based on the assembly's metadata at runtime. Your code can for e.g. read the assemblies relevant metadata using Reflection, and output the descriptive metadata about the analysed assembly.</p>
<p>Reflection can even be used to dynamically bind an object to a specific type that resides within the assembly at runtime and execute code that resides within the type’s methods. This is known as late binding.</p>
<p>Most of the time, you won't use reflection to call the code within a .NET assembly and will rather use early binding. Early binding means the C# compiler knows (as it were) about the assemblies' relevant program elements for e.g. an assemblies' classes and public methods at compile time.</p>
<p>Using early binding is the safest way to consume a type’s functionality, because any potential exceptions related to calling code within the early bound object are flagged at compile time. This prevents potentially erroneous code from being released into production, where it can result in runtime errors occurring.</p>
<p>When early binding is used, due to the self-describing nature of .NET assemblies where metadata is stored within the .NET assembly, the C# compiler is able to know (as it were) all the relevant details about the assembly at compile time.</p>
<p>So this metadata stored within .NET assemblies means early binding is possible, where the C# compiler has all the necessary type knowledge, if you like, at compile time.</p>
<p>Using reflection, you are able to use the technique of late binding which occurs at runtime. Late binding can be used to dynamically bind to an object (derived from a type that resides within the relevant assembly) at runtime and consume functionality that resides within the relevant .NET assembly.</p>
<p>This is a powerful tool, but is not a safe way to execute the functionality within a .NET assembly, because late binding means that the calling code learns about the target assembly at runtime by reading its metadata before executing the code within the assembly. The technique of late binding is therefore more prone to runtime errors, as potential errors cannot be dealt with at compile time – that is, before the code within the assembly is executed at runtime.</p>
<p>In the example depicted in figure 96, code within an assembly is dynamically invoked using reflection and late binding.</p>
<p>Figure 95.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Text;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">UtilityFunctions</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BasicMathFunctions</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">DivideOperation</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> number1, <span class="hljs-keyword">double</span> number2</span>)</span>
        {
            <span class="hljs-keyword">return</span> number1 / number2;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">MultiplyOperation</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> number1, <span class="hljs-keyword">double</span> number2</span>)</span>
        {
            <span class="hljs-keyword">return</span> number1 * number2;
        }
    }
}
</code></pre>
<p>A code example is depicted in figure 96, where the code resides within a different assembly to the assembly that contains the <code>BasicMathFunctions</code> type depicted in figure 95.</p>
<p>In the calling code (depicted in figure 96), reflection is used to late bind to the <code>BasicMathFunctions</code> type and call the <code>MultiplyOperation</code> method. So the code depicted in figure 95 resides within an assembly denoted by a file named "UtilityFunctions.dll".</p>
<p>The "UtilityFunction.dll" assembly resides within the same directory as the assembly that contains the calling code (depicted in figure 96). Reflection is used to dynamically load the "UtilityFunctions" assembly, late bind to the <code>BasicMathFunctions</code> type, and call its <code>MultiplyOperation</code> method.</p>
<p>Figure 96.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Reflection;

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TargetAssemblyFileName = <span class="hljs-string">"UtilityFunctions.dll"</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TargetNamespace = <span class="hljs-string">"UtilityFunctions"</span>;
Assembly assembly = Assembly.LoadFile(
    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TargetAssemblyFileName)
);
Type classType = assembly.GetType(<span class="hljs-string">"UtilityFunctions.BasicMathFunctions"</span>);
<span class="hljs-keyword">object</span> classInstance = Activator.CreateInstance(classType);
MethodInfo method = classType.GetMethod(<span class="hljs-string">"MultiplyOperation"</span>);
<span class="hljs-keyword">object</span>[] paramValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[<span class="hljs-number">2</span>];
paramValues[<span class="hljs-number">0</span>] = <span class="hljs-number">2</span>;
paramValues[<span class="hljs-number">1</span>] = <span class="hljs-number">3</span>;
<span class="hljs-keyword">object</span> result = method.Invoke(classInstance, paramValues);
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{paramValues[<span class="hljs-number">0</span>]}</span> * <span class="hljs-subst">{paramValues[<span class="hljs-number">1</span>]}</span>  = <span class="hljs-subst">{result}</span>"</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 2 * 3  = 6</span>
</code></pre>
<p>For more details and code examples pertaining to reflection, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tGMa9qjncjs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-video-on-asynchronous-programming-in-c">Video on Asynchronous Programming in C</h2>
<p>I haven't covered Asynchronous programming in this C# book. But if you'd like to learn about Asynchronous programming in C#, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/MyblIAk8cNI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on asynchronous programming in C#, check this out:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=MyblIAk8cNI&amp;list=PL4LFuHwItvKb5A9W1myICdC-GJU4_6cKE">Full Video Series on Asynchronous Programming in C#</a></p>
<p>If you'd like to learn about how to create sophisticated web applications using C#, I've provided some resources below.</p>
<p>The first link takes you do a YouTube video playlist that provides step by step instructions on how to build a Shopping Cart SPA (Single Page Application) using the Blazor framework. The second link takes you to a YouTube video playlist that provides step by step instructions on how to build a real-word web application using the ASP .NET Core MVC framework.</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=3_AsedRrqww&amp;list=PL4LFuHwItvKbdK-ogNsOx2X58hHGeQm8c">Full Blazor Shopping Cart SPA (Single Page Application) Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=D7R_ToqDKHg&amp;list=PL4LFuHwItvKZ6Mz5W5wzD9uo3w6tNChhX">Full ASP .Net CORE MVC Course</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The goal of this book is to help you gain an understanding of the powerful features available in the C# programming language. The code examples were designed to provide you with a practical knowledge of these features.</p>
<p>You can apply these code examples yourself using free tools like Visual Studio 2022 Community edition or Visual Studio Code in order to gain hands-on experience working with the concepts discussed in this book.</p>
<p>I have worked with C# for over two decades and have been impressed with the evolution of the language itself as well as the environment in which C# code runs, namely .NET. When you master C#, a whole world of creativity, intellectually challenging concepts, and a multitude of career opportunities will open up to you.</p>
<p>In today’s world, you have the benefit of development tools as well as instructions on how to use those development tools freely available to you. There is also a lot of free content available online on how to use the C# programming language in order to create real-world applications.</p>
<p>Using C#, you can create a large variety of different types of applications. You can create cross platform desktop applications, cross platform mobile applications, a variety of types of web applications like SPAs that leverage the Blazor framework. You can create sophisticated 2D and 3D games. You can create IoT applications. You can create globally distributed cloud native applications that leverage the Micro-service architecture.</p>
<p>You are almost unlimited in terms of the types of applications you can create for a multitude of types of platforms and devices. With C# you can easily integrate AI into your applications as well.</p>
<p>It is a very exciting time to be a C# and .NET developer. I wish you the very best with learning and leveraging this powerful programming language on your journey as a developer!</p>
<p>For a full course for C# beginners and a full Advanced C# course, check out these resources:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=2pquQMSYk6c&amp;list=PL4LFuHwItvKbneXxSutjeyz6i1w32K6di">Full C# for Beginners Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=3cfVmcAkR2w&amp;list=PL4LFuHwItvKaOi-bN1E2WUVyZbuRhVokL">Full Advanced C#  Course</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
