Wednesday, 2 September 2026

Basic C Programs with Output for Beginners

Introduction to C Programming: 7 Basic C Programs with Output for Beginners

C programming is one of the most popular and powerful programming languages for beginners. It was developed by Dennis Ritchie at Bell Laboratories. C is often called a foundation programming language because many modern programming languages such as C++, Java, and others have been influenced by C.

C programming is widely used in system programming, operating systems, embedded systems, application development, and software development. Learning basic C programs helps students understand important programming concepts such as variables, data types, input and output, operators, expressions, and conditional statements.

📑 C Programs Covered in This Tutorial

  1. Hello World Program in C
  2. Sum of Two Numbers in C
  3. Average of Three Numbers in C
  4. Arithmetic Operations on Two Numbers in C
  5. Simple Interest Program in C
  6. Temperature Conversion Program in C
  7. Maximum of Three Numbers Using Conditional Operator

1. Program to Display Hello Message in C

The following is a simple Hello World program in C. It uses the printf() function to display a message on the screen.

📌 C Program

#include <stdio.h>

int main()
{
    printf("Hello, Welcome to C Programming!");
    
    return 0;
}

💻 Output

Hello, Welcome to C Programming!

2. Program to Find Sum of Two Numbers in C

This C program takes two numbers as input from the user using the scanf() function and calculates their sum using the addition operator +.

📌 C Program

#include <stdio.h>

int main()
{
    int num1, num2, sum;

    printf("Enter first number: ");
    scanf("%d", &num1);

    printf("Enter second number: ");
    scanf("%d", &num2);

    sum = num1 + num2;

    printf("Sum = %d", sum);

    return 0;
}

💻 Sample Output

Enter first number: 10
Enter second number: 20
Sum = 30

3. Program to Find Average of Three Numbers in C

This program accepts three numbers from the user and calculates their average. The float data type is used to store decimal values.

📌 Formula

Average = (Number1 + Number2 + Number3) / 3

📌 C Program

#include <stdio.h>

int main()
{
    float num1, num2, num3, average;

    printf("Enter three numbers: ");
    scanf("%f %f %f", &num1, &num2, &num3);

    average = (num1 + num2 + num3) / 3;

    printf("Average = %.2f", average);

    return 0;
}

💻 Sample Output

Enter three numbers: 10 20 30
Average = 20.00

4. Program to Perform All Four Arithmetic Operations in C

This program performs the four basic arithmetic operations on two numbers: addition, subtraction, multiplication, and division.

📌 Arithmetic Operators Used in C

  • + for Addition
  • - for Subtraction
  • * for Multiplication
  • / for Division

📌 C Program

#include <stdio.h>

int main()
{
    float num1, num2;

    printf("Enter two numbers: ");
    scanf("%f %f", &num1, &num2);

    printf("\nAddition = %.2f", num1 + num2);
    printf("\nSubtraction = %.2f", num1 - num2);
    printf("\nMultiplication = %.2f", num1 * num2);

    if(num2 != 0)
        printf("\nDivision = %.2f", num1 / num2);
    else
        printf("\nDivision is not possible because divisor is zero.");

    return 0;
}

💻 Sample Output

Enter two numbers: 20 5

Addition = 25.00
Subtraction = 15.00
Multiplication = 100.00
Division = 4.00

5. Program to Find Simple Interest in C

This C program calculates simple interest by taking the principal amount, rate of interest, and time from the user.

📌 Simple Interest Formula

Simple Interest = (Principal × Rate × Time) / 100

📌 C Program

#include <stdio.h>

int main()
{
    float principal, rate, time, simpleInterest;

    printf("Enter Principal Amount: ");
    scanf("%f", &principal);

    printf("Enter Rate of Interest: ");
    scanf("%f", &rate);

    printf("Enter Time in Years: ");
    scanf("%f", &time);

    simpleInterest = (principal * rate * time) / 100;

    printf("Simple Interest = %.2f", simpleInterest);

    return 0;
}

