[go: up one dir, main page]

0% found this document useful (0 votes)
13 views9 pages

Chapter Four Class 2015

Chapter Four discusses control statements in C++, including selection statements (if, if-else, switch) and repetition statements (for, while, do-while). It explains the syntax and usage of these statements with examples, emphasizing how they control the flow of a program based on logical conditions. The chapter provides a comprehensive overview of how to implement these control structures to manage program execution effectively.

Uploaded by

ephremmulu486
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

Chapter Four Class 2015

Chapter Four discusses control statements in C++, including selection statements (if, if-else, switch) and repetition statements (for, while, do-while). It explains the syntax and usage of these statements with examples, emphasizing how they control the flow of a program based on logical conditions. The chapter provides a comprehensive overview of how to implement these control structures to manage program execution effectively.

Uploaded by

ephremmulu486
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Chapter Four

Control Statements
Flow control in a program is the sequence of statements that are executed in a program depending on
the outcome of a logical condition. Control flow statements in software program are categorized into
selection statements, iteration statements and jump statements.
Selection Statements (Conditional Statements)
There are two types of conditional statements in C++, which are “if statement” and “switch
statement”.
The if Statement
The statements execution dependent upon a condition being satisfied. The executed statement will be
decided whether to be execute or not based on a condition which will be tested either for TRUE or
FALSE result. There are different forms of the “If” statement is: simple if ,if- - -else and if- elseif
statement.
The simple if statement
The simple if statement will decide only one part of the program to be executed if the condition is
satisfied or ignored if the condition fails.
The Syntax is:
if (expression)
statements;

first the “if expression” will be evaluated and if the outcome is non zero (which means TRUE), then the
“statements” is executed. Otherwise, nothing happens and execution resumes to the line immediately
after the “if” block. Most of the time “expression” will have relational expressions testing whether
something is equal, greater, less, or different from something else. Thus any expression, whose final
result is either zero or none zero can be used in ”expression”.
//This is a simple if statement;
//This is a simple if statement; #include<iostream.h>
#include<iostream.h>
#include<iostream.h> using namespace std;
using namespace std;
using namespace std; int main ()
int main ()
int main () {
{
{ int x;
int x=20;
int age; cout<<"enter the number"<<endl;
cin>>x; if(x<20)
if(age>18) cout<<"This is a simple if statement";
if(x)
cout<<" you are an adult "; cout<<"you are an adult"; return 0;
return 0; return 0; }
} } 1
//Multiple statements dependent on the same condition -- // Simple if statement ,check the number is the largest
-{___} #include <iostream.h>
// simple if statement check the number is the largest using namespace std;
&sum of the number int main ()
#include <iostream.h> {
using namespace std; int a,b;
int main () cout<<"Enter the two number ";
{ cin>>a>>b;
int a,b,sum; if(a>b)
cout<<"a is the largest"<<endl;
cout<<"Enter the two number "; return 0;
cin>>a>>b; }
if(a>b)
{
sum=a+b;
a*=4;
} // Simple if statement check the number is the largest
cout<<"a is the largest"<<endl; &sum of the number
cout<<"sum="<<sum <<endl; #include<iostream.h>
cout<<"a="<<a; using namespace std;
return 0; int main ()
} {
int c=10;
int a=5;
int d=++c+a;
if(d>c)
a++;
cout<<"a ="<<a;
return 0;
}

The If-- else statement


The “if - - - else” statement allows us to specify two alternative statements: One which will be executed
if a condition is satisfied and another which will be executed if the condition is not satisfied.
The General Syntax is:
if (expression) //Write a c++ program that will determine whether a given number
statements1;
is positive or negative?
#include<iostream.h>
else
int main()
statements2; {
if (x > 0)
cout << "x is positive";
else
cout << "x is negative";
return 0;
}
2
First “expression” is evaluated
//This and
is if if
- - the outcome
- else is none zero
statement; (true),
//This is if then “statements1”
- - - else statement; will be
//This is if - - - else statement;
executed. Otherwise, which#include<iostream.h>
means the “expression” is false “statements2” will be
#include<iostream.h> executed.
#include<iostream.h>
using namespace std; int main() int main()
int main () { {
{ int x; int testScore;
int age; cout<<"Enter a number: "; cout<<"\nEnter your test score: ";
cin>>x; cin>>testScore;
if(age>18)
if(x%2 = = 0) if(testScore < 70)
cout<<" you are an adult "; cout<<"\n You did not pass: "; // then block
cout<<"The Number is Even";
else else else
cout<<" You are a kid "; cout<<"The Number is Odd"; cout<<"\n You did pass" //else block
return 0; return 0; return 0;
} } } \n jump one line

The above sample program can be diagrammatically expressed as follows:

//This is simple if - - - else statement;


