<?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" version="2.0"><channel><title><![CDATA[Engineering Insights]]></title><description><![CDATA[I am a computer enthusiast who loves programming. I am currently teaching different programming [C, C++, Python].]]></description><link>https://erkushalghimire.com.np</link><generator>RSS for Node</generator><lastBuildDate>Fri, 13 Nov 2026 22:43:07 GMT</lastBuildDate><atom:link href="https://erkushalghimire.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Free AI Tools for Everyday Productivity & Self-Directed Learning]]></title><description><![CDATA[A Complete Beginner's Tutorial for BIT Students. No prior experience needed — every tool mentioned is free. How to Use This Tutorial Work through the…]]></description><link>https://erkushalghimire.com.np/free-ai-tools-for-everyday-productivity-self-directed-learning</link><guid isPermaLink="true">https://erkushalghimire.com.np/free-ai-tools-for-everyday-productivity-self-directed-learning</guid><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Tue, 08 Sep 2026 16:56:02 GMT</pubDate><content:encoded><![CDATA[<p>A Complete Beginner's Tutorial for BIT Students. No prior experience needed — every tool mentioned is free.</p>
<hr />
<p>How to Use This Tutorial</p>
<p>Work through the sections in order. Each one ends with a short, hands-on exercise. The whole tutorial takes about 4–5 hours and ends with a capstone project that combines everything. One section per day over a week works beautifully.</p>
<p>What you'll walk away with:</p>
<ul>
<li><p>A working knowledge of the best free AI tools and when to use each</p>
</li>
<li><p>A reliable prompting framework you can reuse forever</p>
</li>
<li><p>Hands-on experience with research, coding, design, and — building on your recent git/GitHub workshop — using AI to keep growing your version-control skills on your own</p>
</li>
<li><p>The judgment to use AI safely, ethically, and effectively</p>
</li>
</ul>
<hr />
<p>Section 1: Introduction to Free AI Ecosystems</p>
<p>1.1 What These Tools Actually Are</p>
<p>Modern AI tools are like very capable lab partners: they can read, write, summarize, explain, debug, brainstorm, and generate images — instantly and for free. They aren't magic, they don't "think" like humans, and they aren't always right. They're pattern machines trained on enormous amounts of text and code.</p>
<p>That means they're brilliant at explaining, drafting, and organizing — and imperfect at facts. Keep that balance in mind for the entire tutorial.</p>
<p>1.2 Your Free Toolkit</p>
<p>Conversational AI Assistants (Your "Swiss Army Knife")</p>
<p>Tool What It Is Best For Google Gemini Google's AI assistant Research help, very long documents, Google integration ChatGPT (free tier) The most famous AI chatbot Coding help, writing, brainstorming, explaining concepts Microsoft Copilot Built into Windows/Edge; free online Quick answers, image generation, web-connected chat Claude (free tier) Another conversational AI Long, careful writing and nuanced explanations Perplexity (free tier) AI-powered search engine Finding real sources with citations — great for research</p>
<p>Research &amp; Study Tools</p>
<p>Tool What It Is Best For Google NotebookLM Upload documents, then chat with them Summarizing lecture slides, IEEE papers, textbooks — cites its sources SciSpace / Elicit (free tiers) AI for academic papers Understanding research papers, finding literature</p>
<p>Coding &amp; Development Tools</p>
<p>Tool What It Is Best For GitHub Copilot (free for students!) AI pair-programmer in your editor Code suggestions as you type in VS Code GitHub AI features Ask questions about any repository Understanding unfamiliar codebases on GitHub</p>
<blockquote>
<p>Claim your GitHub Student Developer Pack. Copilot and many other premium tools are free for verified students. Verify with your college email — it takes minutes and it's one of the most valuable free resources you'll receive as a BIT student. Whether your stack is C, Java, Python, PHP, or JavaScript, Copilot will be sitting right inside your editor.</p>
</blockquote>
<p>Content &amp; Design Tools</p>
<p>Tool What It Is Best For Canva (Free + Magic Studio AI) Design tool with AI features Posters, presentations, hackathon banners, AI images Gamma (free tier) AI presentation generator Instant slide decks from an outline Ideogram / Bing Image Creator Free AI image generators Custom illustrations and visuals</p>
<p>1.3 Picking the Right Tool for the Job</p>
<p>A simple rule of thumb:</p>
<ul>
<li><p>"Explain / write / brainstorm something" → ChatGPT, Gemini, or Claude</p>
</li>
<li><p>"Help me understand these specific lecture slides or a paper" → NotebookLM</p>
</li>
<li><p>"Find me sources about X" → Perplexity</p>
</li>
<li><p>"Help me write, debug, or understand code" → ChatGPT/Claude + GitHub Copilot</p>
</li>
<li><p>"Make a poster / slides / image" → Canva or Gamma</p>
</li>
</ul>
<p>✅ Exercise 1: Meet Your Tools (15 minutes)</p>
<ol>
<li><p>Create a free account on ChatGPT (chat.openai.com) and Gemini (gemini.google.com).</p>
</li>
<li><p>Ask each the same question: "Explain the difference between a compiler and an interpreter like I'm a first-semester BIT student, using one analogy I'd actually remember in an exam."</p>
</li>
<li><p>Compare the answers. Which explanation was clearer? Which one would you trust more for revision?</p>
</li>
<li><p>Bonus: Ask one of them: "I'm a BIT student. Give me 3 free AI tools that will help me most with programming courses, and what each is best at."</p>
</li>
</ol>
<blockquote>
<p>Reflection: Each tool has a slightly different "personality." Notice which one explains your subjects in a way that clicks — you'll develop preferences, and that's completely normal.</p>
</blockquote>
<hr />
<p>Section 2: Mastering the Art of Prompting</p>
<p>2.1 Why Prompting Matters</p>
<p>A prompt is simply what you type to the AI. Beginners often type vague one-liners like "explain DBMS," get a generic Wikipedia-style wall of text, and conclude "AI isn't that good." The truth: output quality mostly reflects input quality. A simple framework fixes 90% of weak prompts.</p>
<p>2.2 The CRTF Framework: Context · Role · Task · Format</p>
<p>Element What It Means Example C — Context Background the AI needs "I'm a second-semester BIT student preparing for my Data Structures midterm..." R — Role Who the AI should act as "Act as a patient senior who checks my understanding..." T — Task Exactly what you want "...quiz me on linked lists with 5 questions..." F — Format How the output should look "...one question at a time, with feedback after each answer."</p>
<p>You don't need all four every time — but using two or three dramatically improves results.</p>
<p>2.3 Before &amp; After Examples (BIT Edition)</p>
<p>Example 1 — Studying Data Structures</p>
<p>❌ Weak: <code>Explain linked lists</code></p>
<p>✅ CRTF:</p>
<blockquote>
<p>Context: I'm a second-semester BIT student preparing for my Data Structures &amp; Algorithms midterm in 3 days. Role: Act as a patient tutor who checks whether I really understand, not just nod along. Task: Explain singly linked lists, then highlight the 3 concepts most likely to come in the exam, with a typical exam-style question for each. Format: Start with a real-life analogy (like something from daily tech life), then a small code sketch in C, then end with 2 practice questions I should attempt before seeing answers.</p>
</blockquote>
<p>Example 2 — Email to a Lecturer</p>
<p>❌ Weak: <code>Write an email to my teacher</code></p>
<p>✅ CRTF:</p>
<blockquote>
<p>Context: Our DBMS mini-project demo is scheduled for Thursday, but our group's database server crashed and we've lost a day's work. Role: Act as a professional academic writing assistant. Task: Write a polite email to our lecturer requesting a one-day extension and briefly stating our recovery plan. Format: Under 120 words, subject line included, honest and professional — not overdramatic or excuse-heavy.</p>
</blockquote>
<p>Example 3 — Planning a Brutal Week</p>
<p>❌ Weak: <code>Help me plan my week</code></p>
<p>✅ CRTF:</p>
<blockquote>
<p>Context: I have classes Monday–Friday, a DSA lab report due Wednesday, a Computer Networks quiz on Friday, and I'm building a small portfolio website due Sunday. Role: Act as a realistic study coach who knows BIT students overestimate their free time. Task: Build my study plan. Format: A table by day with 2–3 focused blocks, coding practice scheduled when I'm freshest, and a 30-minute daily buffer for when things inevitably go wrong.</p>
</blockquote>
<p>Example 4 — Understanding a Hard Concept (Discrete Math)</p>
<p>❌ Weak: <code>Explain proof by induction</code></p>
<p>✅ CRTF:</p>
<blockquote>
<p>Context: I'm struggling with discrete mathematics — proofs feel abstract and I keep losing marks on them. Role: Act as a tutor who connects math to programming intuition. Task: Explain proof by mathematical induction. Format: Use a programming analogy (like a loop with a base case and an inductive step), show one fully worked example proving 1+2+...+n = n(n+1)/2, then give me one problem to try with hints available on request.</p>
</blockquote>
<p>Example 5 — A Subject You Haven't Taken Yet</p>
<p>❌ Weak: <code>What is subnetting</code></p>
<p>✅ CRTF:</p>
<blockquote>
<p>Context: I'm a BIT student who just finished a Computer Networks lecture on IP addressing and felt lost for the last 20 minutes. Role: Act as a networking TA who explains with diagrams described in words. Task: Explain subnetting and why networks are divided into subnets. Format: Analogy first, then a tiny worked example with a 192.168.x.x network, then a 3-question self-check. Flag anything I should verify against my lecture notes since courses differ.</p>
</blockquote>
<p>2.4 The Iteration Mindset</p>
<p>Your first answer is rarely the final one. Treat AI like a conversation:</p>
<ol>
<li><p>Ask → get output</p>
</li>
<li><p>Critique → "Make it shorter." / "Add a code example in Java instead." / "This analogy doesn't work for me, try another."</p>
</li>
<li><p>Refine → "Now turn the comparison into a table."</p>
</li>
<li><p>Repeat until satisfied</p>
</li>
</ol>
<p>Power move: Add "Ask me 3 questions before you answer" when your request might be missing details. The AI interviews you first, then gives a much better answer.</p>
<p>Second power move: After getting an explanation, paste it back and say "Quiz me on this explanation with 4 increasing-difficulty questions." Explaining and being tested is how knowledge actually sticks.</p>
<p>✅ Exercise 2: Prompt Makeover (20 minutes)</p>
<ol>
<li><p>Write the weakest possible version of: "help me understand SQL joins"</p>
</li>
<li><p>Rewrite it with CRTF — include which semester/course you're in, the confusion you have (INNER vs LEFT always mixing you up?), and the format you want (comparison table + one practice query with data).</p>
</li>
<li><p>Run both in ChatGPT or Gemini. Compare side by side.</p>
</li>
<li><p>Improve the better output: "Now give me a small practice dataset and 3 queries to write myself — don't show answers until I attempt them."</p>
</li>
</ol>
<blockquote>
<p>Reflection: Save your best prompt as a template. You'll reuse frameworks like this constantly — including for git, as you'll see in Project D.</p>
</blockquote>
<hr />
<p>Section 3: Hands-On Mini Projects</p>
<p>🅰️ Project A: Summarize Dense Study Material with NotebookLM</p>
<p>Time: 30 min | Skill: Turning overwhelming readings into usable study notes</p>
<p>NotebookLM lets you upload your own documents (PDFs, lecture slides, Google Docs, pasted text, YouTube links) and chat with them. Crucially, it cites the exact page each answer comes from — a built-in fact-checking superpower. Perfect for that 40-page IEEE paper your teacher assigned, or 80 dense slides on Normalization.</p>
<p>Step-by-Step</p>
<p>Step 1 — Create a notebook. Go to notebooklm.google.com → "New Notebook."</p>
<p>Step 2 — Add a real source. Click "Add Source" and upload something genuinely hard: your Computer Networks lecture slides, a DBMS chapter on Normalization (1NF/2NF/3NF), or a research paper on machine learning/IoT. Wait for it to process.</p>
<p>Step 3 — Read the auto-summary first. NotebookLM generates a source guide with key topics. This gives you the "shape" of the material before you dive in.</p>
<p>Step 4 — Chat with your material. Try these:</p>
<ul>
<li><p>"Explain the main contribution of this paper to a second-year BIT student."</p>
</li>
<li><p>"What are the 5 most exam-worthy concepts in these slides, and why?"</p>
</li>
<li><p>"Create a study guide: key terms, main ideas, likely exam questions."</p>
</li>
<li><p>"Explain 3NF vs BCNF with a concrete table example from the slides." (or: "Walk me through the OSI model layers using only examples from these slides.")</p>
</li>
<li><p>"What does the paper say about limitations, and what questions would a sharp examiner ask about it?"</p>
</li>
</ul>
<p>Step 5 — Verify citations. Every answer includes citation numbers. Click them — NotebookLM highlights the exact passage. Make this a habit; this alone puts you ahead of most students.</p>
<p>Step 6 — Export. Copy your study guide into Google Docs or your notes app. Add your own margin questions.</p>
<p>🎯 Deliverable A one-page study guide: key terms, main ideas, 5 self-test questions — built from material that used to take you three painful readings.</p>
<hr />
<p>🅱️ Project B: Use an LLM as a Coding &amp; Logic Tutor</p>
<p>Time: 30 min | Skill: Learning to debug and understand code without outsourcing your thinking</p>
<p>Golden Rule: AI can be a tutor, not a vending machine. "Fix this" teaches you nothing. "Help me understand why this fails" builds real skill — the difference between passing one lab and becoming the person your classmates ask for help.</p>
<p>Step-by-Step</p>
<p>Step 1 — Set up. Use this tiny Python example (very close to a first-semester lab exercise — a GPA/marks calculator):</p>
<pre><code class="language-python">def calculate_grade(marks):
    total = 0
    for m in marks:
        total = total + m
    return total / len(marks)

