C++ – AppDividend https://appdividend.com Latest Code Tutorials Wed, 18 Sep 2019 10:02:03 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png C++ – AppDividend https://appdividend.com 32 32 Do while Loop in C++ Example | C++ Do-while Loop Program https://appdividend.com/2019/09/18/do-while-loop-in-cpp-example-cpp-do-while-loop-program/ https://appdividend.com/2019/09/18/do-while-loop-in-cpp-example-cpp-do-while-loop-program/#respond Wed, 18 Sep 2019 09:58:36 +0000 http://localhost/wordpress/?p=11356 Do while Loop in C++ Example | C++ Do-while Loop Program

Do while Loop in C++ Example | C++ Do-while Loop Program is today’s topic. Before understanding do while loop, we must have an idea of what loops are and what it is used for. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute the […]

The post Do while Loop in C++ Example | C++ Do-while Loop Program appeared first on AppDividend.

]]>
Do while Loop in C++ Example | C++ Do-while Loop Program

Do while Loop in C++ Example | C++ Do-while Loop Program is today’s topic. Before understanding do while loop, we must have an idea of what loops are and what it is used for. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute the statement of codes repeatedly until a specific condition is satisfied. It eases the work of the programmer and also shortens the code length.

For example, if we want to print a table of particular numbers then with without loops, we had to do calculations multiple times and write different print statements, but with the help of loop, we can write 2-3  lines of code specifying the conditions for the table to print with different iterative variables. It eases the human effort to a very high extent.

Do while Loop in C++

Do while loops are used to iterate over a block of code multiple times. If we are not sure about the number of iterations, then it is of best practice to use the do-while loop.

There are three types of loops for loop, while loop and do-while loop. In this tutorial, we are going to learn about do-while loop.

Note: Do while loop is executed once always because in a do-while loop condition is checked after the loop body.

Syntax of the do-while loop

do
{
  // statements
} while(condition);

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.

See the formal example.

do
{
  cout << "Hello I am a variable and my value is:" << i << endl;
  i = i - 1;
} while (i > 0);

See the output.

Hello I am a variable and my value is:5
Hello I am a variable and my value is:4
Hello I am a variable and my value is:3
Hello I am a variable and my value is:2
Hello I am a variable and my value is:1

Here the first line gets printed without checking the condition. It only happens in the do-while loop.

Flow chart of a do-while loop

 

Do while Loop in C++ Example

Example program on do-while loops

Q1- Write a program to show the working of the do-while loop.

#include <iostream>
using namespace std;

int main()
{
  int i = 10;
  do
  {
    cout << "i= " << i << endl;
    i = i - 1;
  } while (i > 0);
}

See the output.

 

do-while loop

Q2- Print the table in descending order of 10 using the do-while loop.

#include <iostream>
using namespace std;

int main()
{
  int i = 10;
  do
  {
    cout << "10 x " << i << " = " << 10 * i << endl;
    i = i - 1;
  } while (i > 0);
}

See the output.

 

C++ Do-while Loop Program

C++ Nested do-while Loop

If you use a do-while loop inside another do-while loop, it is known as nested do-while loop.

The nested do-while loop is executed fully for each outer do-while loop.

Let’s see a simple example of a nested do-while loop in C++.

#include <iostream>
using namespace std;

int main()
{
  int i = 1;
  do
  {
    int j = 1;
    do
    {
      cout << i << "\n";
      j++;
    } while (j <= 3);
    i++;
  } while (i <= 3);
}

See the output.

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

C++ Infinitive do-while Loop

In C++, if you pass true in the do-while loop, it will be an infinitive do-while loop.

do
{    
  //code to be executed    
} while(true);  

See the following example.

#include <iostream>
using namespace std;

int main()
{
  do
  {
    cout << "Infinitive do-while Loop";
  } while (true);
}

See the output.

Infinitive do-while Loop 
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

Finally, Do while Loop in C++ Example | C++ Do-while Loop Program is over.

Recommended Posts

Data Types in C++ Example

C++ Namespace Example

Break Statement in C++ Example

C++ Switch Example

C++ While Loop Example

The post Do while Loop in C++ Example | C++ Do-while Loop Program appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/18/do-while-loop-in-cpp-example-cpp-do-while-loop-program/feed/ 0
Break Statement in C++ Example | C++ Break Statement Program https://appdividend.com/2019/09/18/break-statement-in-cpp-example-cpp-break-statement-program/ https://appdividend.com/2019/09/18/break-statement-in-cpp-example-cpp-break-statement-program/#respond Wed, 18 Sep 2019 08:41:42 +0000 http://localhost/wordpress/?p=11339 Break Statement in C++ Example | C++ Break Statement Program

Break Statement in C++ Example is today’s topic. The break statement is used to terminate the loop. When we use the break statement, the control from the loop iterations stops, and the control returns to the very first statement after the loop. The break; statement terminates a loop (for, while and do..while loop) and a switch statement immediately […]

The post Break Statement in C++ Example | C++ Break Statement Program appeared first on AppDividend.

]]>
Break Statement in C++ Example | C++ Break Statement Program

Break Statement in C++ Example is today’s topic. The break statement is used to terminate the loop. When we use the break statement, the control from the loop iterations stops, and the control returns to the very first statement after the loop. The break; statement terminates a loop (forwhile and do..while loop) and a switch statement immediately when it appears.

Break Statement in C++

We generally use break statements when we are not sure about how much time we want to iterate over a loop.

The break statement is used when we reach a particular condition for which we want to exit from the loop.

For example, I have a variable k whose value is 10. I am running a loop, and I want to return from the loop when the value of k becomes 5.

I have used a decrementing statement also inside the loop i.e k=k-1; Hence, when the when of k will be decremented to 5, I can use if condition there with a break statement inside to immediately exit the loop and the next statement after the loop.

The main application of the break statement is in the switch case.

Break statements are used in three kinds of loops:

Simple loops

In this break, statements are generally used to increase the efficiency of the program as we can take an example of searching an array. 

Nested loops

In case of nested loops if we use break statements only that particular loop will be exited that means if there is a break statement in the inner loop only the control will be exited from the inner loop, not from the outer loop.

Infinite loops

The break can be used in an infinite loop to stop the running of the infinite loop when a particular condition is reached.

Syntax of break statement

break;

