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

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.

#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.

#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:

## Methods to check whether the character is a vowel or not in c++

In this article, we discuss how to check whether a given character is a vowel or not in c++. The methods that are discussed are given below.

Let’s discuss these methods one by one.

### Method 1-Using if-else statement

In this method, we will use the if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
char ch='u';

if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
{
cout<<"Character "<<ch<<" is a vowel";
}
else
{
cout<<"Character "<<ch<<" is not a vowel";
}
return 0;
}


Output

Character u is a vowel

Note: Here we are writing code for lower case letters. We can use the same logic for upper case letters also.

### Method 2-Using if-else if-else statement

In this method, we use the if-else if-else statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
char ch='u';

if(ch=='a')
{
cout<<"Character "<<ch<<" is a vowel";
}
else if(ch=='e')
{
cout<<"Character "<<ch<<" is a vowel";
}
else if(ch=='i')
{
cout<<"Character "<<ch<<" is a vowel";
}
else if(ch=='o')
{
cout<<"Character "<<ch<<" is a vowel";
}
else if(ch=='u')
{
cout<<"Character "<<ch<<" is a vowel";
}
else
{
cout<<"Character "<<ch<<" is not a vowel";
}
return 0;
}


Output

Character u is a vowel

### Method 3-Using switch statement

In this method, we use the switch statement to check whether a given character is a vowel or not. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
char ch='h';

switch(ch)
{
case 'a':
cout<<"Character "<<ch<<" is a vowel";
break;
case 'e':
cout<<"Character "<<ch<<" is a vowel";
break;
case 'i':
cout<<"Character "<<ch<<" is a vowel";
break;
case 'o':
cout<<"Character "<<ch<<" is a vowel";
break;
case 'u':
cout<<"Character "<<ch<<" is a vowel";
break;
default:
cout<<"Character "<<ch<<" is not a vowel";
}
return 0;
}


Output

Character h is not a vowel

So these are the methods to check whether a given character is a vowel or not.

## C++ Program to Check Whether a Character is an Alphabet or Not

In the previous article, we have discussed C++ Program to Convert String to a Number. In this article, we will see C++ Program to Check Whether a Character is an Alphabet or Not.

## Method to check whether a character is an alphabet or not in c++

In this article, we discuss different methods of how can we check whether a given character is alphabet or not in c++. The methods that are discussed are given below.

Let understand these methods one by one.

### Method 1-Using if-else statement with ASCII value concept

As we know that ASCII value of upper case alphabets is between 65 and 90 i.e. ASCII value of ‘A’ is 65 while that of ‘Z’ is 90, while the ASCII value of lower case alphabets is between 97 and 122 i.e. ASCII value of ‘a’ is 97 while that of ‘z’ is 122. So we use this concept to check whether a given character is an alphabet or not. If the ASCII value of a character is between 65 and 90 or it is between 97 and 122 then the given character is an alphabet else given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
char ch='j';
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
{
cout <<"Character "<<ch<<" is an alphabet";
}
else
{
cout <<"Character "<<ch<<" is not an alphabet";
}
return 0;
}


Output

Character j is an alphabet

### Method 2- Using if-else statement with comparing character concept

In this method instead of comparing the ASCII value of character, we will directly compare characters i.e. if a character is between ‘a’ and ‘z’ or a character is between ‘A’ and ‘Z’ then a given character is an alphabet otherwise given character is not an alphabet. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
char ch='j';
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
cout <<"Character "<<ch<<" is an alphabet";
}
else
{
cout <<"Character "<<ch<<" is not an alphabet";
}
return 0;
}


Output

Character j is an alphabet

### Method 3-Using isalpha( ) method

isalpha( ) is a function in C++ that can be used to check if the passed character is an alphabet or not. It returns a non-zero value if the passed character is an alphabet else it returns 0. Let’s write code for this.

#include <iostream>
using namespace std;

int main() {
char ch='j';
if (isalpha(ch))
{
cout <<"Character "<<ch<<" is an alphabet";
}
else
{
cout <<"Character "<<ch<<" is not an alphabet";
}
return 0;
}


Output

Character j is an alphabet

So these are the methods to check whether a given character is an alphabet or not in c++.

Do you want to learn how to write a simple program in C++ language? If yes, then tap on the C++ Sample Programs link and get the source code for sample and easy programs.

## 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

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

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

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 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++.

## C++ Program to Find Factorial

In the previous article, we have discussed about C++ Program to Display Fibonacci Series. Let us learn how to find factorial in C++ Program.

## Methods to find factorial of a given number in c++

In this article, we discuss different methods of how we can find the factorial of a given number in c++. The list of methods that we will discuss is given below.

Before discussing the different methods let first understand what a factorial of the given number is. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.