💻 Sample Output

Enter Principal Amount: 10000
Enter Rate of Interest: 5
Enter Time in Years: 2

Simple Interest = 1000.00

6. Program for Temperature Conversion in C

This program converts temperature from Celsius to Fahrenheit.

📌 Temperature Conversion Formula

Fahrenheit = (Celsius × 9 / 5) + 32

📌 C Program

#include <stdio.h>

int main()
{
    float celsius, fahrenheit;

    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);

    fahrenheit = (celsius * 9 / 5) + 32;

    printf("Temperature in Fahrenheit = %.2f", fahrenheit);

    return 0;
}

💻 Sample Output

Enter temperature in Celsius: 25

Temperature in Fahrenheit = 77.00

7. Program to Find Maximum of Three Numbers Using Conditional Operator in C

This program finds the largest number among three numbers using the conditional operator. The conditional operator ? : is also known as the ternary operator in C programming.

📌 Syntax of Conditional Operator

condition ? expression1 : expression2;

📌 C Program

#include <stdio.h>

int main()
{
    int a, b, c, max;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

    printf("Maximum number = %d", max);

    return 0;
}

💻 Sample Output

Enter three numbers: 10 25 18

Maximum number = 25

📚 Summary of Basic C Programs

These basic C programs are useful for beginners who are learning C programming and preparing for programming practicals, assignments, viva questions, and coding practice.

Program No. C Program Name
1 Hello World Program in C
2 Sum of Two Numbers in C
3 Average of Three Numbers in C
4 Four Arithmetic Operations in C
5 Simple Interest Program in C
6 Temperature Conversion Program in C
7 Maximum of Three Numbers Using Conditional Operator in C

Program to Calculate the Area of a Circle

Aim

To write a C program to calculate the area of a circle.

Formula

Area of Circle = π × r × r

Where r is the radius of the circle and π = 3.14159.

C Program

#include <stdio.h>

int main()
{
    float radius, area;

    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    area = 3.14159 * radius * radius;

    printf("Area of the circle = %.2f", area);

    return 0;
}

Sample Output

Enter the radius of the circle: 5
Area of the circle = 78.54

Online Area of Circle Calculator

Enter the radius below to calculate the area of the circle:




Example

If the radius of the circle is 5 units:

Area = π × r × r
= 3.14159 × 5 × 5
= 78.54 square units

C Program to Find Square Root Without Using sqrt() Function

In this C program, we will learn how to find the square root of a number without using the built-in sqrt() function. This is useful for beginners to understand how a square root can be calculated using a simple loop and approximation.

What is a Square Root?

The square root of a number is a value which, when multiplied by itself, gives the original number.

Example:

5 × 5 = 25
Therefore, √25 = 5

C Program

The following program finds the square root approximately without using sqrt().

#include <stdio.h>

int main()
{
    float num, i;

    printf("Enter a number: ");
    scanf("%f", &num);

    i = 0;

    while (i * i <= num)
    {
        i = i + 0.01;
    }

    printf("Square root of %.2f is approximately %.2f", num, i);

    return 0;
}

How Does the Program Work?

Suppose the user enters:

25

Initially:

i = 0

The while loop checks whether:

i * i <= num

The value of i is gradually increased:

0.00
0.01
0.02
0.03
...
4.98
4.99
5.00

When i = 5:

5 × 5 = 25

Therefore, the square root is approximately 5.

What Does i = i + 0.01 Mean?

The statement:

i = i + 0.01;

means that 0.01 is added to the current value of i each time the loop runs.

For example:

i = 0
i = 0.01
i = 0.02
i = 0.03
...
i = 4.99
i = 5.00

What If We Use i = i + 0.1?

We can also write:

i = i + 0.1;

In this case, the value increases by 0.1 each time:

0
0.1
0.2
0.3
0.4
...
4.8
4.9
5.0

This makes the program faster because fewer iterations are required, but the answer is less precise.

