Tag: 2022

  • The solution to the CS50 psets 8 Homepage problem (2022)

    The solution to the CS50 psets 8 Homepage problem (2022)

    In this post, we have to design a simple website using HTML, CSS, and Javascript. So this website should have multiple pages. On the homepage, you need to introduce yourself, your favorite hobby or extracurricular activities, or anything else that interests you. And On the other pages, you can create any other things that you like but you need to use HTML, CSS, and Javascript.

    My homepage solution code to the cs50 psets 8 homepage problem

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link active" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container">
                <div class="px-4 py-5 my-5 text-center">
                    <img class="d-block mx-auto mb-4 hero-img" data-value="5" src="https://dasunsucharith.github.io/assets/image/hero_transparent_me.png" alt="Dasun Sucharith">
                    <h1 class="display-5 fw-bold">This is CS50</h1>
                    <div class="col-lg-6 mx-auto">
                        <p class="lead mb-4">
                            The internet has enabled incredible things: we can use a search engine to research anything imaginable, communicate with friends and family members around the globe, play games, take courses, and so much more. But it turns out that nearly all pages we may visit are built on three core languages, each of which serves a slightly different purpose:
                        </p>
                        <div class="d-grid gap-2 d-sm-flex justify-content-sm-center">
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="website()">Visit Website</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="clock()">Clock</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="calendar()">Calendar</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="calculator()">Calculator</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                function website(){
                    location.href = "https://dasunsucharith.github.io/";
                }
                function clock() {
                    location.href = "/clock.html";
                }
                function calendar() {
                    location.href = "/calendar.html";
                }
                function calculator() {
                    location.href = "/calculator.html";
                }
            </script>
        </body>
    </html>

    Simple calculator using HTML

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container mx-auto my-5">
                <form class="calculator" name="calc">
                    <input type="text" class="value form-control" readonly name="txt">
                    <div class="d-grid gap-2 mt-3">
                        <button type="button" class="btn btn-danger" onclick="calc.txt.value=''">C</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='/'">/</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='*'">*</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='7'">7</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='8'">8</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='9'">9</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='-'">-</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='4'">4</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='5'">5</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='6'">6</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='+'">+</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='1'">1</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='2'">2</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='3'">3</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='0'">0</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='00'">00</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='.'">.</button>
                        <button type="button" class="btn btn-success" onclick="document.calc.txt.value=eval(calc.txt.value)">=</button>
                    </div>
                </form>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
        </body>
    </html>
    

    Calendar Page HTML code

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <link rel="stylesheet" type="text/css" href="https://unpkg.com/js-year-calendar@latest/dist/js-year-calendar.min.css" />
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <script src="https://unpkg.com/js-year-calendar@latest/dist/js-year-calendar.min.js"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5">
                <div id="calendar"></div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                document.addEventListener("DOMContentLoaded", function() {
                    new Calendar("#calendar");
                });
            </script>
        </body>
    </html>
    

    Simple clock using HTML

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5 text-center">
                <div class="clock mx-auto my-5">
                    <div class="hour"><div class="hr" id="hr"></div></div>
                    <div class="min"><div class="mn" id="mn"></div></div>
                    <div class="sec"><div class="sc" id="sc"></div></div>
                </div>
                <div id="digitalClock" class="mx-auto">
                    <span id="hour"></span>
                    <span id="minutes"></span>
                    <span id="seconds"></span>
                    <span id="ampm"></span>
                </div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                const hr = document.querySelector("#hr");
                const mn = document.querySelector("#mn");
                const sc = document.querySelector("#sc");
                setInterval(()=>{
                    let day = new Date();
                    let hh = day.getHours() * 30;
                    let mm = day.getMinutes() * 6;
                    let ss = day.getSeconds() * 6;
                    hr.style.transform = `rotateZ(${hh+(mm/12)}deg)`;
                    mn.style.transform = `rotateZ(${mm}deg)`;
                    sc.style.transform = `rotateZ(${ss}deg)`;
                    let hour = document.querySelector("#hour");
                    let minutes = document.querySelector("#minutes");
                    let seconds = document.querySelector("#seconds");
                    let ampm = document.querySelector("#ampm");
                    let h = day.getHours();
                    let m = day.getMinutes();
                    let s = day.getSeconds();
                    let am = "AM";
                    if (h > 12) {
                        h = h - 12;
                        am = "PM";
                    }
                    h = (h < 10) ? "0" + h : h;
                    m = (m < 10) ? "0" + m : m;
                    s = (s < 10) ? "0" + s : s;
                    hour.innerHTML = h + ":";
                    minutes.innerHTML = m + ":";
                    seconds.innerHTML = s + " ";
                    ampm.innerHTML = am;
                }, 1000);
            </script>
        </body>
    </html>
    

    CSS code of the whole project

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5 text-center">
                <div class="clock mx-auto my-5">
                    <div class="hour"><div class="hr" id="hr"></div></div>
                    <div class="min"><div class="mn" id="mn"></div></div>
                    <div class="sec"><div class="sc" id="sc"></div></div>
                </div>
                <div id="digitalClock" class="mx-auto">
                    <span id="hour"></span>
                    <span id="minutes"></span>
                    <span id="seconds"></span>
                    <span id="ampm"></span>
                </div>
            </div>
            
            <!-- Calendar Start -->
            <div class="calendar my-5">
                <div class="calendar-header">
                    <h2 class="year-title">2025</h2>
                </div>
                <div class="months-container d-flex flex-wrap justify-content-center">
                    <div class="month-container">January</div>
                    <div class="month-container">February</div>
                    <div class="month-container">March</div>
                </div>
            </div>
            <!-- Calendar End -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                const hr = document.querySelector("#hr");
                const mn = document.querySelector("#mn");
                const sc = document.querySelector("#sc");
                setInterval(()=>{
                    let day = new Date();
                    let hh = day.getHours() * 30;
                    let mm = day.getMinutes() * 6;
                    let ss = day.getSeconds() * 6;
                    hr.style.transform = `rotateZ(${hh+(mm/12)}deg)`;
                    mn.style.transform = `rotateZ(${mm}deg)`;
                    sc.style.transform = `rotateZ(${ss}deg)`;
                    let hour = document.querySelector("#hour");
                    let minutes = document.querySelector("#minutes");
                    let seconds = document.querySelector("#seconds");
                    let ampm = document.querySelector("#ampm");
                    let h = day.getHours();
                    let m = day.getMinutes();
                    let s = day.getSeconds();
                    let am = "AM";
                    if (h > 12) {
                        h = h - 12;
                        am = "PM";
                    }
                    h = (h < 10) ? "0" + h : h;
                    m = (m < 10) ? "0" + m : m;
                    s = (s < 10) ? "0" + s : s;
                    hour.innerHTML = h + ":";
                    minutes.innerHTML = m + ":";
                    seconds.innerHTML = s + " ";
                    ampm.innerHTML = am;
                }, 1000);
            </script>
        </body>
    </html>
    

    Hope this helps you to solve the cs50 psets 8 homepage problem.

  • The solution to the CS50 labs 8 Trivia problem (2022)

    The solution to the CS50 labs 8 Trivia problem (2022)

    In this post, I’ll share the solution to the CS50 labs 8 Trivia problem. So, in this problem, we need to write a website that lets users answer trivia questions.

    For this problem, we must design a website using HTML, CSS, and Javascript to let users answer trivia questions.

    Here are the HTML & CSS code and the Javascript code of this problem.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
            <title>Trivia!</title>
            <style>
                /* Base styles */
                body {
                    background-color: #fff;
                    color: #212529;
                    font-size: 1rem;
                    font-weight: 400;
                    line-height: 1.5;
                    margin: 0;
                    text-align: left;
                    font-family: 'Montserrat', sans-serif;
                }
    
                /* Container layout */
                .container {
                    margin-left: auto;
                    margin-right: auto;
                    padding-left: 15px;
                    padding-right: 15px;
                    max-width: 960px;
                }
    
                /* Header styling */
                .header {
                    background-color: #477bff;
                    color: #fff;
                    margin-bottom: 2rem;
                    padding: 2rem 1rem;
                    text-align: center;
                }
    
                /* Section styling */
                .section {
                    padding: 0.5rem 2rem 1rem 2rem;
                    margin-bottom: 1rem;
                    border-radius: 0.25rem;
                }
    
                .section:hover {
                    background-color: #f5f5f5;
                    transition: background-color 0.15s ease-in-out;
                }
    
                /* Typography */
                h1 {
                    font-family: 'Montserrat', sans-serif;
                    font-size: 48px;
                    margin: 0;
                }
    
                /* Button styles */
                button, 
                input[type="submit"] {
                    background-color: #d9edff;
                    border: 1px solid transparent;
                    border-radius: 0.25rem;
                    font-size: 0.95rem;
                    font-weight: 400;
                    line-height: 1.5;
                    padding: 0.375rem 0.75rem;
                    text-align: center;
                    transition: color 0.15s ease-in-out, 
                                background-color 0.15s ease-in-out, 
                                border-color 0.15s ease-in-out, 
                                box-shadow 0.15s ease-in-out;
                    vertical-align: middle;
                    cursor: pointer;
                    margin: 0.25rem;
                }
    
                button:hover,
                input[type="submit"]:hover {
                    background-color: #bce0ff;
                }
    
                /* Input styles */
                input[type="text"] {
                    line-height: 1.8;
                    width: 25%;
                    padding: 0.375rem 0.75rem;
                    border: 1px solid #ced4da;
                    border-radius: 0.25rem;
                    transition: background-color 0.15s ease-in-out,
                                border-color 0.15s ease-in-out;
                }
    
                input[type="text"]:hover {
                    background-color: #f5f5f5;
                    transition: background-color 0.15s ease-in-out;
                }
    
                input[type="text"]:focus {
                    outline: none;
                    border-color: #80bdff;
                    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
                }
    
                /* Feedback messages */
                #msg,
                #msg2 {
                    color: #666;
                    margin: 1rem 0;
                    font-size: 1.25rem;
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>Trivia!</h1>
            </div>
    
            <div class="container">
                <div class="section">
                    <h2>Part 1: Multiple Choice </h2>
                    <hr>
                    <h3>What is the approximate ratio of people to sheep in New Zealand?</h3>
                    <h2 id="msg"></h2>
                    <button class="button">6 people per 1 sheep</button>
                    <button class="button">3 people per 1 sheep</button>
                    <button class="button">1 people per 1 sheep</button>
                    <button class="button">1 people per 3 sheep</button>
                    <button id="correct" class="button">1 people per 6 sheep</button>
                </div>
    
                <div class="section">
                    <h2>Part 2: Free Response</h2>
                    <hr>
                    <h3>In which country is it illegal to own only one guinea pig, as a lone guinea pig might get lonely?</h3>
                    <input type="text">
                    <button id="button">Check Answer</button>
                    <h2 id="msg2"></h2>
                </div>
            </div>
    
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    let correct_button = document.querySelector('#correct');
                    let incorrect_buttons = document.querySelectorAll('.button:not(#correct)');
                    let msg = document.querySelector('#msg');
                    let msg2 = document.querySelector('#msg2');
    
                    correct_button.addEventListener('click', function() {
                        correct_button.style.backgroundColor = 'green';
                        correct_button.style.color = 'white';
                        msg.innerHTML = 'Correct!';
                    });
    
                    incorrect_buttons.forEach(button => {
                        button.addEventListener('click', function() {
                            button.style.backgroundColor = 'red';
                            button.style.color = 'white';
                            msg.innerHTML = 'Incorrect';
                        });
                    });
    
                    document.querySelector('#button').addEventListener('click', function() {
                        let input = document.querySelector('input');
                        if (input.value.toLowerCase() === 'switzerland') {
                            input.style.backgroundColor = 'lightgreen';
                            msg2.innerHTML = 'Correct!';
                        } else {
                            input.style.backgroundColor = 'lightcoral';
                            msg2.innerHTML = 'Incorrect';
                        }
                    });
    
                    // Add keyboard support for the free response question
                    document.querySelector('input').addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            document.querySelector('#button').click();
                        }
                    });
                });
            </script>
        </body>
    </html>

    Hope this helps you! If it did please consider sharing it with your friends!

  • The solution to CS50 psets 7 movies problem (2022)

    The solution to CS50 psets 7 movies problem (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’ll give you the solution to the CS50 psets 7 movies problem. In this problem, we have to write SQL queries to answer questions about a database of movies. SQLite database called movies.db is provided to you. This database stores data from IMDb about movies, the people who directed, and starred in them, and their ratings.

    There are 13 problems. We have to write SQL queries to solve each one of them. Here are my solutions to those questions.

    SQL query to list the titles of all movies released in 2008.

    This query should output a table with a single column for the title of each movie.

    select title from movies where year=2008;

    SQL query to determine the birth year of Emma Stone.

    This query should output a table with a single column and a single row (not counting the header) containing Emma Stone’s birth year. For this, you may assume that there is only one person in the database with the name Emma Stone.

    select birth from people where name="Emma Stone";

    SQL query to list the titles of all movies with a release date on or after 2018, in alphabetical order.

    This query should output a table with a single column for the title of each movie. Movies released in 2018 should be included, as should movies with release dates in the future.

    select title from movies where year >= 2018 order by title asc;

    SQL query to determine the number of movies with an IMDb rating of 10.0.

    This query should output a table with a single column and a single row (not counting the header) containing the number of movies with a 10.0 rating.

    select count(movie_id) from ratings where rating=10;

    SQL query to list the titles and release years of all Harry Potter movies, in chronological order.

    This query should output a table with two columns, one for the title of each movie and one for the release year of each movie. You may assume that the title of all Harry Potter movies will begin with the words “Harry Potter”, and that if a movie title begins with the words “Harry Potter”, it is a Harry Potter movie.

    select title, year from movies where title like 'Harry Potter%' order by year;

    SQL query to determine the average rating of all movies released in 2012.

    This query should output a table with a single column and a single row (not counting the header) containing the average rating.

    select avg(rating) from ratings join movies on movies.id=ratings.movie_id where movies.year=2012;

    SQL query to list all movies released in 2010 and their ratings, in descending order by rating. For movies with the same rating, order them alphabetically by title.

    This query should output a table with two columns, one for the title of each movie and one for the rating of each movie.

    select ratings.rating, movies.title
    from ratings join movies
    on ratings.movie_id=movies.id
    where movies.year=2010
    order by ratings.rating desc, movies.title asc;

    SQL query to list the names of all people who starred in Toy Story.

    This query should output a table with a single column for the name of each person. You may assume that there is only one movie in the database with the title Toy Story.

    select name from people
    join stars on stars.person_id=people.id
    join movies on stars.movie_id=movies.id
    where movies.title="Toy Story";

    SQL query to list the names of all people who starred in a movie released in 2004, ordered by birth year.

    This query should output a table with a single column for the name of each person. People with the same birth year can be listed in any order. If a person appeared in more than one movie in 2004, they should appear in your results once.

    select distinct name from people
    join stars on stars.person_id=people.id
    join movies on stars.movie_id=movies.id
    join ratings on ratings.movie_id=movies.id
    where movies.year=2004
    order by people.birth;

    SQL query to list the names of all people who have directed a movie that received a rating of at least 9.0.

    This query should output a table with a single column for the name of each person. If a person directed more than one movie that received a rating of at least 9.0, they should only appear in your results once.

    select name from people
    join directors on directors.person_id=people.id
    join movies on directors.movie_id=movies.id
    join ratings on ratings.movie_id=movies.id
    where ratings.rating >= 9;

    SQL query to list the titles of the five highest-rated movies (in order) that Chadwick Boseman starred in, starting with the highest-rated.

    This query should output a table with a single column for the title of each movie. You may assume that there is only one person in the database with the name Chadwick Boseman.

    select title from movies
    join stars on stars.movie_id=movies.id
    join people on stars.person_id=people.id
    join ratings on ratings.movie_id=movies.id
    where people.name = "Chadwick Boseman"
    order by ratings.rating desc
    limit 5;

    SQL query to list the titles of all movies in which both Johnny Depp and Helena Bonham Carter starred.

    This query should output a table with a single column for the title of each movie. You may assume that there is only one person in the database with the name Johnny Depp. You may assume that there is only one person in the database with the name Helena Bonham Carter.

    select title from movies
    join stars on stars.movie_id = movies.id
    join people on stars.person_id = people.id
    where people.name = "Johnny Depp"
    and title in (select title from movies
    join stars on stars.movie_id = movies.id
    join people on stars.person_id = people.id
    where people.name = "Helena Bonham Carter");

    SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.

    This query should output a table with a single column for the name of each person. There may be multiple people named Kevin Bacon in the database. Be sure to only select Kevin Bacon born in 1958. Kevin Bacon himself should not be included in the resulting list.

    select name from people
    join stars on stars.person_id = people.id
    join movies on stars.movie_id = movies.id
    where movies.id in
    (select movies.id from movies
    join people on stars.person_id = people.id
    join stars on stars.movie_id = movies.id
    where people.name = "Kevin Bacon"
    and people.birth = 1958 )
    and people.name != "Kevin Bacon";

    Hope these solutions will help you. If it did, consider sharing with your friends which also need these answers.

  • The Solution to CS50 labs 5 & psets 5 problems (2022)

    The Solution to CS50 labs 5 & psets 5 problems (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’m giving you my solutions to CS50 lab 5 and problem set 5 problems. Hope these solutions will help you to better understand the problems and be a guide for your solutions too.

    The Solution to CS50 labs 5 Inheritance Problem (2022)

    For this problem, we have to write a code that simulate the inheritance of blood types of each member of a family. So, a C file called inheritance.c is provided for us. And the code in this file is not complete. We have to complete the code using the given instructions in the manual.

    Here is my solution to this problem,

    // Simulate genetic inheritance of blood type
    
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    // Each person has two parents and two alleles
    typedef struct person
    {
        struct person *parents[2];
        char alleles[2];
    }
    person;
    
    const int GENERATIONS = 3;
    const int INDENT_LENGTH = 4;
    
    person *create_family(int generations);
    void print_family(person *p, int generation);
    void free_family(person *p);
    char random_allele();
    
    int main(void)
    {
        // Seed random number generator
        srand(time(0));
    
        // Create a new family with three generations
        person *p = create_family(GENERATIONS);
    
        // Print family tree of blood types
        print_family(p, 0);
    
        // Free memory
        free_family(p);
    }
    
    // Create a new individual with `generations`
    person *create_family(int generations)
    {
        // TODO: Allocate memory for new person
        person *n = malloc(sizeof(person));
        if (n == NULL)
        {
            return NULL;
        }
    
        // If there are still generations left to create
        if (generations > 1)
        {
            // Create two new parents for current person by recursively calling create_family
            person *parent0 = create_family(generations - 1);
            person *parent1 = create_family(generations - 1);
    
            // TODO: Set parent pointers for current person
            n->parents[0] = parent0;
            n->parents[1] = parent1;
    
            // TODO: Randomly assign current person's alleles based on the alleles of their parents
            n->alleles[0] = n->parents[0]->alleles[rand() % 2];
            n->alleles[1] = n->parents[1]->alleles[rand() % 2];
        }
    
        // If there are no generations left to create
        else
        {
            // TODO: Set parent pointers to NULL
            n->parents[0] = NULL;
            n->parents[1] = NULL;
    
            // TODO: Randomly assign alleles
            n->alleles[0] = random_allele();
            n->alleles[1] = random_allele();
    
        }
    
        // TODO: Return newly created person
        return n;
    }
    
    // Free `p` and all ancestors of `p`.
    void free_family(person *p)
    {
        // TODO: Handle base case
        if (p == NULL)
        {
            return;
        }
    
        // TODO: Free parents recursively
        free_family(p->parents[0]);
        free_family(p->parents[1]);
    
        // TODO: Free child
        free(p);
    
    }
    
    // Print each family member and their alleles.
    void print_family(person *p, int generation)
    {
        // Handle base case
        if (p == NULL)
        {
            return;
        }
    
        // Print indentation
        for (int i = 0; i < generation * INDENT_LENGTH; i++)
        {
            printf(" ");
        }
    
        // Print person
        if (generation == 0)
        {
            printf("Child (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
        else if (generation == 1)
        {
            printf("Parent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
        else
        {
            for (int i = 0; i < generation - 2; i++)
            {
                printf("Great-");
            }
            printf("Grandparent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
    
        // Print parents of current generation
        print_family(p->parents[0], generation + 1);
        print_family(p->parents[1], generation + 1);
    }
    
    // Randomly chooses a blood type allele.
    char random_allele()
    {
        int r = rand() % 3;
        if (r == 0)
        {
            return 'A';
        }
        else if (r == 1)
        {
            return 'B';
        }
        else
        {
            return 'O';
        }
    }

    The Solution to CS50 psets 5 Speller problem (2022)

    For this problem, we have to implement a C program that spell-checks a file using hash tables. Bunch of files are provided for us for this problem set. But we just have to make changes only to the dictionary.c file. We have to use hash tables for this problem. All the required guide is given to us in the website.

    So, here is what my solution looks like to this problem.

    // Implements a dictionary's functionality
    
    #include <ctype.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <strings.h>
    #include <cs50.h>
    
    #include "dictionary.h"
    
    // Represents a node in a hash table
    typedef struct node
    {
        char word[LENGTH + 1];
        struct node *next;
    }
    node;
    
    // TODO: Choose number of buckets in hash table
    const unsigned int N = (LENGTH + 1) *'z';
    
    int total_words = 0;
    
    // Hash table
    node *table[N];
    
    // Returns true if word is in dictionary, else false
    bool check(const char *word)
    {
        // TODO
        // Obtain the hash index
        int index = hash(word);
    
        node *cursor = table[index];
        while (cursor != NULL)
        {
            if (strcasecmp(cursor->word, word) == 0)
            {
                return true;
            }
            cursor = cursor->next;
        }
    
        return false;
    }
    
    // Hashes word to a number
    unsigned int hash(const char *word)
    {
        // TODO: Improve this hash function
        int sum = 0;
        for (int i = 0; i < strlen(word); i++)
        {
            sum += tolower(word[i]);
        }
        return (sum % N);
    }
    
    // Loads dictionary into memory, returning true if successful, else false
    bool load(const char *dictionary)
    {
        // TODO
        // open the dictionary
        FILE *file = fopen(dictionary, "r");
        if (file == NULL)
        {
            return false;
        }
    
        // read one word at a time from file
        char word[LENGTH + 1];
    
        while (fscanf(file, "%s", word) != EOF)
        {
            // create a new node
            node *n = malloc(sizeof(node));
            if (n == NULL)
            {
                return false;
            }
    
            // Copy over the word to the node
            strcpy(n->word, word);
            n->next = NULL;
    
            // Obtain hashing index
            int index = hash(word);
            if (table[index] == NULL)
            {
                table[index] = n;
            }
            else
            {
                n->next = table[index];
                table[index] = n;
            }
            total_words++;
        }
        fclose(file);
        return true;
    }
    
    // Returns number of words in dictionary if loaded, else 0 if not yet loaded
    unsigned int size(void)
    {
        // TODO
        return total_words;
    }
    
    // Unloads dictionary from memory, returning true if successful, else false
    bool unload(void)
    {
        // TODO
        // Free the linked list
        for (int i = 0; i < N; i++)
        {
            node *head = table[i];
            node *cursor = head;
            node *tmp = head;
    
            while (cursor != NULL)
            {
                cursor = cursor->next;
                free(tmp);
                tmp = cursor;
            }
        }
        return true;
    }

    Hope this will be helpful for you.

  • Google Digital Garage Module 4 All Questions and Answers

    Google Digital Garage Module 4 All Questions and Answers

    Fundamentals of Digital Marketing | Module 4 – Plan your online business strategy

    Important: Right answers will be marked in green color

    In this post, I’ll include all the questions and answers for the google digital garage module 4, fundamentals of digital marketing. Hope this helps you to understand these questions and also learn about Digital marketing.

    You might also like: Google digital garage module 11 all questions and answers

    The Benefits of an Online Strategy | questions & answers

    Sam has recently decided to launch an online fitness coaching service. He has registered a domain name and set up a website, but is unsure of how to launch his business online in a way that will help him grow sustainably.

    Help Sam create his own online business strategy, by selecting the correct steps he should take.


    Q: What should his first step be?

    A: Define business goals


    Q: What should his second step be?

    A: Write a mission statement


    Q: What should his third step be?

    A: Identify his USP


    Taking a business online | questions & answers

    Omar owns a stall selling homemade cosmetics and wants to launch an e-commerce website. He has lots of experience selling his products in person at markets but is now hoping to reach more customers online.

    Can you advise Omar on how to make both his online and offline business successful?


    Q: He should focus on duplicating his successful offline efforts to an online audience

    A: False


    Q: He should sell at a cheaper price on the website to attract more customers.

    A: False


    Q: He should identify his various online and offline audiences, and how best to engage them.

    A: True


    Q: He should consider paid online advertising as the sole means of promoting his business online.

    A: False


    Understanding customer behavior | questions & answers

    Holly owns a dance studio. To improve sales of dance classes, she is reviewing how her marketing team could update the company’s online presence.

    As part of the rebrand, the team listened to customer feedback and mapped customer journeys. They identified two things online customers generally struggled with: navigating the website and finding the business’s contact information.

    Which of the brand’s touchpoints should Holly modify to help address her customer’s feedback?


    A: Website Layout

    B: Instagram account

    C: Instructor’s blog

    D: Email marketing


    How to stand out from the competition | questions & answers

    Bobbie owns a protein shake company, which has been trading for three years. Her products are stocked in a number of gyms, but the company has not seen much growth in recent months. Bobbie would now like to break into the online market to boost product sales.

    Which of the following actions should Bobbie take to identify opportunities for online business growth?


    A: Hire a financial planner

    B: Identify a USP

    C: Ship to new countries

    D: Build a SWOT analysis

    E: Distribute feedback forms to suppliers

    F: Review competitor websites


    Using goals to improve business performance | questions & answers

    Ryan has written some KPIs to help his fitness centers achieve the business goal of “Improving overall client satisfaction”.

    Review these four KPIs. Which do you think fit the criteria of being specific, measurable, attainable, relevant, and time-bound?


    A: Ensure 80% of clients use the gym’s online system to book personal training appointments

    B: Increase how much money customers spend in the gym’s juice bar

    C: A score of 85% or more in the annual survey for the question, “Would you recommend this gym to a friend?”

    D: Ensure 90% of new gym members book an induction session within the first two weeks of joining


    Google digital garage module 4 end of topic assessment | Topic Quiz – Questions & Answers


    1. what is the first step in creating an online business strategy?

    A. Identifying business goals

    B. Understanding what the completion is doing

    C. Knowing the market

    D. Aligning goals to the strategy


    2. What is the purpose of the “See, Think, Do, Care” framework?

    A. To help determine a marketing strategy

    B. To help a business understand the customer journey online

    C. To help a business reach a global audience

    D. To give insight into a specific customer group


    3. Why is optimizing customer touchpoints online beneficial for businesses?

    A. It allows brands to add pop-up ads at every point of the customer journey, ensuring high visibility

    B. It gives businesses the opportunity to save money on online advertising

    C. It provides customers with value every time they come into contact with a brand, helping build trust

    D. It gives businesses an opportunity to collect more data from potential customers


    4. Once you’ve worked out your Unique Selling Point (USP), how would you use it in a long-term online strategy?

    A. Incorporate it within marketing materials across all channels to help raise customer awareness

    B. Create an email campaign letting your customers know why you are unique

    C. Film a video explaining your unique selling point and send it to employees

    D. Create a press release and distribute it through your channels


    5. What type of information can KPIs provide?

    A. Audience segmentation

    B. Long-term projections

    C. Financial viability

    D. Board decisions


    Conclusion

    Hope these questions and answers help you to understand lessons more. If it helps please do share with your friends that are searching for these answers.

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

  • The Solution to CS50 Lab 04 Volume Problem (2022)

    The Solution to CS50 Lab 04 Volume Problem (2022)

    We can use C language to modify audio files. In this lab 4 problem, we have to write a C program to increase the volume of an audio file. The input audio file is given to us in .wav format (INPUT.wav). We need to write the program so that when the user executes the following command in the terminal will provide another .wav file which includes the Audio increased output.

    $ ./volume INPUT.wav OUTPUT.wav 2.0

    Here “volume” is the program that executes. “OUTPUT.wav” is the output file. And 2.0 is the factor in which the volume should be increased of the input file.

    Solution for the cs50 lab 04

    We have two tasks to do in this lab. The first one is to copy the header from input files to output files. The second task is to read samples from the input file and write updated data to the output file.

    Copy the header from input file to output file

        uint8_t header[HEADER_SIZE];
        fread(&header, HEADER_SIZE, 1, input);
        fwrite(&header, HEADER_SIZE, 1, output);

    Read samples from the input file and write updated data to the output file.

        int16_t buffer;
        while (fread(&buffer, sizeof(int16_t), 1, input))
        {
            // Apply factor to the output file
            buffer *= factor;
            fwrite(&buffer, sizeof(int16_t), 1, output);
        }

    Full code

    // Modifies the volume of an audio file
    
    #include <stdint.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    // Number of bytes in .wav header
    const int HEADER_SIZE = 44;
    
    int main(int argc, char *argv[])
    {
        // Check command-line arguments
        if (argc != 4)
        {
            printf("Usage: ./volume input.wav output.wav factor\n");
            return 1;
        }
    
        // Open files and determine scaling factor
        FILE *input = fopen(argv[1], "r");
        if (input == NULL)
        {
            printf("Could not open file.\n");
            return 1;
        }
    
        FILE *output = fopen(argv[2], "w");
        if (output == NULL)
        {
            printf("Could not open file.\n");
            return 1;
        }
    
        float factor = atof(argv[3]);
    
        // TODO: Copy header from input file to output file
        uint8_t header[HEADER_SIZE];
        fread(&header, HEADER_SIZE, 1, input);
        fwrite(&header, HEADER_SIZE, 1, output);
    
        // TODO: Read samples from input file and write updated data to output file
        int16_t buffer;
        while (fread(&buffer, sizeof(int16_t), 1, input))
        {
            // Apply factor to the output file
            buffer *= factor;
            fwrite(&buffer, sizeof(int16_t), 1, output);
        }
    
        // Close files
        fclose(input);
        fclose(output);
    }

    Hope this helps! Leave a comment if you want more clarification on this!

  • The solution to CS50 psets 2 substitution problem (2022)

    The solution to CS50 psets 2 substitution problem (2022)

    CS50 psets 2 substitution problem (2022)

    For the cs50 psets 2 substitution problem we have to write a program that implements substitution cipher. The output should be as shown below.

    $ ./substitution JTREKYAVOGDXPSNCUIZLFBMWHQ
    plaintext:  HELLO
    ciphertext: VKXXN

    Substitution Cipher

    In a substitution cipher, we “encrypt” a message by replacing every letter in the message with another letter. To do that, we use a key. So, in this case, mapping each of the letters of the alphabet to the letter it should correspond to when we encrypt it.

    In order to decrypt the message, the receiver of the message would need to know the key. Using that key they can reverse the process and translate the encrypted text (ciphertext) back into the original message (plaintext).

    Example:

    A key might be a string like this NQXPOMAFTRHLZGECYJIUWSKDVB. This 26-character key means that A (the first character of the alphabet) is converted into N (the first character of the key). Z ( the last letter of the alphabet) should be converted into B ( the last character of the key). Like that, each and every letter in the alphabet is converted into the corresponding character of the key.

    Read more about substitution cipher.

    Code

    So, here is my solution to this problem.

    #include <cs50.h>
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    void substitution(string key);
    void substitution_value(char position, string key);
    
    int main(int argc, string argv[])
    {
        if (argc == 2 ) // checks if there is only 2 strings
        {
            if (strlen(argv[1]) == 26) // checks if the argument contain only 26 characters
            {
                for (int i = 0; i < strlen(argv[1]); i++) // loop through the argument string
                {
                    if (!isalpha(argv[1][i])) // checks if there is only alphabetical characters in the key string
                    {
                        printf("Key must contain 26 characters.\n");
                        return 1;
                    }
    
                    // checks if the key contains repeated characters
                    for (int j = i + 1; j < strlen(argv[1]); j++)
                    {
                        if(toupper(argv[1][i]) == toupper(argv[1][j]))
                        {
                            printf("Key must not contain repeated characters.\n");
                            return 1;
                        }
                    }
                }
    
                // execute the substitution function
                substitution(argv[1]);
    
            }
            else
            {
                printf("Key must contain 26 characters.\n");
                return 1;
            }
        }
        else
        {
            printf("Usage: ./substitution key\n");
            return 1;
        }
    
    }
    
    // substitution function
    void substitution(string key)
    {
        //get plaintext and store it in plaintext string
        string plaintext = get_string("plaintext: ");
    
        // get the length of the plaintext and store it in an integer
        int plaintext_length = strlen(plaintext);
    
        printf("ciphertext: ");
        // iterate through the plaintext string
        for (int k = 0; k < plaintext_length; k++)
        {
            // checks if the plantext has only alphabatical characters
            if (isalpha(plaintext[k]))
            {
                char plaintext_character = plaintext[k];
                if(islower(plaintext_character))
                {
                    substitution_value(tolower(plaintext_character), key);
                }
                else
                {
                    substitution_value(toupper(plaintext_character), key);
                }
            }
            else
            {
                printf("%c", plaintext[k]);
            }
        }
        printf("\n");
    }
    
    void substitution_value(char position, string key)
    {
        string abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        for (int i = 0; i < strlen(abc); i++)
        {
            if (islower(position))
            {
                if (position == tolower(abc[i]))
                {
                    printf("%c", tolower(key[i]));
                }
            }
            else
            {
                if (position == toupper(abc[i]))
                {
                    printf("%c", toupper(key[i]));
                }
            }
        }
    }

    You may also like to read: The solution to cs50 labs 2 scrabble problem (2022)

  • The solution to cs50 labs 2 scrabble problem (2022)

    The solution to cs50 labs 2 scrabble problem (2022)

    In this problem, we have to create a game of Scrabble. In this game, players create words to score points. The number of points is the sum of the point values of each letter in the word.

    So here is my solution for the cs50 labs 2 scrabble problem.

    #include <ctype.h>
    #include <cs50.h>
    #include <stdio.h>
    #include <string.h>
    
    // Points assigned to each letter of the alphabet
    int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
    
    // ASCII values for upercase letters
    int uc_letters[] = {65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90};
    
    // ASCII values for lowercase letters
    int lc_letters[] = {97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122};
    
    int temp_point[] = {};
    
    int compute_score(string word);
    
    int main(void)
    {
        // Get input words from both players
        string word1 = get_string("Player 1: ");
        string word2 = get_string("Player 2: ");
    
        // Score both words
        int score1 = compute_score(word1);
        int score2 = compute_score(word2);
    
        // TODO: Print the winner
        if (score1 > score2)
        {
            printf("Player 1 wins!\n");
        }
        else if (score1 < score2)
        {
            printf("Player 2 wins!\n");
        }
        else
        {
            printf("Tie!\n");
        }
    }
    
    int compute_score(string word)
    {
        // TODO: Compute and return score for string
        int score = 0;
    
        for (int i = 0; i < strlen(word); i++)
        {
            if (isupper(word[i]))
            {
                for (int j = 0; j < sizeof(uc_letters); j++)
                {
                    if (word[i] == uc_letters[j])
                    {
                        temp_point[i] = POINTS[j];
                        score += temp_point[i];
                    }
                }
            }
            else if (islower(word[i]))
            {
                for (int k = 0; k < sizeof(lc_letters); k++)
                {
                    if (word[i] == lc_letters[k])
                    {
                        temp_point[i] = POINTS[k];
                        score += temp_point[i];
                    }
                }
            }
            else
            {
                i++;
            }
        }
    
        return score;
    }
  • The solution to cs50 psets 1 credit problem (2022)

    The solution to cs50 psets 1 credit problem (2022)

    In this problem cs50 psets 1 credit, we have to implement a program called “credit.c” that prompts the user for a credit card number. Then prints out whether it is a valid American Express, Mastercard, or Visa card number by checking in the digits of the input number.

    So, to solve this problem we should use Luhn’s algorithm. If you are looking at this post, I’m guessing that you already know what this formula is and how we should implement the algorithm and build the program.

    I’ll give you my solution for this cs50 psets 1 credit problem.

    #include <cs50.h>
    #include <stdio.h>
    
    //AMERX 15 STRT 34 OR 37
    //MC 16 STRT 51, 52, 53, 54, 55
    //VZA 13 OR 16 STRT 4
    
    int main(void)
    {
        long creditNumber;
    
        do
        {
            creditNumber = get_long("Number: ");
        }
        while (creditNumber <= 0);
    
        long creditCard = creditNumber;
        int sum = 0;
        int count =0;
        long divider = 10;
    
        while (creditCard > 0)
        {
            int lastDigit = creditCard % 10;
            sum = sum + lastDigit;
            creditCard = creditCard / 100;
        }
    
        creditCard = creditNumber / 10;
        while (creditCard > 0)
        {
            int lastDigit = creditCard % 10;
            int byTwo = lastDigit * 2;
            sum = sum + (byTwo % 10) + (byTwo / 10);
            creditCard = creditCard / 100;
        }
    
        creditCard = creditNumber;
        while (creditCard != 0)
        {
            creditCard = creditCard / 10;
            count++;
        }
    
        for (int i = 0; i < count - 2; i++)
        {
            divider = divider * 10;
        }
    
        int firstDigit = creditNumber / divider;
        int firstTwoDigits = creditNumber / (divider / 10);
    
        if ((sum % 10) == 0)
        {
            if (firstDigit == 4 && (count == 13 || count == 16))
            {
                printf("VISA\n");
            }
            else if ((firstTwoDigits == 34 || firstTwoDigits == 37) && count == 15)
            {
                printf("AMEX\n");
            }
            else if ((firstTwoDigits > 50 && firstTwoDigits < 56) && count == 16)
            {
                printf("MASTERCARD\n");
            }
            else
            {
                printf("INVALID\n");
            }
        }
        else {
            printf("INVALID\n");
        }
    }
    

    If you found this post useful, give it a share!

    you may also like to read: The solution to CS50 psets 1 cash problem (2022)

  • Passive Income Ideas To Help You Make Money In 2025

    Passive Income Ideas To Help You Make Money In 2025

    Introduction

    In a world where financial security is a growing concern, passive income has become one of the most powerful ways to build wealth and create financial freedom. Unlike traditional 9-to-5 jobs that require active effort to earn money, passive income allows you to generate revenue with minimal ongoing involvement. Whether you’re looking to supplement your income, escape the paycheck-to-paycheck cycle, or eventually achieve complete financial independence, 2025 presents more opportunities than ever to do so.

    Thanks to advancements in automation, digital platforms, and AI-driven solutions, passive income has never been more accessible. From selling digital products that require no physical inventory to leveraging AI for content creation, investing in real estate without the hassle of property management, or earning through smart financial strategies, the possibilities are endless.

    Passive income sources generally fall into four main categories:

    1. Digital Products & Online Businesses – Selling e-books, courses, blogs, and automated online stores that generate income on autopilot.
    2. Investment-Based Income – Earning money through dividend stocks, bonds, REITs, and peer-to-peer lending.
    3. Real Estate & Rental Opportunities – Owning or leasing properties, short-term vacation rentals, or even renting out parking spaces.
    4. AI-Driven Passive Income – Using artificial intelligence to automate businesses, create digital assets, or make data-driven investments.

    This guide will explore some of the best passive income ideas for 2025, helping you identify the right opportunities to start making money while you sleep. Whether you have a little capital to invest or prefer to start from scratch, there’s a passive income strategy for everyone.

    You may also like to read: How to make money from debt? 5 ways to make money from Debt



    1. Digital Products & Online Businesses

    The internet has revolutionized the way people generate income, allowing entrepreneurs to create digital products and automate online businesses that earn money long after the initial effort is put in. In 2025, the demand for digital content, e-learning, and e-commerce solutions is at an all-time high, making these passive income ideas more lucrative than ever.

    Sell Digital Products

    One of the easiest and most scalable ways to earn passive income is by selling digital products. Unlike physical goods, digital assets such as e-books, templates, PDFs, printables, stock photos, and music files can be created once and sold repeatedly with no additional production costs. Platforms like Gumroad, Etsy, and Shopify make it easy to set up an online storefront and automate sales, allowing you to generate consistent income with minimal upkeep.

    Online Courses

    If you have expertise in a particular field, creating and selling an online course can be a highly profitable passive income stream. Platforms like Udemy, Teachable, and Kajabi allow educators and entrepreneurs to host pre-recorded courses on subjects ranging from marketing and business to design and personal development. Once a course is created and marketed effectively, it can generate sales for years without requiring constant updates. AI tools can also help streamline the course creation process by assisting with scriptwriting, video editing, and course structuring.

    Blogging & Niche Websites

    Blogging remains one of the most reliable passive income methods, especially when combined with monetization strategies like affiliate marketing, display ads (Google AdSense, Mediavine), sponsored posts, and digital product sales. By focusing on a specific niche—such as personal finance, health and wellness, tech reviews, or travel—bloggers can attract a targeted audience and create a steady revenue stream. With the help of AI tools for content research, writing, and SEO optimization, running a profitable blog in 2025 is more automated than ever.

    For those with a creative side, print-on-demand (POD) is a great way to monetize artwork or graphic designs. POD businesses allow entrepreneurs to sell custom T-shirts, mugs, posters, phone cases, tote bags, and more without managing inventory. Platforms like Printful, Redbubble, and Teespring handle printing, fulfillment, and shipping, making it a truly passive business model. The key to success in POD is creating trendy, evergreen, or niche-specific designs that resonate with a particular audience.

    Dropshipping

    Dropshipping is an e-commerce model that allows you to sell physical products without holding inventory. When a customer places an order, a third-party supplier (such as those found on AliExpress, Spocket, or Zendrop) ships the product directly to them. This means you don’t need to worry about manufacturing, warehousing, or shipping logistics. Dropshipping stores can be built on platforms like Shopify and WooCommerce, with automation tools helping to streamline order processing and marketing efforts.

    Digital Products & Online Businesses

    Final Thoughts

    Digital products and online businesses offer some of the most scalable passive income opportunities available today. Whether you prefer creating content, teaching skills, or running an automated e-commerce store, the potential for long-term earnings is significant. The key to success in this space is high-quality content, smart automation, and strategic marketing—all of which are easier than ever in 2025.


    2. Technology & AI-Powered Passive Income

    The rapid advancement of artificial intelligence has opened up new ways to generate passive income with minimal effort. In 2025, AI-driven opportunities are more accessible than ever, allowing entrepreneurs, creatives, and investors to automate revenue streams, scale businesses, and optimize financial growth. Here are some of the best AI-powered passive income ideas to consider:

    AI-Generated Content & Art

    Artificial intelligence is transforming creative industries, making it possible for individuals to generate and sell digital content with little manual effort. AI-powered tools like MidJourney, DALL·E, and Stable Diffusion allow users to create unique artwork, illustrations, and stock images, which can then be sold on platforms like Shutterstock, Adobe Stock, or Etsy. Similarly, AI-generated music, voiceovers, and even AI-written books are becoming popular assets that can be monetized. Once created, these digital products can be sold repeatedly, generating a steady passive income stream.

    AI-Powered Blogging & Affiliate Marketing

    AI tools like ChatGPT, Jasper, and Copy.ai make content creation easier than ever, allowing entrepreneurs to automate the research, writing, and optimization of blog posts. By leveraging AI to generate high-quality SEO-friendly content, bloggers can attract traffic and monetize their sites through Google AdSense, affiliate marketing, and sponsored posts. AI-powered SEO tools also help bloggers find profitable keywords and optimize content for better rankings, increasing revenue potential with minimal manual input.

    AI Chatbots & Automation Services

    Businesses are increasingly adopting AI chatbots to improve customer service, automate sales funnels, and provide instant support. Platforms like ChatGPT API, ManyChat, and Drift enable individuals to build and deploy AI-driven chatbots for companies, earning passive income through subscription models or licensing fees. Entrepreneurs can also create AI automation tools for social media management, email marketing, or workflow automation and sell them as software-as-a-service (SaaS) products.

    Mobile App Development

    No-code and low-code platforms such as Adalo, Glide, and Bubble have made it easier than ever for non-developers to create mobile applications. AI-driven mobile apps—whether productivity tools, fitness trackers, or language-learning assistants—can generate revenue through in-app ads, premium subscriptions, or pay-to-download models. The beauty of app development as a passive income source is that once the app is built and marketed effectively, it continues to generate revenue with minimal maintenance.

    AI-Driven Investment Strategies

    AI-powered trading bots and robo-advisors are revolutionizing the way people invest. Platforms like Wealthfront, Betterment, and M1 Finance use AI to automate portfolio management, optimize asset allocation, and maximize returns based on real-time market data. Additionally, algorithmic trading bots on platforms like Binance and eToro enable investors to execute trades automatically, making AI a powerful tool for passive income in stock markets, cryptocurrency, and forex trading.

    The rise of AI is creating a new frontier for passive income, allowing individuals to generate revenue with smart automation and minimal effort. Whether you’re interested in digital content, online business automation, or AI-assisted investing, leveraging technology in 2025 will be key to building scalable, sustainable income streams.

    AI-Powered Passive Income Opportunities

    3. Investment-Based Passive Income

    Investment-based passive income is one of the most time-tested ways to generate wealth. By strategically placing money into financial instruments, investors can earn steady returns with minimal ongoing effort. These methods allow individuals to build wealth over time, diversify income streams, and create financial security for the future.

    Dividend Stocks

    Investing in dividend-paying stocks is one of the most reliable ways to earn passive income. Companies that generate consistent profits often distribute a portion of their earnings to shareholders in the form of dividends—regular cash payments that can provide a steady income stream. Investors can choose from blue-chip stocks like Coca-Cola, Johnson & Johnson, or Procter & Gamble, which have a history of paying dividends for decades. For added diversification, investors can also opt for dividend-focused ETFs and index funds like Vanguard Dividend Appreciation ETF (VIG) or Schwab U.S. Dividend Equity ETF (SCHD).

    💡 Pro Tip: Reinvesting dividends through a Dividend Reinvestment Plan (DRIP) can accelerate portfolio growth over time.

    REITs (Real Estate Investment Trusts)

    If you want exposure to real estate without the hassle of property management, Real Estate Investment Trusts (REITs) are an excellent option. REITs own and manage income-generating properties such as apartment complexes, office buildings, shopping malls, and hotels. Investors earn passive income through rental income and property appreciation, all without needing to own physical real estate. Popular REITs include Realty Income (O), Vanguard Real Estate ETF (VNQ), and Public Storage (PSA).

    💡 Pro Tip: Look for REITs with high and stable dividend yields for reliable passive income.

    High-Yield Savings & Bonds

    For those seeking low-risk passive income, high-yield savings accounts and bonds are excellent options. Unlike traditional savings accounts, high-yield savings accounts from online banks offer interest rates between 4–5%, allowing your money to grow passively.

    Bonds, on the other hand, are fixed-income investments where you lend money to governments or corporations in exchange for interest payments. Some popular options include:

    • U.S. Treasury Bonds (low risk, government-backed)
    • Municipal Bonds (tax-advantaged income for long-term investors)
    • Corporate Bonds (higher returns but slightly more risk)

    💡 Pro Tip: Consider bond index funds like the Vanguard Total Bond Market ETF (BND) for diversified exposure.

    Peer-to-Peer Lending

    Peer-to-peer (P2P) lending allows individuals to lend money to borrowers and earn interest on their loans, often at rates higher than traditional savings accounts or bonds. Platforms like LendingClub, Prosper, and Funding Circle connect lenders with borrowers, allowing for diversified loan investments across various risk levels.

    While P2P lending can generate double-digit returns, it’s important to assess borrower credit scores and diversify across multiple loans to mitigate default risks.

    💡 Pro Tip: Invest in loans with high credit ratings to reduce risk while maintaining solid returns.

    Annuities

    Annuities are a financial product designed to provide a guaranteed stream of income, typically for retirement. In an annuity, you make a lump-sum investment with an insurance company, and in return, receive regular payments for a set period—or even for life.

    There are different types of annuities, including:

    • Fixed Annuities – Provide a guaranteed, stable payout.
    • Variable Annuities – Offer returns based on market performance.
    • Indexed Annuities – Link returns to stock market indices like the S&P 500.

    💡 Pro Tip: Annuities work best as a supplement to other retirement income streams, providing stability in uncertain markets.

    Investment-Based Passive Income Strategies

    Final Thoughts

    Investment-based passive income is one of the most effective ways to build wealth over time with minimal effort. Whether through dividends, REITs, bonds, P2P lending, or annuities, these options allow you to earn money while you sleep—as long as you invest wisely and remain patient. In 2025, leveraging these investment opportunities can help you achieve long-term financial security and independence.


    4. Real Estate & Alternative Rental Income

    Real estate has long been one of the most reliable ways to build wealth, and in 2025, innovative rental strategies are making passive income in this sector more accessible than ever. Whether you own property or want to invest in real estate without the responsibilities of direct ownership, there are multiple ways to generate passive income from real estate assets.

    Traditional Rental Properties

    Owning residential or commercial rental properties remains one of the most popular passive income strategies. By purchasing a property and renting it out to tenants, landlords can earn monthly rental income while also benefiting from property appreciation over time.

    To maximize returns:

    • Choose properties in high-demand areas with strong rental markets.
    • Use property management services to minimize hands-on involvement.
    • Consider multi-unit properties for higher cash flow potential.

    💡 Pro Tip: Look for rental properties in cities with growing job markets and low vacancy rates for steady demand.

    Short-Term Rentals (Airbnb, Vrbo)

    Short-term vacation rentals have become a lucrative passive income stream, especially in tourist-friendly areas. Platforms like Airbnb and Vrbo allow homeowners to rent out spare rooms or entire properties to travelers for higher nightly rates compared to long-term rentals.

    Key advantages of short-term rentals:
    ✔ Higher income potential than traditional rentals.
    ✔ More flexibility—rent when it suits you.
    ✔ Can be automated using smart locks, cleaning services, and pricing tools.

    💡 Pro Tip: Optimize your listing with high-quality photos, competitive pricing, and positive guest reviews to increase bookings.

    Crowdfunded Real Estate

    For those who want to invest in real estate without buying and managing properties, crowdfunded real estate is a smart alternative. Platforms like Fundrise, RealtyMogul, and CrowdStreet allow investors to pool money into real estate projects, such as apartment buildings, office spaces, and commercial developments.

    Benefits of crowdfunded real estate:
    ✔ Lower capital requirement compared to buying properties.
    ✔ Professional management—no landlord responsibilities.
    ✔ Access to high-value real estate projects.

    💡 Pro Tip: Diversify by investing in multiple projects to reduce risk and increase passive income stability.

    Parking Space Rental

    If you have an unused driveway, garage, or parking spot, you can lease it out for extra income—especially in urban areas where parking is limited. Websites like Pavemint, JustPark, and SpotHero make it easy to rent out parking spaces to daily commuters, event-goers, or even long-term renters.

    ✔ Requires minimal effort—just list your space and collect payments.
    ✔ High demand in cities, near airports, and close to event venues.
    ✔ Works even if you don’t own a home—some apartment complexes allow subleasing of parking spots.

    💡 Pro Tip: If you live near a stadium, downtown area, or popular venue, charge premium rates for event parking.

    Specialty Storage Rentals

    With the rising costs of self-storage, many people are looking for alternative storage solutions for boats, RVs, motorcycles, and other large items. If you have extra land, a barn, or unused garage space, you can rent it out to individuals needing long-term storage solutions.

    ✔ Great for people who own rural or suburban land.
    ✔ Storage requires less maintenance compared to traditional rentals.
    ✔ Can generate passive income with little effort after setup.

    💡 Pro Tip: Market your storage space on platforms like Neighbor.com to reach renters looking for affordable storage options.

    Diverse Real Estate Income Strategies

    Final Thoughts

    Real estate offers diverse passive income opportunities beyond just traditional home rentals. Whether you’re investing in properties, renting out space, or participating in crowdfunded real estate, there are plenty of ways to build wealth through real estate in 2025. By leveraging smart technology, automation, and property management services, real estate investing can become a low-maintenance source of long-term income.


    5. Physical Business & Unconventional Passive Income Ideas

    Not all passive income comes from digital products or investments—some of the best opportunities exist in physical businesses and unconventional strategies. These ideas require varying degrees of upfront investment but can generate consistent, hands-off revenue once established. Here are some of the most creative ways to earn passive income in 2025.

    Vending Machines

    Owning and stocking vending machines is a simple yet effective way to generate passive income. Once installed in high-traffic areas like malls, offices, gyms, or schools, vending machines can generate sales 24/7 with minimal maintenance.

    To maximize profits:
    ✔ Choose high-footfall locations with a steady flow of customers.
    ✔ Stock popular, high-margin products like snacks, drinks, or even tech accessories.
    ✔ Automate restocking and payments using cashless payment systems and remote monitoring software.

    💡 Pro Tip: Consider niche vending machines, such as healthy snacks, beauty products, or even electronics, to stand out in the market.

    Car Advertising

    If you drive regularly, why not turn your car into a money-making machine? Companies like Wrapify and Carvertise pay drivers to display ads on their vehicles. Once wrapped, you earn passive income just by driving as usual.

    ✔ No upfront costs—the company provides the wrap.
    ✔ Can earn between $100 to $500 per month, depending on location and mileage.
    ✔ Works best in urban areas with high traffic visibility.

    💡 Pro Tip: Avoid companies that ask for upfront payments—legitimate car ad companies never charge drivers.

    Leasing Land for Solar/Wind Farms

    With the rising demand for renewable energy, leasing land for solar panels or wind turbines has become a profitable passive income stream. Energy companies pay landowners to use their property for clean energy production, providing long-term lease payments without requiring active management.

    ✔ Generates stable, long-term income over 20+ years.
    ✔ Supports sustainable energy initiatives.
    ✔ Requires little to no maintenance on your part.

    💡 Pro Tip: If you own land in a rural area with strong wind or sunlight exposure, reach out to energy companies for potential leasing opportunities.

    Automated Franchises

    Franchising is often associated with hands-on business operations, but some franchises are designed to run with minimal effort. Investing in an automated franchise, such as a self-service laundromat, car wash, or ATM business, can create steady income with minimal involvement.

    Top passive franchise ideas:
    Self-Service Laundromats – Require little staffing; automated payment systems handle transactions.
    Car Washes – Drive-through models operate with minimal human supervision.
    Ice & Water Vending Machines – Self-serve machines require occasional maintenance but generate income around the clock.

    💡 Pro Tip: Research franchise fees and profit margins before investing to ensure long-term profitability.

    Buying & Flipping Websites

    Just like flipping real estate, buying and flipping websites is a lucrative digital-age business model. Platforms like Flippa, Empire Flippers, and Motion Invest allow you to purchase undervalued websites, optimize them for better traffic and revenue, and resell them for a profit.

    Steps to flipping websites:
    1️⃣ Buy an existing website with stable traffic and monetization potential.
    2️⃣ Improve SEO, content, and user experience to increase revenue.
    3️⃣ Monetize effectively using ads, affiliate links, or digital products.
    4️⃣ Sell the website for a higher price after increasing its value.

    💡 Pro Tip: Focus on sites with recurring revenue models, such as membership sites or e-commerce stores, for higher resale value.

    Which Passive income strategy should I pursue?

    Final Thoughts

    Physical business and unconventional passive income ideas provide excellent opportunities beyond digital investments. Whether you’re leasing land for solar farms, setting up vending machines, or flipping websites, these methods can generate steady, scalable income. The key is to find low-maintenance opportunities that require minimal oversight while delivering long-term financial benefits.


    Conclusion

    Building passive income in 2025 is more accessible than ever, thanks to advancements in digital platforms, AI-driven automation, and alternative investment opportunities. Whether you’re selling digital products, investing in dividend stocks, renting out real estate, or exploring unconventional business ideas, there are countless ways to generate sustainable, hands-off income that can grow over time.

    The key to success with passive income lies in choosing the right strategy based on your skills, resources, and long-term financial goals. Some methods, like dividend investing and high-yield savings accounts, require minimal effort but gradual returns, while others, such as AI-powered blogging or real estate rentals, may need more upfront work but offer significant long-term potential.

    As technology continues to evolve, automation and AI-driven tools will play an even bigger role in simplifying passive income generation. Whether you’re leveraging AI for content creation, investing with robo-advisors, or setting up automated online businesses, staying ahead of these trends will give you a competitive edge in building financial freedom.

    Earning passive income isn’t about getting rich overnight—it’s about creating multiple income streams that work for you in the long run. Start small, automate where possible, and reinvest your earnings to scale up over time. The more you diversify your income sources, the closer you get to financial independence and security.

    Passive income is no longer just a financial buzzword—it’s a real and achievable strategy for anyone looking to build wealth, gain financial freedom, and reduce dependence on a traditional 9-to-5 job. Whether you’re tech-savvy, business-minded, or prefer hands-off investments, there’s a passive income idea suited to your skills, resources, and interests.

    If you’re a creative entrepreneur, digital products, online courses, blogging, and print-on-demand businesses allow you to leverage your skills and creativity with minimal overhead costs. Those who prefer tech-driven income streams can explore AI-powered blogging, chatbot development, and mobile apps, while investors can turn to dividend stocks, REITs, and peer-to-peer lending for steady returns. Meanwhile, real estate remains a tried-and-true method for building wealth, whether through traditional rentals, short-term Airbnb listings, or even leasing land for renewable energy projects.

    The key to financial success in 2025 is diversification—relying on just one passive income stream can be risky, but spreading your investments across multiple channels reduces financial uncertainty and increases long-term stability. A mix of digital assets, investments, and physical businesses can help ensure that you’re earning even when the economy shifts or market trends change.

    Start by identifying one or two passive income ideas that align with your strengths and resources. Whether it’s launching a blog, investing in dividend stocks, or renting out extra space, taking the first step today could lead to significant financial growth in the years to come. The opportunities are limitless—you just need to start.

    Now’s the time to take action—choose a passive income idea that fits your lifestyle and start building your future today! 🚀


    FAQ: Passive Income Ideas for 2025

    1. What is passive income, and how does it work?

    Passive income is money earned with minimal ongoing effort after an initial setup. Unlike active income from a job, passive income allows you to generate revenue continuously from investments, digital products, rental properties, or automated businesses. Examples include earning dividends from stocks, selling an online course, or collecting rent from real estate.

    2. How much money do I need to start earning passive income?

    The amount needed depends on the passive income method. Some, like blogging, affiliate marketing, or print-on-demand, require little to no upfront investment. Others, like real estate, dividend investing, or vending machines, need more capital. The key is to choose an income stream that fits your budget and scale it over time.

    3. What are the best passive income ideas for beginners?

    If you’re just starting, consider low-risk and low-cost options such as:

    • Blogging & affiliate marketing (monetized through ads and sponsorships)
    • Selling digital products (e-books, templates, courses)
    • Investing in dividend stocks or REITs (low-maintenance investment income)
    • Print-on-demand stores (selling custom T-shirts, mugs, and posters)

    These require minimal upfront investment and can grow into substantial passive income sources over time.

    4. How long does it take to start making passive income?

    The timeline varies depending on the method. Dividend stocks and rental income can start generating passive income immediately after investment, while blogging, online courses, and e-commerce may take months to a year to build traction. Consistency and reinvestment in growth strategies can significantly speed up results.

    5. Can AI help me generate passive income?

    Absolutely! AI is revolutionizing passive income by automating content creation, digital marketing, investing, and online business operations. Some AI-driven passive income ideas include:

    • AI-powered blogging & affiliate marketing
    • Automated chatbot businesses
    • AI-generated stock photos & digital art
    • Algorithmic trading & robo-advisors

    Using AI can help you save time, scale faster, and optimize revenue generation with minimal effort.