In real practice, break statement is almost always used inside the body of the conditional statement (if…else) inside the loop.

See the following example.

for(int i=0;i<=5;i++)
{
	cout<<i<<endl;
			
	if(i==3)
	{
		break;
	}
	i=i+1;	
}

See the output.

0
1
2

Here we can see that run only runs three times as the value of i reaches 3 the break statement is executed, and the loop is terminated at that point.

Flow chart of break statement

 

Break Statement in C++ Example

Example programs on break statement

Q1- Write a program to show the mechanism of a break statement.

#include <iostream>
using namespace std;

int main()
{
  int k = 10;
  cout << "We will break from the loop when the value of variable k will be equal to 5" << endl;
  for (int i = 10; i > 0; i--)
  {
    if (k == 5)
    {
      break;
    }
    cout << "Value of k is: " << k << endl;
    k -= 1;
  }
  cout << "We breaked out from the loop!" << endl;
  return (0);
}

See the output.

 

Example programs on break statement

Q2-Write a program to break from an array search if the number is found.

#include <iostream>
using namespace std;
int main()
{
  int n, f;
  cout << "Enter the elements in array: ";
  cin >> n;
  int a[n];
  for (int i = 0; i < n; i++)
  {
    cout << "Enter element number " << i + 1 << "=";
    cin >> a[i];
  }
  cout << "Enter the number you want to search:";
  cin >> f;
  for (int i = 0; i < n; i++)
  {
    if (a[i] == f)
    {
      cout << "Element found at index:" << i << endl;
      break;
      cout << "We used break so that this line won't run" << endl;
    }
  }
  cout << "Holla !! We breaked out from the loop as soon as we found the element" << endl;
  return (0);
}

See the output.

 

C++ Break Statement Program

Example: break statement in Switch Case

We have already discussed the Switch Case on this blog.

#include <iostream>
using namespace std;

int main()
{
  int num = 11;
  switch (num)
  {
  case 21:
    cout << "Case 1 " << endl;
    break;
  case 11:
    cout << "Case 11 " << endl;
    break;
  case 10:
    cout << "Case 3 " << endl;
    break;
  default:
    cout << "Default " << endl;
  }
  cout << "Hey, I'm out of the switch case";
  return 0;
}

See the output.

Case 11 
Hello, I am from Stranger Things

In this example, we have a break statement after each Case block, and this is because if we don’t have it, then the subsequent case block would also execute.

Finally, the Break Statement in C++ Example | C++ Break Statement Program is over.

Recommended Posts

Constructor Overloading in C++

Function Overloading in C++ Tutorial With Example

C++ Friend Function Example

C++ Destructor Example

C++ String Class Tutorial

The post Break Statement in C++ Example | C++ Break Statement Program appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/18/break-statement-in-cpp-example-cpp-break-statement-program/feed/ 0
Switch case in C++ Program | C++ Switch Example https://appdividend.com/2019/09/14/switch-case-in-cpp-program-cpp-switch-example/ https://appdividend.com/2019/09/14/switch-case-in-cpp-program-cpp-switch-example/#respond Sat, 14 Sep 2019 11:08:28 +0000 http://localhost/wordpress/?p=11240 Switch case in C++ Program | C++ Switch Example

Switch case in C++ Program | C++ Switch Example is today’s topic. Switch case is prolonged if-else conditions like we have many conditions, and we need to perform different actions based on that condition. Switch case statements are used if we want a particular block of code to run only if a specific condition is […]

The post Switch case in C++ Program | C++ Switch Example appeared first on AppDividend.

]]>
Switch case in C++ Program | C++ Switch Example

Switch case in C++ Program | C++ Switch Example is today’s topic. Switch case is prolonged if-else conditions like we have many conditions, and we need to perform different actions based on that condition. Switch case statements are used if we want a particular block of code to run only if a specific condition is satisfied. We have already seen the For loop and while loop in C++.

Switch case in C++

Switch case is used at the place of lengthy if-else. It is because of increased complexity in the case of nested if-else as a lot of parenthesis and conditions deteriorate the neatness of the code and makes it hard to understand.

Syntax of switch case in C++

switch(expression)
{
	case constant:			
			//code block
	case constant:			
			//code block
	case constant:			
			//code block
	default:  
			//code block
}

See the code.

int a=2;
switch(a)
{
  case 1:  	cout<<"Hello I am case one!"<<endl;
		break;
  case 2: 	cout<<"Hello I am the case two!"<<endl;
		break;
  case 3: 	cout<<"Hello I am case three!"<<endl;
		break;
  default: 	cout<<"Hello I am default"<<endl;
}

See the following output.

Hello, I am case two!

Explanation: In the above code, I have passed an in the switch statement. The value of a there is two hence case 2 gets executed over there;

Note:

It is essential to use break statement in all the cases except the default as if we don’t write break in each case statement all the following case gets executed. For example, in the above code, if we don’t write a break in each case statement, we will get the following output.

Hello I am case two!
Hello, I am case three!
Hello, I default!

Hence, writing a break in every case statement is essential as it takes us out of the switch case after the execution of that particular case which is the requirement of the question.

Flowchart of the Switch case

 

Switch case in C++ Program

Note: The variable used in the switch case must be one of the following from short,

byte, int, char. The values of each case must be the same datatype as of the variable.

Essential Points about Switch Case Statements

  1. Duplicate case values are not allowed.
  2. An expression provided in a switch should result in the constant value; otherwise, it would not be valid.
  3. The default statement is optional. Even if the switch case statement does not have the default statement, it would run without any error.
  4. A break statement is used inside a switch to terminate the statement sequence. When the break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  5. The break statement is optional. If omitted, execution will continue into the next case. A flow of control will fall through to subsequent cases until a break is reached.
  6. Nesting of switch statements is allowed, which means you can have the switch statements inside another switch statement. However, the nested switch statements should be avoided as it makes a program more complex and less readable.

Example programs of switch case

Q1- Write a program to demonstrate the mechanism of switch case.

#include<iostream>
using namespace std;
int main(){
	
char a ='c';
switch(a)
{
 case 'a':  	
	cout<<"Case 1"<<endl;
	break;
 case 'b': 	
	cout<<"Case 2"<<endl;
	break;
 case 'c': 	
	cout<<"Case 3"<<endl;
	break;
 default: 	
	cout<<"Default case"<<endl;
 }
 return 0;
}