print(calculate_grade([80, 75, 90]))
</code></pre>
<p>Step 2 — Ask for explanation, not a fix.</p>
<blockquote>
<p>"I'm learning Python for my BIT course. Walk me through this code line by line like I'm seeing it for the first time, then explain what would happen if the marks list was empty, and what happens in C if I wrote the same loop with <code>int marks[]</code> but miscounted the size."</p>
</blockquote>
<p>Step 3 — Debug together, coach style. Introduce a bug — pass an empty list, or an off-by-one error in a loop — then prompt:</p>
<blockquote>
<p>"This code gives me a ZeroDivisionError. Don't give me the fix yet — ask me questions to help me find the bug myself, like a lab tutor would."</p>
</blockquote>
<p>Asking the AI to coach rather than solve is one of the most powerful learning moves in this entire tutorial.</p>
<p>Step 4 — Level it up to your actual courses. Try one of these:</p>
<ul>
<li><p>Java/OOP: "Explain the difference between method overloading and overriding using a <code>Student</code> and <code>GraduateStudent</code> class example, then quiz me with code snippets to classify."</p>
</li>
<li><p>DSA: "Here's my bubble sort code. It works, but ask me questions to help me figure out its time complexity myself before telling me."</p>
</li>
<li><p>SQL: "Here's my query and the error message from MySQL. Help me diagnose it — first ask me what I think each clause does."</p>
</li>
<li><p>Web: "Here's my HTML/CSS — why is my navbar overlapping the heading? Guide me to inspect it rather than just fixing it."</p>
</li>
</ul>
<p>Step 5 — Verify. AI sometimes explains code confidently but incorrectly. Run it yourself (replit.com, programiz, or your own compiler) and ask: "Are there edge cases where this explanation breaks?"</p>
<p>⚠️ The Blind Copy-Paste Trap: Code you can't explain line-by-line will break in your viva, may violate academic integrity, and teaches you nothing. The litmus test: if you can't explain a solution, you haven't finished the task. Lab examiners love asking "explain what this line does" — be ready.</p>
<p>🎯 Deliverable A 3-entry "debugging journal": the bug, what the AI suggested, what you learned, one question you still have.</p>
<hr />
<p>🅲 Project C: Generate Visual Assets &amp; Structured Outlines</p>
<p>Time: 30 min | Skill: Creating presentation-ready visuals and content plans</p>
<p>Part 1 — The Outline Comes First</p>
<p>Step 1 — Generate with CRTF:</p>
<blockquote>
<p>Context: I'm making a 5-slide presentation on "How HTTPS Keeps Your Login Password Safe" for my Computer Networks class. Role: Act as a presentation designer who understands technical audiences. Task: Create a 5-slide outline with a clear narrative arc. Format: For each slide — a claim-based title, 3 short bullets, and a visual suggestion.</p>
</blockquote>
<p>Step 2 — Critique it:</p>
<ul>
<li><p>"Which slide is weakest and how would you improve it?"</p>
</li>
<li><p>"Rewrite slide 3's title as a full sentence that makes a claim." (Claim-based titles make technical presentations far stronger — compare "Encryption" vs. "TLS encrypts data before it leaves your browser.")</p>
</li>
</ul>
<p>Part 2 — Generate Visuals</p>
<p>Step 3 — Create a custom illustration. In Canva: open a design → "Apps" → "Magic Media." Or use bing.com/create.</p>
<ul>
<li><p>❌ "a picture of a computer network"</p>
</li>
<li><p>✅ "Clean flat illustration of a laptop sending an encrypted envelope through a cloud to a server, padlock icons along the path, blue and teal palette, minimal tech style"</p>
</li>
</ul>
<p>Step 4 — Apply design basics. Free AI images can look generic — make them yours: add your own bold text overlay, stick to 2–3 consistent colors, and remember one strong diagram beats three weak stock images.</p>
<p>Step 5 — Shortcut with Gamma (gamma.app). Paste your outline and get a full slide draft instantly. Treat it as a starting point to edit, not a finished product — AI decks almost always have too much text per slide.</p>
<p>BIT-flavored topic ideas if you need them: "What is an API — explained with a restaurant analogy," "Why every BIT student should use git," "How a SQL query actually executes," "A beginner's map of cloud computing," a poster for your college's IT club or hackathon.</p>
<p>🎯 Deliverable A 5-slide deck (or poster) with: one custom AI visual, claim-based titles, and no more than 20 words per slide.</p>
<hr />
<p>🅳 Project D: Use AI as Your Personal Git &amp; GitHub Mentor</p>
<p>Time: 40 min | Skill: Continuing your version-control journey independently after your workshop</p>
<p>You just completed a 3-day git/GitHub workshop — a fantastic foundation! Here's a secret professional developers know: nobody memorizes git. Even senior engineers look things up constantly. The difference is they know what to ask and how to verify the answer. This project teaches you to use AI exactly the way professionals do — as a mentor that takes you beyond the workshop, on your own. Given that every BIT group project, hackathon, and eventually every job expects git fluency, this is one of the highest-value sections in the tutorial.</p>
<p>Why This Project Exists</p>
<p>Workshops teach the happy path: <code>init</code>, <code>add</code>, <code>commit</code>, <code>push</code>, <code>pull</code>, maybe a merge. Real group projects get messier. Your post-workshop growth comes from questions like:</p>
<ul>
<li><p>"I committed to the wrong branch — how do I move it?"</p>
</li>
<li><p>"My teammate and I edited the same <code>database.config</code> file — how do I resolve this conflict?"</p>
</li>
<li><p>"What's the difference between <code>merge</code> and <code>rebase</code>, and when do I use each?"</p>
</li>
<li><p>"What makes a good commit message or Pull Request description?"</p>
</li>
<li><p>"I ran something scary and my work 'disappeared' — can I get it back?"</p>
</li>
</ul>
<p>These are exactly the questions AI answers well — if you ask well and verify carefully.</p>
<p>Step-by-Step</p>
<p>Step 1 — Set up your sandbox (5 min). Experiment here, never in your actual assignment repos — some git commands can overwrite history.</p>
<pre><code class="language-bash">mkdir ai-git-practice &amp;&amp; cd ai-git-practice
git init
echo "practice repo for AI mentoring" &gt; README.md
git add . &amp;&amp; git commit -m "initial commit"
</code></pre>
<p>Step 2 — Coach, don't vending-machine (10 min).</p>
<blockquote>
<p>Context: I just finished a 3-day beginner git/GitHub workshop. I understand add, commit, push, pull, and basic branching. Role: Act as a patient git mentor who teaches through guided discovery. Task: Teach me how <code>git stash</code> works. Format: First explain with an everyday analogy (imagine you're mid-feature and the teacher announces a hotfix...), then give me a tiny hands-on exercise, then ask 2 questions to check my understanding.</p>
</blockquote>
<p>Then run the exercise in your terminal before continuing. Reading about git is weak; typing it is strong.</p>
<p>Step 3 — Practice the "Explain My Situation" debugging pattern (10 min). When something goes wrong, don't say "it doesn't work." Always provide evidence — the same habit that will make you excellent at debugging code:</p>
<pre><code class="language-bash">git status              # What state is my repo in?
git log --oneline -5    # What did I recently do?
git branch -a           # What branches exist?
</code></pre>
<p>Then prompt:</p>
<blockquote>
<p>Role: Act as a git debugging mentor. Task: Help me understand what happened before telling me how to fix it. Format: Here are my <code>git status</code>, <code>git log --oneline -5</code>, and <code>git branch -a</code> outputs: [paste]. Ask me questions to diagnose, then propose the safest fix, explaining each command before I run it.</p>
</blockquote>
<p>Try it for real — make a mess on purpose:</p>
<ol>
<li><p>Commit a change on <code>main</code>.</p>
</li>
<li><p><code>git checkout -b feature-login</code> — make another commit.</p>
</li>
<li><p><code>git checkout main</code> — notice the feature commit "disappeared" from the log.</p>
</li>
<li><p>Use the evidence routine + AI mentor to find out where it went and how to recover it.</p>
</li>
</ol>
<p>Step 4 — Verify before you execute (10 min). AI sometimes invents git flags that don't exist or casually suggests destructive commands. A wrong git command can lose a whole evening of work. Your verification routine, every time:</p>
<ol>
<li><p>Ask for the explanation, not just the command. "What does <code>--force-with-lease</code> do, and why is it safer than <code>--force</code>?" If the AI can't explain clearly, don't run it.</p>
</li>
<li><p>Check official docs. <code>man git-&lt;command&gt;</code> or git-scm.com.</p>
</li>
<li><p>Use safety rails. Prefer <code>stash</code> over deleting. Prefer <code>--force-with-lease</code> over <code>--force</code>. When unsure, ask: "Is there a non-destructive way to do this?"</p>
</li>
<li><p>Commit before experimenting. A commit is a save point. And ask your mentor to teach you <code>git reflog</code> — the single best recovery tool beginners don't know.</p>
</li>
</ol>
<p>Step 5 — Level up: learn one post-workshop skill (10 min). Pick one and learn it with the coach technique:</p>
<p>Skill Why It Matters for BIT Students Starter Prompt Good commit messages Your history is your project's story — lecturers and recruiters read it "Give me 5 bad commit messages and improve each. Then critique mine: [paste]" Resolving merge conflicts The #1 real-world hurdle in group projects "Walk me through creating and resolving a merge conflict step by step, checking my work at each stage" Pull Requests &amp; review How real dev teams (and good group projects) collaborate "Explain the PR workflow like a senior dev mentoring a new teammate, including what makes a good PR description" <code>.gitignore</code> &amp; undoing mistakes Stop committing <code>node_modules/</code> and <code>.exe</code> files; learn to undo safely "Teach me .gitignore for a Python/Java web project, and three safe ways to undo the last commit"</p>
<p>🎯 Deliverable A "git learning log" (in your practice repo's README) with 3 entries:</p>
<ul>
<li><p>One concept learned beyond the workshop, explained in your own words</p>
</li>
<li><p>One confusing situation you debugged — including the evidence you gathered and the fix</p>
</li>
<li><p>One AI-suggested command you verified before running — and how you verified it</p>
</li>
</ul>
<hr />
<p>Section 4: Best Practices &amp; Pitfalls</p>
<p>4.1 Hallucinations: AI's Confident Lies</p>
<p>AI sometimes generates plausible-sounding false information — fake statistics, invented library functions, wrong syntax flags, non-existent papers. Every major tool does this occasionally.</p>
<p>Defense strategies:</p>
<ul>
<li><p>Citations are a signal, not proof. Verify important claims at the original source.</p>
</li>
<li><p>Ask for sources, then actually open them.</p>
</li>
<li><p>Cross-examine. Ask two different tools the same factual question. Disagreement = time to check the real docs.</p>
</li>
<li><p>Extra skepticism for: version numbers and APIs (programming libraries change fast — AI may be outdated), numbers, dates, quotes, and niche topics.</p>
</li>
</ul>
<p>4.2 Data Privacy: Don't Feed the Beast</p>
<ul>
<li><p>Never paste passwords, API keys, database credentials, your college ID details, or other people's personal data into AI tools. A classic mistake: pasting a <code>database.config</code> file with live credentials into a chatbot. Don't.</p>
</li>
<li><p>Assume anything you type may be stored (most free services use inputs to improve their models unless you opt out — check settings).</p>
</li>
<li><p>Use "temporary chat" modes where available.</p>
</li>
</ul>
<p>4.3 Academic &amp; Professional Ethics</p>
<ol>
<li><p>AI is a tutor and editor, not an author. If you submit code or a report, you must be able to explain and defend every part of it — lab vivas exist precisely to check this.</p>
</li>
<li><p>Know your college's policy. Many allow AI for brainstorming and feedback but not for generating submitted work. When in doubt, ask your lecturer.</p>
</li>
<li><p>Disclose when required. Some courses now require an AI-use statement.</p>
</li>
<li><p>At work/in internships: check your employer's AI policy before pasting anything work-related.</p>
</li>
</ol>
<p>4.4 The Fact-Check Workflow (Memorize This)</p>
<pre><code class="language-plaintext">1. GENERATE → Get the AI's answer
2. FLAG     → Mark anything factual (numbers, names, dates, APIs, claims)
3. VERIFY   → Check each flagged item at a primary source (official docs!)
4. CITE     → Reference the real source, not the AI
5. SENSE-CHECK → Does it pass my "does that sound right?" test?
</code></pre>
<p>4.5 The "Confidently Wrong Command" Pitfall</p>
<p>AI tools sometimes suggest git or terminal commands with incorrect flags, wrong syntax, or unsafe defaults — stated with total confidence. Unlike a wrong essay paragraph, a wrong command can destroy uncommitted work. The defense is the Verify routine from Project D: understand before you execute, check official docs (git-scm.com, official language docs), commit before experimenting, and know that <code>git reflog</code> is your safety net. If an AI suggestion includes <code>--force</code>, <code>--hard</code>, or <code>clean</code>, treat it as a red traffic light: stop, verify, proceed carefully.</p>
<p>✅ Exercise 4: Spot the Hallucination (15 min)</p>
<ol>
<li><p>Ask any AI: "Give me 5 statistics about AI and software job demand in South Asia with sources," or "What are the most in-demand programming languages in 2026, with sources?"</p>
</li>
<li><p>Try to find each source online. How many actually exist? Do the numbers match?</p>
</li>
<li><p>Now the programmer version: ask "What arguments does Python's <code>requests.get()</code> accept?" — then compare the answer to the official <code>requests</code> documentation. Any invented or outdated parameters?</p>
</li>
</ol>
<p>✅ Exercise 4b: Mentor Swap (20 min)</p>
<p>Pair up. Each of you deliberately creates a small git problem in your practice repo (a misplaced commit, an unwanted staged change, a "lost" branch). Exchange only the evidence outputs (<code>git status</code>, <code>git log --oneline</code>). Each of you uses an AI mentor to diagnose and propose a fix for your partner's problem. Then compare the AI's diagnosis with what your partner actually did. How close was it? What extra questions did you need to ask?</p>
<hr />
<p>🏆 Final Capstone Challenge</p>
<p>Combine everything:</p>
<ol>
<li><p>Pick a real topic from your current semester — e.g., Normalization, the OSI model, recursion, or OOP principles.</p>
</li>
<li><p>Use NotebookLM on your actual lecture slides or a paper → produce a study guide.</p>
</li>
<li><p>Use CRTF prompting to generate a 5-slide outline → build it in Canva or Gamma with one AI visual.</p>
</li>
<li><p>Use an LLM as a tutor to quiz you on the topic — ask it to interview you with questions, not just lecture.</p>
</li>
<li><p>Create a git practice repo, and use your AI mentor to learn one post-workshop skill. Log it in your git learning log.</p>
</li>
<li><p>Fact-check one claim from each tool using the 5-step workflow.</p>
</li>
</ol>
<p>Time: 1.5 hours. You'll finish with a complete mini-project built entirely with free tools — and, more importantly, the judgment and the self-learning loop to keep growing for the rest of your degree.</p>
<hr />
<p>Parting Advice</p>
<p>The students who thrive with AI aren't the ones who use it the most — they're the ones who use it deliberately: as a tutor, a sparring partner, and a first-draft machine, while keeping their own judgment firmly in charge. And now that you've seen it with git in Project D, you know the deeper secret: the same evidence → prompt → verify → execute → reflect loop works for learning anything in BIT — a new language, a framework, cloud, anything. Your workshop gave you a foundation. These tools let you build on it — in any direction you choose — for free, for the rest of your career.</p>
<p>Start small. Stay curious. Verify everything important. And always ask: "Did I actually learn something?"</p>
<p>Happy coding — and welcome to the profession. 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Git & GitHub: A Complete Beginner's Guide]]></title><description><![CDATA[Theory first, then hands-on practice with Git BashA step-by-step guide for students with zero prior experience. Understanding Git & GitHub Installing Git &…]]></description><link>https://erkushalghimire.com.np/git-github-a-complete-beginner-s-guide</link><guid isPermaLink="true">https://erkushalghimire.com.np/git-github-a-complete-beginner-s-guide</guid><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Mon, 07 Sep 2026 16:44:50 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>Theory first, then hands-on practice with Git Bash</strong><br />A step-by-step guide for students with zero prior experience.</p>
</blockquote>
<hr />
<h2>Table of Contents</h2>
<ol>
<li><p><a href="#1-understanding-git--github">Understanding Git &amp; GitHub</a></p>
</li>
<li><p><a href="#2-installing-git--first-time-setup">Installing Git &amp; First-Time Setup</a></p>
</li>
<li><p><a href="#3-creating-your-first-repository">Creating Your First Repository</a></p>
</li>
<li><p><a href="#4-the-git-workflow-track-stage-commit">The Git Workflow: Track, Stage, Commit</a></p>
</li>
<li><p><a href="#5-branching-work-without-fear">Branching: Work Without Fear</a></p>
</li>
<li><p><a href="#6-connecting-to-github">Connecting to GitHub</a></p>
</li>
<li><p><a href="#7-team-collaboration-workflow">Team Collaboration Workflow</a></p>
</li>
<li><p><a href="#8-resolving-merge-conflicts">Resolving Merge Conflicts</a></p>
</li>
<li><p><a href="#9-quick-reference-cheat-sheet">Quick Reference Cheat Sheet</a></p>
</li>
</ol>
<hr />
<h2>1. Understanding Git &amp; GitHub</h2>
<h3>What is Git?</h3>
<p>Git is a <strong>distributed version control system</strong>. It keeps a complete history of every change you make to your project files. Unlike saving multiple copies of a file (like <code>project_v1.doc</code>, <code>project_v2.doc</code>), Git stores only the <em>differences</em> between versions, making it efficient and powerful.</p>
<h3>What is GitHub?</h3>
<p>GitHub is a <strong>cloud hosting service</strong> for Git repositories. It stores your code online, provides a web interface to browse history, and enables team collaboration through features like Pull Requests and Issues. Git works entirely offline on your computer; GitHub comes into play when you want to share or back up.</p>
<blockquote>
<p><strong>Key analogy:</strong> Git is the engine; GitHub is the garage where you park and showcase your car.</p>
</blockquote>
<h3>Why do we need version control?</h3>
<ul>
<li><p><strong>Time travel:</strong> Revert to any previous version of your project instantly.</p>
</li>
<li><p><strong>Experimentation:</strong> Try new ideas on a branch without risking your stable code.</p>
</li>
<li><p><strong>Collaboration:</strong> Multiple people work on the same files without overwriting each other.</p>
</li>
<li><p><strong>Accountability:</strong> Every change is labeled with who made it, when, and why.</p>
</li>
<li><p><strong>Backup:</strong> Push to GitHub and your work is safe even if your computer fails.</p>
</li>
</ul>
<h3>Core Concepts You Must Know</h3>
<table>
<thead>
<tr>
<th>Term</th>
<th>Definition</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Repository (repo)</strong></td>
<td>A folder that Git watches. Contains your project files plus a hidden <code>.git/</code> folder that stores the entire history.</td>
</tr>
<tr>
<td><strong>Commit</strong></td>
<td>A snapshot of your files at one moment in time. Each commit has a unique hash ID and a message explaining the change.</td>
</tr>
<tr>
<td><strong>Working Directory</strong></td>
<td>The actual files on your computer that you edit. This is where you write code, create folders, and modify documents.</td>
</tr>
<tr>
<td><strong>Staging Area (Index)</strong></td>
<td>A "preparation zone" where you decide which changes will be included in the next commit. Think of it as a shopping cart.</td>
</tr>
<tr>
<td><strong>Local Repository</strong></td>
<td>The complete history stored on your computer inside the <code>.git/</code> folder. All commits live here first.</td>
</tr>
<tr>
<td><strong>Remote Repository</strong></td>
<td>A copy of your repo hosted online (e.g., GitHub). You push local commits to it and pull others' changes from it.</td>
</tr>
<tr>
<td><strong>Branch</strong></td>
<td>An independent line of development. The default branch is <code>main</code>. Branches let you work on features in isolation.</td>
</tr>
<tr>
<td><strong>Merge</strong></td>
<td>Combining the changes from one branch into another. Usually merging a feature branch back into <code>main</code>.</td>
</tr>
</tbody></table>
<h3>The Three States of Git</h3>
<p>Every file in a Git repository is in one of three states:</p>
<ol>
<li><p><strong>Modified</strong> — You changed the file but haven't told Git to track the change yet.</p>
</li>
<li><p><strong>Staged</strong> — You marked the file to be included in the next commit (<code>git add</code>).</p>
</li>
<li><p><strong>Committed</strong> — The change is safely stored in your local repository (<code>git commit</code>).</p>
</li>
</ol>
<pre><code class="language-javascript">Working Directory  →  Staging Area  →  Local Repository
     (edit files)       (git add)        (git commit)
</code></pre>
<hr />
<h2>2. Installing Git &amp; First-Time Setup</h2>
<h3>Theory: Why configure Git before using it?</h3>
<p>Every commit you make is stamped with your name and email. This information helps teammates (and your future self) know who made each change and when. Without configuring this, Git will refuse to commit.</p>
<h3>Step 1 — Download and Install Git</h3>
<ul>
<li><p>Go to <strong>git-scm.com</strong> and download the Windows installer.</p>
</li>
<li><p>Run it and accept all default options.</p>
</li>
<li><p>After installation, open <strong>Git Bash</strong> from your Start menu.</p>
</li>
</ul>
<h3>Step 2 — Verify Installation</h3>
<p>Type this in Git Bash and press Enter:</p>
<pre><code class="language-bash">$ git --version
git version 2.43.0.windows.1
</code></pre>
<p>If you see a version number, Git is installed correctly.</p>
<h3>Step 3 — Set Your Identity</h3>
<p>Replace the text in quotes with your actual name and email. These will appear on every commit.</p>
<pre><code class="language-bash">$ git config --global user.name "Your Full Name"
$ git config --global user.email "your.email@example.com"
</code></pre>
<blockquote>
<p><strong>Tip:</strong> Use the same email you will use for your GitHub account. This links your commits to your GitHub profile.</p>
</blockquote>
<h3>Step 4 — Set the Default Branch Name</h3>
<p>This ensures new repositories use <code>main</code> instead of the older <code>master</code> name.</p>
<pre><code class="language-bash">$ git config --global init.defaultBranch main
</code></pre>
<h3>Step 5 — Verify Your Settings</h3>
<pre><code class="language-bash">$ git config --list
user.name=Your Full Name
user.email=your.email@example.com
init.defaultbranch=main
</code></pre>
<p>Press <strong>Q</strong> to exit the list view.</p>
<h3>Step 6 — Create a GitHub Account</h3>
<p>Go to <strong>github.com</strong> and sign up with the same email you configured above. You will need this in the GitHub section.</p>
<hr />
<h2>3. Creating Your First Repository</h2>
<h3>Theory: What happens when you run <code>git init</code>?</h3>
<p>Running <code>git init</code> creates a hidden folder named <code>.git</code> inside your project directory. This folder is Git's database — it stores every commit, every branch, and the entire history of your project. You only need to run <code>git init</code> once per project.</p>
<h3>Step 1 — Navigate to Your Documents Folder</h3>
<p>Open Git Bash and type:</p>
<pre><code class="language-bash">$ cd Documents
</code></pre>
<p>This moves you into your Documents directory where we will build the project.</p>
<h3>Step 2 — Create a New Folder</h3>
<pre><code class="language-bash">$ mkdir my-portfolio
</code></pre>
<p><code>mkdir</code> stands for "make directory." This creates a folder named <code>my-portfolio</code>.</p>
<h3>Step 3 — Move Into the New Folder</h3>
<pre><code class="language-bash">$ cd my-portfolio
$ pwd
/c/Users/YourName/Documents/my-portfolio
</code></pre>
<p><code>pwd</code> (print working directory) confirms where you are.</p>
<h3>Step 4 — Create the HTML File</h3>
<p>Open this folder in VS Code (recommended):</p>
<pre><code class="language-bash">$ code .
</code></pre>
<p>Then create <code>index.html</code> with this content:</p>
<pre><code class="language-html">&lt;!-- index.html --&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;title&gt;My Portfolio&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Hello, I am learning Git!&lt;/h1&gt;
  &lt;p&gt;This is my first tracked project.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Save the file. If you don't have VS Code, use Notepad and save it as <code>index.html</code> inside the <code>my-portfolio</code> folder.</p>
<h3>Step 5 — Create a CSS File</h3>
<p>Create <code>style.css</code> in the same folder:</p>
<pre><code class="language-css">/* style.css */
body {
  font-family: Arial, sans-serif;
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  background-color: #f9f9f9;
}
h1 {
  color: #333;
}
</code></pre>
<h3>Step 6 — Create a README File</h3>
<p>Create <code>README.md</code> in the same folder:</p>
<pre><code class="language-markdown"># My Portfolio

A simple HTML portfolio to learn Git and GitHub.
</code></pre>
<h3>Step 7 — Verify Your Folder Structure</h3>
<p>In Git Bash, type:</p>
<pre><code class="language-bash">$ ls
index.html  README.md  style.css
</code></pre>
<p>You should see all three files listed.</p>
<h3>Step 8 — Initialize the Repository</h3>
<pre><code class="language-bash">$ git init
Initialized empty Git repository in C:/Users/YourName/Documents/my-portfolio/.git/
</code></pre>
<p>This creates the hidden <code>.git</code> folder. Your folder is now a Git repository.</p>
<h3>Step 9 — Check Git's View of Your Folder</h3>
<pre><code class="language-bash">$ git status
On branch main

No commits yet

Untracked files:
  (use "git add &lt;file&gt;..." to include in what will be committed)
        index.html
        README.md
        style.css
</code></pre>
<p>Git sees your files but is not tracking them yet. They are "untracked."</p>
<hr />
<h2>4. The Git Workflow: Track, Stage, Commit</h2>
<h3>Theory: The Four Areas of Git</h3>
<p>When you work with Git, your files move through four conceptual areas:</p>
<ol>
<li><p><strong>Working Directory</strong> — where you edit files</p>
</li>
<li><p><strong>Staging Area</strong> — where you prepare changes</p>
</li>
<li><p><strong>Local Repository</strong> — where commits are stored</p>
</li>
<li><p><strong>Remote Repository</strong> — GitHub's copy</p>
</li>
</ol>
<p>Right now we focus on the first three.</p>
<h3>Step 1 — Stage a Single File</h3>
<pre><code class="language-bash">$ git add index.html
</code></pre>
<p>This moves <code>index.html</code> from "untracked" to "staged." It is now in the staging area, ready to be committed.</p>
<h3>Step 2 — Check the Status Again</h3>
<pre><code class="language-bash">$ git status
On branch main

No commits yet

Changes to be committed:
  (use "git rm --cached &lt;file&gt;..." to unstage)
        new file:   index.html

Untracked files:
        README.md
        style.css
</code></pre>
<p>Notice: <code>index.html</code> is now green (staged), while the other two are still red (untracked).</p>
<h3>Step 3 — Stage All Remaining Files at Once</h3>
<pre><code class="language-bash">$ git add .
</code></pre>
<p>The dot (<code>.</code>) means "everything in the current directory." This stages <code>README.md</code> and <code>style.css</code> in one command.</p>
<pre><code class="language-bash">$ git status
Changes to be committed:
        new file:   index.html
        new file:   README.md
        new file:   style.css
</code></pre>
<h3>Step 4 — Create Your First Commit</h3>
<pre><code class="language-bash">$ git commit -m "Add initial HTML5 portfolio page with styling"
[main (root-commit) a1b2c3d] Add initial HTML5 portfolio page with styling
 3 files changed, 25 insertions(+)
 create mode 100644 index.html
 create mode 100644 README.md
 create mode 100644 style.css
</code></pre>
<p>The <code>-m</code> flag stands for "message." The string in quotes describes what this commit contains. The hash <code>a1b2c3d</code> is the unique ID for this commit.</p>
<blockquote>
<p><strong>Commit message tip:</strong> Write in present tense, be specific. <code>"Add navigation bar"</code> is better than <code>"changes"</code> or <code>"update"</code>.</p>
</blockquote>
<h3>Step 5 — View Your Commit History</h3>
<pre><code class="language-bash">$ git log --oneline
a1b2c3d (HEAD -&gt; main) Add initial HTML5 portfolio page with styling
</code></pre>
<p><code>HEAD -&gt; main</code> means this is the latest commit on your <code>main</code> branch.</p>
<h3>Step 6 — Make Another Change</h3>
<p>Edit <code>index.html</code> and add a footer inside the body:</p>
<pre><code class="language-html">&lt;body&gt;
  &lt;h1&gt;Hello, I am learning Git!&lt;/h1&gt;
  &lt;p&gt;This is my first tracked project.&lt;/p&gt;
  &lt;footer&gt;
    &lt;p&gt;&amp;copy; 2026 My Portfolio&lt;/p&gt;
  &lt;/footer&gt;
&lt;/body&gt;
</code></pre>
<p>Save the file.</p>
<h3>Step 7 — See What Changed</h3>
<pre><code class="language-bash">$ git status
On branch main
Changes not staged for commit:
  (use "git add &lt;file&gt;..." to update what will be committed)
        modified:   index.html
</code></pre>
<p>Git knows <code>index.html</code> was modified, but the change is not staged yet.</p>
<h3>Step 8 — See the Exact Line-by-Line Changes</h3>
<pre><code class="language-bash">$ git diff
diff --git a/index.html b/index.html
+ &lt;footer&gt;
+   &lt;p&gt;&amp;copy; 2026 My Portfolio&lt;/p&gt;
+ &lt;/footer&gt;
</code></pre>
<p>Lines starting with <code>+</code> were added. Lines with <code>-</code> would be removed.</p>
<h3>Step 9 — Stage and Commit the Footer</h3>
<pre><code class="language-bash">$ git add index.html
$ git commit -m "Add footer with copyright notice"
</code></pre>
<h3>Step 10 — View the Updated History</h3>
<pre><code class="language-bash">$ git log --oneline
e4f5g6h (HEAD -&gt; main) Add footer with copyright notice
a1b2c3d Add initial HTML5 portfolio page with styling
</code></pre>
<p>Your history now shows two commits. The newest is at the top.</p>
<hr />
<h2>5. Branching: Work Without Fear</h2>
<h3>Theory: Why Use Branches?</h3>
<p>A branch is an independent copy of your code. When you create a branch, Git makes a lightweight pointer to your current commit. You can edit, break, and experiment on a branch without affecting <code>main</code>. Once your feature works, you merge it back. This is how professional teams work.</p>
<h3>Step 1 — See What Branch You Are On</h3>
<pre><code class="language-bash">$ git branch
* main
</code></pre>
<p>The asterisk (<code>*</code>) shows you are currently on the <code>main</code> branch.</p>
<h3>Step 2 — Create a New Branch</h3>
<pre><code class="language-bash">$ git switch -c feature-contact-page
Switched to a new branch 'feature-contact-page'
</code></pre>
<p><code>-c</code> means "create." This command both creates the branch and switches to it in one step.</p>
<h3>Step 3 — Confirm You Are on the New Branch</h3>
<pre><code class="language-bash">$ git branch
* feature-contact-page
  main
</code></pre>
<p>The asterisk is now next to <code>feature-contact-page</code>.</p>
<h3>Step 4 — Create a New File on the Branch</h3>
<p>Create <code>contact.html</code> in your project folder with this content:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;title&gt;Contact Me&lt;/title&gt;
  &lt;link rel="stylesheet" href="style.css"&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Contact Me&lt;/h1&gt;
  &lt;form&gt;
    &lt;label&gt;Name: &lt;input type="text" name="name"&gt;&lt;/label&gt;&lt;br&gt;&lt;br&gt;
    &lt;label&gt;Email: &lt;input type="email" name="email"&gt;&lt;/label&gt;&lt;br&gt;&lt;br&gt;
    &lt;button type="submit"&gt;Send Message&lt;/button&gt;
  &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Save the file.</p>
<h3>Step 5 — Stage and Commit the New File</h3>
<pre><code class="language-bash">$ git add contact.html
$ git commit -m "Add contact page with simple form"
</code></pre>
<h3>Step 6 — View the Branch History</h3>
<pre><code class="language-bash">$ git log --oneline
i7j8k9l (HEAD -&gt; feature-contact-page) Add contact page with simple form
e4f5g6h Add footer with copyright notice
a1b2c3d Add initial HTML5 portfolio page with styling
</code></pre>
<h3>Step 7 — Switch Back to Main</h3>
<pre><code class="language-bash">$ git switch main
Switched to branch 'main'
</code></pre>
<h3>Step 8 — Check if contact.html Exists on Main</h3>
<pre><code class="language-bash">$ ls
index.html  README.md  style.css
</code></pre>
<p><strong>Notice:</strong> <code>contact.html</code> is gone! It only exists on the <code>feature-contact-page</code> branch. This is the power of branching — your main code stays clean while you experiment.</p>
<h3>Step 9 — Merge the Feature Branch</h3>
<pre><code class="language-bash">$ git merge feature-contact-page
Updating e4f5g6h..i7j8k9l
Fast-forward
 contact.html | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
 create mode 100644 contact.html
</code></pre>
<p>Git performed a "fast-forward" merge because <code>main</code> had no new commits since the branch was created.</p>
<h3>Step 10 — Verify the Merge</h3>
<pre><code class="language-bash">$ ls
contact.html  index.html  README.md  style.css

$ git log --oneline
i7j8k9l (HEAD -&gt; main, feature-contact-page) Add contact page with simple form
</code></pre>
<p><code>contact.html</code> is now on <code>main</code> too.</p>
<h3>Step 11 — Delete the Feature Branch</h3>
<pre><code class="language-bash">$ git branch -d feature-contact-page
Deleted branch feature-contact-page (was i7j8k9l).
</code></pre>
<p>The branch is deleted, but the commits remain in your history.</p>
<hr />
<h2>6. Connecting to GitHub</h2>
<h3>Theory: Local vs Remote</h3>
<p>Until now, all your commits have lived only on your computer. A <strong>remote</strong> is a copy of your repository stored on another machine — in our case, GitHub's servers. Pushing uploads your commits. Pulling downloads others' commits. This is how you back up your work and share it.</p>
<h3>Step 1 — Create a Repository on GitHub</h3>
<ol>
<li><p>Go to <strong>github.com</strong> and sign in.</p>
</li>
<li><p>Click the <strong>+</strong> icon in the top-right corner → <strong>New repository</strong>.</p>
</li>
<li><p>Fill in the details:</p>
</li>
</ol>
<ul>
<li><p><strong>Repository name:</strong> <code>my-portfolio</code></p>
</li>
<li><p><strong>Description:</strong> <code>My first Git project</code> (optional)</p>
</li>
<li><p><strong>Visibility:</strong> Public</p>
</li>
<li><p><strong>Initialize with README:</strong> UNCHECK this box (you already have a README)</p>
</li>
<li><p><strong>Add .gitignore:</strong> None</p>
</li>
<li><p><strong>Choose a license:</strong> None</p>
</li>
</ul>
<ol>
<li>Click <strong>Create repository</strong>.</li>
</ol>
<h3>Step 2 — Copy the Repository URL</h3>
<p>On the next page, under "Quick setup," copy the HTTPS URL. It looks like:</p>
<pre><code class="language-javascript">https://github.com/yourusername/my-portfolio.git
</code></pre>
<h3>Step 3 — Make Sure You Are in Your Project Folder</h3>
<pre><code class="language-bash">$ cd ~/Documents/my-portfolio
$ pwd
</code></pre>
<h3>Step 4 — Add GitHub as Your Remote</h3>
<pre><code class="language-bash">$ git remote add origin https://github.com/yourusername/my-portfolio.git
</code></pre>
<p>Replace <code>yourusername</code> with your actual GitHub username. The word <code>origin</code> is the conventional name for your primary remote.</p>
<h3>Step 5 — Verify the Remote Was Added</h3>
<pre><code class="language-bash">$ git remote -v
origin  https://github.com/yourusername/my-portfolio.git (fetch)
origin  https://github.com/yourusername/my-portfolio.git (push)
</code></pre>
<h3>Step 6 — Push Your Commits to GitHub</h3>
<pre><code class="language-bash">$ git push -u origin main
Enumerating objects: 12, done.
Counting objects: 100% (12/12), done.
Writing objects: 100% (12/12), 1.45 KiB | 1.45 MiB/s, done.
Total 12 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/yourusername/my-portfolio.git
 * [new branch]      main -&gt; main
branch 'main' set up to track 'origin/main'.
</code></pre>
<p>The <code>-u</code> (upstream) flag tells Git to remember this connection. Next time, you can simply type <code>git push</code>.</p>
<blockquote>
<p><strong>Note:</strong> If Git asks for your username and password, enter your GitHub username and a <strong>Personal Access Token</strong> (not your GitHub password). Create one at GitHub → Settings → Developer settings → Personal access tokens.</p>
</blockquote>
<h3>Step 7 — Verify on GitHub</h3>
<p>Refresh your GitHub repository page in your browser. You should see all your files: <code>index.html</code>, <code>style.css</code>, <code>README.md</code>, and <code>contact.html</code>.</p>
<h3>Step 8 — The Push-Pull Cycle</h3>
<p>Edit <code>README.md</code> to add a new line:</p>
<pre><code class="language-markdown"># My Portfolio

A simple HTML portfolio to learn Git and GitHub.
This project is now hosted on GitHub!
</code></pre>
<p>Then in Git Bash:</p>
<pre><code class="language-bash">$ git add README.md
$ git commit -m "Update README with GitHub note"
$ git push
</code></pre>
<p>Because you used <code>-u</code> earlier, <code>git push</code> now works without specifying <code>origin main</code>.</p>
<hr />
<h2>7. Team Collaboration Workflow</h2>
<h3>Theory: How Teams Collaborate on GitHub</h3>
<p>When you want to contribute to someone else's project (or when teammates contribute to yours), you do not push directly to their repository. Instead, you <strong>fork</strong> their repo (make your own copy), work on your copy, then submit a <strong>Pull Request</strong> asking them to pull your changes into their project. This is the standard open-source workflow.</p>
<h3>Step 1 — Fork a Repository on GitHub</h3>
<p>Find a public repository you want to contribute to (or ask a friend for theirs). Click the <strong>Fork</strong> button in the top-right corner of the repository page. GitHub creates a copy under your account.</p>
<h3>Step 2 — Clone Your Fork</h3>
<p>On your fork's page, click the green <strong>Code</strong> button, copy the HTTPS URL, then in Git Bash:</p>
<pre><code class="language-bash">$ cd ~/Documents
$ git clone https://github.com/YOURNAME/their-repo.git
Cloning into 'their-repo'...
remote: Enumerating objects: 45, done.
Receiving objects: 100% (45/45), done.
</code></pre>
<h3>Step 3 — Enter the Cloned Folder</h3>
<pre><code class="language-bash">$ cd their-repo
$ git remote -v
origin  https://github.com/YOURNAME/their-repo.git (fetch)
origin  https://github.com/YOURNAME/their-repo.git (push)
</code></pre>
<p><code>origin</code> points to your fork, not the original repository.</p>
<h3>Step 4 — Add the Original Repository</h3>
<pre><code class="language-bash">$ git remote add upstream https://github.com/ORIGINALOWNER/their-repo.git
$ git remote -v
origin    https://github.com/YOURNAME/their-repo.git (fetch)
origin    https://github.com/YOURNAME/their-repo.git (push)
upstream  https://github.com/ORIGINALOWNER/their-repo.git (fetch)
upstream  https://github.com/ORIGINALOWNER/their-repo.git (push)
</code></pre>
<p>You now have two remotes: <code>origin</code> (your fork) and <code>upstream</code> (the original).</p>
<h3>Step 5 — Update Your Main Branch</h3>
<pre><code class="language-bash">$ git switch main
$ git pull upstream main
$ git push origin main
</code></pre>
<p>This ensures you are working with the latest code from the original repository.</p>
<h3>Step 6 — Create a Feature Branch</h3>
<pre><code class="language-bash">$ git switch -c fix-typo-in-readme
</code></pre>
<p>Always create a branch with a descriptive name.</p>
<h3>Step 7 — Make Your Change, Stage, and Commit</h3>
<pre><code class="language-bash">$ git add .
$ git commit -m "Fix typo in README introduction"
</code></pre>
<h3>Step 8 — Push the Branch to Your Fork</h3>
<pre><code class="language-bash">$ git push -u origin fix-typo-in-readme
</code></pre>
<h3>Step 9 — Open the Pull Request on GitHub</h3>
<p>Go to your fork on GitHub. You will see a yellow banner saying:</p>
<blockquote>
<p>"fix-typo-in-readme had recent pushes. Compare &amp; pull request"</p>
</blockquote>
<p>Click <strong>Compare &amp; pull request</strong>.</p>
<h3>Step 10 — Write a Good Pull Request</h3>
<ul>
<li><p><strong>Title:</strong> Short and clear (e.g., "Fix typo in README introduction")</p>
</li>
<li><p><strong>Description:</strong> Explain what you changed and why</p>
</li>
<li><p>Click <strong>Create pull request</strong></p>
</li>
</ul>
<p>The project owner will review your changes and either merge them or request modifications.</p>
<hr />
<h2>8. Resolving Merge Conflicts</h2>
<h3>Theory: What Causes a Conflict?</h3>
<p>A merge conflict occurs when two branches have changed the <strong>same lines</strong> of the same file in different ways. Git cannot decide which version is correct, so it stops and asks you to choose. Conflicts are normal, not errors. They simply mean human judgment is needed.</p>
<h3>Step 1 — Make Sure You Are on Main</h3>
<pre><code class="language-bash">$ cd ~/Documents/my-portfolio
$ git switch main
</code></pre>
<h3>Step 2 — Create Branch A and Change the Heading</h3>
<pre><code class="language-bash">$ git switch -c branch-a
</code></pre>
<p>Edit <code>index.html</code> and change the h1 text to:</p>
<pre><code class="language-html">&lt;h1&gt;Welcome to my website&lt;/h1&gt;
</code></pre>
<p>Save, then commit:</p>
<pre><code class="language-bash">$ git add index.html
$ git commit -m "Change heading to Welcome to my website"
</code></pre>
<h3>Step 3 — Switch Back to Main and Create Branch B</h3>
<pre><code class="language-bash">$ git switch main
$ git switch -c branch-b
</code></pre>
<p>Edit <code>index.html</code> and change the h1 text to something different:</p>
<pre><code class="language-html">&lt;h1&gt;Hello, welcome to my portfolio&lt;/h1&gt;
</code></pre>
<p>Save, then commit:</p>
<pre><code class="language-bash">$ git add index.html
$ git commit -m "Change heading to Hello, welcome to my portfolio"
</code></pre>
<h3>Step 4 — Attempt to Merge Branch A into Main</h3>
<pre><code class="language-bash">$ git switch main
$ git merge branch-a
</code></pre>
<p>This should succeed (fast-forward) because main has not changed.</p>
<h3>Step 5 — Now Merge Branch B (This Will Conflict)</h3>
<pre><code class="language-bash">$ git merge branch-b
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
</code></pre>
<p>Git has stopped and is waiting for you to resolve the conflict.</p>
<h3>Step 6 — Check Which Files Are Conflicted</h3>
<pre><code class="language-bash">$ git status
On branch main
You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add &lt;file&gt;..." to mark resolution)
        both modified:   index.html
</code></pre>
<h3>Step 7 — Open the Conflicted File</h3>
<p>Open <code>index.html</code> in your editor. You will see conflict markers:</p>
<pre><code class="language-html">&lt;header&gt;
&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD
  &lt;h1&gt;Welcome to my website&lt;/h1&gt;
=======
  &lt;h1&gt;Hello, welcome to my portfolio&lt;/h1&gt;
&gt;&gt;&gt;&gt;&gt;&gt;&gt; branch-b
&lt;/header&gt;
</code></pre>
<ul>
<li><p><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD</code> — Your current branch's version (from branch-a, now on main)</p>
</li>
<li><p><code>=======</code> — Divider</p>
</li>
<li><p><code>&gt;&gt;&gt;&gt;&gt;&gt;&gt; branch-b</code> — The other branch's version</p>
</li>
</ul>
<h3>Step 8 — Resolve the Conflict</h3>
<p>Edit the file to keep the version you want, and <strong>remove all conflict markers</strong>:</p>
<pre><code class="language-html">&lt;header&gt;
  &lt;h1&gt;Welcome to my portfolio&lt;/h1&gt;
&lt;/header&gt;
</code></pre>
<p><strong>Critical:</strong> Remove these lines completely:</p>
<ul>
<li><p><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD</code></p>
</li>
<li><p><code>=======</code></p>
</li>
<li><p><code>&gt;&gt;&gt;&gt;&gt;&gt;&gt; branch-b</code></p>
</li>
</ul>
<h3>Step 9 — Stage the Resolved File</h3>
<pre><code class="language-bash">$ git add index.html
</code></pre>
<h3>Step 10 — Complete the Merge</h3>
<pre><code class="language-bash">$ git commit
</code></pre>
<p>Git opens an editor with a default merge message. Just save and close the file.</p>
<h3>Step 11 — Verify the Resolution</h3>
<pre><code class="language-bash">$ git log --oneline
m9n0o1p (HEAD -&gt; main) Merge branch 'branch-b'
</code></pre>
<h3>Safety Commands</h3>
<pre><code class="language-bash"># Abort a merge and return to pre-merge state
git merge --abort

# Check for leftover conflict markers before committing
git diff --check

# Use a visual merge tool (optional)
git config --global merge.tool vscode
git mergetool
</code></pre>
<blockquote>
<p><strong>Critical:</strong> Never commit conflict markers. Always verify the file looks correct before staging.</p>
</blockquote>
<hr />
<h2>9. Quick Reference Cheat Sheet</h2>
<h3>Setup</h3>
<table>
<thead>
<tr>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>git init</code></td>
<td>Initialize a new repository</td>
</tr>
<tr>
<td><code>git clone &lt;url&gt;</code></td>
<td>Copy a remote repository locally</td>
</tr>
<tr>
<td><code>git config --global user.name "Name"</code></td>
<td>Set commit author name</td>
</tr>
<tr>
<td><code>git config --global user.email "Email"</code></td>
<td>Set commit author email</td>
</tr>
</tbody></table>
<h3>Daily Workflow</h3>
<table>
<thead>
<tr>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>git status</code></td>
<td>Check current state</td>
</tr>
<tr>
<td><code>git add &lt;file&gt;</code></td>
<td>Stage a file</td>
</tr>
<tr>
<td><code>git add .</code></td>
<td>Stage all changes</td>
</tr>
<tr>
<td><code>git commit -m "msg"</code></td>
<td>Save a snapshot</td>
</tr>
<tr>
<td><code>git push</code></td>
<td>Upload commits</td>
</tr>
<tr>
<td><code>git pull</code></td>
<td>Download and merge changes</td>
</tr>
<tr>
<td><code>git diff</code></td>
<td>See unstaged changes</td>
</tr>
</tbody></table>
<h3>Branching</h3>
<table>
<thead>
<tr>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>git branch</code></td>
<td>List branches</td>
</tr>
<tr>
<td><code>git switch -c &lt;name&gt;</code></td>
<td>Create and switch to branch</td>
</tr>
<tr>
<td><code>git switch &lt;name&gt;</code></td>
<td>Switch branches</td>
</tr>
<tr>
<td><code>git merge &lt;branch&gt;</code></td>
<td>Merge a branch into current</td>
</tr>
<tr>
<td><code>git branch -d &lt;name&gt;</code></td>
<td>Delete a merged branch</td>
</tr>
</tbody></table>
<h3>Undoing</h3>
<table>
<thead>
<tr>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>git restore &lt;file&gt;</code></td>
<td>Discard unstaged changes</td>
</tr>
<tr>
<td><code>git reset HEAD~1</code></td>
<td>Undo last commit (keep changes)</td>
</tr>
<tr>
<td><code>git revert &lt;hash&gt;</code></td>
<td>Create a commit that undoes a past commit</td>
</tr>
<tr>
<td><code>git stash</code></td>
<td>Temporarily save changes</td>
</tr>
<tr>
<td><code>git stash pop</code></td>
<td>Restore stashed changes</td>
</tr>
</tbody></table>
<h3>Remote</h3>
<table>
<thead>
<tr>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>git remote -v</code></td>
<td>List remotes</td>
</tr>
<tr>
<td><code>git remote add &lt;name&gt; &lt;url&gt;</code></td>
<td>Add a remote</td>
</tr>
<tr>
<td><code>git fetch</code></td>
<td>Download remote changes</td>
</tr>
<tr>
<td><code>git push -u origin main</code></td>
<td>Push and set upstream</td>
</tr>
</tbody></table>
<h3>.gitignore Template for Web Projects</h3>
<pre><code class="language-gitignore"># OS files
.DS_Store
Thumbs.db

# Editor files
.vscode/
.idea/
*.swp

# Dependencies
node_modules/

# Build output
dist/
build/
</code></pre>
<hr />
<h2>Best Practices Checklist</h2>
<ul>
<li><p>[ ] Commit early, commit often</p>
</li>
<li><p>[ ] Write clear, present-tense commit messages</p>
</li>
<li><p>[ ] Create a branch for every feature or fix</p>
</li>
<li><p>[ ] Pull before you push to avoid conflicts</p>
</li>
<li><p>[ ] Review your changes with <code>git diff</code> before committing</p>
</li>
<li><p>[ ] Never commit passwords, API keys, or <code>node_modules</code></p>
</li>
<li><p>[ ] Use a <code>.gitignore</code> file from day one</p>
</li>
<li><p>[ ] Keep commits small and focused on one logical change</p>
</li>
</ul>
<hr />
<p><em>Happy coding! Remember: every expert was once a beginner. Git becomes intuitive with practice.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to build a program to solve a certain problem ?]]></title><description><![CDATA[The six steps that are required to build a computer program for solving a certain problem are explained below: Problem Analysis: Problem analysis is the…]]></description><link>https://erkushalghimire.com.np/how-to-build-a-program-to-solve-a-certain-problem</link><guid isPermaLink="true">https://erkushalghimire.com.np/how-to-build-a-program-to-solve-a-certain-problem</guid><category><![CDATA[structure of c program]]></category><category><![CDATA[build a program]]></category><category><![CDATA[compilation steps]]></category><category><![CDATA[debugging]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Fri, 29 Dec 2023 16:44:31 GMT</pubDate><content:encoded><![CDATA[<p>The six steps that are required to build a computer program for solving a certain problem are explained below:</p>
<ol>
<li><p><strong><mark>Problem Analysis:</mark></strong> Problem analysis is the process of defining a problem and decomposing overall system into smaller parts to identify possible inputs, processes and outputs associated with the problem.</p>
</li>
<li><p><strong><mark>Problem Design:</mark></strong> This stage consists of preparing algorithms, flowcharts and pseudocodes. Generally, this stage intends to make the program more user friendly, feasible and optimized.</p>
</li>
<li><p><strong><mark>Coding:</mark></strong> Transforming the program logic design into a computer language format i.e. actual writing of computer programs is known as coding. It can be said that coding is the act of transforming operations explained in algorithm or in each boxes of flowchart into statement of the programming language.</p>
</li>
<li><p><strong><mark>Compilation and Execution:</mark></strong> The conversion process of high level language into machine level language with the help of language translators(compiler) is known as compilation. Once the compilation process is complete it is linked with other object programs and library files resulting in an binary program(executable file). Thus obtained binary program is loaded into the memory for the purpose of execution.</p>
</li>
<li><p><strong><mark>Debugging and Testing:</mark></strong> The presence of bugs(errors) in the program can cause it to behave unexpectedly or even crash. Debugging is the process of detecting and correcting existing and potential bugs in a software program. Testing is the process to find bugs. Testing ensures that the program performs  the required task correctly.</p>
</li>
<li><p><strong><mark>Program Documentation:</mark></strong> Any written text, illustrations or video that describe a software or program to its users is called a program or software documentation. Documentation should be from the point of view of the reader. Industry standards should be used and should be updated.</p>
</li>
</ol>
<h1 id="heading-different-types-of-errors">Different Types Of Errors</h1>
<p>The common errors that are encountered during programming in any language can be generally categorized as:</p>
<ol>
<li><p><strong>Syntax Error :</strong> an error that occurs when the code does not follow the syntax rules of programming language. For example: <code>printf(“Hello World)</code> will show a syntax error because semicolon(<code>;</code>) is missing at the end.</p>
</li>
<li><p><strong>Logical Error :</strong> an error that occurs when there is the logical mistake such as <code>&gt;=</code> instead of <code>&gt;</code> or an infinite loop and so on . The code may run/execute but the desired result is not obtained. </p>
</li>
<li><p><strong>Runtime Error :</strong> an error that occurs when the program is being executed or running. For example, trying to open a file(File Handling) that doesn’t exist .</p>
</li>
</ol>
<h1 id="heading-debugging-vs-testing">Debugging Vs Testing</h1>
<table><tbody><tr><td><p><strong>Factors</strong></p></td><td><p><strong>Debugging</strong></p></td><td><p><strong>Testing</strong></p></td></tr><tr><td><p>WHAT ?</p></td><td><p>Fix error</p></td><td><p>Find error</p></td></tr><tr><td><p>WHEN ?</p></td><td><p>Done at Development phase</p></td><td><p>Done at Testing phase </p></td></tr><tr><td><p>WHO ?</p></td><td><p>Performed by developers</p></td><td><p>Performed by system testers.</p></td></tr><tr><td><p>HOW ?</p></td><td><p>Manual operation</p></td><td><p>Manual or automatic operation</p></td></tr></tbody></table>