#include<iostream.h>
//Sample of if--- else statement int main()
condition {
#include<iostream.h> //Sample of if--- else statement int a,b;
int main() condition cout<<"Enter the number:";
{ #include<iostream.h> cin>>a;
int x; int main() if(a>11)
cout<<"Enter a number: "; { {
cin>>x; int a=10; a*=5;
if(x%2!=0) cout<<"Enter the number:"; ++a;
cout<<"The Number is Odd"; cin>>a; cout<<"a="<<a;
else if(a>11) }
cout<<"The Number is Even"; cout<<"Wellcome to Lab class"; else
else {
return 0; cout<<" a is lessthan 11 "; b+=6
} --b;
return 0; cout<<"b="<<b;
} }
return 0; }
3
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
Write C++ program which is calculate a quadratic
int main()
{ equation of the form ax2+bx+c=0, when a,b,c E
double a,b,c,x1,x2; real numbers but a!=0
cout<<"Enter The value of a,b,and c"<<endl; x=
−𝑏±√𝑏 2 −4𝑎𝑐
cin>>a>>b>>c; 2𝑎
if((a!=0)&&(b*b-(4*a*c))>=0)
{
x1=(-b-sqrt(b*b-4*a*c))/(2*a);
x2=(-b+sqrt(b*b-4*a*c))/(2*a);
cout<<"x1="<<setw(6)<<x1<<endl;
cout<<"x2="<<setw(6)<<x2<<endl;
}
else
cout<<"Invalid data";
return 0;
}

The “if else if…else” statement


The third form of the “if” statement is the “if …else if” statement. The “if else if” statement allows us to
specify more than two alternative statements each will be executed based on testing one or more
conditions. //Sample of if….elseif….else
The General Syntax is:
statement that check age statues
if (expression1) if (expression1)
#include<iostream.h>
statements1; statements1;
else if(expression2) using namespace std; else if(expression2)
statements2; int main () statements2;
. { .
. int age; .
cout<<"enter the age";
. .
cin>>age; else if(expressionN)
else if(expressionN)
statementsN; if(age <= 12) statementsN;
else cout<<"\n you are kid"; else
statements else if(age<=80) statements
cout<<"\n you are adulet";
else
cout<<"\n you are old"<<endl;
return 0; }
First “expression1” is evaluated and if the outcome is none zero (true), then “statements1” will be
executed. Otherwise, which means the “expression1” then “expression2” will be evaluated: if the out put
of expression2 is True then “statements2” will be executed otherwise the next “expression” in the else
if statement will be executed and so on. If all the expressions in the “if” and “else if” statements are False
then “statements” under else will be executed.

4
The Switch Statement

Another C++ selection statement that implements a selection control flow is the switch statement
(multiple-choice statement). The switch statement provides a way of choosing between a set of
alternatives based on the value of an expression.
The switch statement has four components: The General Syntax might be:

▪ Switch switch(constant_expression)
▪ Case {
▪ Default case constant1:
▪ Break statements;
.
.
case constant n:
statements;
default:
statements;
}

When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached. When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement. A switch statement can have an
optional default case, which must appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed in the default case. Now let us see
the effect of including a break statement in the switch statement.
//Program that demonstrate use of switch statement #include<iostream.h>
#include <iostream> int main()
using namespace std; {
int main() char grade;
{ cout<<"Enter Grade";
int classyear; cin>>grade;
cout<<"Please enter your class year in integer:"; switch(grade){
cin>> classyear; case 'A': cout<<"Ecellent";
switch (classyear){ break;
case 1: cout<<"You are 1st year.\n"; case 'B': cout<<"Very Good";
break; break;
case 2: cout<<"You are 2nd year.\n";
break; case 'C': cout<<"Good";
case 3: cout<<"You are 3rd year.\n"; break;
break; case 'D': cout<<"Fair";
case 4: cout<<"You are 4th year.\n"; break;
break; case 'F': cout<<"Fail";
case 5: cout<<"You are 5th year.\n"; break;
break; default: cout<<"Invalid Grade value ";
default: cout<<"An error class year!\n"; }
} }
}

5
Repetition Statements
Repetition statements control a block of code to be executed repeatedly for a fixed number of times or
until a certain condition fails.
➢ There are three C++ repetition statements:
1) The For Statement or loop
2) The While statement or loop
3) The do…while statement or loop
The for statement / loop
The “for” statement (also called loop) is used to repeatedly execute a block of instructions until a
specific condition fails.
The General Syntax is:
for(expression1 ; expression2 ; expression3)

statements;
The for loop has three expressions:
Expression1: is one or more statements that will be executed only once and before the looping starts.
Expression2: is the part that decides whether to proceed with executing the instructions in the loop
or to stop. Expression2 will be evaluated each time before the loop continues. The output of
expression2 should be either non zero (to proceed with the loop) or zero (to stop the loop) to represent
true and false output respectively.
Expression3: is one or more statements that will be executed after each iteration.
Thus, first expression1 is evaluated and then each time the loop is executed, expression2 is evaluated.
If the outcome of expression2 is non zero then statements is executed and expression3 is evaluated.
Otherwise, the loop is terminated. In most programs, the “for loop” will be used for such expressions
where expression1 is initialization, expression2 is condition and expression3 is either increment or
decrement.
The general format can be expressed as follows for the sake of clarity:
for(initialization ; condition ; increase/decrease)
statement;
Steps of execution of the for loop:
1. Initialization is executed. (will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop finishes and statement
is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is executed and the loop gets
back to step two.
//Program that demonstrate for loop Guess the output of the following code:
int main (){ int main()
int i; {
for (i=0; i<=10; i++) for(int i=10;i>0;i--)
{ {
cout<<i<<” ”;} cout<<i<<“,”;
cout<<endl; }
return 0; } cout<< “FIRE!”;
return 0; }

6
//Program that demonstrate nested for loop
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main (){ int main (){
int i,j; int i,j;
for(i=0;i<=10;i++) { for(i=5;i>=1;i--) { //for(i=1;i<=5;i++)try it
for (j=0;j<=i;j++) for (j=i;j>=1;j--) //for(j=i;j<=5;j++)
{ {
cout<<j;} int i,j; cout<<j;}
cout<<endl; for(i=1,j=2;i<=4;i++,j+=2) { cout<<endl;
cout<<i<<" "<<j<<endl;
} }
}
return 0; return 0;
} }

The while statements


The while statement (also called while loop) provides a way of repeating a statement or a block as long
as a condition holds / is true.
The general for loop is equivalent to the following while loop:

Syntax: // sum the numbers between 0 to 100


#include <iostream.h>
Expression1; //initialization int main()
{
while(expression2){// condition int sum=0, num=1;
while(num<=100)
statement; // loop-body {
sum+=num;//sum=sum+num
expression; increment/decrement ++num;
}
cout<<"Sum of 1 to 100 is "<<sum<<endl;
return 0;
}
#include<iostream.h>
int main ()
{ #include <iostream.h>
int n; using namespace std;
cout << "Enter the number > "; int main() {
cin>>n; int age=1;
int i= 1;
while (age<=10){
int sum = 0;
while (i <= n) ++age;
sum += i++; cout << ++age << '\n';
cout<< "Sum= "<<sum; }
return 0; return 0;
} }

7
Do…while loop
The do statement (also called the do while loop) is similar to the while statement, except that its body is
executed first and then the loop condition is examined. In do…while loop, we are sure that the body of
the loop will be executed at least once. Then the condition will be tested.
The general syntax is:
do
{
statement;
}

while(expression); // condition

First statement is executed and then expression is evaluated. If the outcome of the expression is nonzero,
then the whole process is repeated. Otherwise the loop is terminated. Do while lopp

#include <iostream.h>
using namespace std; #include <iostream.h>
int main() { using namespace std;
int n; int main() {
cout<<"enter n"; int age;
do { cout<<"enter age";
cin >> n; do {
cout << n * n << '\n'; cin >> age;
} cout << ++age << '\n';
while (n != 0); }
return 0; while (age<=10);
} return 0;
}
The continue and break statements

The continue statement


The continue statement terminates the current iteration of a loop and instead jumps to the next iteration.
➢ It is an error to use the continue statement outside a loop.
➢ In while and do while loops, the next iteration commences from the loop condition.
➢ In a “for” loop, the next iteration commences from the loop’s third expression.
E.g.:

for(int n=10;n>0;n--)
{
if(n = = 5)
continue; //causes a jump to n
cout<<n<< “,”;
}

8
The break statement
A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a jump
out of these constructs, and hence terminates them. Like the continue statement, a break statement only
applies to the “loop” or “switch” immediately enclosing it. It is an error to use the break statement outside
a loop or a switch statemen
// break loop example
#include <iostream.h> }
using namespace std; #include<iostream.h>
int main () using namespace std;
{ int main()
{
for (int n=10; n>0; n--)
for (int age=10; age>0;age--) {
{
cout<<age;
cout << n << ", "; if(age==5){
if (n==3) cout<<" waw execution are abotred";
{
cout << "countdown aborted!"; break; }
break; } }
} return 0; }
}
return 0;

The goto statement


goto allows to make an absolute jump to another point in the program. This unconditional jump ignores
nesting levels, and does not cause any automatic stack unwinding. Therefore, it is a feature to use with
care, and preferably within the same block of statements, especially in the presence of local variables.
The destination point is identified by a label, which is then used as an argument for the goto statement.
A label is made of a valid identifier followed by a colon (:).
goto is generally deemed a low-level feature, with no particular use cases in modern higher-level
programming paradigms generally used with C++. But, just as an example, here is a version of our
countdown loop using goto: #include <iostream.h>
// goto loop example using namespace std;
#include <iostream.h> int main ()
using namespace std; {
int main () int age=100;
{ myage:
int n=10; //cout<<age;
myclass:
cout << age << ", ";
cout << n << ", ";
n--; age--;
if (n>0) goto myclass; if (age>0) goto myage;
cout << "liftoff!\n"; cout << "liftoff!\n";
return 0; return 0;
} }
9

You might also like