C++ Program to Display Fibonacci Series using Loops, Recursion, Dynamic Programming

C++ Program to Display Fibonacci Series

In the previous article, we have discussed about C++ Program to Reverse a Number. Let us learn how to Display Fibonacci Series in C++ Program. Know different methods to print Fibonacci series in C++ explained step by step with sample programs. You can use the technique of your choice to display the Fibonacci series in no time. You can use this quick tutorial over here as a reference to resolve any doubts of yours.

Methods to display Fibonacci series in c++

In this article, we understand how to display the Fibonacci series in c++. Methods that we will discuss are given below.

Before understanding these methods let us understand first what is Fibonacci series is. The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

Here we can see the next number in the series is the sum of the previous two numbers. Now we see different methods to display the series.

Method 1-Using Loops

In this method, we are given a number up to which we have to print the series. As we understand that in this series the next number is the sum of previous two numbers therefore we have to store first two number in a variable by ourself because these numbers are fixed and by these numbers, we can display the series. Let write the code for this.

C++ Program to print Fibonacci Series using Loops

#include <iostream>
using namespace std;

int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    cout << "Fibonacci Series: ";

    for (int i = 0; i < n-2; i++) {
       
        if(i == 0) {
            cout << t1 << " ";
        }
        if(i == 1) {
            cout << t2 << " ";
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << " ";
    }
    return 0;
}

Output

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Method 2: Using Recursion

As we understand that in this series the next number is the sum of the previous two numbers, therefore, we have to build faith in our program that the sum of the last two-digit will give the next digit, and by having this faith we call the recursive function. Let write code for this.

C++ Program to print Fibonacci Series using Recursion

#include <iostream>
using namespace std;

int fibonacci(int n){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    return fibonacci(n-1)+fibonacci(n-2);
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm;
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

Method – 3 Using Dynamic Programming

When we analyze the recursive code of the Fibonacci series we will see that we call the recursive function for a number multiple times which is not a good practice. In this approach, we will see that instead of calling recursive function for a given number again and again we store the result for that number in an array so that if that number come again instead of calling recursive call for that number we will simply return the result of that number from the array. Let write the code for this.

#include <iostream>
using namespace std;

int fibonacci(int n,int f[]){
    
    if(n==1){
        return 0;
    }
    if(n==2){
        return 1;
    }
    if(f[n] != -1){
        return f[n];
    }
    
    f[n] = fibonacci(n-1,f)+fibonacci(n-2,f);
    return f[n];
}
int main() {
    int n=10, t1 = 0, t2 = 1, nextTerm,f[10];
    for(int i=0;i<=n;i++)
    {
        f[i]=-1;
    }
    for(int i=1;i<=n;i++)
    {
     cout<<fibonacci(i,f)<<" ";
    }
    return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

So these are the methods to display the Fibonacci series in c++.

Related Programs:

C++ Program to Convert Octal Number to Decimal Number

C++ Program to Convert Octal Number to Decimal Number

In the previous article, we have discussed about C++ Program to Convert Decimal Number to Binary Number. Let us learn how to Convert Octal Number to Decimal Number in C++ Program.

Methods to Convert Octal Numbers to Decimal Numbers in C++

In this article, we will discuss different methods of converting octal to decimal numbers in c++. The list of the methods that we will discuss is given below.

Let discuss the basic idea for converting octal to a decimal number which will help us later in writing the code. Let discuss the approach with the help of an example. Suppose the octal number is 67 then its decimal form is 55. We will write 67 as 6*(8^1)+7*(8^0) which is equivalent to 55. So here we see we extract the digit of decimal number and multiply the digit with the power of 8 in increasing order. This means the first digit is multiplied with 8 to the power 0 while the second digit is multiplied with 8 to the power 1 and so on. So this is the intuition. Let’s discuss different methods to do it.

Method 1-Using Loop with arithmetic operator

In this approach, we will take the help of a loop and modulo(%) and division(/) operator to extract the digit of the binary number. When we extract the digit we will simply multiply the digit with a power of 8 and stored the result in the variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;


int convertOctalToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, rem;
    while (n!=0)
    {
        rem = n%10;
        n /= 10;
        decimalNumber += rem*pow(8,i);
        i++;
    }
    return decimalNumber;
}

int main()
{
    long long n=67;
    cout << n << " in octal is " << convertOctalToDecimal(n) << " in decimal";
    return 0;
}

Output

67 in octal is 55 in decimal

Method 2-Using pre-defined function

In c++ there is a pre-defined function that is used to convert octal to decimal numbers. Here we are talking about stoi() function. Let us see what the stoi() function is.stoi() stands for the string to integer, it is a standard library function in C++ STL, it is used to convert a given string in various formats (like binary, octal, hex, or a simple number in string formatted) into an integer. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string n="67";
    cout << n << " in octal is " <<  stoi(n, 0, 8) << " in decimal";
    
    return 0;
}