<h1 id="heading-steps-involved-during-compilation-of-a-source-code-written-in-c">Steps Involved During Compilation Of A Source Code Written In C</h1>
<ul>
<li><p>Source code <code>my_program.c</code> is transferred to the preprocessor.</p>
</li>
<li><p>Preprocessor transforms the source code to expanded source code <code>my_program.i</code>.</p>
</li>
<li><p>Extended/Expanded Source Code is transferred to the compiler to be converted into assembly code <code>my_program.s</code>.</p>
</li>
<li><p>Assembly Code is transferred to Assembler to be converted into object code <code>my_program.o / my_program.obj</code>.</p>
  <details><summary>Note</summary><div data-type="detailsContent">In the context of compiling C source code, the term "compiler" is often used more broadly to refer to the entire compilation process, which includes several stages. While it's true that the compilation process involves multiple steps, including preprocessing, compiling, assembling, and linking, the term "compiler" is commonly used to describe the entire process as a whole.</div></details></li>
<li>Object Code is combined with library files and other objects to generate an executable code <code>my_program.exe</code>.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703865089218/fe0a394a-709c-4d2e-abc2-a6540e0efc09.png" alt="Compilation of a source code written in C" class="image--center mx-auto" /></p>
<h1 id="heading-structure-of-a-program-in-c">Structure Of A Program In C</h1>
<pre><code class="lang-c"><span class="hljs-comment">/* 1. Documentation Section */</span>
<span class="hljs-comment">//A program to find the area of a circle. Programmed by Er. Kushal Ghimire</span>