0.1 vs 0.01

Increment Accuracy Speed
i = i + 1 Low Fast
i = i + 0.1 About 1 decimal place Faster
i = i + 0.01 About 2 decimal places Slower
i = i + 0.001 About 3 decimal places More iterations

Example Output

Enter a number: 25
Square root of 25.00 is approximately 5.01

The result may show 5.01 because the loop stops after the value becomes slightly greater than the actual square root.

Key Points

  • No sqrt() function is used.
  • The program uses a while loop.
  • i * i is used to check the square of the current value.
  • i = i + 0.01 gradually increases the value of i.
  • A smaller increment provides better approximation but requires more iterations.

Conclusion

This simple C program demonstrates how a square root can be approximated without using the built-in sqrt() function. It is a good beginner example for understanding loops, floating-point numbers, conditions, and approximation.

C Program to Calculate Electricity Bill

In this C program, we will learn how to calculate an electricity bill based on the number of units consumed. The program uses if-else conditions to apply different rates for different ranges of electricity consumption.

What is an Electricity Bill?

An electricity bill is generally calculated according to the number of electricity units consumed. Different unit ranges may have different rates.

For this example, we will use the following rates:

Units Consumed Rate per Unit
0 – 100 units ₹5
101 – 200 units ₹7
201 – 300 units ₹10
Above 300 units ₹12

These rates are used only for learning the C programming concept. Actual electricity tariffs vary by electricity provider and consumer category.

C Program

#include <stdio.h>

int main()
{
    int units;
    float bill;

    printf("Enter electricity units consumed: ");
    scanf("%d", &units);

    if (units <= 100)
    {
        bill = units * 5;
    }
    else if (units <= 200)
    {
        bill = (100 * 5) + ((units - 100) * 7);
    }
    else if (units <= 300)
    {
        bill = (100 * 5) + (100 * 7) + ((units - 200) * 10);
    }
    else
    {
        bill = (100 * 5) + (100 * 7) + (100 * 10)
             + ((units - 300) * 12);
    }

    printf("Electricity Bill = Rs. %.2f", bill);

    return 0;
}

How Does the Program Work?

First, the program asks the user to enter the number of electricity units consumed.

Enter electricity units consumed: 250

The program then checks the number of units using if-else if-else statements.

Example: 250 Units

Suppose the consumer has used 250 units.

The calculation will be:

First 100 units:
100 × ₹5 = ₹500

Next 100 units:
100 × ₹7 = ₹700

Remaining 50 units:
50 × ₹10 = ₹500

Total Bill:
₹500 + ₹700 + ₹500 = ₹1700

Example Output

Enter electricity units consumed: 250
Electricity Bill = Rs. 1700.00

Understanding the Condition

The first condition checks whether the units are less than or equal to 100:

if (units <= 100)
{
    bill = units * 5;
}

If the units are between 101 and 200, the first 100 units are charged at ₹5 and the remaining units are charged at ₹7.

bill = (100 * 5) + ((units - 100) * 7);

Similarly, for units between 201 and 300, the program calculates the charges for the first 100 units, the next 100 units, and then the remaining units separately.

Why Do We Use (units - 100)?

Suppose the user enters 150 units.

The first 100 units are already charged at ₹5. Therefore, only the remaining 50 units need to be charged at ₹7.

150 - 100 = 50

Therefore:

100 × ₹5 = ₹500
50 × ₹7  = ₹350

Total = ₹850

Key Points

  • The program takes electricity consumption in units as input.
  • if-else if-else is used to select the appropriate slab.
  • Each electricity slab has a different rate.
  • The bill is calculated progressively for higher unit consumption.
  • %.2f displays the bill with two digits after the decimal point.

Conclusion

This C program is a useful beginner example for understanding if-else conditions, arithmetic operators, user input, and slab-based calculations. Similar logic can be used in programs for calculating water bills, telephone bills, income tax, and other charges.

C Program to Print Numbers from 1 to N Using While Loop