Output

67 in octal is 55 in decimal

So these are the methods to convert octal numbers to decimal numbers in c++.

Python Program to Set nth Bit of a Number

Program to Set nth Bit of a Number

In the previous article, we have discussed Python Program to Get nth Bit of a Number

Given a number and the bit position, the task is to set the nth bit of the given Number.

For example:

Let the number = 5

Bit position=1

To set the 1st-bit position(0 indexing):

Its binary form = 101

When we set the 0 at the 1st index becomes 1 that is 111 which is equal to the number 7.

Bitwise or (|) operator:

If one of two bits is 1, sets each bit to 1.

Examples:

Example1:

Input:

Given Number = 5 
Bit position(in range 0-31)= 1

Output:

The given number { 5 } after set the { 1 } bit position =  7

Example2:

Input:

Given Number = 8
Bit position(in range 0-31)= 2

Output:

The given number { 8 } after set the { 2 } bit position = 12

Program to Set nth Bit of a Number in Python

Below are the ways to set the nth bit of the given Number in Python:

Method #1: Using Bitwise |(or) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the bit position as static input and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 5
# Give the bit position as static input and store it in another variable.
bitpositin = 1
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

The given number { 5 } after set the { 1 } bit position =  7

Method #2: Using Bitwise |(or) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the bit position as user input using the int(input()) function and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise | operation for the given number and the above result and store it in another variable say set_numb
  • Print the given number after set the nth bit of the given Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the bit position as user input using the int(input()) function and 
# store it in another variable.
bitpositin = int(input("Enter some random number = "))
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise | operation for the given number and the above result and
# store it in another variable say set_numb.
set_numb = gvn_numb | numbr_bit
# Print the given number after set the nth bit of the given Number.
print("The given number {", gvn_numb,
      "} after set the {", bitpositin, "} bit position = ", set_numb)

Output:

Enter some random number = 8
Enter some random number = 2
The given number { 8 } after set the { 2 } bit position = 12

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

Need of Operator Overloading in C++ ?

Need of Operator Overloading

In the previous article, we have discussed about C++ : How to Find Duplicates in a Vector. Let us learn Operator Overloading in C++ Program.

Need of Operator Overloading in C++

1)Operator Overloading

Operator overloading is a feature of object-oriented programming that enables a programmer to redefine a built-in operator to work with user-defined data types.
Let’s pretend we’ve created a class called Integer to handle integer operations. To handle the various operations, we can use the functions add(), subtract(), multiply(), and divide(). However, it is preferable to use operators that correspond to the given operations(+, -, *, and /, respectively) to make the code more understandable and improve readability, i.e. we can substitute the following code with the following code.

2)Example of Operator Overloading (concatenate two strings)

When using the + operator with two integers, for example, the numbers are added, while when using the + operator with two string arguments, the strings are concatenated.

Below is the Implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string string1 = "BTechGeeks";
    string string2 = "Platform";
    // For strings, the + operator is overloaded by default.
    // It will join the strings together.
    string string3 = string1 + string2;
    cout << "concatenated string = " << string3 << endl;
    return 0;
}

Output:

concatenated string = BTechGeeksPlatform

Operators for primitive data types such as int, double, string, and so on are already overloaded. However, we cannot overload user-defined classes.