<span class="hljs-comment">/* 2. Link Section */</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-comment">/* 3. Definition Section */</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> PI 3.14</span>

<span class="hljs-comment">/* 4. Global Section */</span>
<span class="hljs-comment">/* 4.1 Global Variable Declaration */</span>
<span class="hljs-keyword">float</span> result; 
<span class="hljs-comment">/* 4.2 Function Declaration/Prototype */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">area_of_circle</span><span class="hljs-params">(<span class="hljs-keyword">float</span>)</span></span>; 
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>;

<span class="hljs-comment">/* 5. Main Section */</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">/* 5.1 Declaration Part */</span>
    <span class="hljs-keyword">float</span> radius;

    <span class="hljs-comment">/* 5.2 Executable Part */</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter radius of a circle: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%f"</span>, &amp;radius);
    area_of_circle(radius);
    display();

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

<span class="hljs-comment">/* 6. User Defined FUnction Section */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">area_of_circle</span><span class="hljs-params">(<span class="hljs-keyword">float</span> r)</span>
</span>{
    result = PI * r * r;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe area of circle is %f"</span>, result);
}
</code></pre>
<ol>
<li><p><strong><mark>Documentation Section</mark></strong></p>
<ul>
<li><p>Code Documentation</p>
</li>
<li><p>Programmers Details</p>
</li>
<li><p>Date and Time</p>
</li>
<li><p>Copyright Information</p>
</li>
</ul>
</li>
<li><p><strong><mark>Link Section</mark></strong></p>
<ul>
<li>Include Header Files</li>
</ul>
</li>
<li><p><strong><mark>Definition Section</mark></strong></p>
<ul>
<li>Define Macros and Symbolic Constant</li>
</ul>
</li>
<li><p><strong><mark>Global Section</mark></strong></p>
<ul>
<li><p>Global Variable</p>
</li>
<li><p>Function Prototype</p>
</li>
</ul>
</li>
<li><p><strong><mark>Main Section</mark></strong></p>
<ol>
<li><p><strong>Declaration Part</strong></p>
<ul>
<li>Declare The Variables</li>
</ul>
</li>
<li><p><strong>Executable Part</strong></p>
<ul>
<li>Code To Execute</li>
</ul>
</li>
</ol>
</li>
<li><p><strong><mark>User Defined Section</mark></strong></p>
<ul>
<li>Define The Function Declared Previously On Global Section</li>
</ul>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Memory Layout In C]]></title><description><![CDATA[To understand memory management in C, you must be familiar with memory segments, storage class specifiers, datatypes, type qualifiers and type modifiers…]]></description><link>https://erkushalghimire.com.np/memory-layout-in-c</link><guid isPermaLink="true">https://erkushalghimire.com.np/memory-layout-in-c</guid><category><![CDATA[memory-management]]></category><category><![CDATA[datatypes]]></category><category><![CDATA[c programming]]></category><category><![CDATA[storage class]]></category><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Sat, 16 Sep 2023 06:41:05 GMT</pubDate><content:encoded><![CDATA[<p>To understand memory management in C, you must be familiar with <strong>memory segments</strong>, <strong>storage class specifiers</strong>, <strong>datatypes,</strong> <strong>type qualifiers</strong> and <strong>type modifiers</strong>. Let us discuss each topic in detail.</p>
<blockquote>
<p>Note: This section is very important for writing an efficient program in C. This article is dedicated to teaching memory management in C. You may have to read it multiple times to understand it fully.<br />Conversion:<br /><strong>8bits = 1 byte</strong>, 1024 bytes = 1KB, 1024 KB = 1MB, 1024MB = 1GB</p>
</blockquote>
<h1 id="heading-memory-segments">Memory Segments</h1>
<p>The compiler of C divides the main memory into four major segments. Let us understand each segment in brief.</p>
<ol>
<li><p><strong><mark>Code Segment:</mark></strong> This segment has a <strong>fixed</strong> size i.e. the size of the code segment neither increases nor decreases. This segment of memory is managed(allocation and deallocation) by the compiler itself. This segment of memory is responsible for storing the executable code so that the CPU can execute it. The code segment stores the program's instructions but not the data that the program operates on.</p>
</li>
<li><p><strong><mark>Data Segment:</mark></strong> This segment has a <strong>fixed</strong> size i.e. the size of the data segment neither increases nor decreases. This segment of memory is managed(allocation and deallocation) by the compiler itself. This segment of memory is responsible for storing the data that are necessary till the whole program is over i.e. <strong>static variables</strong> and <strong>global variables</strong>.</p>
<ol>
<li><p><strong><mark>Unitialized Data [Block Started by Symbol (BSS)] Segment:</mark></strong> The BSS segment is part of a program's data segment where uninitialized static or global variables are stored. The variables stored in this segment are initialized to 0 by the operating system during execution.</p>
</li>
<li><p><strong><mark>Initialized Data Segment:</mark></strong> This segment is part of a program's data segment where initialized static or global variables are stored. The variables store the actual value that was initialized.</p>
</li>
</ol>
</li>
<li><p><strong><mark>Stack:</mark></strong> This segment has a <strong>fixed</strong> size i.e. the size of the stack neither increases nor decreases. This segment of memory is managed(allocation and deallocation) by the compiler itself. This segment of memory is responsible for storing the data that are necessary till the function call is over i.e. <strong>local variables</strong>. Every function call is maintained in the stack. When the function is called, the <strong>stack frame</strong> containing every data and instructions of that function is pushed/inserted into the stack i.e. Memory is allocated for local variables. After the function is over, the stack frame of that function is popped/removed from the stack i.e. Memory is deallocated for local variables. This is why, the variables declared inside the function are inaccessible from outside of the function.<br /> <strong>Stack Overflow:</strong> Since the size of a stack is fixed, the space available sometimes is not enough for the function calls. The stack gets full. In such case, there is no more space for another function call and we get a stack overflow. During compilation, the size of the stack frame is calculated and on that basis, the size of the stack is allocated during execution. If there are multiple function calls such as recursive function calls there might be a high chance of stack overflow.</p>
</li>
<li><p><strong><mark>Heap:</mark></strong> This segment <strong>doesn't have a fixed</strong> size i.e. the size of the heap can increase or decrease as per our needs. This segment of memory is essential for dynamic memory allocation <strong>(DMA)</strong>. This segment of memory must be managed by the programmers themselves i.e. allocate yourself and deallocate yourself. We can allocate memory dynamically using <strong>malloc()</strong>, <strong>calloc()</strong> and <strong>realloc()</strong> functions. Since the allocated memory could be anywhere, the above-mentioned functions return a memory address of that allocated memory. To store a memory address we use pointers. In short, we can access the heap memory through pointers. The memory allocated using the above functions must be deallocated. We can deallocate dynamically allocated memory using the <strong>free()</strong> function. The heap is sometimes referred to as free memory. We must be careful while using heap memory because if we forget to release the memory (deallocate), the program will have a <strong>memory leakage</strong>.</p>
</li>
</ol>
<h1 id="heading-storage-class-specifier">Storage Class Specifier</h1>
<p>Storage specifiers are used to determine how and where variables are stored in memory, their scope, and their lifetime within a program.</p>
<blockquote>
<ul>
<li><p><strong>HOW</strong> are the variables accessed in different segments of the memory?</p>
</li>
<li><p><strong>WHERE</strong> are the variables stored?</p>
</li>
<li><p><strong>HOW</strong> long is the life of stored variables?</p>
</li>
</ul>
</blockquote>
<ol>
<li><p><strong><mark>auto:</mark></strong><br /> This is a default storage class specifier. Variables declared with the "auto" storage class specifier are allocated memory on the stack. They are typically accessed using stack-based memory allocation and deallocation mechanisms.</p>
</li>
<li><p><strong><mark>extern:</mark></strong><br /> Variables declared with "extern" are typically not allocated memory at the point of declaration. Instead, they are associated with global symbols, and their memory is allocated elsewhere (in another translation unit or object file). They are used for sharing data between files. They are accessed using symbol resolution during linking.</p>
</li>
<li><p><strong><mark>static:</mark></strong><br /> Variables declared as "static" are allocated memory in a data segment.</p>
</li>
<li><p><strong><mark>register:</mark></strong><br /> Variables declared as "register" are often allocated memory in the CPU register.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-keyword">int</span> globalVar;
 <span class="hljs-comment">// Global variable with static storage duration</span>
 <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> globalStaticVar = <span class="hljs-number">10</span>;

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
     <span class="hljs-comment">// Automatic variable (default storage class specifier is "auto")</span>
     <span class="hljs-keyword">auto</span> <span class="hljs-keyword">int</span> localVarAuto = <span class="hljs-number">5</span>;

     <span class="hljs-comment">// Static variable with block scope</span>
     <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> localVarStatic = <span class="hljs-number">7</span>;

     <span class="hljs-comment">// Extern variable (declared in another file)</span>
     <span class="hljs-keyword">extern</span> <span class="hljs-keyword">int</span> globalExternVar;

     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Auto variable: %d\n"</span>, localVarAuto);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Static variable: %d\n"</span>, localVarStatic);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Static global variable: %d\n"</span>, globalStaticVar);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Extern variable: %d\n"</span>, globalExternVar);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
