C++ Data Structure Programs with Output: Recursion, Factorial, Fibonacci, Arrays & Strings Explained

 

C++ Programming

Data Structures & C++ Programming

Recursion, arrays, strings, searching, and stacks — complete C++ programs with outputs and simple explanations.

Visual Presentation

C++ Data Structure Topics at a Glance

🔁
Topic 1
Recursion
📦
Topic 2
Arrays
🔤
Topic 3
Strings
🔍
Topic 4
Searching
📚
Topic 5
Stack
Recursion Call Stack — factorial(5)
factorial(5) 5 × factorial(4)
factorial(4) 4 × factorial(3)
factorial(3) 3 × factorial(2)
factorial(2) 2 × factorial(1)
factorial(1) returns 1 ✅ Base Case
← Calls go deeper    Base case reached    Results unwind back →
Introduction

Introduction to Data Structures and C++ Programming

When someone begins learning programming, especially data structures using C++, they quickly encounter several important concepts such as recursion, arrays, strings, searching, and stacks. These concepts form the foundation of algorithm design and efficient problem solving. Think of them as the basic tools in a programmer's toolbox. Without understanding them properly, building complex systems becomes very difficult.

C++ remains one of the most popular languages used to teach data structures and algorithms because it provides both low-level memory control and high-level programming features. In many universities and technical courses, students learn recursion through classical examples like factorial and Fibonacci series. These examples are used because they clearly demonstrate how a function can call itself repeatedly until a stopping condition is reached. Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem.

Another important reason these topics are taught together is that they show how different programming techniques work together. Arrays help store collections of data, strings manage text information, and recursion helps break down complex problems into simpler steps. Once these concepts are mastered, programmers can move on to advanced structures such as trees, graphs, and dynamic programming. In this article, we will explore complete C++ programs with outputs and simple explanations for important data structure topics including recursion, arrays, strings, and other essential algorithms.

Section 01

Understanding Recursion in Programming

Recursion might seem confusing at first, but it becomes very intuitive once you visualize how it works. Imagine standing between two mirrors facing each other. You see endless reflections repeating again and again. Recursion works in a similar way: a function calls itself repeatedly until a specific stopping condition is reached.

In programming terms, recursion is a technique where a function solves a problem by calling itself with smaller inputs until it reaches a base case that stops further calls. This is especially useful when a problem can be divided into smaller subproblems of the same type.

How Recursion Works

🛑

Base Case

The condition where recursion stops. Without a base case, recursion would continue forever and eventually cause a stack overflow error.

🔁

Recursive Case

The part where the function calls itself with smaller input, progressively moving closer to the base case.

Base Case and Recursive Case Explained

A recursive function must always move closer to its base case. If it doesn't, the program will keep calling the function endlessly. For example, in factorial calculation:

Base Case: n == 0 or n == 1
Recursive Case: n * factorial(n-1)

This simple structure makes recursion powerful. Many algorithms such as tree traversal, divide-and-conquer algorithms, and dynamic programming techniques rely heavily on recursion.

Factorial Breakdown

Let's imagine calculating the factorial of 5. Instead of multiplying all numbers directly, recursion breaks it down like this:

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

Once the program reaches 1, it stops and starts returning results back through each function call.

Section 02

Factorial Using Recursion

The factorial of a number is the product of all positive integers less than or equal to that number.