See the output.

 

Example programs of switch case

Q2- Write a program to do addition, subtraction, multiplication using switch case. 

#include<iostream>
using namespace std;
int main(){
	
char x ='c';
int a=5,b=6,d;
switch(x)
{
  case 'a':  	
		d=a+b;
		cout<<"The value of addition is= "<<d<<endl;
		break;
  case 'b': 	
		d=b-a;
		cout<<"The value of substraction is= "<<d<<endl;
		break;
  case 'c': 
		d=b*a;	
	cout<<"The value of multiplication is= "<<d<<endl;
	break;
  default: 	
	cout<<"Default case"<<endl;
  }
  return 0;
}

See the output.

 

C++ Switch Example

Finally, Switch case in C++ Program | C++ Switch Example is over.

Recommended Posts

C++ Array Tutorial With Example

C++ Lambda Function Tutorial

C++ Iterators Tutorial With Example

C++ List Tutorial With Example

C++ Constructor Tutorial With Example

The post Switch case in C++ Program | C++ Switch Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/14/switch-case-in-cpp-program-cpp-switch-example/feed/ 0
While Loop in C++ Program | C++ While Loop Example https://appdividend.com/2019/09/14/while-loop-in-cpp-program-cpp-while-loop-example/ https://appdividend.com/2019/09/14/while-loop-in-cpp-program-cpp-while-loop-example/#respond Sat, 14 Sep 2019 10:01:20 +0000 http://localhost/wordpress/?p=11226 While Loop in C++ Program | C++ While Loop Example

While Loop in C++ Program | C++ While Loop Example is today’s topic. For understanding while loop, we must have prior knowledge of loops in C++. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute a statement of codes repeatedly until a specific condition […]

The post While Loop in C++ Program | C++ While Loop Example appeared first on AppDividend.

]]>
While Loop in C++ Program | C++ While Loop Example

While Loop in C++ Program | C++ While Loop Example is today’s topic. For understanding while loop, we must have prior knowledge of loops in C++. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute a statement of codes repeatedly until a specific condition is satisfied. It eases the work of the programmer and also shortens the code length. We have already seen For loop.

While Loop in C++ Program

For example, if we want to print a table of a particular number, we can directly do it with 3-4 lines of code using the loop.

The problem with loops is that it increases the complexity of the code and sometimes we work for an optimized code then we are supposed to look at different methods by which we can solve that problem by using loops.

The thing with the loop is that we have to give parameters of the loop, which includes iterative conditions that are different for different kinds of loops. We need to run the loop and provide iteration conditions.

There are 3 types of loops for loop, while loop and do-while loop. In this tutorial, we will learn about while loop.

While loops are used for executing a block of code repeatedly until the condition returns false.

The syntax for while loop

while(condition)
{
	// Statements
}

See the following code.

k=5;
while(k!=0)
{	cout<<k<<endl;
	k=k-1
}

The above example will print the value of k starting from 5 until it’s value becomes 0 in a new separated line every time.

Flow chart of while loop

 

While Loop in C++ Program

Working of while loop

While loops first evaluate the condition and if it returns true, then the programming statements which are inside the loop get executed. This keeps on going until the condition inside while loop returns false.

When the condition returns false, the control comes out of the loop.

Difference between for loop and while loop:

The main difference between for loop and while loop is that in while loop we are supposed to use increment and decrement counter inside the loop so that the loop variables get changed on each iteration, and after successfully running the loop it returns true whereas in for loop we use increment and decrement counter in the parameter section of the code.

Let’s see the following example.

In case of for loop:  for(int i=0;i<5;i++)

In case of while loop:

while(k!=0)
{     
   cout<<k<<endl;
   k=k-1;
}

Example program for while loop in C++

Q1- Write a program to show the mechanism of a while loop.

#include<iostream>
using namespace std;
int main()
{
	int t=5;
	cout<<"Hello I am going to print the value of variable t in decending order"<<endl;
	while(t!=0)
	{
		cout<<t<<endl;
		t=t-1;
	}
	return(0);
}

See the following output.

 

Example program for while loop in C++

Q2- Write a program to print the table of 10 using a while loop.

#include<iostream>
using namespace std;
int main()
{
		int t=1,k=10;
		cout<<"Table of 10"<<endl;
		while(t!=11)
		{
			cout<<"10 X "<<t<<"="<<k*t<<endl;
			t=t+1;
		}
		return(0);
}

See the output.

 

while loop tutorial

Infinite While loop

The while loop that never stops, is said to be an infinite while loop, when we give a condition in such a way so that it never returns false, then a loop becomes an infinite and repeats itself indefinitely.

An example of infinite while loop:
While loop would never end as I’m decrementing the value of i, which is one so the condition i<=6 would never return false.

#include <iostream>
using namespace std;
int main(){
   int i=1; while(i<=6) {
      cout<<"Value of variable i is: "<<i<<endl; i--;
   }
}

Displaying the items of an array using a while loop

See the following code that displays the elements of an array using a while loop.

#include <iostream>
using namespace std;
int main(){
   int arr[]={21,87,15,99, -12};
   /* The array index starts with 0, the
    * first element of array has 0 index
    * and represented as arr[0]
    */
   int i=0;
   while(i<5){
      cout<<arr[i]<<endl;
      i++;
   }
}

See the output.

21
87
15
99
-12

Finally, While Loop in C++ Program | C++ While Loop Example is over.

Recommended Posts

C++ Friend Function Example

C++ Destructor Example

C++ String Class Tutorial

C++ Structure Example

Virtual Function in C++ Example

The post While Loop in C++ Program | C++ While Loop Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/14/while-loop-in-cpp-program-cpp-while-loop-example/feed/ 0
For loop in C++ Program | C++ For Loop Example https://appdividend.com/2019/09/14/for-loop-in-cpp-program-cpp-for-loop-example/ https://appdividend.com/2019/09/14/for-loop-in-cpp-program-cpp-for-loop-example/#respond Sat, 14 Sep 2019 08:56:18 +0000 http://localhost/wordpress/?p=11210 For loop in C++ Program | C++ For Loop Example

For loop in C++ Program | C++ For Loop Example is today’s topic. For understanding for loop, we must have prior knowledge of loops in C++. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute the statement of codes repeatedly until a specific condition […]

