Skip to main content

Learn C++ Flow of Control





6.1 Conditional branching - if


if statement

An if statement contains a Boolean expression and block of statements enclosed within braces.


Structure of if statement

if (boolean expression ) 

/* if expression is true */

statements... ; /* Execute statements */


If the Boolean expression is true then statement block is executed otherwise (if false) program directly goes to next statement without executing Statement block.


if...else statement

If statement block with else statement is known as as if...else statement. Else portion is non-compulsory.


Structure of if...else


if(condition)

{

  statements...

}

else

{

  statements...

}


If the condition is true, then compiler will execute the if block of statements, if false then else block of statements will be executed.


Nested if...else statement

We can use multiple if-else for one inside other this is called as Nested if-else.


Structure of Nested if...else


if(condition)

{

  statements...

}

else if

{

  statements...

}

else

{

  statements...

}







6.2 Conditional selection - switch


A switch statement is used instead of nested if...else statements. It is multiple branch decision statement of C++. A switch statement tests a variable with list of values for equivalence. Each value is called a case.

The case value must be a constant integer. 


Structure of switch() statement

switch (expression)

{

  case value: statements...

  case value: statements...

  default : statements...

}


Individual case keyword and a semi-colon (:) is used for each constant. Switch tool is used for skipping to particular case, after jumping to that case it will execute all statements from cases beneath that case this is called as ''Fall Through''. 


In the example below, for example, if the value 2 is entered, then the program will print two one something else!


int main()

{

  int i;

  cout << ''Enter an integer: '';

  cin>>i;   switch(i)

  {

    case 4: cout << ''four''; break;

    case 3: cout << ''three''; break;

    case 2: cout << ''two '';

    case 1: cout << ''one '';

    default: cout << ''something else!'';

  }

  return 0;

}


To avoid fall through, the break statements are necessary to exit the switch. If value 4 is entered, then in case 4 it will just print four and ends the switch.


The default label is non-compulsory, It is used for cases that are not present.





6.3 Loops - while & for


while loop


The while loop calculates the expression before every loop. If the expression is true then block of statements is executed, so it will not execute If the condition is initially false. It needs the parenthesis like the if statement.


while ( expression ) 

/* while expression is true do following*/

  statements... ;


Do While loop

This is equivalent to a while loop, but it have test condition at the end of the loop. The Do while loop will always execute at least once.


do

  statements ;

while ( expression );

/* while expression is true do...*/


For loop

This is very widely held loop.

For loops work like the corresponding while loop shown in the above example. The first expression is treated as a statement and executed, then the second expression is test or condition which is evaluated to see if the body of the loop should be executed. The third expression is increment or decrement which is performed at the end of every iteration/repetition of the loop.


for (expr1; expr2; expr3)

  statements...;


In while loop it can happen that the statement will never execute But In the do-while loop, test condition is based at the end of loop therefore the block of statement will always execute at least once. This is the main difference between the while and the do-while loop.


For example, to execute a statement 5 times: 


for (i = 0; i < 5; i++)

  cout << i << endl;


Another way of doing this is:

i = 5;

while (i--)

  statements;


While using this method, make sure that value of i is greater than zero, or make the test i-->0.





6.4 Break and Continue


Break statement


Break statement is usually used to terminate a case in the switch statement. 

Break statement in loops to instantly terminates the loop and program control goes to the next statement after the loop.


If break statement is used in nested loops (i.e., loop within another loop), the break statement will end the execution of the inner loop and Program control goes back to outer loop.


Syntax :

break;


Continue statement


In C++ programming language the continue statement works slightly similar to the break statement. The continue restarts the loop with the next value of item. All the line code below continue statement is skips.


Syntax :

continue; 


In the for loop, continue statement skips the test condition and increment value of the variable to execute again and In the while and do...while loops, continue skips all the statements and program control goes to at the end of loop for tests condition.





6.5 Random number


C (and by extension C++) comes with a built-in pseudo-random number generator. It is implemented as two separate functions that live in the cstdlib header:

srand() sets the initial seed value. srand() should only be called once.

rand() generates the next random number in the sequence (starting from the seed set by srand()).


Here’s a sample program using these functions:

int main()

{

int count;

srand(5323);

// set initial seed value to 5323


// Print 10 random numbers

for (i=0; i < 10; i++)

{

cout << rand() << "\t";

}

}


The output of this program will be any 10 numbers.


The range of rand()


rand() generates pseudo-random integers between 0 and RAND_MAX, a constant in stdlib that is typically set to 32767.


Generally, we do not want random numbers between 0 and RAND_MAX — we want numbers between two other values, which we’ll call Low and High.

For example, if we’re trying to simulate the user rolling a dice, we want random numbers between 1 and 6.


It turns out it’s quite easy to take the result of rand() can convert it into whatever range we want:

// Generate a random number between Low and High (inclusive)

unsigned int GetRandomNumber(int Low, int High)

{

return (rand() % (High - Low + 1)) + Low;

}




 

Comments

Popular posts from this blog

How To install Kali Linux (nethunter) On Android (Without root) via proot-distro and install Kali Linux Xfce Desktop On Android using Termux

What is kali linux? Kali Linux is a Debian-derived Linux distribution designed for digital forensics and penetration testing. It is maintained and funded by Offensive Security , This tutorial isn't only about learning how to install Kali Linux. Okay let's run down what we will be doing                        Table Of Content •Installing Kali Linux Terminal •Installing Kali Linux Desktop •Installing Default packages  •Creating vncserver port •Closing vncserver port •Closing multiple vncserver ports  •Reseting Kali Linux •Uninstalling Kali Linux  Okay!!!! Let's Begin Requirements: • Termux  : Click Here To Download Termux   Installation:   Please you can also copy and paste the commands below    The First thing we have to do is to make sure our repositories are up to date, to do that type the command  pkg update   It is essent...

How To Create a Strong Virus And A Payload with Python 2023

Let’s start by saying that viruses are a little bit anachronistic in 2023… nowadays other kinds of  malware (like worms for example:) are far more common than viruses. Moreover, modern operative systems are more secure and less prone to be infected than MS-DOS or Windows 95 were (sorry Microsoft…) and people are more aware of the risk of malware in general. Moreover, to write a computer virus, probably Python is not the best choice at all. It’s an interpreted language and so it needs an interpreter to be executed. Yes, you can embed an interpreter to your virus but your resulting virus will be heavier and a little clunky… let’s be clear, to write a virus probably other languages that can work to a lower level and that can be compiled are probably a better choice and that’s why in the old days it was very common to see viruses written in C or Assembly. That said, it is still possible to write computer viruses in Python, and in this article, you will have a practical demonstration. T...

How To install Windows 10 in Termux(Without rooting your Android phone)

   Hello guys what's up, Today we are going to see how easily we can run Windows 10 Operating System on Android Phone just by running few commands on Termux and if you will like this post I will also show you how to run the Windows 8.1 and Kali Linux GUI(Without root) on Android using Termux only in an upcoming post so just comment down below if you are interested. This method is quite interesting as this will make you understand how powerful a Linux terminal can be so without wasting any more time let’s start this tutorial. Below you will find all the resources you need and their download links so Download all the files, install, and copy it to your smartphone's Internal or External Storage. Requirements: •ZArchiver : Click Here To Download ZArchiver • Termux  : Click Here To Download Termux • AVNC :  Click Here To Download AVNC • Windows 10 : Click Here To Download The Windows 10 File After download the windows 10 file you need to Install termux and AVNC server...