Formula
n! = n × (n-1) × (n-2) × ... × 1
Example
5! = 5 × 4 × 3 × 2 × 1 = 120
C++ Program for Factorial Using Recursion
#include <iostream>
using namespace std;
long long factorial(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Factorial of " << num << " is " << factorial(num);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is 120
Explanation — Step by Step
1

The function calls factorial(5)

2

It becomes 5 × factorial(4)

3

Then 4 × factorial(3), then 3 × factorial(2), then 2 × factorial(1)

Once the program reaches factorial(1), it returns 1, and the calculations move backward through the call stack until the final result 120 is produced.

Section 03

Fibonacci Series Using Recursion

The Fibonacci sequence is another classic example used to demonstrate recursion. Each number in the sequence is the sum of the two numbers before it.

Mathematical Formula
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2)
Sequence
0
1
1
2
3
5
8
13
C++ Program for Fibonacci Series
#include <iostream>
using namespace std;
int fibonacci(int n)
{
if(n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
int main()
{
int n;
cout << "Enter number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for(int i=0;i<n;i++)
cout << fibonacci(i) << " ";
return 0;
}
Output
Enter number of terms: 6
Fibonacci Series: 0 1 1 2 3 5
Explanation

Here's how the recursion works when calculating fibonacci(5):

fibonacci(5)
= fibonacci(4) + fibonacci(3)
= (fibonacci(3)+fibonacci(2)) + (fibonacci(2)+fibonacci(1))

The function continues breaking the problem into smaller calls until it reaches the base conditions (0 or 1). After that, the results combine to produce the final sequence.

Section 04

Arrays in C++

An array is a collection of elements stored in contiguous memory locations. All elements in an array must be of the same data type. Arrays are extremely important in data structures because they allow efficient storage and quick access to data.

Think of an array like a row of lockers in a school hallway. Each locker has a number (index), and you can access any locker directly if you know its number.

C++ Program to Insert and Display Array Elements

#include <iostream>
using namespace std;
int main()
{
int arr[5];
cout<<"Enter 5 numbers:"<<endl;
for(int i=0;i<5;i++)
cin>>arr[i];
cout<<"Array elements are:"<<endl;
for(int i=0;i<5;i++)
cout<<arr[i]<<" ";
return 0;
}
Output
Enter 5 numbers:
10 20 30 40 50

Array elements are:
10 20 30 40 50
Explanation

The program first declares an array of size 5. A loop is then used to input values from the user. Another loop prints the elements stored in the array. Arrays allow efficient access because each element can be accessed using its index.

C++ Program to Find Largest Element in an Array

#include <iostream>
using namespace std;
int main()
{
int arr[5] = {10, 45, 23, 89, 34};
int largest = arr[0];
for(int i=1;i<5;i++)
{
if(arr[i] > largest)
largest = arr[i];
}
cout<<"Largest element is "<<largest;
return 0;
}
Output
Largest element is 89
Explanation

The program assumes the first element is the largest. It then compares each element with the current largest value. If a bigger value is found, it replaces the current largest value.

Section 05

Strings in C++

A string is a sequence of characters used to represent text. In C++, strings can be handled using arrays of characters or the string class from the standard library. Strings are used in almost every software system, from processing user input to managing data in databases. Because of this, learning basic string manipulation programs is very important.

C++ Program to Reverse a String

#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout<<"Enter a string: ";
getline(cin,str);
for(int i=str.length()-1;i>=0;i--)
cout<<str[i];
return 0;
}
Output
Enter a string: hello
olleh
Explanation

The program calculates the length of the string and prints characters in reverse order. This simple technique demonstrates how string indexing works.

C++ Program to Count Vowels in a String

#include <iostream>
using namespace std;
int main()
{
char str[100];
int vowels = 0;
cout<<"Enter a string: ";
cin.getline(str,100);
for(int i=0;str[i]!='\0';i++)
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'
|| str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
vowels++;
}
cout<<"Number of vowels: "<<vowels;
return 0;
}
Output
Enter a string: programming
Number of vowels: 3
Section 06

Other Important Data Structure Programs

Beyond recursion, arrays, and strings, there are many other programs frequently taught in data structures courses.

🔍

C++ Program for Linear Search

#include <iostream>
using namespace std;
int main()
{
int arr[5] = {10,20,30,40,50};
int key;
cout<<"Enter number to search: ";
cin>>key;
for(int i=0;i<5;i++)
{
if(arr[i]==key)
{
cout<<"Element found at position "<<i+1;
return 0;
}
}
cout<<"Element not found";
return 0;
}
Output
Enter number to search: 30
Element found at position 3
📚

C++ Program for Stack Using Array

#include <iostream>
using namespace std;
int stack[5];
int top = -1;
void push(int x)
{
if(top==4)
cout<<"Stack Overflow"<<endl;
else
{
top++;
stack[top]=x;
}
}
void display()
{
for(int i=top;i>=0;i--)
cout<<stack[i]<<" ";
}
int main()
{
push(10);
push(20);
push(30);
display();
return 0;
}
Output
30 20 10
Stack LIFO Visualization (Last In First Out)
30 ← Top
20
10 ← Bottom
Section 07

Comparison: Recursion vs Iteration

Recursion vs Iteration — Feature Comparison

Feature
Recursion
Iteration
Method
Function calls itself
Uses loops
Memory Usage
Higher due to call stack
Lower
Readability
Often easier for complex problems
Sometimes longer code
Speed
Can be slower
Usually faster
Conclusion

Key Takeaways

Learning C++ data structure programs such as recursion, arrays, strings, searching algorithms, and stacks provides a strong foundation for computer science students and developers. These topics are not just academic exercises; they form the backbone of real-world software development.

Recursion demonstrates how complex problems can be solved by repeatedly solving smaller subproblems. Factorial and Fibonacci examples clearly show how recursive functions work step by step. Arrays and strings introduce fundamental ways to store and manipulate data efficiently. Additional programs such as searching algorithms and stack implementations expand a programmer's understanding of algorithmic problem solving.

Once these basics are mastered, programmers can confidently move toward advanced data structures like linked lists, trees, graphs, heaps, and dynamic programming algorithms.

FAQs

Frequently Asked Questions

Q1

What is recursion in C++?

Recursion is a programming technique where a function calls itself to solve smaller parts of a problem until a base condition stops the recursion.

Q2

Why are factorial and Fibonacci used to explain recursion?

They are simple mathematical problems that naturally break into smaller versions of themselves, making them perfect examples for understanding recursion.

Q3

What is the base case in recursion?

The base case is the stopping condition that prevents infinite recursive calls.

Q4

What are arrays used for in C++?

Arrays store multiple values of the same data type in contiguous memory locations and allow quick access using indexes.

Q5

Is recursion better than loops?

It depends on the problem. Recursion is elegant for problems like tree traversal, but loops are often more efficient for simple repetitive tasks.


Post a Comment

0 Comments