In this C program, we will take a number N from the user and print all the numbers from 1 to N using a while loop.

C Program

#include <stdio.h>

int main()
{
    int n, i = 1;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    while (i <= n)
    {
        printf("%d ", i);
        i++;
    }

    return 0;
}

How the Program Works

  1. The user enters the value of n.
  2. The variable i is initialized to 1.
  3. The while loop checks whether i <= n.
  4. If the condition is true, the value of i is printed.
  5. The statement i++ increases the value of i by 1.
  6. The loop continues until i becomes greater than n.

Sample Output

Enter the value of n: 10
1 2 3 4 5 6 7 8 9 10

Dry Run

i Condition (i <= n) Output i++
1 1 <= 10 → True 1 2
2 2 <= 10 → True 2 3
3 3 <= 10 → True 3 4
... ... ... ...
10 10 <= 10 → True 10 11
11 11 <= 10 → False Loop stops -

Important Points

  • while is an entry-controlled loop.
  • The loop condition is checked before executing the loop body.
  • i++ is necessary; otherwise, the loop may become an infinite loop.
  • The program prints numbers starting from 1 up to the value entered by the user.

Conclusion

This is a simple example of using a while loop in C. It is useful for understanding initialization, condition checking, and incrementing a loop variable.

🎯 Practice is the Key to Learning C Programming!

These basic C programs help beginners understand important concepts such as input and output, variables, arithmetic operators, conditional operators, and mathematical calculations in C programming. Try changing the input values and experiment with these programs to improve your programming skills.

Friday, 6 March 2026

CSS HTML Examples With Code

 

1. Super Market Web Page using Internal CSS

<!DOCTYPE html>
<html>
<head>
<title>Super Market</title>

<style>
body{
font-family: Arial;
background-color: #f2f2f2;
}

h1{
color: white;
background-color: green;
text-align: center;
padding: 10px;
}

.container{
width: 80%;
margin: auto;
}

.product{
background-color: white;
padding: 10px;
margin: 10px;
border: 1px solid gray;
}

</style>

</head>

<body>

<h1>Fresh Super Market</h1>

<div class="container">

<div class="product">
<h3>Rice</h3>
<p>Price: ₹60 per kg</p>
</div>

<div class="product">
<h3>Milk</h3>
<p>Price: ₹50 per litre</p>
</div>

<div class="product">
<h3>Bread</h3>
<p>Price: ₹30</p>
</div>

<div class="product">
<h3>Apples</h3>
<p>Price: ₹120 per kg</p>
</div>

<div class="product">
<h3>Eggs</h3>
<p>Price: ₹6 per egg</p>
</div>

</div>

</body>
</html>

2. Resume using Inline CSS

<!DOCTYPE html>
<html>
<head>
<title>My Resume</title>
</head>

<body style="font-family: Arial; background-color: #f4f4f4;">

<h1 style="color: blue;">Manisha Bhardwaj</h1>

<p style="font-size:18px;">Email: manisha@email.com</p>
<p style="font-size:18px;">Phone: 9876543210</p>

<h2 style="color: green;">Career Objective</h2>
<p style="font-size:16px;">To work in a challenging environment where I can use my skills and knowledge.</p>

<h2 style="color: green;">Education</h2>
<ul style="font-size:16px;">
<li>B.Tech / MCA</li>
<li>12th from CBSE</li>
<li>10th from CBSE</li>
</ul>

<h2 style="color: green;">Skills</h2>
<ul style="font-size:16px;">
<li>HTML</li>
<li>CSS</li>
<li>Python</li>
</ul>

<h2 style="color: green;">Hobbies</h2>
<ul style="font-size:16px;">
<li>Reading</li>
<li>Music</li>
<li>Traveling</li>
</ul>

</body>
</html>

Friday, 20 February 2026

CSS and type of CSS

1. Inline CSS (The "Direct Note")This is written directly inside the HTML tag. 
It’s like putting a sticker right on an object.Best for: Changing just one specific thing very quickly.Example:
HTML