3)Need of Operator Overloading for a User Defined Class

The overload operator is also available in C++ for user-defined classes.

Assume we have a user-defined class called ComplexNumber, and we have generated two objects of it, i.e.

class ComplexNum
{
    int real;
    int imaginary;
public:
    ComplexNumber(int re, int im) :
            real(re), imaginary(im)
    {}
};

Let’s say we want to use the + operator with two objects, i.e.

ComplexNum cm1(5, 2);
ComplexNum cm2(9, 7);
// calling +(operator) for the above objects
ComplexNumber cm3 = cm1 + cm2;

It will show a compile error, indicating that, like other operators, the + operator is overloaded by default for primitive data types only, not for user-defined classes.
When we use the + operator with ComplexNumber operands, the compiler is stumped.

We must overload a user specified class if we want to use the + operator for it. Let’s look at how to overload the + operator in the ComplexNumber class.

4)How to use a given class to overload an operator

To use operator overloading for user define class it is implemented as below,

operator X(arguments)

Here X represents the operator symbol, such as +, –, /, and so on.
The following are examples of operator functions: either a global function or a function that is a part of a class.

5)Overloading + Operator for Complex Number class

Since the + operator is a binary one, it can accept two arguments.
It takes two arguments, namely two objects of our custom class, and returns a new object of the same class.

This feature now has access to the private members of the user-defined class ComplexNumber. As a result, we must declare it as a friend function, i.e.

Now, if we use the + operator with ComplexNumber class objects, this global overloaded function, i.e.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;

class ComplexNum {
    int real;
    int imaginary;

public:
    ComplexNum(int re, int im)
        : real(re)
        , imaginary(im)
    {
    }
    void print()
    { // printing the real and imaginary part of the complex
      // number
        cout << real << " + " << imaginary << "i" << endl;
    }
    // overloading + operator for complexNum class
    friend ComplexNum operator+(ComplexNum obj1,
                                ComplexNum obj2);
};
// overloading + operator for complexNum class
ComplexNum operator+(ComplexNum object1, ComplexNum object2)
{
    return ComplexNum(object1.real + object2.real,
                      object1.imaginary
                          + object2.imaginary);
}
int main()
{
    ComplexNum cm1(5, 2);
    ComplexNum cm2(9, 7);
    cm1.print();
    cm2.print();
    // calling + opertor for two objects
    ComplexNum cm3 = cm1 + cm2;
    cm3.print();
    return 0;
}

Output:

5 + 2i
9 + 7i
14 + 9i

Here both imaginary and real part of Complex number is added

Similarly we can overload any operator by the same method as given above.

Related Programs:

boost::any Usage in CPP

boostany Usage details

In the previous article, we have discussed about How to Copy all Values from a Map to a Vector in CPP. Let us Learn boost::any Usage in C++ Program.

Boost::any in C++

1)Boost::any

Strongly typed languages, such as C++, require each variable to have a particular type that determines what kind of data it can store. Other programming languages, such as JavaScript, allow developers to store any type of data in variables. In JavaScript, for example, a single variable may contain a string, then a number, and finally a boolean value.

boost::any provides the boost::any class, which, like JavaScript variables, can store arbitrary types of data.

Header file used :
#include<boost/any.hpp>
Syntax:

boost::any variable_name;Variables of type boost::any are not entirely limitless in terms of what they can store; there are some, although minor, preconditions. Any value contained in a boost::any variable must be copy-constructible. As a result, since C/C++ arrays are not copy-constructible, they cannot be stored.

2)Prebuilt Functions of  Boost::Any

  1. clear( ) : It is used to remove the data from a variable.
  2. empty() : It is used to determine whether or not a variable is empty. This function is usually used in conjunction with if-else conditions.
  3. swap( ) : It is used to swap the contents in two variables of any datatype.
  4. type( ) : When we need to know what kind of data a variable contains, we use it.
  5. any_cast( ): This function returns a copy of the variable and is commonly used for printing.
  6. bad_any_cast( ) : Where the data does not fit the template datatype and an error occurs, is commonly used for try and capture blocks.

3)Implementation of boost::any