The post For loop in C++ Program | C++ For Loop Example appeared first on AppDividend.

]]>
For loop in C++ Program | C++ For Loop Example

For loop in C++ Program | C++ For Loop Example is today’s topic. For understanding for loop, we must have prior knowledge of loops in C++. Loops are used when we want a particular piece of code to run multiple times. We use loops to execute the statement of codes repeatedly until a specific condition is satisfied. It eases the work of the programmer and also shortens the code length.

For loop in C++ Program

For example, if we want to print numbers from 1 to 1000, then if we don’t use loops, we have to write 1000 different print statements for printing numbers from 1 to 1000. With the help of loops, we can write this code in 2 lines. We need to run the loop and give iteration conditions.

There are 3 types of loops for loop, while loop and do-while loop. In this tutorial, we will learn about for loop.

A for loop is the repetition control structure that is generally used to write a code more efficiently which is supposed to be executed a specific number of times.

How for loop works

  1. An initialization statement is executed only once at a beginning.
  2. Then, test expression is evaluated.
  3. If a test expression is false, then for loop is terminated. But if a test expression is true, codes inside the body of for loop is executed, and update expression is updated.
  4. A test expression is evaluated, and this process repeats until the test expression is false.

Syntax of for loop

for(initialization; condition; increment/decrement)
{
	//statements
}

See the following example.

for(int i=1;i<=100;i++)
{
	cout<<i<<endl;
}

Explanation: The above code will print numbers from 1 to 100.

Flow chart of for loop

 

For loop in C++ Program

Parameters of for loop

for(initialization; condition; increment/decrement)
{
	// Statements
}

The initialization step is executed to initialize the program counter it done once only. The program counter is also known as loop control variables.

The next parameter is the condition where the condition is checked for which the loop is supposed to run.

After that, there is an increment/decrement counter which increases or decreases the counter once the statements are executed.

Example program of for loop in C++

Q1- Write a program to show the mechanism the for loop.

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print numbers from 1 to 20 using for loop"<<endl;
	for(int i=1;i<=20;i++)
	{
		cout<<"The number is:"<<i<<endl;
	}
	return 0;
	
}

See the output.

Example program of for loop in C++

 

Q2-Write a program to print all the even numbers from 1 to 20 using for loop.

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print even numbers from 1 to 100 using for loop"<<endl;
	for(int i=2;i<=100;i=i+2)
	{
		cout<<"The even number is:"<<i<<endl;
	}
	return 0;
	
}

 

 

See the output.

C++ For Loop

Q3- Write a program to print all the odd numbers from 1 to 100 using for loop.

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print odd numbers from 1 to 100 using for loop"<<endl;
	for(int i=1;i<=100;i=i+2)
	{
		cout<<"The odd number is:"<<i<<endl;
	}
	return 0;
	
}

See the output.

 

C++ For Loop Example

Infinite for loop in C++

The loop is said to be infinite when it executes repeatedly and never stops. It usually happens by mistake. When you set a condition in for loop in such a way that it never returns false, it becomes the infinite loop.

See the following example.

#include <iostream>
using namespace std;
int main(){
   for(int i=1; i>=1; i++){
      cout<<"Value of variable i is: "<<i<<endl;
   }
   return 0;
}

It is an infinite loop as we are incrementing a value of i so it would always satisfy the condition i>=1, the condition would never return false.

Here is another example of an infinite loop.

// infinite loop
for ( ; ; ) {
   // statement(s)
}

Display elements of an array using for loop

See the following program that displays items of an array using for loop.

#include <iostream>
using namespace std;
int main(){
   int arr[]={21,9,56,99, 202};
   /* We have set the value of variable i
    * to 0 as the array index starts with 0
    * which means the first element of array 
    * starts with zero index.
    */
   for(int i=0; i<5; i++){
      cout<<arr[i]<<endl;
   }
   return 0;
}

See the following output.

21
9
56
99
202

Finally, For loop in C++ Program | C++ For Loop Example is over.

Recommended Posts

If-else Statements in C++ Example Tutorial

C++ Recursion Example

C++ Inline Functions Example

Access Specifiers in C++ Example

Scope Resolution Operator in C++ Example Tutorial

The post For loop in C++ Program | C++ For Loop Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/14/for-loop-in-cpp-program-cpp-for-loop-example/feed/ 0
C++ If-else Statements Example https://appdividend.com/2019/09/05/c-if-else-statements-example/ https://appdividend.com/2019/09/05/c-if-else-statements-example/#respond Thu, 05 Sep 2019 10:16:13 +0000 http://localhost/wordpress/?p=11071 If-else Statements in C++ Example Tutorial

If-else Statements in C++ Example Tutorial is today’s topic. When we need to execute a particular block of code only when a condition is met, we use if-else statements. When we execute statements on conditions, we call it decision making in C++. For decision making, there are four types of control statements named: If statements […]

The post C++ If-else Statements Example appeared first on AppDividend.

]]>
If-else Statements in C++ Example Tutorial

If-else Statements in C++ Example Tutorial is today’s topic. When we need to execute a particular block of code only when a condition is met, we use if-else statements. When we execute statements on conditions, we call it decision making in C++. For decision making, there are four types of control statements named:

  1. If statements
  2. If else statements
  3. Nested if statements
  4. Nested if-else statements

If statements

This block of code is only executed when a condition in if block is true for every other condition the block of code doesn’t execute.

#Syntax for if statements

if(condition)
{
	block of code(statements);
}

Example

if(input_string="HI")
{
	cout<<"Hello";
}

Real-life example

Suppose we want to go out for a movie the first thing we will check before moving out is if it is raining or not(if condition) if it is raining we will not go to watch the movie(blocks inside if condition didn’t run because it is raining outside and the condition is not met).

If else statements:

The main block of code is executed if the condition inside if block is met otherwise the statements of else block gets executed automatically.

Syntax:

if(condition)
{
	statements;
}
else
{
	statements;
}

Example:

int a=5;
if(a>5)
{
	cout<<"a is greater than 5"<< endl;
}
else
{
	cout<<"a is less than 5"<< endl;
}

Real-life example

Suppose it is raining outside and if it is raining heavily we wear a raincoat otherwise we can go for an umbrella.

Nested if statements