I am Blue!

2. Internal CSS (The "Instruction List")This is written at the top of your HTML file inside a 





3. External CSS (The "Separate Book")This is the most professional way. 
You create a completely separate file (ending in .css) and link it to your HTML.
Best for: 
Big websites with many pages. 
You can change the color of 100 pages at once just by changing one line in the CSS file!
Example:In your HTML: In your style.css file: body { background-color: lightgreen; }


EXAMPLE OF CSS AND HTML

Project Name: The Season Watcher 3000

The Real-Life Question: "How can we create a dashboard that shows the current season, but makes it look like a high-tech app where the buttons glow and the boxes pop out when you touch them?"




The HTML File (index.html)

This is the Structure. We are creating a "Container" to hold our four "Season Cards."

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Season Watcher 3000</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <h1 class="main-title">Smart Home: Season Monitor</h1>

    <div class="dashboard">
        <div class="card" id="spring">
            <div class="icon">🌸</div>
            <h2>Spring</h2>
            <p>Status: Blooming</p>
            <button class="btn">View Garden</button>
        </div>

        <div class="card" id="summer">
            <div class="icon">☀️</div>
            <h2>Summer</h2>
            <p>Status: Sunny</p>
            <button class="btn">Check AC</button>
        </div>

        <div class="card" id="autumn">
            <div class="icon">🍂</div>
            <h2>Autumn</h2>
            <p>Status: Windy</p>
            <button class="btn">Clear Leaves</button>
        </div>

        <div class="card" id="winter">
            <div class="icon">❄️</div>
            <h2>Winter</h2>
            <p>Status: Freezing</p>
            <button class="btn">Heat On</button>
        </div>
    </div>

</body>
</html>

2. The External CSS File (style.css)

This is the Style. We use "Flexbox" to align the boxes and "Transitions" to make them move smoothly.

CSS
/* General Page Setup */
body {
    background-color: #1a1a2e; /* Dark "Space" Blue */
    color: white;
    font-family: 'Segoe UI', sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 50px;
}

.main-title {
    margin-bottom: 40px;
    text-transform: uppercase;
    letter-spacing: 3px;
    border-bottom: 2px solid #0f3460;
}

/* The Grid/Dashboard Layout */
.dashboard {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    justify-content: center;
}

/* Designing the Individual Cards */
.card {
    background-color: #16213e;
    border: 2px solid #0f3460;
    border-radius: 20px;
    padding: 30px;
    width: 200px;
    text-align: center;
    /* This makes the animation smooth! */
    transition: all 0.4s ease;
}

/* Real-Life Interaction: The Hover Effect */
.card:hover {
    transform: scale(1.1) rotate(2deg); /* Grows and tilts slightly */
    border-color: #e94560;
    box-shadow: 0px 10px 30px rgba(233, 69, 96, 0.5);
}

.icon {
    font-size: 50px;
    margin-bottom: 10px;
}

/* Making the Buttons Glow */
.btn {
    background-color: #e94560;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 50px;
    cursor: pointer;
    font-weight: bold;
    margin-top: 15px;
}

.btn:hover {
    background-color: white;
    color: #e94560;
}

What makes this a "Good" Demo?

  1. The "Pop" (Scale): In the CSS, transform: scale(1.1) makes the card grow when you touch it with the mouse. This feels like a modern app.

  2. The "Glow" (Box-Shadow): Using box-shadow on hover makes the card look like it’s lighting up.

  3. Flexbox: The display: flex command in the .dashboard section acts like a magnet, pulling all the cards into a neat line automatically.

Thursday, 19 February 2026

HTML CODE FOR DISPLAYING 4 DIFFERENT HTML PAGES ON SINGLE HTML PAGE USING FRAMES