Below is the implementation:

#include "boost/any.hpp"
#include <bits/stdc++.h>
using namespace std;
int main()
{

    // declaring any data type
    boost::any a, b, c, d;

    // Initializing "a" with some random integer value
    a = 100;

    // Printing the value of a using boost::any_cast
    cout << boost::any_cast<int>(a) << endl;

    // Initializing "b" with some random character value
    b = 'S';

    // Printing the value of b using boost::any_cast
    cout << boost::any_cast<char>(b) << endl;

    // Initializing "c" with some random string value
    c = string("BTechGeeks");

    // Printing the value of c using boost::any_cast
    cout << boost::any_cast<string>(c) << endl;

    // Initializing "d" with some random float value
    d = 98.7423;

    // Printing the value of d using boost::any_cast
    cout << boost::any_cast<double>(a) << endl;

    // Giving integer value to b and providing float as
    // parameter for any_cast
    // it gives error so we used try and catch block
    // to handle the error
    try {
        boost::any b = 100;
        cout << boost::any_cast<float>(b) << endl;
    }
    catch (boost::bad_any_cast& e) {
        cout << "Exception is Caught while converting : "
             << e.what() << endl;
        
    }

    return 0;
}

Output:

100
S
BTechGeeks
Exception is Caught while converting : boost::bad_any_cast: failed conversion using boost::any_cast

Related Programs:

C++ Program to Convert Decimal Number to Octal Number

C++ Program to Convert Decimal Number to Octal Number

In the previous article, we have discussed about C++ Program to Convert Octal Number to Decimal Number. Let us learn how to Convert Decimal Number to Octal Number in C++ Program.

Methods to convert decimal number to octal number in c++

In this article, we discuss different methods by which we can convert decimal numbers to octal numbers in c++. The methods that we will discuss today are given below.

First, discuss the basic intuition behind converting decimal to octal numbers in c++. Suppose a number is 16 and we have to find an octal form of 16 then we can do like this:-

16%8==0     octal=0              16/8=2

2%8==2      octal=20            2/8=0

and we stop as our number becomes 0. So we get octal of a number like this. Now we will discuss different methods of doing this task.

Method 1-Using arithmetic operator with array

As we see in the example above we do the task in the same manner. We store the remainder of the number when divided by 8 in the array and after that, we divide the number by 8. We perform the following steps till our number is greater than 0. After that, we will print the elements of the array in the reverse form which will be the answer. Let’s write the code for this.

#include <iostream>
using namespace std;

void decimalToOctal(int n)
{
    int octalNum[100],num=n;
    int i = 0;
    while (n > 0) {
        octalNum[i] = n % 8;
        n = n / 8;
        i++;
    }
    cout<<num<<" in octal form is ";
    for (int j = i - 1; j >= 0; j--)
    {
        cout << octalNum[j];
    }
}

int main()
{
    int n = 16;
    decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

Method 2-Using arithmetic operator without the array

We can also do the same task without using the array. Here the idea is the same but instead of an array, we use a variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int decimalToOctal(int n)
{
     long long octalNumber = 0;
    int rem, i = 1, step = 1;

    while (n!=0)
    {
        rem = n%8;
        n /= 8;
        octalNumber += rem*i;
        i *= 10;
    }
    return octalNumber;
}

int main()
{
    int n = 16;
    cout<<n<<" in octal form is "<<decimalToOctal(n);
    return 0;
}

Output

16 in octal form is 20

So these are the methods to convert decimal number to octal number in c++.

C++ Program to Convert Single Character to String

C++ Program to Convert Single Character to String

In the previous article, we have discussed about C++ Program to Find of Size of Datatypes. Let us learn how to  Convert Single Character to String in C++ Program.

Methods to Convert Single Character to String in c++

In this article, we discuss different methods of how we can convert a single character to a string in c++. The methods that we discuss are given below.

Let’s understand each method one by one.

Method 1-Using “=” operator

In this method, we simply assign a character value to a string. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str=ch;
    cout<<str;
    return 0;
}

Output

d

Method 2-Using “+=” operator