When there is an if condition inside an if condition we call it nested if-else statements.

Syntax

if(condition)
{
	if(condition)
	{
		statements;
	}
}

Example

a=5;
if(a>0)
{
	cout<<"a is greater than 0"<<endl;
	if(a==5)
	{
		cout<<"a is equal to 5"<<endl;
	}
}

Real-life example

Suppose it is raining outside I will decide to go out only if it is raining slowly.

Nested if-else

We use nested if-else to check the multiple conditions. In the control structure, there is only one if or one else, but inside that, there are more if-else conditions present to check the hierarchy of conditions.

Syntax:

if(condition)
{
	statements;
}
else
{
	if(condition)
	{	
		statements;
	}
	else
	{
		statements;
	}
}

See the following example.

a=5;
if(a>0)
{
	if(a=5)
	{
		cout<<"Value of a is"<<a<<endl;
	}
	else
	{
		cout<<"Value of a is positive but not equal to 5"<<endl;
	}
}

Real-world example:

If we are going for a football match and we see Lionel Messi playing, we will support that team.

Flowchart

Control statements are a fundamental part of any programming language, and everyone should know of it to understand the mechanism of how the code is working and how one can change to code and give it a direction where we can reach a solution.

Flowchart

Example programs

Write a program to show the mechanism of only if statements.

#include<iostream>
using namespace std;
int main()
{
	int var=1;
	if(var==1)
	{
		cout<<"Hello everyone"<<endl;
	}
}

See the output.

 

Example programs

Write a program to show a mechanism of nested if statements.

#include<iostream>
using namespace std;
int main()
{
	int var=5;
	if(var>0)
	{
		if(var==5)
		{
			cout<<"Hello I am a positive number and my value is 5";
		}
	}
}

See the output.

 

If-else Statements in C++

Write a program to show the mechanism of if-else statements.

#include<iostream>
using namespace std;
int main()
{
	int var=5;
	if(var>0)
	{
		cout<<"Hello I am positive number"<<endl;
	}
	else
	{
		cout<<"Hello I am negative number"<<endl;
	}
}

See the output.

 

Write a program to show the mechanism of if-else statements.

Write a program to show the mechanism of nested if-else statements.

#include<iostream>
using namespace std;
int main()
{
	int var;
	cin>>var;
	if(var>0)
	{
		cout<<"Hello I am positive number"<<endl;
		if(var==5)
		{
			cout<<"hello I am positive and my value is 5"<<endl;
		}
		else
		{
				cout<<"Hello I am positive and my value is not equal to 5"<<endl;
		}
	}
	else
	{
		cout<<"Hello I am negative number"<<endl;
	}
	
}

See the output.

 

If statements in C++

Finally, If-else Statements in C++ Example Tutorial is over.

Recommended Posts

Multithreading In C++ Example Tutorial

Queues in C++ Example | C++ Standard Template Library

Multiple Multilevel and Hierarchical Inheritance in C++ Example

C++ Recursion Example | Recursion Program In C++ Tutorial

C++ Insertion Sort Example | Insertion Sort Program In C++

Polymorphism in C++ Example | C++ Polymorphism Tutorial

C++ Heap Sort Example | Heap Sort Program In C++

The post C++ If-else Statements Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/05/c-if-else-statements-example/feed/ 0
Multithreading In C++ Example | C++ Multithreading Tutorial https://appdividend.com/2019/08/21/multithreading-in-cpp-example-cpp-multithreading-tutorial/ https://appdividend.com/2019/08/21/multithreading-in-cpp-example-cpp-multithreading-tutorial/#respond Wed, 21 Aug 2019 07:57:23 +0000 http://localhost/wordpress/?p=10807 Multithreading In C++ Example | C++ Multithreading Tutorial

Multithreading In C++ Example Tutorial is today’s topic. Multithreading is a type of model which at the time of execution allows multiple threads to exist within the context of the process such that they execute independently, but they share the process resource. A thread is the smallest sequence of programming instructions that can be managed […]

The post Multithreading In C++ Example | C++ Multithreading Tutorial appeared first on AppDividend.

]]>
Multithreading In C++ Example | C++ Multithreading Tutorial

Multithreading In C++ Example Tutorial is today’s topic. Multithreading is a type of model which at the time of execution allows multiple threads to exist within the context of the process such that they execute independently, but they share the process resource. A thread is the smallest sequence of programming instructions that can be managed by the scheduler. Running threads in parallel can increase the efficiency of programs.

Multithreading In C++

Multithreading is a technoscientific form of multitasking, and multitasking is a characteristic that allows the computer to run two or more programs simultaneously. Mainly, there are two types of multitasking:

1) process-based multitasking

2) thread-based multitasking.

Process-based multitasking controls the parallel execution of programs.

Thread-based multitasking deals with a concurrent execution of parts of the same program.

A multithreaded program contains two or more elements that can run concurrently. Each part of such a program is called the thread, and each thread defines a separate path of execution.

Multithreading support was introduced in C+11.  The std::thread is the thread class that describes a single thread in C++.

If we want to start a thread, we need to create the new thread object and pass the executing code to be called (i.e., a callable object) into the constructor of the object. Once the object is created the new thread.

#Multithreading in different systems

Multithreading in multicore and multiprocessor systems indicates that different threads are executed at the same time on different processors.

Multithreading in single-core systems divides the time between the different threads.

The operating system sends a certain number of instructions from different threads to the processor. Threads are not executed concurrently but in different time slots.

Operating System only exaggerates their simultaneous execution. This feature of an operating system is called multithreading.

#Syntax for creating a thread

It is essential to include the following header file.

#include<thread>

To create a thread, we have to create the object of the Thread class.

thread  thread_1;

#Example for creating and initializing a thread

See the following code file.

#include <iostream>
#include <thread>
using namespace std;

void threadFunction()
{
  cout << "Hello I am multithread How are you?" << endl;
}

int main()
{
  //pass a function to thread
  thread fun_1(threadFunction);
  fun_1.join();
  return (0);
}

See the output.

 

Multithreading In C++

Here in the output, we can see it shows an error. It’s because the main thread finishes before the fun_1 finishes.

If we want to remove the error, we can use the join() function as it will wait for all the running threads to complete before ending the main thread.

#Joining threads

Usually, we join two or more threads with join() function of the thread class.