To display four separate HTML files on a single page using a "frames" approach, we use the tag. This is the classic way to split a browser window into multiple independent sections. Since replaces the tag, this "Master" file will pull the content from four other files you create. 1. The Master File (index.html) This file defines the layout. It creates two rows and two columns. The Four Seasons - Master Frame <body> Your browser does not support frames. Please update your browser. </body> HTML 

  The Four Seasons - Master Frame <body> Your browser does not support frames. Please update your browser. </body> 2. The Four Content Files You must create these four files and save them in the same folder as your index.html. 
<frameset cols="50%,50%" rows="50%,50%">
    <frame name="springFrame" noresize="" scrolling="yes" src="spring.html">
    <frame name="summerFrame" noresize="" scrolling="yes" src="summer.html">
    <frame name="autumnFrame" noresize="" scrolling="yes" src="autumn.html">
    <frame name="winterFrame" noresize="" scrolling="yes" src="winter.html">
    
    <noframes>
        <body>
            Your browser does not support frames. Please update your browser.
        </body>
    </noframes>
</frame></frame></frame></frame></frameset>

 File 1: spring.html HTML 

Spring Season

Spring is a time of rebirth. Flowers bloom and the weather turns mild.

File 2: summer.html HTML 

Summer Season

Summer is the hottest season. It is perfect for vacations and swimming.

File 3: autumn.html HTML 

Autumn Season

In Autumn, leaves change color to gold and red before falling.

File 4: winter.html HTML 

Winter Season

Winter brings snow and ice. It is the coldest time of the year.

How to run this: Create a folder on your computer. 
 Save the first block of code as index.html.
 Save the four season codes as spring.html, summer.html, autumn.html, and winter.html. 
 Open index.html with your browser. 
 Key Attributes Used: rows="50%,50%":
 Splits the screen horizontally into two equal halves. cols="50%,50%": 
Splits the screen vertically into two equal halves. 
 noresize: Prevents the user from dragging the borders to change frame sizes.
 scrolling="yes": Adds a scrollbar if your content or image is too large for the frame.

Monday, 9 February 2026

Minor Project Ideas for B.tech Computer Science

B.Tech Minor Project: Data Science using Regression

This project uses Linear Regression for continuous prediction and Logistic Regression for binary classification problems such as pass/fail and disease prediction.

   MINOR PROJECT IDEAS 


1. Heart Disease Prediction

Problem:
Classify if a person has heart disease.

Inputs:

  • Age

  • BP

  • Cholesterol

  • Heart rate

Output:

  • Disease / No disease

    Heart Disease Prediction

    Problem:
    Classify if a person has heart disease.

    Inputs:

    • Age

    • BP

    • Cholesterol

    • Heart rate

    Output:

    • Disease / No disease




2. 

2. College Placement Probability Prediction System

(Highly impressive for viva)

Problem

Predict whether a student will get placed + expected salary range.

Models

  • Logistic Regression → placed / not placed

  • Linear Regression → expected package

Features

  • CGPA trend

  • Coding test scores

  • Internship experience

  • Soft-skill ratings

Extra Credit

  • Feature importance analysis

  • Probability confidence score


3.

3. Financial Credit Risk & EMI Recommendation System

(Industry-oriented)

Problem

Predict:

  • Loan approval probability

  • Safe EMI amount

Models

  • Logistic Regression → loan approval

  • Linear Regression → EMI amount

Features

  • Income trend

  • Expenses

  • Credit behavior

  • Loan tenure

BIG Add-On

  • Risk tiers (Low / Medium / High)


4. 

4. Smart Energy Consumption Forecasting System

(Engineering + Sustainability)

Problem

Forecast electricity consumption & detect over-usage risk.

Models

  • Linear Regression → energy units

  • Logistic Regression → overload risk

Features

  • Appliance usage

  • Seasonal effects

  • Household size

Outputs

  • Monthly forecast

  • Warning alerts


5. Smart Traffic Congestion & Accident Risk System

(Engineering + AI)

Problem

Predict:

  • Traffic congestion level

  • Accident probability

