Total Pageviews

Wednesday, July 1, 2026

Recursion

 

📘 Module 4: Recursion (5 Lectures)




🎓 Module 4: Recursion

Total Lectures: 5


📖 Lecture 1: Introduction to Recursion

<div style="background:#E3F2FD;padding:15px;border-left:8px solid #1976D2;border-radius:8px;">

🔹 What is Recursion?

Recursion is a programming technique in which a function calls itself to solve a problem.

Instead of using loops (for, while), recursion repeatedly breaks a problem into smaller subproblems until a stopping condition (called the Base Case) is reached.

</div>

🎯 Real-Life Examples

📂 Opening a folder inside another folder.

🪞 Looking into two mirrors facing each other.

🪆 Russian Dolls (Matryoshka Dolls)

🏢 Climbing stairs one step at a time.


General Syntax

return_type function_name(parameters)
{
if(base_condition)
return value;

return function_name(smaller_problem);
}

Basic Structure of Recursion

            Function Call

Is Base Case True?
/ \
Yes No
│ │
Return Result Call Same Function

Smaller Problem

Important Terms

TermMeaning
Recursive FunctionFunction that calls itself
Base CaseStops recursion
Recursive CallFunction calling itself
Call StackStores function calls

Example 1: Print Numbers from 1 to 5

#include<stdio.h>

void print(int n)
{
if(n>5)
return;

printf("%d ",n);

print(n+1);
}

int main()
{
print(1);
return 0;
}

Output

1 2 3 4 5

Example 2: Countdown

#include<stdio.h>

void countdown(int n)
{
if(n==0)
return;

printf("%d ",n);

countdown(n-1);
}

int main()
{
countdown(5);
}

Output

5 4 3 2 1

📖 Lecture 2: Developing Recursive Definition of Simple Problems


Steps to Develop Recursive Solution

<div style="background:#FFF3E0;padding:15px;border-left:8px solid orange;border-radius:8px;">

Step 1

Identify the smallest problem.

Step 2

Find the Base Case.

Step 3

Reduce the problem.

Step 4

Call the function again.

</div>

Example 1: Factorial

Mathematical Definition

5! = 5×4×3×2×1

n! = n × (n-1)!

0! = 1

Algorithm

factorial(n)

if n==0
return 1

return n * factorial(n-1)

Program

#include<stdio.h>

int factorial(int n)
{
if(n==0)
return 1;

return n*factorial(n-1);
}

int main()
{
printf("%d",factorial(5));
}

Output

120

Example 2: Sum of First N Numbers

Sum(5)

5+4+3+2+1

=5+Sum(4)

Program

#include<stdio.h>

int sum(int n)
{
if(n==0)
return 0;

return n+sum(n-1);
}

int main()
{
printf("%d",sum(5));
}

Output

15

Example 3: Power

2^5

=2 × Power(2,4)

Program

#include<stdio.h>

int power(int a,int b)
{
if(b==0)
return 1;

return a*power(a,b-1);
}

int main()
{
printf("%d",power(2,5));
}

Output

32

📖 Lecture 3: Advantages and Limitations of Recursion


🌟 Advantages

<div style="background:#E8F5E9;padding:15px;border-left:8px solid green;border-radius:8px;">

✔ Simple Code

✔ Easy to Understand

✔ Less Coding

✔ Suitable for Tree Problems

✔ Useful in Graph Algorithms

✔ Natural Solution for Divide & Conquer

✔ Cleaner than loops in many algorithms

</div>

Applications

ApplicationExample
Tree TraversalInorder, Preorder
Graph SearchDFS
SortingMerge Sort
SearchingBinary Search
MathematicsFactorial
Dynamic ProgrammingMemoization
CompilerParsing

⚠ Limitations

<div style="background:#FFEBEE;padding:15px;border-left:8px solid red;border-radius:8px;">

❌ More Memory

❌ Function Call Overhead

❌ Slower than Loops

❌ Stack Overflow

❌ Difficult Debugging

❌ Infinite Recursion if Base Case Missing

</div>

Comparison

FeatureIterationRecursion
Uses LoopYesNo
Uses StackNoYes
SpeedFasterSlower
MemoryLessMore
CodeLongerShorter
DebuggingEasyDifficult

📖 Lecture 4: Understanding Internal Stack Implementation


Every Recursive Call Creates

✔ Parameters

✔ Local Variables

✔ Return Address

✔ Function State

All are stored inside the Call Stack.


Example

factorial(4)

Calls

factorial(4)



factorial(3)



factorial(2)



factorial(1)



factorial(0)