The function only executes when all the threads except main thread are finished. It means that a main thread will wait until the child thread does not finish its execution.

Once the join() function returns anything, the threads become not joinable.

The thread is not joinable when it is default constructed or is moved/assigned to another thread or join() or detach() the member function is called.

To check if the thread is joined or not we use the joinable() function. It returns true if the function is joined and false if the function is not joined.

#Detaching threads

We use detach() function for detaching threads.

This function detaches the thread from a parent thread. It allows the parent and child threads to be executed independently from each other.

#Passing arguments to a thread

We can use the function with parameters for thread initialization. See the following code example.

void fun_1(int x, float y, char *z)
{
  cout << "The value of integer variable" << x << endl;
  cout << "The value of float variable" << y << endl;
  cout << "The char variable=" << z << endl;
}

The above function takes three arguments. If we want to initialize a thread with this function, first we have to pass the pointer to this function, then pass the parameters to the function in the same order as they are in the parameter list of a function. It can be done in the following way(continuing the above example).

char *z = "AppDividend";

  thread var_1(fun_1, 5, 4.2, z);
  if (var1.joinable())
    var_1.join();

Every thread has a unique identifier which is identified with the help of thread ID.

#Example Program of Multithreading in C++

See the following code.

#include <iostream>
#include <thread>
using namespace std;

void threadFunc()
{
  cout << "Hello I am multithread How are you?" << endl;
}

int main()
{
  //pass a function to thread
  thread funcTest1(threadFunc);
  funcTest1.detach();
  if (funcTest1.joinable())
  {
    //main is blocked until funcTest1 is not finished
    funcTest1.join();
  }
  else
  {
    cout << "The function is detached now" << endl;
  }
}

See the output.

 

Program of Multithreading in C++

#Create three threads and print a message from each thread in C++

See the following code.

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void *Printmsg(void *thread_id)
{
  long t_id;
  t_id = (long)thread_id;
  cout << "I am a thread and my Thread ID is: " << t_id << endl;
  pthread_exit(NULL);
}

int main()
{
  pthread_t threads[NUM_THREADS];
  int k;
  int i;

  for (i = 0; i < NUM_THREADS; i++)
  {
    cout << "main() : creating thread, " << i << endl;
    k = pthread_create(&threads[i], NULL, Printmsg, (void *)i);

    if (k)
    {
      cout << "Error:unable to create thread," << k << endl;
      exit(-1);
    }
  }
  pthread_exit(NULL);
}

See the output.

 

C++ Multithreading Tutorial

Finally, Multithreading In C++ Example | C++ Multithreading Tutorial is over.

The post Multithreading In C++ Example | C++ Multithreading Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/21/multithreading-in-cpp-example-cpp-multithreading-tutorial/feed/ 0
Queues in C++ Example | C++ Standard Template Library https://appdividend.com/2019/08/20/queues-in-c-example-c-standard-template-library/ https://appdividend.com/2019/08/20/queues-in-c-example-c-standard-template-library/#respond Tue, 20 Aug 2019 08:09:53 +0000 http://localhost/wordpress/?p=10758 Queues in C++ Example | C++ Standard Template Library

Queues in C++ Example | C++ Standard Template Library is today’s topic. Queues are an abstract data structure which follows the FIFO algorithm, i.e. the data item which is put first in the queue will be accessed first. Queues are open at both the ends, unlike stacks which are open at only one end.   […]

The post Queues in C++ Example | C++ Standard Template Library appeared first on AppDividend.

]]>
Queues in C++ Example | C++ Standard Template Library

Queues in C++ Example | C++ Standard Template Library is today’s topic. Queues are an abstract data structure which follows the FIFO algorithm, i.e. the data item which is put first in the queue will be accessed first. Queues are open at both the ends, unlike stacks which are open at only one end.

 

Queues in C++ Example

Queues in C++

Queues are the type of container adaptor, specifically designed to operate in a FIFO context (first-in-first-out), where items are inserted into one end of the container and extracted from the other container.

Queues are implemented as containers adaptors, which are classes that use the encapsulated object of the specific container class as its underlying container, providing the particular set of member functions to access its items. Items are pushed into a “back” of the specific container and popped from its “front”.

We can create a queue in C++ with the following syntax.

queue<data_type>queue_name

For example   queue<int>queue1;

It is also important to add header file #include<queue>

Elements in the queue are inserted at the back end and are deleted from the front end.

In STL there are many functions supported by queues some of them are listed below.

The functions supported by the queue are the following.

#empty() 

An empty function is used to check whether the queue is empty or not.

Syntax:  

queue_name.empty()

An empty() function returns true if the queue is empty or false if the list is not empty.

Note:  There is no parameter passed in the empty function. If we pass any parameter, it will show an error.

#size()

The size() function is used to find the size of the queue.

Syntax:   

queue_name.size()

The size() function returns a number of elements present in the queue.

Note: There is no parameter passed in the size function. If we pass any parameter, it will show an error.

#swap()

The swap() function is used to swap the elements of two different queues of the same type.

Syntax:

queue_name1.swap(queue_name2)

There is no return value the operation swaps the elements of queue_name1 to queue_name2.

Note: It is essential to have the queues of the same type length of the queues can be variable.

#emplace()

Emplace function is used to insert a new element in the queue.

Syntax:

queue_name.emplace(value)

Value parameter holds the value of the element which we want to add to the queue.

The element is added at the back end of the queue.

Note: It is important to have the value parameter of the same type of elements already present in the queue.

#front()

The front function is used to access the oldest element present in the queue or the element at the front end. As queues follow first come first out hence it access the first element. 

Syntax: 

queue_name.front()

There is no parameter in the front function.

Note: If the queue is empty, the front function shows an undefined behavior.

#back()

The back function is used to fetch the first element from the back end of the latest insertion in the queue.

Syntax

queue_name.back()

There is no parameter in the back function.

Note: If the queue is empty, the front function shows an undefined behavior.

#push()

The push() function is used to insert an item in the queue from the back end.

Syntax:

queue_name.push(value)

The parameter in the push function is the value we want to push in the queue.

Note: It is important to have the value of the same type as of the already existing elements.

#pop()

The pop function is used to remove an element from the queue.

Syntax:

queue.name.pop()

It removes the oldest element present in the queue of the front element of the queue.