As we know a string is a collection of characters. So if we take an empty string and add the character to it so we can convert that character into the string. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str="";
    str+=ch;
    cout<<str;
    return 0;
}

Output

d

Method 3-Using append( ) function

This method is just similar to the += operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str.append(1,ch);
    cout<<str;
    return 0;
}

Output

d

Method 4-Using assign( ) function

This method is just similar to the = operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    char ch='d';
    string str;
    str.assign(1,ch);
    cout<<str;
    return 0;
}

Output

d

So these are the methods to convert a single character to a string in c++.

C++ is a powerful general-purpose programming language. It is mostly used to develop browsers, operating systems, games and so on. Beginners who want to know more inversions of C++ language can learn the Basic C++ Programs for a better and quick understanding of the coding.

C++ Program to Convert String to a Number

C++ Program to Convert String to a Number

In the previous article, we have discussed about C++ Program to Convert Single Character to String. Let us learn how to Convert String to a Number in C++ Program.

Program to Convert String to a Number in c++

In this article, we discuss how we can convert a string to a number in c++. For example, suppose we a string “123” then we have to convert it to integer 123. The methods that are discussed are given below.

Let’s discuss these methods one by one.

Method 1-Using stoi( ) function

The stoi() function takes a string as an argument and returns its value. Let’s understand this with the help of an example.

#include <iostream>
using namespace std;

int main() {
    string str="123";
    
    cout<<stoi(str)<<endl;
    
    string str1="123abd";
    cout<<stoi(str1);
    return 0;
}

Output

123
123

Method 2-Using atoi( ) function

 The atoi() function takes a character array or string literal as an argument and returns its value. Let’s understand this with the help of an example.

#include <bits/stdc++.h>
using namespace std;

int main() {
     const char* str1 = "123";
    cout<<atoi(str1)<<endl;
    
    
    const char* str2= "123 geek";
    cout<<atoi(str2)<<endl;
    return 0;
}

Output

123
123

So these are the methods to convert a string to a number in c++.

The list of C++ Example Programs include swapping number, addition, multiplication of two numbers, factorial of a number and many more. Interested people can get the cpp code to get a clear idea on the programming language.

C++ Program to Find Largest Number Among Three Numbers

C++ Program to Find Largest Number Among Three Numbers

In the previous article, we have discussed about C++ Program to Calculate Sum of First N Natural Numbers. Let us learn how to find Largest Number Among Three Numbers in C++ Program.

Method to find the largest number among 3 numbers in c++

In this article, we see different methods by which we can largest of 3 numbers using c++. Let see all the methods one by one.

Method 1-Using if statements

In this method, we use three if statements for all three numbers. In the first, if statement we will compare the first number with the second and third numbers and if it is greater than both the number then we will say number 1 is the largest. In the second if statement we will compare the second number with the first and third numbers and if it is greater than both the number then we will say number 2 is the largest. In the third, if statement we will compare the third number with the second and first numbers and if it is greater than both the number then we will say number 3 is the largest. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n1=10,n2=12,n3=9;
     if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    if(n3 >= n1 && n3 >= n2)
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Here we see that 12 is the largest among the 3 numbers.

Method 2-Using if-else statement

There is a flaw in the first method because in the first method all the if statement runs. Suppose if we get that number 1 is the greatest is greatest in first if statement then in that case also all if statement runs. So to improve this we can use the if-else statement. In if-else statements, if one condition pass then we will not go to further statements. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Method 3-Using nested if-else statement

This method is a more efficient version than the first two methods. Let write a code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if (n1 >= n2) {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Largest number: 12

Method 4-Using Ternary operator

The ternary operator is a way of using an if-else statement in one line.So by using the ternary operator we can reduce our code line with the same logic that we discuss above. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     int max = (n1 > n2) ?
          (n1 > n3 ? n1 : n3) :
          (n2 > n3 ? n2 : n3);
    cout << "Largest number among "
         << n1 << ", " << n2 << " and "
         << n3 << " is " << max << "." ;

    return 0;
}

Output

The largest number among 10, 12, and 9 is 12.