Stack Formation

Top

factorial(0)

factorial(1)

factorial(2)

factorial(3)

factorial(4)

Bottom

Returning Phase

factorial(0)=1



factorial(1)=1×1



factorial(2)=2×1



factorial(3)=3×2



factorial(4)=4×6=24

Visual Diagram

CALLS

main()



fact(4)



fact(3)



fact(2)



fact(1)



fact(0)

-------------------

RETURNS

1



1



2



6



24

Stack Memory Illustration

+--------------------+
| factorial(0) |
+--------------------+
| factorial(1) |
+--------------------+
| factorial(2) |
+--------------------+
| factorial(3) |
+--------------------+
| factorial(4) |
+--------------------+
| main() |
+--------------------+

📖 Lecture 5: Programs Using Recursion


Program 1: Fibonacci Series

#include<stdio.h>

int fib(int n)
{
if(n<=1)
return n;

return fib(n-1)+fib(n-2);
}

int main()
{
int i;

for(i=0;i<10;i++)
printf("%d ",fib(i));
}

Output

0 1 1 2 3 5 8 13 21 34

Program 2: Reverse a Number

#include<stdio.h>

void reverse(int n)
{
if(n==0)
return;

printf("%d",n%10);

reverse(n/10);
}

int main()
{
reverse(12345);
}

Output

54321

Program 3: Print Array

#include<stdio.h>

void display(int a[],int n,int i)
{
if(i==n)
return;

printf("%d ",a[i]);

display(a,n,i+1);
}

int main()
{
int a[]={10,20,30,40};

display(a,4,0);
}

Output

10 20 30 40

Program 4: GCD Using Recursion

#include<stdio.h>

int gcd(int a,int b)
{
if(b==0)
return a;

return gcd(b,a%b);
}

int main()
{
printf("%d",gcd(18,12));
}

Output

6

Program 5: Decimal to Binary

#include<stdio.h>

void binary(int n)
{
if(n==0)
return;

binary(n/2);

printf("%d",n%2);
}

int main()
{
binary(13);
}

Output

1101

🎯 Viva Questions

  1. Define recursion.
  2. What is a recursive function?
  3. What is the base case?
  4. Why is the base case necessary?
  5. Explain the recursive case.
  6. What is a call stack?
  7. Why can recursion cause stack overflow?
  8. Differentiate recursion and iteration.
  9. Give real-life examples of recursion.
  10. Explain internal stack implementation with an example.

📌 Interview Questions

  • Can every recursive program be converted into an iterative program?
  • Why is recursion slower than iteration?
  • What is tail recursion?
  • What is indirect recursion?
  • How does the compiler manage recursive function calls?
  • What happens if the base case is omitted?
  • Which data structure is used internally to implement recursion?

Tuesday, June 30, 2026

class 12 semester 3 mcq question for practise wbchse

Python MCQ Quiz (200 Questions)

Python Programming MCQ Quiz (200 Questions)

Monday, June 29, 2026

K-Means Clustering in Machine Learning using Python

 

🟢 K-Means Clustering in Machine Learning


Note: K-Means Clustering is an Unsupervised Machine Learning algorithm. It groups similar data points into clusters without using labeled data.


🟦 Program Aim

Aim:

To implement the K-Means Clustering Algorithm using Python and group customers based on their annual income.


🟩 Algorithm Used

K-Means Clustering


🟨 Problem Statement

A shopping mall wants to divide its customers into different groups based on their Annual Income.

The objective is to identify customers with similar income levels for better marketing and promotional strategies.


🟪 Step 1: Install Required Library

Install Scikit-Learn if it is not already installed.

pip install scikit-learn

Explanation

Scikit-Learn provides the KMeans algorithm.


🟦 Step 2: Import Required Libraries

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

Explanation

LibraryPurpose
pandasStore and manage data
matplotlibPlot graphs
sklearn.clusterProvides the KMeans algorithm

🟩 Step 3: Create the Dataset

data = {
"Income":[20,22,25,28,60,62,65,68]
}

df = pd.DataFrame(data)

print(df)

Explanation

The dataset contains the annual income (in thousands) of eight customers.

CustomerIncome (₹ Thousands)
120
222
325
428
560
662
765
868

Notice that the data naturally forms two groups:

  • Low Income
  • High Income

🟨 Step 4: Create the K-Means Model

model = KMeans(n_clusters=2, random_state=42)

Explanation

  • KMeans() creates the clustering model.
  • n_clusters=2 means divide the data into 2 clusters.
  • random_state=42 ensures the same result every time the program runs.

