CPP Language / Control Structures

They are of 2 types. They were

1. Decision making statements.
2. Looping Statements.

Decision statements
Syntax Example
if (condition)
{ Block1}


if (x == 100)
cout << "x is 100";


if (condition)
{Block1}
Else
{ Block2}

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";


if (cond1)
{ Block1}
else if (cond2)
{ Block1}

--------------
else if (cond2)
{ Blockn}
else
{ Default Block}


if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";


Looping statements
Syntax Program Output

while (expression)
{ Block1}


#include
using namespace std;
int main ()
{
int n = 10;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "Program End!\n";
}

// custom countdown using while
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Program End!


do statement
{ Block1}
while (condition);

// echo a statement
#include
#include
using namespace std;

int main ()
{
string str;
do {
cout << "Enter text: ";
getline (cin,str);
cout << "You entered: " << str << '\n';
} while (str != "bye");
}


Enter text: hello
You entered: hello
Enter text: hi
You entered: hi
Enter text: bye
You entered:bye


for (initialization; condition; increase)
{ Block1}


#include
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "Program End!\n";
}


10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Program End!


Home     Back