So these are the methods to find the largest among 3 numbers in c++.

C++ Program to Check if it is Sparse Matrix or Not

Program to Check if it is Sparse Matrix or Not

In the previous article, we have discussed about C++ Program to Print Identity Matrix. Let us learn how to Check if it is Sparse Matrix or Not in C++ Program.

What is a matrix:

A matrix is a rectangular numeric sequence separated into columns and rows. A matrix element, also known as an entry, is a number that occurs in a matrix.

Example:

The matrix shown above has 5 rows and 4 columns, with entries ranging from 1 to 20.

The dimensions of a matrix reflect the number of rows and columns in this sequence.

Because there are 5 rows and 4 columns, this is referred to as a 5*4 matrix.

Sparse Matrix:

A matrix is said to be sparse if the majority of its members are 0. It means that it has a small number of non-zero elements.

To determine if the given matrix is sparse or not, we first count the number of zero members in the matrix. The matrix’s size is then determined. The number of zero items in an array must be more than size/2 for the matrix to be sparse.

Program to Check if it is Sparse Matrix or Not in C++

We will create a program to determine whether or not the given matrix is sparse matrix or not.

Approach:

  • Scan the number of rows and columns of the given matrix and store it in variables row sum and colsum
  • Create a matrix with given dimensions rowsum and colsum
  • Loop through the array, counting the amount of zeros in the array and storing the result in the variable count.
  • Calculate the array’s size by multiplying the number of rows by the array’s number of columns.
  • If the count exceeds size/2, the given matrix is a sparse matrix. That signifies that the majority of the array’s elements are zeroes.
  • Otherwise, the matrix is not sparse.
  • The Exit of the Program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;

// Driver Code
int main()
{
    int rownum, colnum;
    // Scanning number of rows of the given matrix
    cout << "Enter number of rows of the given matrix : "
         << endl;
    cin >> rownum;
    cout << endl;
    // Scanning number of columns of the given matrix
    cout << "Enter number of columns of the given matrix : "
         << endl;
    cin >> colnum;
    cout << endl;
    // creating a matrix with rownum as rows and colnum as
    // columns
    int givenMat[rownum][colnum];
    // scanning all the elements of the matrix
    for (int i = 0; i < rownum; i++) {
        cout << "enter the row elements " << endl;
        for (int j = 0; j < colnum; j++) {
            cout << "enter the element" << endl;
            cin >> givenMat[i][j];
        }
    }
    // taking a variable zeroCount which counts the
    // total number of 0 elements in the given matrix
    // and initializing it to 0
    int zeroCount = 0;
    // traversing the matrix and counting numbeer of zeros
    // in it
    for (int i = 0; i < rownum; i++) {
        for (int j = 0; j < colnum; j++) {
            // cheecking if the element is 0 or not
            // if the element is 0 then increase the zero
            // count by 1
            zeroCount = zeroCount + 1;
        }
    }
    // printing the matrix
    for (int i = 0; i < rownum; i++) {

        for (int j = 0; j < colnum; j++) {

            cout << givenMat[i][j] << " ";
        }
        cout << endl;
    }
    // checking the condition of sparse matrix
    if (zeroCount > (rownum * colnum) / 2) {
        cout
            << "the given matrix givenMat is sparse matrix";
    }
    else {
        cout << "the given matrix givenMat is not a sparse "
                "matrix";
    }

    return 0;
}

Output:

Enter number of rows of the given matrix : 
5
Enter number of columns of the given matrix : 
4
enter the row elements 
enter the element
1
enter the element
0
enter the element
0
enter the element
2
enter the row elements 
enter the element
5
enter the element
0
enter the element
0
enter the element
0
enter the row elements 
enter the element
5
enter the element
0
enter the element
0
enter the element
9
enter the row elements 
enter the element
12
enter the element
0
enter the element
8
enter the element
0
enter the row elements 
enter the element
7
enter the element
0
enter the element
0
enter the element
0
1 0 0 2 
5 0 0 0 
5 0 0 9 
12 0 8 0 
7 0 0 0 
the given matrix givenMat is sparse matrix

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.
Related Programs: