Escolar Documentos
Profissional Documentos
Cultura Documentos
3/8/2013
They include:
a) decision statements
b) iteration statements
c) jump statements
d) exit function
Decision Statements
The important decision statements in C++ are:
a) if statement
b) if-else statement
c) switch statement
if (a=2)
{a++;}
if (a=2)
{a++;}
else
{a*=3;}
3/8/2013
Example (if)
Example (if-else)
#include <iostream>
#include <iostream>
#include <cstdlib>
#include <cstdlib>
int main()
int main()
magic = rand();
magic = rand();
if (guess == magic)
if (guess == magic)
else
return 0;
return 0;
}
#include <iostream>
else
#include <cstdlib>
int main()
magic = rand();
else
if (guess == magic)
{
return 0;
}
3/8/2013
if-else statement
for (int k=0; k<=6; k++)
{ if (k==1)
{ cout<< k is 1\n;}
else if (k==3)
{cout<<k is 3\n;}
else
{cout<<k is random\n;}
}
Example
for (int k=0; k<=6; k++)
{ switch (k)
{ case 1:
case 3:
case 5:
cout<< k is odd\n;break;
default:
cout<<k is even\n;}
}
if-else statement
operator
Can evaluate character or
constant integer only
Requires break statements
to jump to next structure
A switch statement is more
efficient than nested if-else
statement
relational operators
Can evaluate data of any
type
Does not require jump
statement
3/8/2013
Iterative Statements
The important iterative statements in C++ are:
a) while loop
b) do-while loop
do
c) for loop
{block of statements;}
while (test statement) ;
for (initialization;condition;increase)
{block of statements;}
Example
while (n>0)
{cout << x=10;
cout<<y=2; }
3/8/2013
Example
Example
do
{cout<<x=10\n<<y=2;}
while (k==0) ;
3/8/2013
Example
#include <iostream>
#include <cmath>
using namespace std;
main ()
{ int k, N, Y;
cin>>N;
for (k=0; k<=N; k++)
{ Y=k;
if (k>0)
Y=4*k+pow(k,2);
}
return (0);
}
Jump Statements
The important jump statements in C++ are:
a) continue statement
b) goto statement
c) break statement
3/8/2013
continue;
Example
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
int main ()
{ double x, y, Add;
for (int k=0; k<=10; k++)
{ if (k==3) continue;
cin>>x>>y;
Add=x+y;
cout<<k<<"\t"<<Add<<endl;
}
return (0);
}
int main()
{ int x;
for(x=0; x<=100; x++)
{ if(x%2) continue;
cout << x << ' ';
}
return 0;
}
Example
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
int main ()
{ int x = 1;
loop1:
x++; cout<<x<<' ';
if(x < 100) goto loop1;
system("pause");
return (0);
}
int main ()
{ InputData:
int k; cin>>k;
if (k!=4) goto InputData;
cout<<k<<endl;
return (0);
}
break
3/8/2013
statement
VS exit
break statement
Usually appears in the
body of while/do-while/for
loops, if and switch
statement.
Used to terminate current
loop early.
Format: break;
Example
function
Example
exit function
Usually appears in the
Example