Models

  • Linear Regression → congestion index

  • Logistic Regression → accident risk

Features

  • Vehicle count

  • Time of day

  • Weather


6. Social Media Misinformation Risk Analyzer

(Trending & Research-oriented)

Problem

Predict whether content is misleading.

Models

  • Logistic Regression → fake / real

  • Linear Regression → virality score

Features

  • Engagement metrics

  • Posting time

  • Account credibility

BIG VALUE

  • Explainable coefficients

  • Ethical AI discussion


7. CROP DISEASE PREDICTION SYSTEM

(Data Science Project using Logistic Regression)

🔹 . Problem Statement

Early detection of crop diseases is critical to reduce yield loss and improve agricultural productivity.
This project aims to predict whether a crop is diseased or healthy based on environmental and crop-related parameters using Logistic Regression.


🔹 . Why this project is “BIG & GOOD”

  • Real-world agricultural problem

  • Social + economic impact

  • Explainable ML (important for farmers)

  • Can be extended to yield loss prediction

  • Faculty-friendly & industry-relevant


🔹 . Project Objectives

  • Predict disease presence (Yes/No)

  • Analyze factors causing disease

  • Provide early warning

  • (Optional) Predict severity or yield loss


🔹 . Dataset (Non-image, Data Science based)

Input Features (examples)

  • Temperature (°C)

  • Humidity (%)

  • Rainfall (mm)

  • Soil moisture

  • Soil pH

  • Crop type

  • Season

  • Fertilizer usage

  • Pesticide usage

Output

  • Disease (0 = Healthy, 1 = Diseased)

📌 Datasets:

  • Kaggle: Crop Disease / Agriculture datasets

  • Government agriculture data

  • Synthetic dataset (acceptable for minor project)


🔹 . Machine Learning Models Used

✅ Logistic Regression (Main Model)

Used because:

  • Output is binary

  • Easy to interpret coefficients

  • Works well with tabular data

Equation:

P(Disease)=11+e(β0+β1x1+...+βnxn)P(\text{Disease}) = \frac{1}{1 + e^{-(\beta_0 + \beta_1x_1 + ... + \beta_nx_n)}}

(Optional) Linear Regression

  • Predict severity level

  • Predict expected yield loss


🔹 . System Architecture

  1. Data Collection

  2. Data Preprocessing

  3. Feature Selection

  4. Logistic Regression Model

  5. Prediction

  6. Result Visualization

  7. Recommendation System


🔹 . Implementation Flow (Python)

  • Load dataset

  • Handle missing values

  • Train-test split

  • Train Logistic Regression model

  • Evaluate using:

    • Accuracy

    • Confusion Matrix

    • Precision, Recall

  • Plot:

    • Probability curve

    • Feature importance


🔹 . Results to Show (VERY IMPORTANT)

  • Disease prediction accuracy

  • Confusion matrix

  • Probability vs threshold graph

  • Feature impact analysis

  • Sample predictions


🔹 . Future Scope (Makes project BIG)

  • Image-based disease detection (CNN)

  • IoT sensor integration

  • Mobile app for farmers

  • Real-time weather API

  • Crop recommendation system


10.Intelligent Crop Yield Forecasting System

(Different from disease prediction)

Problem:
Predict crop yield before harvest.

Models:

  • Linear Regression → yield (tons/hectare)

  • Logistic Regression → low / normal yield risk

Features:
Rainfall, soil nutrients, fertilizer, season


11.  Air Pollution Level Prediction & Health Risk Alert

Problem:
Predict AQI and classify health risk.

Models:

  • Linear Regression → AQI value

  • Logistic Regression → hazardous / safe

Features:
PM2.5, PM10, NO₂, SO₂, temperature


 


Monday, 2 February 2026

DATA SCIENCE LAB MANUAL

 

 Example 1: Linear Regression