Note: It will show an error if the parameter is passed in the pop function.

#Examples of queues in STL

Write a program to insert three elements in a queue using emplace function and check if the queue is empty or not. Print a string to show if the queue is empty or not.

#include <iostream>
#include <queue>
using namespace std;
int main()
{
  queue<int> queue1;
  queue1.emplace(1);
  queue1.emplace(2);
  queue1.emplace(3);

  if (queue1.empty())
  {
    cout << "The queue is empty";
  }
  else
  {
    cout << "The queue is not empty";
  }
  return 0;
}

See the following output.

 

Queues in C++

Example2: Write a program to add five elements in the queue using push function and remove one element using pop function and print the queue afterward.

#include <iostream>
#include <queue>
using namespace std;

int main()
{
  queue<int> queue2;
  queue2.push(0);
  queue2.push(1);
  queue2.push(2);
  queue2.push(3);
  queue2.push(4);
  // queue has element 0,1,2,3,4

  queue2.pop();

  // after poping one element queue becomes 0,1,2,3

  // Printing queue elements
  cout << "Elements of the queue are:";
  while (!queue2.empty())
  {
    cout << ' ' << queue2.front();
    queue2.pop();
  }
}

See the following output.

 

Examples of queues in STL

Example3: Write a program to print the size of the queue, the front element of the queue, and the back element of the queue.

#include <iostream> 
#include <queue> 
using namespace std; 
  
int main() 
{ 
    queue<int> queue3; 
    queue3.push(0); 
    queue3.push(1); 
    queue3.push(2);
	queue3.push(3);
	queue3.push(4);
	
	cout<<"Size of the queue is: "<<queue3.size()<<endl;
	cout<<"The element at the front is:"<<queue3.front()<<endl;
	cout<<"The element at the back is:"<<queue3.back()<<endl;	
	return(0);
}

See the following output.

 

C++ Standard Template Library

Example4: Create two queues add elements to both the queues and swap the queues and print the swapped queues.

#include <iostream>
#include <queue>
using namespace std;

int main()
{
  queue<int> queue2;
  queue<int> queue1;
  queue1.push(0);
  queue1.push(1);
  queue1.push(2);
  queue1.push(3);
  queue1.push(4);

  queue2.push(5);
  queue2.push(6);
  queue2.push(7);
  queue2.push(8);
  queue2.push(9);

  queue1.swap(queue2); //Swapping

  cout << "Elements of queue1 after swapping are:";
  while (!queue1.empty())
  {
    cout << queue1.front() << " ";
    queue1.pop();
  }

  // Print the second set
  cout << endl
       << "Elements of queue2 after swapping are:";
  while (!queue2.empty())
  {
    cout << queue2.front() << " ";
    queue2.pop();
  }

  return 0;
}

See the output.

 

Standard Template Library in C++

At last, Queues in C++ Example | C++ Standard Template Library is over.

The post Queues in C++ Example | C++ Standard Template Library appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/20/queues-in-c-example-c-standard-template-library/feed/ 0
Multiple Multilevel and Hierarchical Inheritance in C++ Example https://appdividend.com/2019/08/19/multiple-multilevel-and-hierarchical-inheritance-in-cpp-example/ https://appdividend.com/2019/08/19/multiple-multilevel-and-hierarchical-inheritance-in-cpp-example/#respond Mon, 19 Aug 2019 10:06:37 +0000 http://localhost/wordpress/?p=10729 Multiple Multilevel and Hierarchical Inheritance in C++ Example

Multiple Multilevel and Hierarchical Inheritance in C++ Example is today’s topic. Before getting started with Multiple, Multilevel, and Hierarchical inheritance, it is essential to understand inheritance. Inheritance allows properties of the base class to be used in the derived class. It is a necessary feature of object-oriented programming. In more technical words we can say […]

The post Multiple Multilevel and Hierarchical Inheritance in C++ Example appeared first on AppDividend.

]]>
Multiple Multilevel and Hierarchical Inheritance in C++ Example

Multiple Multilevel and Hierarchical Inheritance in C++ Example is today’s topic. Before getting started with Multiple, Multilevel, and Hierarchical inheritance, it is essential to understand inheritance. Inheritance allows properties of the base class to be used in the derived class. It is a necessary feature of object-oriented programming. In more technical words we can say that when an object of base class acquires all the properties of the parent object automatically and we can access the features of the parent class with the help of child’s object then it is an inheritance.

Multiple Inheritance in C++

When a derived class is derived from more than one base class, it is known as multiple inheritance.

 

Multiple Inheritance

In the above example, we can see that the child is derived from both the parents.

There is an ambiguity in multiple inheritance which occurs at the time of function overriding. For example, two-parent classes have the same function which is not overridden in the child class, and if we try to call the function using the object of the child class, it shows in compiler error as the compiler doesn’t know which function to call. (Example program in the last).

#Multilevel Inheritance in C++

When one class inherits the properties of another class, which is further inherited by another class, it is known as multilevel inheritance.

 

Multilevel Inheritance in C++

In the above example, we can see that the child is derived from parents and parents are further derived from grandparents; hence, they show multilevel inheritance.

The level of inheritance can be extended to any number depending upon the relation.

See examples at last for better understanding.

#Hierarchical Inheritance in C++

It is an inheritance in which we usually derive more than one derived class from a particular base class.

 

Multiple Multilevel and Hierarchical Inheritance

In the above example, we can see that Civil, CSE, and Mechanical are hierarchically derived from Engineering itself, which shows hierarchical inheritance.

#Programs of Multiple, Multilevel and Hierarchical Inheritance in C++

Write a program to show a mechanism of Multiple Inheritance.

#include <iostream>
using namespace std;

class patna
{ //Creating base class of patna
public:
  patna()
  {
    cout << "Hello I am from base class of Patna !! " << endl;
  }
};

class delhi
{
public:
  delhi()
  {
    cout << "Hello I am from base class of Delhi" << endl; //creating base class of delhi
  }
};

class check : public patna, public delhi //derived class of two base classes
{
public:
  void check_fun()
  {
    cout << "hello I am derived class function" << endl;
  }
};

int main()
{
  check obj;
  obj.check_fun();
  return 0;
}

See the following output.

 

Multiple Inheritance Program

Write the program to show the mechanism of Multilevel Inheritance.