🟦 Step 5: Train the Model

model.fit(df)

Explanation

The algorithm learns the patterns in the dataset.

During training, K-Means automatically:

  • Chooses cluster centers (centroids)
  • Assigns each data point to the nearest centroid
  • Recalculates the centroids
  • Repeats until the centroids no longer change

🟩 Step 6: Find Cluster Labels

df["Cluster"] = model.labels_

print(df)

Explanation

model.labels_ stores the cluster number assigned to each customer.

Example Output

IncomeCluster
200
220
250
280
601
621
651
681

Cluster 0 → Low Income

Cluster 1 → High Income


🟨 Step 7: Display Cluster Centers

print(model.cluster_centers_)

Explanation

Cluster centers (centroids) represent the average value of each cluster.

Example Output

[[23.75]
[63.75]]

Meaning

Cluster 1 Average Income = ₹23.75 Thousand

Cluster 2 Average Income = ₹63.75 Thousand


🟦 Step 8: Predict the Cluster of a New Customer

prediction = model.predict([[55]])

print("Cluster =", prediction[0])

Explanation

Suppose a new customer has an income of ₹55 Thousand.

The algorithm predicts the cluster to which the customer belongs.

Example Output

Cluster = 1

🟩 Step 9: Plot the Clusters

plt.scatter(df["Income"],
[1]*len(df),
c=df["Cluster"],
s=120)

plt.title("K-Means Clustering")

plt.xlabel("Income")

plt.yticks([])

plt.show()

Explanation

This graph displays:

  • Different colors represent different clusters.
  • Customers in the same cluster have similar income levels.

🟪 Complete Python Program

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# Create Dataset

data = {
"Income":[20,22,25,28,60,62,65,68]
}

df = pd.DataFrame(data)

print("Original Dataset")

print(df)

# Create Model

model = KMeans(
n_clusters=2,
random_state=42
)

# Train Model

model.fit(df)

# Display Cluster Labels

df["Cluster"] = model.labels_

print("\nClustered Dataset")

print(df)

# Display Cluster Centers

print("\nCluster Centers")

print(model.cluster_centers_)

# Predict New Customer

prediction = model.predict([[55]])

print("\nNew Customer belongs to Cluster =", prediction[0])

# Plot Graph

plt.scatter(
df["Income"],
[1]*len(df),
c=df["Cluster"],
s=120
)

plt.title("K-Means Clustering")

plt.xlabel("Income")

plt.yticks([])

plt.show()

🟥 Sample Output

Original Dataset

Income

20

22

25

28

60

62

65

68

Clustered Dataset

Income Cluster

20 0

22 0

25 0

28 0

60 1

62 1

65 1

68 1

Cluster Centers

[[23.75]

[63.75]]

New Customer belongs to Cluster = 1

🟦 Step-by-Step Working of K-Means

Step 1

Choose the number of clusters (K).

Example:

K = 2

Step 2

Randomly select two centroids.

C1

C2

Step 3

Calculate the distance of every data point from each centroid.

Step 4

Assign each data point to its nearest centroid.

Step 5

Calculate new centroids.

Step 6

Repeat Steps 3–5 until the centroids no longer change.

Step 7

Final clusters are formed.


🟨 Workflow Diagram

Customer Dataset


Choose K


Select Initial Centroids


Calculate Distance


Assign Data Points


Update Centroids


Repeat Until Stable


Final Clusters

🟩 Advantages

✔ Simple and easy to implement

✔ Fast for large datasets

✔ Efficient clustering algorithm

✔ Easy to understand

✔ Works well with numerical data


🟥 Limitations

❌ Number of clusters (K) must be specified in advance.

❌ Sensitive to outliers.

❌ Works best for spherical clusters.

❌ Different initial centroids may produce different results.


🟦 Applications

  • 🛒 Customer Segmentation
  • 🏥 Disease Pattern Analysis
  • 📷 Image Compression
  • 🌐 Website User Grouping
  • 🎯 Recommendation Systems
  • 📊 Market Basket Analysis
  • 🛰 Satellite Image Segmentation

🟨 Viva Questions

  1. What is K-Means Clustering?
  2. Why is K-Means called an unsupervised algorithm?
  3. What is a centroid?
  4. What is the purpose of n_clusters?
  5. What is random_state?
  6. What happens during each iteration of K-Means?
  7. Name two applications of K-Means Clustering.
  8. What are the limitations of K-Means?

⭐ One-Line Revision

K-Means Clustering groups similar data points into K clusters by repeatedly assigning points to the nearest centroid and updating the centroids until stable clusters are formed.