PREDITING PRICE BASES ON AREA

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# 1. Example Data
# X = Input (Area of house)
# Y = Output (Price)
X = np.array([100, 200, 300, 400, 500]).reshape(-1, 1)
Y = np.array([10, 20, 30, 40, 50])

# 2. Create and train the model
model = LinearRegression()   # intercept is included by default
model.fit(X, Y)

# 3. Get slope and intercept
m = model.coef_[0]        # slope
b = model.intercept_      # intercept

# 4. Prediction
x_new = 350
y_pred = model.predict([[x_new]])

# 5. Plot the graph
X_line = np.linspace(100, 500, 100).reshape(-1, 1)
Y_line = model.predict(X_line)

plt.scatter(X, Y)          # original data points
plt.plot(X_line, Y_line)   # regression line
plt.scatter(x_new, y_pred) # predicted point
plt.xlabel("Area")
plt.ylabel("Price")
plt.title("Simple Linear Regression")
plt.show()

# 6. Print results
print("Slope (m):", m)
print("Intercept (b):", b)
print("Equation: Y =", m, "* X +", b)
print("Predicted Price for", x_new, ":", y_pred[0])








 Example 2: Linear Regression (Study Hours vs Marks)

👉 Problem Statement

Predict student marks based on study hours.



import numpy as np

import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression


# Data

X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)  # Study hours

Y = np.array([35, 40, 50, 60, 70])            # Marks


# Model

model = LinearRegression()

model.fit(X, Y)


# Slope and intercept

m = model.coef_[0]

b = model.intercept_


# Prediction

hours = 6

predicted_marks = model.predict([[hours]])


# Plot

X_line = np.linspace(1, 6, 100).reshape(-1, 1)

Y_line = model.predict(X_line)


plt.scatter(X, Y)

plt.plot(X_line, Y_line)

plt.scatter(hours, predicted_marks)

plt.xlabel("Study Hours")

plt.ylabel("Marks")

plt.title("Linear Regression: Study Hours vs Marks")

plt.show()


# Output

print("Slope (m):", m)

print("Intercept (b):", b)

print("Equation: Y =", m, "* X +", b)

print("Predicted Marks for", hours, "hours:", predicted_marks[0])






2. Logistic Regression code  

Program 1: Student Pass / Fail Prediction



import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix

# Dataset
data = {
    'Hours_Studied': [1,2,3,4,5,6,7,8],
    'Passed': [0,0,0,0,1,1,1,1]
}

df = pd.DataFrame(data)

# Features and target
X = df[['Hours_Studied']]
y = df['Passed']

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=0
)

# Model
model = LogisticRegression()
model.fit(X_train, y_train)

# Prediction
y_pred = model.predict(X_test)

# Results
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Intercept (β0):", model.intercept_)
print("Coefficient (β1):", model.coef_)  

OUTPUT 
Accuracy: 1.0 Confusion Matrix: [[1 0] [0 1]] Intercept (β0): [-4.4350521] Coefficient (β1): [[1.01750279]]

Program 2: Salary > 50K Prediction (Binary Classification)

# Logistic Regression – Example 2 (Salary Prediction) import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # Dataset data = { 'Age': [22,25,30,35,40,45,50,55], 'Experience': [0,1,3,5,7,10,15,20], 'High_Salary': [0,0,0,1,1,1,1,1] } df = pd.DataFrame(data) # Features and target X = df[['Age', 'Experience']] y = df['High_Salary'] # Train-test split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=1 ) # Model model = LogisticRegression() model.fit(X_train, y_train) # Prediction y_pred = model.predict(X_test) # Results print("Accuracy:", accuracy_score(y_test, y_pred)) print("Intercept (β0):", model.intercept_) print("Coefficients (β1, β2):", model.coef_)

Accuracy: 0.6666666666666666 Intercept (β0): [-13.33988536] Coefficients (β1, β2): [[0.45410297 0.17502853]]

Basic C Programs with Output for Beginners

Introduction to C Programming: 7 Basic C Programs with Output for Beginners C programming is one of the most popular and powe...