#include <iostream>
using namespace std;

class city
{
public:
  city()
  {
    cout << "Hello I am the 1st base class of cities" << endl;
  }
};
class delhi : public city
{
public:
  delhi()
  {
    cout << "Hello I am the capital of India Delhi" << endl;
  }
};
class location : public delhi
{
public:
  location()
  {
    cout << "I am vasant kunj(location) in Delhi" << endl;
  }
};

// main function
int main()
{
  location obj;
  return 0;
}

See the following output.

 

Multilevel Inheritance Program

Write a program to show the mechanism of Hierarchical Inheritance.

#include <iostream>
using namespace std;

class city
{
public:
  city()
  {
    cout << "I am the base class of cities" << endl;
  }
};

class delhi : public city
{
public:
  void check_1()
  {
    cout << "I am the capital of India Delhi" << endl;
  }
};

class mumbai : public city
{
public:
  void check_2()
  {
    cout << "I am the city of dreams Mumbai" << endl;
  }
};

int main()
{
  delhi obj1;
  mumbai obj2; //constructor will be called two times as both the objects will call the constructor of the base class.
  obj1.check_1();
  obj2.check_2();

  return 0;
}

See the following output.

 

Hierarchical Inheritance Program

Finally, Multiple Multilevel and Hierarchical Inheritance in C++ Example is over.

The post Multiple Multilevel and Hierarchical Inheritance in C++ Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/19/multiple-multilevel-and-hierarchical-inheritance-in-cpp-example/feed/ 0
C++ Recursion Example | Recursion Program In C++ Tutorial https://appdividend.com/2019/08/17/cpp-recursion-example-cpp-recursion-program-tutorial/ https://appdividend.com/2019/08/17/cpp-recursion-example-cpp-recursion-program-tutorial/#respond Sat, 17 Aug 2019 08:59:33 +0000 http://localhost/wordpress/?p=10687 C++ Recursion Example | Recursion Program In C++ Tutorial

C++ Recursion Example | Recursion Program In C++ Tutorial is today’s topic. When a function calls itself, it is known as recursion. The function which calls the function itself is known as a recursive function. The main aim of recursion is to break a bigger problem into a smaller problem. Base case solutions are usually […]

The post C++ Recursion Example | Recursion Program In C++ Tutorial appeared first on AppDividend.

]]>
C++ Recursion Example | Recursion Program In C++ Tutorial

C++ Recursion Example | Recursion Program In C++ Tutorial is today’s topic. When a function calls itself, it is known as recursion. The function which calls the function itself is known as a recursive function. The main aim of recursion is to break a bigger problem into a smaller problem. Base case solutions are usually provided, and then we express the solution of the bigger problem in terms of that base case solution step by step. It is essential to add a base case because if we don’t add a base case recursion will never stop.

C++ Recursion Example

Recursion is a process in which the function calls itself directly or indirectly is called recursion, and the corresponding function is called the recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are the Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

#What is the base condition in recursion

In recursive program, the solution to a base case is provided, and a to stop it.solution to the bigger problem is expressed in terms of smaller problems.

int fact(int n)
{
    if (n < = 1) // base case
        return 1;
    else    
        return n*fact(n-1);    
}

In the above example, a base case for n < = 1 is defined and a larger value of the number can be solved by converting to a smaller one till the base case is reached.

The recursion continues until some condition is met to stop it.

If we want to prevent an infinite recursion, if…else statement (or similar approach) can be used where one branch makes a recursive call, and others don’t.

#How can we particular problem is solved using the recursion

The idea is to represent the problem in terms of one or more smaller problems, and add one or more base conditions that stop a recursion.

For example, we compute factorial the n if we know the factorial of (n-1). The base case for the factorial would be n = 0. We return 1 when n = 0.

There are two types of recursions.

  1. Direct Recursion
  2. Indirect Recursion

#Direct Recursion

When the function calls itself, it is called direct recursion.

#Indirect Recursion

When the function calls another function, and that function calls back the first function, then we call it an indirect recursion.

 For example, function A calls the function B, and Function B calls the function A.

#Syntax of recursive functions

return_type   function_name
{
     function_name();
}
int main()
{
     function_name();
}

#Fibinacci Series Program using recursion in C++

Write a program to print Fibonacci series using recursion in C++.

#include <iostream>
using namespace std;
void fib(int);
int main()
{
  int n;
  cout << "Program to print the fibonacci series\n";
  cout << "\nEnter the number of terms:";
  cin >> n;
  fib(n);
  return 0;
}

void fib(int n)
{
  int a = 0, b = 1, c, i;
  cout << "\n";
  cout << "\t" << a << "\t" << b;
  for (i = 3; i <= n; i++)
  {
    c = a + b;
    cout << "\t" << c;
    a = b;
    b = c;
  }
}

See the following output.

 

C++ Recursion Example

#Factorial number using recursion in C++

See the following program.

#include <iostream>
using namespace std;
int rec(int);

main()
{
  int a, fact;
  cout << "Enter the number:";
  cin >> a;
  fact = rec(a);
  cout << "\nFactorial of a number:" << fact;
}
int rec(int x)
{
  int f;
  if (x == 1)
    return (1);
  else
    f = x * rec(x - 1);
  return (f);
}

See the following output.

 

Factorial number using recursion in C++

Suppose the user entered 5, which is passed to the rec() function.

  1. In the first rec() function, test expression inside if statement is true. The return (f) statement is executed, which calls the second rec() function and argument passed is x-1, which is 4.
  2. In the second rec() function, test expression inside if statement is true. The return (f) statement is executed, which calls the third rec() function and argument passed is x-1, which is 3.
  3. In the third rec() function, test expression inside if statement is true. The return (f) statement is executed, which calls the fourth function, and the argument passed is x-1, which is 2.
  4. In the fourth rec() function, test expression inside if statement is true. The return (f) statement is executed, which calls the fourth function, and the argument passed is x-1, which is 1.
  5. In the fifth rec() function, test expression inside if statement is false. The return 1 statement is executed.
  6. So, that is how we get the 5*4*3*2*1 = 120.

Finally, C++ Recursion Example | Recursion Program In C++ Tutorial is over.

The post C++ Recursion Example | Recursion Program In C++ Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/17/cpp-recursion-example-cpp-recursion-program-tutorial/feed/ 0