Now we will discuss different methods to find the factorial of a given number.
<h3>Method 1-Iterative approach

As we discussed above that the factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. Hence we simply apply a for loop from 1 to a given number a store their multiplication in a variable and then print it. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
int res = 1, i,n=6;
for (i = 1; i <= n; i++)
{
res *= i;
}
cout<<"Factorial of given number "<<n<<" is "<<res;

return 0;
}

Output

Factorial of given number 6 is 720

### Method 2-Using Recursion

Let analyze how we can calculate the factorial of a given number using recursion.

Suppose we want to calculate the factorial of the number 6. So we can write it as:-

factorial(6)=6*5*4*3*2*1  and if we analyze that 5*4*3*2*1 is also the factorial of number 5 so we can break factorial of 6 into factorial(6)=6* factorial(5) So that’s how we can call the recursive function. Let write the code for this.

#include <iostream>
using namespace std;
int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
int n=6;
cout<<"Factorial of given number "<<n<<" is "<<factorial(6);

return 0;
}

Output

Factorial of given number 6 is 720

### Method 3-Using Dynamic Programming

The problem with the above recursive is that we have to call the recursive function for a particular number multiple times. Here Dynamic programming solves this problem. Instead of calling a recursive function for a given number again and again we store the result of that number in an array and when this number we directly return its value from the array instead of calculating the value again. Let’s write the code for this.

#include <iostream>
using namespace std;
int result[1000] = {0};
int factorial(int n) {
if (n >= 0) {
result[0] = 1;
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}
}
int main() {
int n=6;
cout<<"Factorial of a given number "<<n<<" is "<<factorial(n);
return 0;
}

Output

Factorial of a given number 6 is 720

So these are the methods to calculate the factorial of a given number in c++.

## Methods to insert records if not exist in MySQL

In this article, we discuss how to insert single or multiple records in SQL tables if they are not present. If records are already present then no updation occurs.

Before going to the actual content first let create a table and insert some dummy data into it.

CREATE TABLE student_details(
student_id INT auto_increment,
student_name VARCHAR(255),
primary key (student_id));
INSERT INTO student_details (student_name,student_address)
VALUES("Mayank","Kolkata"),
("Raj","Delhi"),
("Abhay","Delhi"),
("Aman","Jaipur"),
("Rahul","Mumbai"),
("Shubh","Merrut");
select * from student_details;

Output

1 Mayank Kolkata
2 Raj Delhi
3 Abhay Delhi
4 Aman Jaipur
5 Rahul Mumbai
6 Shubh Merrut

So this is our student_details table.

Now we will see how to insert single or multiple records if not exist in the table. Let first see the syntax or sample SQL query to do this task after that we will implement the query on our table.

### INSERT NOT EXISTS Syntax

If a subquery returns any rows at all, NOT EXISTS subquery is FALSE. It means that if the subquery in the NOT EXIST clause is TRUE, it will return no rows.

Syntax:INSERT INTO table_name (column1, column2, ....)                                           SELECT * FROM (SELECT value1, value2,....) AS temp                                          WHERE NOT EXISTS (<conditional_subquery>);

table_name: It is the name of that table where we want to insert the data.

<conditional_subquery>: It is the sub-query including a select statement to get the row with a particular condition.

### INSERT single record if NOT EXISTS in MySQL

Now with the help of the above query, we will see how to insert a single record if it is NOT EXISTS in MySQL.

INSERT INTO student_details (student_name,student_address)
SELECT * FROM (SELECT 'Manish' AS student_name, 'Agra' AS student_address) AS temp
WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Manish' ) LIMIT 1

Output

1 Mayank Kolkata
2 Raj Delhi
3 Abhay Delhi
4 Aman Jaipur
5 Rahul Mumbai
6 Shubh Merrut
7 Manish Agra

Here we see that one record with student_name=’Manish’ and student_address=’Agra’ is inserted.

Suppose we will fire this query again. Let see what happens.

 0 rows inserted. (Query took 0.0012 seconds.)

When we try to execute this query again we see that this time no record is inserted because the record is already present in the SQL table. So we can say that this query only inserts records when NOT EXIST in MySQL.

### INSERT multiple records if NOT EXISTS in MySQL

What if we have more than one record to be inserted, and before every insert, we want to ensure that the record with the same column value does not exist. Let see how to write an SQL query for this.

INSERT INTO student_details (student_name, student_address)
SELECT student_name, student_address FROM
( SELECT student_name , student_address FROM
( SELECT 'Ravi' as student_name , 'Shimla' as student_address ) AS temp_1
WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Ravi' )
UNION ALL
SELECT student_name, student_address FROM ( SELECT 'Raju' as student_name , 'Bandra' as student_address ) AS temp_2 WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Raju' ) )
alias_student_details

Output