</ol>
<h1 id="heading-datatype">Datatype</h1>
<p>Datatypes are used to define the nature of the data and valid operations. The data types can be classified into three groups:</p>
<ol>
<li><p><strong><mark>Fundamental/Primitive Datatype: </mark></strong> These are the basic building blocks of data representation in C. They are <strong>int</strong>, <strong>char</strong>, <strong>float</strong>, <strong>double</strong> and <strong>void</strong>.</p>
<ol>
<li><p><strong><mark>int:</mark></strong><br /> - a decimal integer data can be held in a variable of int datatype.<br /> - an integer datatype allocates either 2 bytes(older standards/16-bit compiler) or 4 bytes(newer standards/32-bit compiler) of space/memory.<br /> - Range: 2^16 = 65536 i.e. -32,768 to +32767</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">int</span> num = <span class="hljs-number">5</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of num is %d"</span>, num);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nMy PC takes %lu bytes to store an integer."</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>char:</mark></strong><br /> - character data can be held in a variable of char data type.<br /> - character datatype allocates one byte[8 bit] of memory.<br /> - Range: 2^8 = 256 i.e. -128 to +127</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">char</span> ch = <span class="hljs-string">'K'</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of ch is %c"</span>, ch);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nMy PC takes %lu bytes to store a character."</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">char</span>));
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>float:</mark></strong><br /> - a decimal floating point data can be held in a variable of float data type.<br /> - a float datatype allocates 4 bytes of memory.<br /> - Range: -3.4E+38 to +3.4E+38</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">float</span> marks = <span class="hljs-number">77.56</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of marks is %f"</span>, marks);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nMy PC takes %lu bytes to store a float."</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>double:</mark></strong><br /> - a decimal floating point data can be held in a variable of double data type.<br /> - a double datatype allocates 8 bytes of memory.<br /> - Range: -1.7E+308 to +1.7E+308</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">double</span> marks = <span class="hljs-number">78.98</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of marks is %lf"</span>, marks);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nMy PC takes %lu bytes to store a double."</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">double</span>));
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>void:</mark></strong><br /> - It holds no value.<br /> - They are mostly used in function definition to tell the compiler that it doesn't return a value after execution.<br /> - It is also used to create void pointers that can point to data of any type, especially in dynamic memory allocation.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
 <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdlib.h&gt;</span></span>
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">(<span class="hljs-keyword">int</span>*)</span></span>;
 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">int</span> *ptr;
     ptr = (<span class="hljs-keyword">int</span>*)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
     *ptr = <span class="hljs-number">5</span>;
     display(ptr);
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *num)</span>
 </span>{
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of num is %d"</span>, *num);
 }
</code></pre>
</li>
</ol>
</li>
<li><p><strong><mark>Derived/Non-Primitive Datatype:</mark></strong> These are created by modifying fundamental data types. They are <strong>array</strong>, <strong>pointer</strong> and <strong>function</strong>.</p>
<ol>
<li><p><strong><mark>Array:</mark></strong> Represents a collection of elements of the same data type. Since, an array is a collection of similar items, the use of a loop is common.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-comment">// declaration</span>
     <span class="hljs-keyword">int</span> num[<span class="hljs-number">5</span>], i;
     <span class="hljs-keyword">float</span> marks[<span class="hljs-number">3</span>];
     <span class="hljs-comment">// initialization</span>
     <span class="hljs-keyword">char</span> name[<span class="hljs-number">50</span>] = <span class="hljs-string">"Kushal Ghimire"</span>;
     <span class="hljs-comment">// assignment</span>
     marks[<span class="hljs-number">0</span>] = <span class="hljs-number">44.44</span>;
     marks[<span class="hljs-number">1</span>] = <span class="hljs-number">55.55</span>;
     marks[<span class="hljs-number">2</span>] = <span class="hljs-number">66.66</span>;
     <span class="hljs-comment">//input</span>
     <span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">5</span>; i++)
     {
         <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nEnter num[%d]: "</span>, i);
         <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num[i]);
     }
     <span class="hljs-comment">//output</span>
     <span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">5</span>; i++)
     {
         <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\n num[%d] = %d "</span>, i, num[i]);
     }
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>Pointer:</mark></strong> Holds the memory address of another variable.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-comment">// initialization of a variable</span>
     <span class="hljs-keyword">int</span> num = <span class="hljs-number">5</span>;
     <span class="hljs-comment">// declaration of a pointer</span>
     <span class="hljs-keyword">int</span> *p;
     <span class="hljs-comment">// assignment of memory address of a variable to a pointer</span>
     p = &amp;num;
     <span class="hljs-comment">// Using Variables    </span>
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of num is %d"</span>, num);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe memory address of num is %p"</span>, (<span class="hljs-keyword">void</span>*)&amp;num);
     <span class="hljs-comment">// Using Pointers    </span>
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of num is %d"</span>, *p);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe memory address of num is %p"</span>, (<span class="hljs-keyword">void</span>*)p);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong><mark>Function:</mark></strong> Represents a function that can take arguments and return a value.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">square</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span></span>;
 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-keyword">int</span> returned_value, num = <span class="hljs-number">9</span>;
     returned_value = square(num);
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nNum = %d and Square = %d"</span>, num, returned_value);
     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">square</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span>
 </span>{
     <span class="hljs-keyword">return</span> n*n;
 }
</code></pre>
</li>
</ol>
</li>
<li><p><strong><mark>User-Defined Datatype: </mark></strong> These datatypes are created by the programmer using either <code>struct, union, enum</code>. If the new defined data type needs a meaningful name, we can define a meaningful name using <code>typedef</code>.</p>
<ol>
<li><p><strong>Struct:</strong> Groups variables of different data types under a single name.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-comment">// definition of a user defined datatype with a tagname student</span>
 <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">student</span>
 {</span>
     <span class="hljs-keyword">int</span> roll;
     <span class="hljs-keyword">float</span> marks;
     <span class="hljs-keyword">char</span> name[<span class="hljs-number">100</span>];
 };

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-comment">// declaration of a user defined datatype</span>
     <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">student</span> <span class="hljs-title">s1</span>;</span>

     <span class="hljs-comment">// initialization of a user defined datatype</span>
     s1.roll = <span class="hljs-number">1</span>;
     s1.marks = <span class="hljs-number">55.79</span>;
     s1.name <span class="hljs-string">"Samir Karki"</span>;

     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Roll = %d Marks = %f Name = %s"</span>, s1.roll, s1.marks, s1.name);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong>Union:</strong> Similar to structures, but only one member can have a value at a time.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-comment">//tagname = student</span>
 <span class="hljs-keyword">union</span> student
 {
     <span class="hljs-keyword">int</span> roll;
     <span class="hljs-keyword">float</span> marks;
     <span class="hljs-keyword">char</span> name[<span class="hljs-number">100</span>];
 };

 <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
 </span>{
     <span class="hljs-comment">// declaration of a user defined datatype</span>
     <span class="hljs-keyword">union</span> student s1;

     s1.roll = <span class="hljs-number">1</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Roll = %d"</span>, s1.roll);

     s1.marks = <span class="hljs-number">55.79</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nMarks = %f"</span>, s1.marks);

     s1.name <span class="hljs-string">"Samir Karki"</span>;
     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nName = %s"</span>, s1.name);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong>Type Definition:</strong> When the meaningful name of a user defined datatype is needed we use typedef keyword in c. For example,</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">student</span>
 {</span>
     <span class="hljs-keyword">int</span> roll;
     <span class="hljs-keyword">float</span> marks;
     <span class="hljs-keyword">char</span> name[<span class="hljs-number">100</span>];
 };
 <span class="hljs-comment">// Type definition: instead of "struct student", i want to write "student".</span>
 <span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">student</span> <span class="hljs-title">student</span>;</span>

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

     s1.roll = <span class="hljs-number">1</span>;
     s1.marks = <span class="hljs-number">55.79</span>;
     s1.name <span class="hljs-string">"Samir Karki"</span>;

     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Roll = %d Marks = %f Name = %s"</span>, s1.roll, s1.marks, s1.name);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
<li><p><strong>Enumeration:</strong> Defines a set of named integer constants.</p>
<pre><code class="lang-c"> <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

 <span class="hljs-keyword">enum</span> color {red, blue, green };

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

 </span>{

     <span class="hljs-keyword">enum</span> color c1;

     c1 = blue;

     <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d"</span>,c1);

     <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
 }
</code></pre>
</li>
</ol>
</li>
</ol>
<h1 id="heading-type-qualifier">Type Qualifier</h1>
<p>Modify the properties and usage of data types or variables of the data type, often adding constraints or indicating specific behaviors. <strong>const</strong> and <strong>volatile</strong> are type qualifiers in ANSI C.<br /><strong>const:</strong> Indicates that a variable's value cannot be modified after initialization, ensuring immutability.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> n = <span class="hljs-number">11</span>;
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> num = <span class="hljs-number">7</span>;
    <span class="hljs-comment">//changing the value of a variable</span>
    n = <span class="hljs-number">15</span>;
    <span class="hljs-comment">//changing the value of a constant is not allowed</span>
    num = <span class="hljs-number">9</span>; <span class="hljs-comment">//this line will give an error    </span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of num is %d"</span>, num);
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nThe value of n is %d"</span>, n);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong>volatile:</strong> The volatile keyword is a type qualifier that is used to indicate that a variable can be changed by external sources or in ways that are not explicitly specified by the program. For example, the value of that variable may be received from a sensor (another hardware). Another example, could be taken of a multithreading concept where multiple threads might be working with the shared variables and such variables should not be optimized by the compiler.</p>
<pre><code class="lang-c"><span class="hljs-comment">/*
This code is just a demonstration and it won't compile or run if you copied it.
Suppose there is a readSensor() defined somewhere.
*/</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">int</span> sensorValue; <span class="hljs-comment">// Declare a volatile variable</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Code that interacts with hardware or external sources</span>
    sensorValue = readSensor(); <span class="hljs-comment">// Read sensor value from a function</span>
    <span class="hljs-comment">// Use the sensor value without the compiler optimizing it away</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Sensor Value: %d\n"</span>, sensorValue);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<h1 id="heading-type-modifier">Type Modifier</h1>
<p>Datatype modifiers specify various properties and characteristics of program elements, including storage, type, and other attributes. We can modify the base data type itself using<code>long, short, signed, unsigned</code> in C.</p>
<p><strong><mark>short:</mark></strong> If your compiler allocates 4 bytes for a normal integer then it will allocate 2 byes of memory for short int.</p>
<p><strong><mark>long:</mark></strong> If your compiler allocates 4 bytes for a normal integer then it will allocate 8 byes of memory for long int.</p>
<p><strong><mark>signed:</mark></strong> It is a default modifier. The signed integer can hold positive as well as negative values. Thus, the range is of 2 bytes. 2^16 = 65536 i.e. -32,768 to +32767.</p>
<p><strong><mark>unsigned:</mark></strong> The unsigned integer can hold only positive values. Thus, the range is of 4 bytes.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

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

</span>{

    <span class="hljs-keyword">short</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> num = <span class="hljs-number">1</span>;

    <span class="hljs-keyword">long</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> fact=<span class="hljs-number">1</span>;

    <span class="hljs-keyword">int</span> negative_num = <span class="hljs-number">-1</span>;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\n Short Unsigned Number = %hu \t Size = %lu byte"</span>, num, <span class="hljs-keyword">sizeof</span>(num));

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\n Long Unsigned Number = %lu \t Size = %lu bytes"</span>, fact, <span class="hljs-keyword">sizeof</span>(fact));

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\n Negative Signed Number = %d \t Size = %lu bytes"</span>, negative_num, <span class="hljs-keyword">sizeof</span>(negative_num));

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

}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694951844139/08aa7957-df14-4cb6-9d0a-c5514f473e29.jpeg" alt class="image--center mx-auto" /></p>
<p>In short, <strong>type qualifiers</strong> modify the behavior of variables of a specific data type, while <strong>type modifiers</strong> alter the base data type itself to create variations of that type.</p>
]]></content:encoded></item><item><title><![CDATA[Fundamentals of C]]></title><description><![CDATA[C programming, developed by Dennis Ritchie at Bell Labs in the early 1970s, played a pivotal role in the history of computing. It evolved from the B…]]></description><link>https://erkushalghimire.com.np/fundamentals-of-c</link><guid isPermaLink="true">https://erkushalghimire.com.np/fundamentals-of-c</guid><category><![CDATA[fundamentals of programming]]></category><category><![CDATA[C]]></category><category><![CDATA[Keywords]]></category><category><![CDATA[identifiers]]></category><category><![CDATA[local and global variables]]></category><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Thu, 14 Sep 2023 04:02:55 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-backgroundhistory"><strong><mark>Background/History</mark></strong></h1>
<p>C programming, developed by Dennis Ritchie at Bell Labs in the early 1970s, played a pivotal role in the history of computing. It evolved from the B programming language, to improve the portability and efficiency of software. The key events in its history include:</p>
<p><strong><mark>Creation of C (Early 1970s):</mark></strong> Dennis Ritchie and his colleagues created C as a general-purpose programming language, allowing for more structured and efficient coding than its predecessor, B.</p>
<p><strong><mark>UNIX Development (Early 1970s):</mark></strong> C became an integral part of the UNIX operating system's development, enabling its portability across different hardware platforms.</p>
<p><strong><mark>K&amp;R C (1978):</mark></strong> Ritchie and Brian Kernighan published "The C Programming Language," commonly referred to as K&amp;R C, which established the language's syntax, concepts, and usage. This book became a foundational resource for programmers.</p>
<p><strong><mark>ANSI C Standardization (1983-1989):</mark></strong> The American National Standards Institute (ANSI) developed a standardized version of C, known as ANSI C or C89. This standardization helped establish C's widespread adoption and portability across different compilers and systems.</p>
<p><strong><mark>C90 Standard (1990):</mark></strong> Building on ANSI C, the International Organization for Standardization (ISO) released the C90 standard, further solidifying C's features and specifications.</p>
<p><strong><mark>C99 Standard (1999):</mark></strong> The ISO introduced the C99 standard, which brought enhancements to the language, such as improved support for complex numbers, variable-length arrays, and inline functions.</p>
<p><strong><mark>C11 Standard (2011):</mark></strong> The C11 standard introduced new features, including multi-threading support, atomic operations, and improved type-generic macros.</p>
<h1 id="heading-unix-os-development-in-c"><strong><mark>UNIX OS Development in C</mark></strong></h1>
<p>UNIX development in C was a significant milestone in the history of computing. UNIX, an operating system created in the late 1960s and early 1970s by Ken Thompson and Dennis Ritchie at Bell Labs, was <mark>one of the first operating systems to be largely developed using the C programming language</mark>. Here's an overview of UNIX development in C:</p>
<p><strong>Transition from Assembly Language:</strong> Before UNIX, operating systems were often developed using assembly languages specific to each hardware platform. This made porting software across different machines a cumbersome process. C's design allowed for writing system-level code that could be compiled on various hardware architectures with minimal modifications.</p>
<p><strong>Porting UNIX:</strong>  As C code could be compiled on different machines, the task of porting UNIX to new hardware architectures became much easier. This played a significant role in UNIX's rapid expansion to various platforms.</p>
<p><strong>Rewriting in C:</strong>  In the early stages of UNIX development, portions of the operating system were rewritten in C. This transition provided the developers with a common programming language that could be used across different parts of the system.</p>
<p><strong>Kernel and System Software:</strong> The core of the UNIX operating system, including the kernel and system utilities, was written in C. This decision highlighted the language's ability to handle low-level operations and interact directly with hardware components.</p>
<p><strong>Legacy and Influence:</strong> UNIX's development in C left an enduring legacy. Many modern operating systems and software projects are still influenced by the ideas and design principles introduced by UNIX and the use of a high-level language like C.</p>
<hr />
<h1 id="heading-literals"><strong><mark>Literals</mark></strong></h1>
<p>A literal is a representation of a fixed, unchanging value within the source code. It can be a value of a specific data type, such as numbers (integers or floating-point), characters, or strings.Literals are constants and do not change during program execution.Examples in C: 42 (integer literal), 3.14 (floating-point literal), 'A' (character literal), "Hello" (string literal).</p>
<hr />
<h1 id="heading-statements"><strong><mark>Statements </mark></strong></h1>
<p>A statement is a complete instruction that performs a specific action or set of actions. It is the fundamental building block of a program and is used to express computations, assignments, control flow, and other operations. A statement in C typically ends with a semicolon (;) to indicate the termination of the instruction. It can be as simple as a single expression or as complex as a compound statement, which consists of multiple statements enclosed within curly braces ({}) and is often used for control flow structures like loops and conditional statements.</p>
<p>Here are some examples of C statements:</p>
<p><strong><mark>Return Statement:</mark></strong> This statement returns the value from a function.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;   <span class="hljs-comment">//return statement</span>
}
</code></pre>
<p><strong><mark>Assignment Statement:</mark></strong> The value 10 is assigned to a variable named x using an assignment statement.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> x;
    x = <span class="hljs-number">10</span>; <span class="hljs-comment">//assignment statement</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Function call statement:</mark></strong>  printf("Hello, World!"); is a function call statement that displays <em>Hello, World!</em> as an output.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello, World!"</span>); <span class="hljs-comment">//function call statement</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Loop statement:</mark></strong> This statement is used to repeatedly execute a certain block of instructions.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> i;
    <span class="hljs-keyword">for</span>(i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) <span class="hljs-comment">//loop statement</span>
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, i);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Conditional statement:</mark></strong> This statement executes the selected part of a block using a condition.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> x = <span class="hljs-number">7</span>;
    <span class="hljs-keyword">if</span> (x &gt; <span class="hljs-number">0</span>) <span class="hljs-comment">//conditional statement</span>
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"x is positive"</span>);
    } 
    <span class="hljs-keyword">else</span> 
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"x is non-positive"</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Expression Statement:</mark></strong> This statement evaluates the expression and updates the value of 'x'.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> x = <span class="hljs-number">1</span>, y= <span class="hljs-number">2</span>, z;
    z = x + y;   <span class="hljs-comment">//expression statement</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Switch Statement:</mark></strong> This statement executes a certain block of case based on switch condition.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> x;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nEnter x: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;x);

    <span class="hljs-keyword">switch</span> (x)    <span class="hljs-comment">//switch statement</span>
    {
        <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
            <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of x is 1"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
            <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of x is 2"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Value of x is neither 1 nor 2"</span>);
   }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong><mark>Goto Statement:</mark></strong> goto statement allows you to transfer control unconditionally from one part of the code to another.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

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

    <span class="hljs-comment">// Using a label for the goto statement</span>
    start:

    <span class="hljs-keyword">if</span> (i &lt;= <span class="hljs-number">5</span>) 
    {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d "</span>, i);
        i++;
        <span class="hljs-keyword">goto</span> start; <span class="hljs-comment">// Jump to the 'start' label</span>
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<hr />
<h1 id="heading-tokens"><strong><mark>Tokens</mark></strong></h1>
<p>Tokens are the smallest individual units in a programming language. They are the building blocks that make up the source code. Tokens include keywords, identifiers, operators, constants, and punctuation symbols. For example, in the statement <code>int x = 10;</code>, the tokens are <code>int</code>, <code>x</code>, <code>=</code>, and <code>10</code>.</p>
<blockquote>
<p>Tokens are the smallest individual components of the source code, while statements are larger constructs made up of one or more tokens that represent a complete action or instruction in the program.</p>
</blockquote>
<hr />
<h1 id="heading-keywords-and-identifiers"><strong><mark>Keywords and Identifiers</mark></strong></h1>
<p><strong>Keywords</strong> are <strong><mark>built-in reserved words</mark></strong> in a C programming language. They are predefined words in C. <strong>There are 32 keywords in ANSI C</strong>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>auto</td><td>break</td><td>case</td><td>char</td></tr>
</thead>
<tbody>
<tr>
<td><strong>const</strong></td><td><strong>continue</strong></td><td><strong>default</strong></td><td><strong>do</strong></td></tr>
<tr>
<td><strong>double</strong></td><td><strong>else</strong></td><td><strong>enum</strong></td><td><strong>extern</strong></td></tr>
<tr>
<td><strong>float</strong></td><td><strong>for</strong></td><td><strong>goto</strong></td><td><strong>if</strong></td></tr>
<tr>
<td><strong>int</strong></td><td><strong>long</strong></td><td><strong>register</strong></td><td><strong>return</strong></td></tr>
<tr>
<td><strong>short</strong></td><td><strong>signed</strong></td><td><strong>sizeof</strong></td><td><strong>static</strong></td></tr>
<tr>
<td><strong>struct</strong></td><td><strong>switch</strong></td><td><strong>typedef</strong></td><td><strong>union</strong></td></tr>
<tr>
<td><strong>unsigned</strong></td><td><strong>void</strong></td><td><strong>volatile</strong></td><td><strong>while</strong></td></tr>
</tbody>
</table>
</div><p><strong>Identifiers</strong> are <strong><mark>user-defined words</mark></strong> in a C programming language. They are defined by the programmers following the rules of an identifier. Examples of an identifier are a variable name, a constant name, a function name, an array name, a structure name, etc.</p>
<h2 id="heading-rules-of-an-identifier"><strong><mark>Rules of an identifier:</mark></strong></h2>
<ul>
<li><p>Identifiers in C can consist of <strong>letters</strong>(both uppercase and lowercase), <strong>digits</strong> and <strong>underscores</strong>. However, an identifier must begin with either underscore(_) or alphabets/letters.<br />  VALID : <code>num</code>, <code>_num</code>, <code>num1</code>, <code>fir12st</code><br />  INVALID : <code>1num</code></p>
</li>
<li><p>Whitespaces (Blank Spaces) and hyphens(-) are not allowed in an identifier.<br />  VALID : <code>first_name</code>, <code>firstname</code>, <code>firstName</code><br />  INVALID : <code>first name</code>, <code>first-name</code>, <code>num-12</code></p>
</li>
<li><p>Keywords cannot be used as an identifier.<br />  VALID : <code>intt</code>, <code>choice</code>, <code>ret</code>, <code>FLOAT</code><br />  INVALID : <code>int</code>, <code>char</code>, <code>return</code>, <code>while</code></p>
</li>
<li><p>C is a case-sensitive language, so uppercase and lowercase letters are treated as distinct.<br />  VALID : <code>num</code>, <code>NUM</code>, <code>nuM</code>, <code>nUm</code> and <code>Num</code> are different in C.</p>
</li>
<li><p>An identifier must be unique.<br />  VALID :<code>int num;</code> and <code>float num;</code> is <strong>allowed</strong> in the <strong>different</strong> scopes.<br />  INVALID : <code>int num;</code> and <code>float num;</code> is <strong>not allowed</strong> in the <strong>same</strong> scope.</p>
</li>
<li><p>The C standards don't specify an exact maximum length for identifiers, but most compilers have practical limits. Generally, the first 31 characters of an identifier are significant in older C standards.</p>
</li>
</ul>
<hr />
<h1 id="heading-variable"><strong><mark>Variable</mark></strong></h1>
<p>A variable is a named storage location in a memory. It is used to store and manipulate data within a program. Variables are crucial for storing values, such as numbers, text, or complex data structures, which can be used and modified as the program executes. A variable has the following key aspects:</p>
<ul>
<li><p><strong><mark>Name:</mark></strong> Each variable has a unique name that is used to identify it in the program.</p>
</li>
<li><p><strong><mark>Scope:</mark></strong> Each variable has a scope or a range. The variable cannot be accessed outside of its scope.<br />  <strong>Local Scope :</strong> The variable can be accessed within a particular block only such as inside a function or a loop. Such variables are called <strong>local variables</strong>. Sometimes, it is desired to <em>extend</em> the life of a variable that is declared inside the function (local scope) to the global scope. We can achieve this by using a <code>static</code> keyword. Such variables are called <strong>static variables</strong>.<br />  <strong>Global Scope :</strong> The variable can be accessed from anywhere in the program. We must be careful with such variables because they can be modified from every part of our program. Such variables are called <strong>global variables</strong>.</p>
</li>
<li><p><strong><mark>Life:</mark></strong> Each variable also has a life. The life of a variable means the period between a variable <strong>memory allocation(birth)</strong> and its <strong>deallocation(death)</strong>.<br />  <strong>Local variables</strong> are allocated during the execution of the local block such as function and get deallocated after the completion of that function. There is no default initialization of local variables. It contains garbage values.<br />  <strong>Static variables</strong> and <strong>Global variables</strong> are allocated during the start of the program itself and get deallocated after the completion of the whole program. The default initialization of static and global variables is 0.</p>
</li>
</ul>
<hr />
<h1 id="heading-constant"><strong><mark>Constant</mark></strong></h1>
<p>A constant is an <strong><mark>immutable</mark></strong> named storage location in a memory i.e. The value stored in a constant cannot be modified throughout the program during execution; hence the name, constant. A constant is defined using a <code>const</code> keyword.</p>
<ol>
<li><p><strong><mark>Integer Constants</mark></strong></p>
<p> We have to <strong>explicitly</strong> initialize the value of an integer constant during it's declaration.</p>
<p> <code>const int num = 7;</code></p>
</li>
<li><p><strong><mark>Floating Point Constants</mark></strong></p>
<p> We have to <strong>explicitly</strong> initialize the value of a floating point constant during it's declaration.</p>
<p> <code>const float marks = 55.55;</code></p>
</li>
<li><p><strong><mark>Character Constants</mark></strong></p>
<p> We have to <strong>explicitly</strong> initialize the value of a character constant during it's declaration.</p>
<p> <code>const char ch = 'K';</code></p>
</li>
<li><p><strong><mark>String Constants</mark></strong></p>
<p> We have to <strong>explicitly</strong> initialize the value of a string constant during it's declaration.</p>
<p> <code>const char name[] = "C Programming is fun";</code></p>
</li>
<li><p><strong><mark>Symbolic Constants</mark></strong></p>
<p> These constants are not explicitly initialized because they are defined by the preprocessor directives.</p>
<p> <code>#define PI 3.14</code></p>
<p> Here, PI is a symbolic constant with a value of 3.14. It is often termed as macros. The value of macro is replaced by the preprocessor directive during the first phase of compilation.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Fundamentals of a computer system]]></title><description><![CDATA[Understand the fundamentals of computer programming from scratch]]></description><link>https://erkushalghimire.com.np/fundamentals-of-a-computer-system</link><guid isPermaLink="true">https://erkushalghimire.com.np/fundamentals-of-a-computer-system</guid><category><![CDATA[C]]></category><category><![CDATA[c programming]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Kushal Ghimire]]></dc:creator><pubDate>Tue, 12 Sep 2023 07:40:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/OiUDGKHHuN0/upload/2ab41d59805c9569332eb21a1fe99e96.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ul>
<li>What is a computer? What are the components of a computer system?</li>
</ul>
<h1 id="heading-introduction"><strong><mark>Introduction</mark></strong></h1>
<p>A computer is an electronic device that accepts inputs from the input devices, processes them and displays the result in output devices. The result obtained can also be saved on the storage devices for future use.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694502177366/441abbec-df40-4b29-8142-c1c68f42caef.png" alt class="image--center mx-auto" /></p>
<p>A computer is composed of two components: <strong><mark>Hardware</mark></strong> and <strong><mark>Software</mark></strong>.</p>
<p><strong>Hardware</strong>: The physical parts of a computer system are called hardware. For example, input devices(Keyboard, Mouse, etc.), memory devices(RAM, ROM, Hard disk, etc.), output devices(Monitor, Speaker, etc. ), processors, etc.</p>
<ul>
<li><p><strong>Input devices</strong>: These devices read input from the user. For example, Keyboard, Mouse, Touchpad, etc.</p>
</li>
<li><p><strong>Output devices</strong>: These devices provide an output to the user. For example, Monitor, Printer, Speaker, etc.</p>
</li>
<li><p><strong>CPU</strong>: Performs different operations based on instructions.</p>
</li>
<li><p><strong>Storage/Memory Devices</strong>: Stores the data or output.</p>
</li>
</ul>
<h1 id="heading-hierarchy-of-memory"><strong><mark>Hierarchy Of Memory</mark></strong></h1>
<ol>
<li><p><strong>Internal Memory</strong>: Memory integrated within the CPU or closest to the CPU.</p>
<ol>
<li><p><strong>Register</strong>: A, W, Z, B, C, D, E, H, L 8085up</p>
</li>
<li><p><strong>Cache</strong>: L1 Cache, L2 Cache</p>
</li>
</ol>
</li>
<li><p><strong>Primary/Main Memory</strong>: Memory that communicates with the CPU.</p>
<ol>
<li><p><strong>RAM</strong>: volatile memory. Read and Write Operations</p>
</li>
<li><p><strong>ROM</strong>: non-volatile memory. Read Only Operation</p>
</li>
</ol>
</li>
<li><p><strong>Secondary Memory</strong>: stores the data permanently.</p>
<ol>
<li><p><strong>Hard disk</strong>: stores the data permanently in a disk.</p>
</li>
<li><p><strong>USB Drive / Pendrive</strong>: stores the data permanently and is easily portable from one device to another.</p>
</li>
</ol>
</li>
</ol>
<p><strong><mark>Major Factors Of Memory</mark></strong></p>
<table><tbody><tr><td><p>Factors</p></td><td><p>Memory</p></td></tr><tr><td><p>Speed</p></td><td><p>Internal Memory  &gt;  Primary Memory  &gt; Secondary Memory</p></td></tr><tr><td><p>Size</p></td><td><p>Internal Memory  &lt;  Primary Memory  &lt; Secondary Memory</p></td></tr><tr><td><p>Cost</p></td><td><p>Internal Memory  &gt;  Primary Memory  &gt; Secondary Memory</p></td></tr></tbody></table>

<p><strong>Software</strong>: Software is a set of programs that performs a specific task. For example, OS, media player, file manager, etc.<br />There are two types of software: <mark>System Software</mark> and <mark>Application Software</mark></p>
<p><strong>System Software</strong>: A software that is used to communicate with hardware and/or application software is called system software.</p>
<ol>
<li><p><strong>Operating System (OS)</strong> - Windows, Linux, etc.</p>
</li>
<li><p><strong>Utility Software</strong> - Antivirus, Disk Management Tools, etc.</p>
</li>
<li><p><strong>Device Drivers</strong> - Audio Drivers, Video Drivers, etc.</p>
</li>
</ol>
<p><strong>Application Software</strong>: A software that is used to perform a specific application or a set of operations is called an application software.<br />An application software is further categorized into two types: <mark>Tailored Software</mark> and <mark>Packaged Software</mark></p>
<ol>
<li><p><strong>Tailored/Customized/Bespoke Software</strong>:  An application software that is developed as per the requirements of a particular user or business entity is called a tailored software application. For example, School Attendance System, Library Management System, etc.</p>
</li>
<li><p><strong>Packaged/Generic Software</strong>: An application software that is developed as an <em>off-the-shelf</em> product designed for many consumers and can meet many client’s general requirements is called a packaged software application. For example, MS Office.</p>
</li>
</ol>
<p><strong><mark>Features of good software</mark></strong></p>
<ol>
<li><p><strong>Portability</strong>: the ability of a program to run on different platforms with or without minimal changes.</p>
</li>
<li><p><strong>Maintainability</strong>: should be easy to bring changes or fix bugs.</p>
</li>
<li><p><strong>Reliable</strong>: should be reliable or trustworthy i.e. should always work.</p>
</li>
<li><p><strong>Efficient</strong>: should be efficient in performing the task/job.</p>
</li>
<li><p><strong>Readability</strong>: should be understandable by other programmers/developers.</p>
</li>
</ol>
<h1 id="heading-working-on-a-computer"><mark>Working on a computer</mark></h1>
<ul>
<li>How does a computer operate?</li>
</ul>
<p><img src="https://lh4.googleusercontent.com/xr9REC9bbV70f4v84HM8-ZDt-q4ZCqGfiHW4sSanMN8bwm8WXMj-rdsqGDAc0EHuGEMuV_3SRl2UhelcWgU5r5D0-xiI2Qa6DrLJGpKn8ROuza2oozEgewJlM9vp6lZPrRroeUoWYeulkB2jD4tSg1g" alt /></p>
<p>When you press the power button to start a computer system, the boot loader program stored in ROM locates the operating system in the hard disk and loads it to the RAM. The OS loaded in the RAM is executed by the CPU with the help of a cache and register for faster execution. This is how a computer starts. The main takeaway of this section is how different memories interact with each other. In summary, we store/install our program or software in secondary memory and when we open the installed software, it is loaded to the RAM from secondary memory and executed by the CPU.</p>
<p>We will be writing programs/applications in the C programming language which will also be stored in secondary memory. When we open/run that program, it will be loaded to RAM and executed by the CPU.</p>
<h1 id="heading-instruction-vs-program-vs-software"><strong><mark>Instruction vs. Program vs. Software</mark></strong></h1>
<ul>
<li>Understand Instruction, Program and Software</li>
</ul>
<p><strong>Instruction</strong>: a <em>single</em> machine level operation.</p>
<p><strong>Program</strong>: <em>a set of</em> <strong><em>instructions</em></strong> that perform a specific task.</p>
<p><strong>Software</strong>: <em>a set of</em> <strong><em>programs</em></strong> that perform a specific task.</p>
<hr />
<p><strong>Program</strong>: A set of instructions that performs a specific task is called a program. For example, a program to perform mathematical calculations.</p>
<p><strong>Instruction</strong>: An instruction refers to a single machine-level operation that can be executed by the processor. These instructions are typically represented in binary codes or mnemonics that correspond to specific hardware operations, such as arithmetic operations or memory manipulations.</p>
<ol>
<li><p><strong>Assembly Instruction</strong>: an instruction written in assembly language using mnemonics. For example, <code>ADD A, B</code> is an 8085 microprocessor instruction to add the contents of register B to the contents of register A (i.e. accumulator) and store the result in the accumulator.</p>
</li>
<li><p><strong>Binary Instruction</strong>: an instruction written in machine language using only 0 or 1. For example, the equivalent binary instruction of the above assembly instruction will be</p>
</li>
</ol>
<table><tbody><tr><td><p>Opcode</p></td><td><p>Source Register</p></td><td><p>Source Register</p></td><td><p>Destination Register</p></td><td><p>Function Code</p></td></tr><tr><td><p>10000000</p></td><td><p>111</p></td><td><p>000</p></td><td><p>111</p></td><td><p>000</p></td></tr><tr><td><p>ADD A, B</p></td><td><p>A</p></td><td><p>B</p></td><td><p>A</p></td><td><p>ADD</p></td></tr></tbody></table>

<p>Hence, <code>10000000111000111000</code> is a binary instruction to perform an addition.</p>
<hr />
<h1 id="heading-representation-of-data-in-binary"><strong><mark>Representation of data in binary</mark></strong></h1>
<ul>
<li>How does a computer represent different types of data (integer, floating, character, string, etc.)?</li>
</ul>
<p><strong><mark>Binary Representation of a character/string</mark></strong>:</p>
<p>A single character or a string is generally represented in binary using the <strong>ASCII</strong> (American Standard Code for Information Interchange) code. They can also be represented using other encoding techniques such as <strong>Unicode</strong>.</p>
<p><img src="https://lh3.googleusercontent.com/Jf7hDbgJIYbCd2CBy6QnkNBkvK1fEtiylNbFO6bTvHR8ufj4sFiUehzmcTRvkDUfTb7L2yTqdq-kuMolgPaoGkAp9czEyUbvPh5HX1-YAlsagcVek4OogRVXzws7FJFff-4mO9YO2CeGV4SwBzYwFNc" alt /></p>
<p>We don't need to remember every ASCII value but the following values are some of the frequently used values.</p>
<table><tbody><tr><td><p>Character</p></td><td><p>ASCII Value</p></td></tr><tr><td><p>\0 (NULL)</p></td><td><p>0</p></td></tr><tr><td><p>A - Z</p></td><td><p>65 - 90</p></td></tr><tr><td><p>a - z</p></td><td><p>97 - 122</p></td></tr></tbody></table>

<p>The ASCII value of the string <strong>Hello</strong> will be :<br />H = 1001000, e = 1100101, l = 1101100, l = 1101100, o = 1101111.</p>
<p>i.e. <code>10010001100101110110011011001101111</code></p>
<blockquote>
<p>Note: The difference in the ASCII values of uppercase and lowercase letters is 32. i.e. <strong>A</strong> = 65 and <strong>a</strong> = 65+32 = 97<br /><strong>Z</strong> = 90 and <strong>z</strong> = 90+32 = 122</p>
</blockquote>
<p><strong><mark>Binary Representation of an integer number</mark></strong>:</p>
<p>An integer number is converted into a binary number. The MSB of the binary number is used to distinguish between a positive and a negative number. If the MSB is 0 then, the number is a positive number else, it is a negative number.</p>
<blockquote>
<p>(<code>123</code>)10 in decimal = (<code>0 1111011</code>)2 in  binary</p>
<p>(<code>-123</code>)10 in decimal = (<code>1 1111011</code>)2 in binary</p>
</blockquote>
<p><strong><mark>Binary Representation of a Floating Point Number</mark></strong>:</p>
<p>A floating point number is generally represented in binary using the IEEE standard. For example, IEEE 754 standard representation of 123.45 is obtained as follows:</p>
<blockquote>
<ol>
<li><p>Convert 123.45 to binary:</p>
<ul>
<li><p>Integer part: <code>123</code> in decimal is <code>1111011</code> in binary.</p>
</li>
<li><p>Fractional part: Convert <code>0.45</code> to binary (approximately). <code>0.0111001100110011...</code></p>
</li>
</ul>
</li>
<li><p>Normalize the binary representation:</p>
<ul>
<li>Combine the integer and fractional parts: <code>1111011.0111001100110011...</code></li>
</ul>
</li>
<li><p>Determine the exponent:</p>
<ul>
<li><p>The exponent is <code>6</code> (from the normalized form).</p>
</li>
<li><p>Add the bias (<code>127</code>) to the exponent: <code>6 + 127 = 133</code></p>
</li>
<li><p>Convert the exponent to binary: <code>133</code> in decimal is <code>10000101</code> in binary.</p>
</li>
</ul>
</li>
<li><p>Encode the sign, exponent, and fraction:</p>
<ul>
<li><p>Sign bit: <code>0</code> (positive)</p>
</li>
<li><p>Exponent: <code>10000101</code> (from step 3)</p>
</li>
<li><p>Fraction: Take the fractional part from the normalized form and pad with zeros to fill 23 bits: <code>01110011001100110011010</code></p>
</li>
</ul>
</li>
</ol>
<p>Putting it all together, the IEEE 754 representation becomes:</p>
<p><code>0 10000101 01110011001100110011010</code></p>
</blockquote>
<h1 id="heading-programming-languages"><strong><mark>Programming Languages</mark></strong></h1>
<p>A programming language is a formal system of rules and syntax that enables humans to communicate instructions to computers. It serves as an intermediary between human-readable code and machine-executable instructions. Programming languages provide a way to write algorithms, create software, and control hardware by specifying a set of commands, functions, and structures.</p>
<h1 id="heading-classification-of-programming-language"><strong><mark>Classification of Programming Language</mark></strong></h1>
<h2 id="heading-low-level-language"><strong><mark>Low-Level Language:</mark></strong></h2>
<p>A set of instructions written for a computer system either at the <strong>machine level (0 or 1)</strong> or the <strong>assembly level (mnemonics)</strong> with the proper knowledge of the hardware involved is called a low-level program. Such programming languages are commonly referred to as low-level programming languages.</p>
<h3 id="heading-machine-level-language"><strong><mark>Machine Level Language</mark></strong>:</h3>
<p>A set of instructions written for a computer system at the machine level (0 or 1) with the proper knowledge of the hardware involved is called a machine-level program. Such programming languages are commonly referred to as machine-level programming languages. This is the only language that a  computer is capable of understanding without any translation. The term machine code and object code are used interchangeably.</p>
<h3 id="heading-assembly-level-language"><strong><mark>Assembly Level Language</mark></strong>:</h3>
<p>A set of instructions written for a computer system at the assembly level (mnemonics) with the proper knowledge of the hardware involved is called an assembly-level program. Such programming languages are commonly referred to as assembly-level programming languages. Since the instructions are written using mnemonic codes, they need to be translated into machine code before execution.</p>
<h2 id="heading-high-level-language"><strong><mark>High-Level Language:</mark></strong></h2>
<p>A set of instructions written for a computer system in a human-friendly language without the depth of knowledge of hardware involved is called a high-level program. Such programming languages are commonly referred to as high-level programming languages. Since the instructions are written in human-friendly language / high level, they need to be translated into machine code before execution. C, C++, Python, Java, etc. are some popular high-level languages.</p>
<h1 id="heading-language-translator"><strong><mark>Language Translator</mark></strong></h1>
<p>A language translator is a tool or a program that converts/translates the source code written in one programming language into an equivalent code of another programming language. These language translators convert our high-level codes into machine-understandable codes. The popular language translators are <strong>Assemblers</strong>, <strong>Compilers</strong> and <strong>Interpreters</strong>.</p>
<h2 id="heading-assembler"><strong><mark>Assembler</mark></strong></h2>
<p>The language translator that translates the code written in assembly language into object code is called an assembler.</p>
<h2 id="heading-compiler"><strong><mark>Compiler</mark></strong></h2>
<p>The language translator that translates the code written in a high-level language into assembly code and eventually an object code through assembler is called a compiler. The compiler translates/compiles the whole source code at once and gives an object code that could be loaded into memory during execution. Since the whole file is translated all at once before execution, compiler-based languages are fast. C and C++ use compilers to translate source code into object code.</p>
<h2 id="heading-interpreter"><strong><mark>Interpreter</mark></strong></h2>
<p>The language translator that translates the code written in a high-level language into object code is called an interpreter. The interpreter translates/interprets the source code line by line and gives an object code that could be loaded into memory during execution. Since the translation is performed multiple times due to the line-by-line translation approach, interpreter-based languages are slower than compiler-based languages. Python uses an interpreter to translate source code into object code.</p>
<h1 id="heading-generation-of-programming-language"><strong><mark>Generation of Programming Language</mark></strong></h1>
<blockquote>
<p>It's important to note that the division of languages into generations is not universally agreed upon, and the boundaries between generations can be subjective. The categorization provided below is a commonly accepted representation of the evolution of programming languages.</p>
</blockquote>
<h2 id="heading-first-generation-language-1gl"><strong><mark>First Generation Language (1GL)</mark></strong></h2>
<p><strong><mark>Machine Language</mark></strong><mark>:</mark></p>
<p>First-generation languages are machine languages that directly correspond to the hardware architecture of a computer. Instructions are written using binary code, consisting of sequences of 0s and 1s. Each instruction represents a specific operation or command that the computer can execute. Machine language is low-level and specific to a particular computer architecture, making it challenging to program and understand.</p>
<h2 id="heading-second-generation-language-2glassembly-language"><strong><mark>Second Generation Language (2GL)<br />Assembly Language:</mark></strong></h2>
<p>Assembly languages provide a more human-readable representation of machine code by using symbols and mnemonics instead of binary code. These languages are specific to a particular computer architecture and require an assembler to translate the code into machine language.</p>
<h2 id="heading-third-generation-language-3gl"><strong><mark>Third Generation Language (3GL)</mark></strong></h2>
<p><strong><mark>High-Level Language:</mark></strong></p>
<p>Third-generation languages are high-level programming languages designed to be more readable and independent of the underlying hardware architecture. They provide higher-level abstractions and a more English-like syntax, making it easier for programmers to write code. Programs written in high-level languages need to be compiled or interpreted into machine code before execution. C, Java, Python, etc. are some of the examples of  3GL.</p>
<h2 id="heading-fourth-generation-language-4gl"><strong><mark>Fourth Generation Language (4GL)</mark></strong></h2>
<p><strong><mark>Domain Specific Language:</mark></strong></p>
<p>Fourth-generation languages are domain-specific languages (DSLs) designed for specific applications or domains. They provide a higher level of abstraction than general-purpose languages and are often used for database management, report generation, or graphical user interface development. 4GLs focus on simplifying the development process by providing built-in functionalities and tools specific to the target domain. SQL (Structured Query Language), MATLAB (Matrix Laboratory), R (Statistical Programming Language), etc. are some of the examples of 4GL.</p>
<h2 id="heading-fifth-generation-language-5gl"><strong><mark>Fifth Generation Language (5GL)</mark></strong></h2>
<p><strong><mark>Natural Language:</mark></strong></p>
<p>Fifth-generation languages are programming languages focused on artificial intelligence (AI) and symbolic computation. They aim to facilitate the development of AI systems and support advanced concepts such as natural language processing, expert systems, and machine learning. 5GLs often provide high-level abstractions and declarative syntax for expressing complex algorithms and problem-solving methodologies. Prolog, LISP(LISt Processing), Haskell, etc. are some of the examples of 5GL.</p>
]]></content:encoded></item></channel></rss>