0% found this document useful (0 votes)
7 views143 pages

Notes Jan29

The document provides an overview of branching and decision-making controls in C/C++, including if-else statements, else-if ladders, switch statements, and logical operators. It includes examples of programs that determine even or odd numbers and find the maximum of two or three numbers, emphasizing the importance of using the correct relational operators. Additionally, it discusses the implications of using nested if-else statements versus else-if ladders for code readability and maintenance.
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)
7 views143 pages

Notes Jan29

The document provides an overview of branching and decision-making controls in C/C++, including if-else statements, else-if ladders, switch statements, and logical operators. It includes examples of programs that determine even or odd numbers and find the maximum of two or three numbers, emphasizing the importance of using the correct relational operators. Additionally, it discusses the implications of using nested if-else statements versus else-if ladders for code readability and maintenance.
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/ 143

MA 211- Computer Programming and Applications

Prof. E. Natarajan,
Department of Mathematics,
IIST, Thiruvananthapuram, Kerala

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 1 / 60


▶ C/C++ supports a following branching/decision making control if –
else statement, else-if ladder, switch statement, Ternary operator (?:),
goto statement

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 2 / 60


▶ C/C++ supports a following branching/decision making control if –
else statement, else-if ladder, switch statement, Ternary operator (?:),
goto statement
▶ The if-else statement defines two blocks, the first block is called if
block and the second block is called else block.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 2 / 60


▶ C/C++ supports a following branching/decision making control if –
else statement, else-if ladder, switch statement, Ternary operator (?:),
goto statement
▶ The if-else statement defines two blocks, the first block is called if
block and the second block is called else block.
▶ The control of execution is transferred inside the if block if the
condition specified in the parentheses is evaluated as true, whereas
the control of execution is transferred inside the else block if the
condition specified is evaluated as false.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 2 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 3 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int x ;
cout < < " Enter a number \ n " ;
cin > > x ;
if ( x %2==0)
{
cout < < " The number is Even \ n " ;
}
else
{
cout < < " The number is Odd \ n " ;
}
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 4 / 60


▶ As an example, let us write a program that accepts two numbers a
and b as input from the user and prints the greatest value on the
computer screen.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 5 / 60


▶ As an example, let us write a program that accepts two numbers a
and b as input from the user and prints the greatest value on the
computer screen.
▶ # include < iostream >
using namespace std ;
int main ()
{
int a , b ;
cout < < " Enter two numbers \ n " ;
cin > >a > > b ;
if (a > b )
{
cout < < " The maximum is " <<a < < endl ;
}
else
{
cout < < " The maximum is " <<b < < endl ;
}
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 5 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 6 / 60


▶ As an example, let us write a program that accepts three numbers a
,b and c as input from the user and prints the greatest value on the
computer screen.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 7 / 60


▶ As an example, let us write a program that accepts three numbers a
,b and c as input from the user and prints the greatest value on the
computer screen.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 7 / 60


▶ Can I write the condition in the program as: a>b>c so as to compare
the value of variable a with b as well as c?

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 8 / 60


▶ Can I write the condition in the program as: a>b>c so as to compare
the value of variable a with b as well as c?
▶ the associativity of the relational operators is from left to right.
Hence, the condition a>b will be evaluated first; which will return a
value as true(1) or false (0).

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 8 / 60


▶ Can I write the condition in the program as: a>b>c so as to compare
the value of variable a with b as well as c?
▶ the associativity of the relational operators is from left to right.
Hence, the condition a>b will be evaluated first; which will return a
value as true(1) or false (0).
▶ Hence, the expression a>b>c will compare the result of condition
a>b with the value of variable c. This means that, the above
expression will compare the value 0 or 1 with the value of variable c,
thereby generating incorrect results.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 8 / 60


▶ Can I write the condition in the program as: a>b>c so as to compare
the value of variable a with b as well as c?
▶ the associativity of the relational operators is from left to right.
Hence, the condition a>b will be evaluated first; which will return a
value as true(1) or false (0).
▶ Hence, the expression a>b>c will compare the result of condition
a>b with the value of variable c. This means that, the above
expression will compare the value 0 or 1 with the value of variable c,
thereby generating incorrect results.
▶ Therefore, we must write two different conditions as a>b and a>c so
as to individually compare the value of variable a with b and c
respectively.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 8 / 60


▶ The logical operators are used to connect multiple conditions so as to
form a single expression. C/C++ supports three logical operators,

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 9 / 60


▶ The logical operators are used to connect multiple conditions so as to
form a single expression. C/C++ supports three logical operators,
▶ &&, !, ||. (And, Not and OR)

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 9 / 60


▶ The logical operators are used to connect multiple conditions so as to
form a single expression. C/C++ supports three logical operators,
▶ &&, !, ||. (And, Not and OR)

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 9 / 60


▶ The logical operators are used to connect multiple conditions so as to
form a single expression. C/C++ supports three logical operators,
▶ &&, !, ||. (And, Not and OR)


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 9 / 60

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 10 / 60



▶ Nesting of if-else blocks can sometimes increase the lines of code
thereby making the program difficult to develop and maintain.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 10 / 60



▶ Nesting of if-else blocks can sometimes increase the lines of code
thereby making the program difficult to develop and maintain.
▶ else-if ladder can be used as an alternative to the nesting of multiple
if-else blocks in the program thereby making the code more readable
and easy to maintain when compared to ‘nesting’ of if-else
statements.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 10 / 60



Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 11 / 60
▶ # include < iostream >
using namespace std ;
int main ()
{
int a ,b , c ;
cout < < " Enter three numbers \ n " ;
cin > >a > >b > > c ;
if (a >= b && a >= c )
{
cout < < " The maximum is " <<a < < endl ;
}
else if (b >= a && b >= c )
{
cout < < " The maximum is " <<b < < endl ;
}
else
{
cout < < " The maximum is " <<c < < endl ;
}
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 12 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under
▶ a = 10; b = 10; c = 5;. In this case the greatest value is 10 but it is
duplicated in two variables a and b. Had it been that we would have
written conditions using operator >, both the below conditions would
be evaluated as false.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under
▶ a = 10; b = 10; c = 5;. In this case the greatest value is 10 but it is
duplicated in two variables a and b. Had it been that we would have
written conditions using operator >, both the below conditions would
be evaluated as false.
▶ a > b && a > c [Condition is false because value of a is not greater
than b]

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under
▶ a = 10; b = 10; c = 5;. In this case the greatest value is 10 but it is
duplicated in two variables a and b. Had it been that we would have
written conditions using operator >, both the below conditions would
be evaluated as false.
▶ a > b && a > c [Condition is false because value of a is not greater
than b]
▶ b > a && b > c [Condition is false because value of b is not greater
than a]

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under
▶ a = 10; b = 10; c = 5;. In this case the greatest value is 10 but it is
duplicated in two variables a and b. Had it been that we would have
written conditions using operator >, both the below conditions would
be evaluated as false.
▶ a > b && a > c [Condition is false because value of a is not greater
than b]
▶ b > a && b > c [Condition is false because value of b is not greater
than a]
▶ Hence in this case control would have been in the last else block
printing value of variable c (which is 5) as greatest.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60


▶ Note that, we have used operator >=(greater than or equal to)
rather than > (greater than) while framing conditions. This makes
the program intelligent to handle equalities in some specific cases.
▶ For example, let us consider the values of a, b and c as under
▶ a = 10; b = 10; c = 5;. In this case the greatest value is 10 but it is
duplicated in two variables a and b. Had it been that we would have
written conditions using operator >, both the below conditions would
be evaluated as false.
▶ a > b && a > c [Condition is false because value of a is not greater
than b]
▶ b > a && b > c [Condition is false because value of b is not greater
than a]
▶ Hence in this case control would have been in the last else block
printing value of variable c (which is 5) as greatest.
▶ This is certainly wrong. To avoid generation of wrong results in such
specific cases we have framed the conditions using >= operator
instead of > operator.
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 13 / 60
▶ Hence the first condition itself is evaluated as true because value of a
is equal to b and greater than c.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 14 / 60


▶ Hence the first condition itself is evaluated as true because value of a
is equal to b and greater than c.
▶ a >= b && a >= c [Condition is true because a is equal to b and
greater than c].

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 14 / 60


▶ Hence the first condition itself is evaluated as true because value of a
is equal to b and greater than c.
▶ a >= b && a >= c [Condition is true because a is equal to b and
greater than c].
▶ This makes the control in the first if block thereby printing the value
of variable a as greatest, which is correct. Remember, it is the fact
that 10 is greatest of all the distinct values anyways.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 14 / 60


Switch case
▶ Consider a scenario wherein a ‘expression’ written in the code can
give any one of the values v 1, v 2, v 3, · · · , vn as a result of its
evaluation. In many cases, we may require to execute different
statements based on the different results generated by the expression.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 15 / 60


Switch case
▶ Consider a scenario wherein a ‘expression’ written in the code can
give any one of the values v 1, v 2, v 3, · · · , vn as a result of its
evaluation. In many cases, we may require to execute different
statements based on the different results generated by the expression.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 15 / 60


Switch case
▶ # include < iostream >
using namespace std ;
int main ()
{
int day ;
cout < < " Enter the day number \ n " ;
cin > > day ;
switch ( day )
{
case 1: cout < < " Sunday \ n " ;
break ;
case 2: cout < < " Monday \ n " ;
break ;
case 3: cout < < " Tuesday \ n " ;
break ;
case 4: cout < < " Wednesday \ n " ;
break ;
case 5: cout < < " Thursday \ n " ;
break ;
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 16 / 60
Switch case

▶ case 6: cout < < " Friday \ n " ;


break ;
case 7: cout < < " Saturday \ n " ;
break ;
default : cout < < " Invalid Day number \ n " ;
}
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 17 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?
▶ When a particular case is satisfied, the switch is considered as closed.
This means that, the control of execution does not come out of switch
block even after all the statements in a particular case are executed.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?
▶ When a particular case is satisfied, the switch is considered as closed.
This means that, the control of execution does not come out of switch
block even after all the statements in a particular case are executed.
▶ In the absence of break statement, the flow of execution falls through
all the case statements written after the case which was satisfied by
the expression.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?
▶ When a particular case is satisfied, the switch is considered as closed.
This means that, the control of execution does not come out of switch
block even after all the statements in a particular case are executed.
▶ In the absence of break statement, the flow of execution falls through
all the case statements written after the case which was satisfied by
the expression.
▶ Hence, we explicitly write the break statement inside each of the case
block so as to avoid the fall through in the execution flow.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?
▶ When a particular case is satisfied, the switch is considered as closed.
This means that, the control of execution does not come out of switch
block even after all the statements in a particular case are executed.
▶ In the absence of break statement, the flow of execution falls through
all the case statements written after the case which was satisfied by
the expression.
▶ Hence, we explicitly write the break statement inside each of the case
block so as to avoid the fall through in the execution flow.
▶ For example, in the above program if we do not write a break
statement and set the value of variable day as 4, then the execution
flow falls through each case block (starting from case 4) and gives the
following output: Wednesday, Thursday, Friday, Saturday, Invalid Day

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60


Switch case
▶ Why do we write a break statement at the end of every case inside a
switch block?
▶ When a particular case is satisfied, the switch is considered as closed.
This means that, the control of execution does not come out of switch
block even after all the statements in a particular case are executed.
▶ In the absence of break statement, the flow of execution falls through
all the case statements written after the case which was satisfied by
the expression.
▶ Hence, we explicitly write the break statement inside each of the case
block so as to avoid the fall through in the execution flow.
▶ For example, in the above program if we do not write a break
statement and set the value of variable day as 4, then the execution
flow falls through each case block (starting from case 4) and gives the
following output: Wednesday, Thursday, Friday, Saturday, Invalid Day
▶ Hence, a break statement is required to be written inside each case
block in order to generate the desired output.
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 18 / 60
▶ The conditional operator is an alternative to an if-else statement. The
operator is also called an ternary operator, which operates on three
operands: condition? expression1:expression2;

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 19 / 60


▶ The conditional operator is an alternative to an if-else statement. The
operator is also called an ternary operator, which operates on three
operands: condition? expression1:expression2;
▶ The operator first evaluates the condition and if the condition is
found to be ‘true’ then the result of the ternary operation is same as
the result returned by the ‘expression1’.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 19 / 60


▶ The conditional operator is an alternative to an if-else statement. The
operator is also called an ternary operator, which operates on three
operands: condition? expression1:expression2;
▶ The operator first evaluates the condition and if the condition is
found to be ‘true’ then the result of the ternary operation is same as
the result returned by the ‘expression1’.
▶ If the condition is found to be ‘false’ then the result of the ternary
operation is same as the result returned by the ‘expression2’.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 19 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int x ,y , res ;
cout < < " Enter the two numbers \ n " ;
cin > >x > > y ;
res =( x < y ) ? x : y ;
cout < < " Minimum is " << res ;
return 0;

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 20 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int x ,y , res ;
cout < < " Enter the two numbers \ n " ;
cin > >x > > y ;
res =( x < y ) ? x : y ;
cout < < " Minimum is " << res ;
return 0;


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 20 / 60
▶ # include < iostream >
using namespace std ;
int main ()
{
int res ,a ,b , c ;
cout < < " Enter 3 nos \ n " ;
cin > >a > >b > > c ;
res =a >= b && a >= c ? a :b >= a && b >= c ? b : c ;
cout < < " Greatest number is " << res < < endl ;
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 21 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int res ,a ,b , c ;
cout < < " Enter 3 nos \ n " ;
cin > >a > >b > > c ;
res =a >= b && a >= c ? a :b >= a && b >= c ? b : c ;
cout < < " Greatest number is " << res < < endl ;
return 0;
}

▶ You could also write the same condition differently by changing the
way in which the conditional operators are nested. For example, the
following statement will also store the greatest of values a, b and c in
variable res: res = a>=b ? a>=c ? a :c : b>=c? b : c;

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 21 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int res ,a ,b , c ;
cout < < " Enter 3 nos \ n " ;
cin > >a > >b > > c ;
res =a >= b && a >= c ? a :b >= a && b >= c ? b : c ;
cout < < " Greatest number is " << res < < endl ;
return 0;
}

▶ You could also write the same condition differently by changing the
way in which the conditional operators are nested. For example, the
following statement will also store the greatest of values a, b and c in
variable res: res = a>=b ? a>=c ? a :c : b>=c? b : c;
▶ Whilst the statement does the same job, the only difference is that,
this statement internally translates to nested if-else blocks instead of
an else if ladder.
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 21 / 60
▶ Loops’ also give programmers a privilege to write the operation once
and execute it multiple times thereby saving on the programmer’s
time as well as reducing lines of code.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 22 / 60


▶ Loops’ also give programmers a privilege to write the operation once
and execute it multiple times thereby saving on the programmer’s
time as well as reducing lines of code.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 22 / 60


▶ Loops’ also give programmers a privilege to write the operation once
and execute it multiple times thereby saving on the programmer’s
time as well as reducing lines of code.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 22 / 60


▶ Loops’ also give programmers a privilege to write the operation once
and execute it multiple times thereby saving on the programmer’s
time as well as reducing lines of code.

▶ Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 22 / 60


▶ For example, let us write a program which prints all the even numbers
from 0 to n.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 23 / 60


▶ For example, let us write a program which prints all the even numbers
from 0 to n.
▶ # include < iostream >
using namespace std ;
int main ()
{
int n , i =0;
cout < < " Enter the upper bound " ;
cin > > n ;
while (i <= n )
{
cout < <i < < endl ;
i = i +2; // Generate next even number
}
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 23 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.
▶ The factorial of any number x is calculated by repeated multiplication
as shown below:=x ∗ (x − 1) ∗ (x − 2) ∗ (x − 3) ∗ (x − 4) · · · ∗ 1

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.
▶ The factorial of any number x is calculated by repeated multiplication
as shown below:=x ∗ (x − 1) ∗ (x − 2) ∗ (x − 3) ∗ (x − 4) · · · ∗ 1
▶ For example, at the first stage we multiply x and (x − 1) and we may
store the result in some temporary variable, going forward in the
expression we multiply this result with another number (x − 2)
thereby creating another temporary result and so on.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.
▶ The factorial of any number x is calculated by repeated multiplication
as shown below:=x ∗ (x − 1) ∗ (x − 2) ∗ (x − 3) ∗ (x − 4) · · · ∗ 1
▶ For example, at the first stage we multiply x and (x − 1) and we may
store the result in some temporary variable, going forward in the
expression we multiply this result with another number (x − 2)
thereby creating another temporary result and so on.
▶ The point to understand here is, for large values of x , we have x
temporary results created, one formed at each stage of evaluation of
the expression.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.
▶ The factorial of any number x is calculated by repeated multiplication
as shown below:=x ∗ (x − 1) ∗ (x − 2) ∗ (x − 3) ∗ (x − 4) · · · ∗ 1
▶ For example, at the first stage we multiply x and (x − 1) and we may
store the result in some temporary variable, going forward in the
expression we multiply this result with another number (x − 2)
thereby creating another temporary result and so on.
▶ The point to understand here is, for large values of x , we have x
temporary results created, one formed at each stage of evaluation of
the expression.
▶ This is also not needed because, once the ith result is generated the
(i − 1)th result is not required to be stored in the system memory as
the expression only needs to keep moving in one direction.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60


▶ Let us write a program to take a number as input from the user and
compute the factorial of the given number.
▶ The factorial of any number x is calculated by repeated multiplication
as shown below:=x ∗ (x − 1) ∗ (x − 2) ∗ (x − 3) ∗ (x − 4) · · · ∗ 1
▶ For example, at the first stage we multiply x and (x − 1) and we may
store the result in some temporary variable, going forward in the
expression we multiply this result with another number (x − 2)
thereby creating another temporary result and so on.
▶ The point to understand here is, for large values of x , we have x
temporary results created, one formed at each stage of evaluation of
the expression.
▶ This is also not needed because, once the ith result is generated the
(i − 1)th result is not required to be stored in the system memory as
the expression only needs to keep moving in one direction.
▶ Therefore, we can store all the temporary results in a single variable
such that the new result generated overwrites the previous result
stored in the variable.
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 24 / 60
▶ Hence, we create a variable with value f = 1, which means that the
first number in the expression will always be multiplied by 1 as there
is no previous result available at the time of first multiplication.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 25 / 60


▶ Hence, we create a variable with value f = 1, which means that the
first number in the expression will always be multiplied by 1 as there
is no previous result available at the time of first multiplication.
▶ # include < iostream >
using namespace std ;
int main ()
{
int f =1 , x ;
cout < < " Enter a number " ;
cin > > x ;
while (x >0)
{
f=f*x;
x - -;
}
cout < < " Factorial is " <<f < < endl ;
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 25 / 60


▶ Let us write a program to take a number as input from the user and
print the sum of digits present in that number at the output.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 26 / 60


▶ Let us write a program to take a number as input from the user and
print the sum of digits present in that number at the output.
▶ For example, if the input data is 123, the program should calculate
the sum of individual digits in the data 1+2+3 and print the result as
6 on the console.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 26 / 60


▶ Let us write a program to take a number as input from the user and
print the sum of digits present in that number at the output.
▶ For example, if the input data is 123, the program should calculate
the sum of individual digits in the data 1+2+3 and print the result as
6 on the console.
▶ Also, the program should be configurable to perform the addition of
digits in the input data immaterial of the number of digits in the
input data.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 26 / 60


▶ Let us write a program to take a number as input from the user and
print the sum of digits present in that number at the output.
▶ For example, if the input data is 123, the program should calculate
the sum of individual digits in the data 1+2+3 and print the result as
6 on the console.
▶ Also, the program should be configurable to perform the addition of
digits in the input data immaterial of the number of digits in the
input data.
▶ This means that the logic should not be hard coded only for three
digit numbers, but must execute for the input numbers of any length.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 26 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 27 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int sum =0 , number , digit ;
cout < < " Enter a number " ;
cin > > number ;
while ( number !=0)
{
digit = number %10; // extract the digit
sum = sum + digit ; // perform addition of digits
number = number /10; // modify number
}
cout < < " Sum of digits is " << sum < < endl ;
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 28 / 60


▶ Fibonacci series requires two numbers to start, the starting two
numbers are generally taken as 0 and 1, the next number in the series
is generated as the addition of previous two numbers.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 29 / 60


▶ Fibonacci series requires two numbers to start, the starting two
numbers are generally taken as 0 and 1, the next number in the series
is generated as the addition of previous two numbers.
▶ Hence, a series starting from 0 and 1 will be
0, 1, 1, 2, 3, 5, 8, 13, 21, · · · .

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 29 / 60


▶ Fibonacci series requires two numbers to start, the starting two
numbers are generally taken as 0 and 1, the next number in the series
is generated as the addition of previous two numbers.
▶ Hence, a series starting from 0 and 1 will be
0, 1, 1, 2, 3, 5, 8, 13, 21, · · · .
▶ Note that the third number in the series is 1, which is obtained by
adding the first two numbers 0 and 1, whereas the fourth number in
the series is 2 which is obtained by adding the previous two numbers,
i.e., second and third numbers (1 + 1 = 2) and so on.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 29 / 60


▶ Fibonacci series requires two numbers to start, the starting two
numbers are generally taken as 0 and 1, the next number in the series
is generated as the addition of previous two numbers.
▶ Hence, a series starting from 0 and 1 will be
0, 1, 1, 2, 3, 5, 8, 13, 21, · · · .
▶ Note that the third number in the series is 1, which is obtained by
adding the first two numbers 0 and 1, whereas the fourth number in
the series is 2 which is obtained by adding the previous two numbers,
i.e., second and third numbers (1 + 1 = 2) and so on.
▶ We will declare integer variables f 1, f 2, and f 3 representing last three
numbers of Fibonacci series at each iteration of while loop.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 29 / 60


▶ We should develop the design of the code such that all the required
number of Fibonacci digits are generated using just three variables
with f 3 = f 1 + f 2.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 30 / 60


▶ We should develop the design of the code such that all the required
number of Fibonacci digits are generated using just three variables
with f 3 = f 1 + f 2.
▶ In this case, f3 will store all the numbers in the Fibonacci series
starting from the third number onwards. Hence, the fourth number in
the Fibonacci series will overwrite the third number in f 3 and the
fifth number of the Fibonacci series will overwrite the fourth number
and so on.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 30 / 60


▶ We should develop the design of the code such that all the required
number of Fibonacci digits are generated using just three variables
with f 3 = f 1 + f 2.
▶ In this case, f3 will store all the numbers in the Fibonacci series
starting from the third number onwards. Hence, the fourth number in
the Fibonacci series will overwrite the third number in f 3 and the
fifth number of the Fibonacci series will overwrite the fourth number
and so on.
▶ As the ith Fibonacci number will be overwritten when (i + 1)th
number is generated, it is important that we print the ith number in
the Fibonacci before we generate (i + 1)th number.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 30 / 60



Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 31 / 60
▶ # include < iostream >
using namespace std ;
int main ()
{
int f1 , f2 , f3 , i =1 , n ;
cout < < " Enter the length of series " ;
cin > > n ;
// First two numbers
f1 =0;
f2 =1;
cout < < f1 < < " \ t " << f2 ;
while (i <= n -2)
{
f3 = f1 + f2 ;
cout < < " \ t " << f3 ;
f1 = f2 ;
f2 = f3 ;
i ++;
}
cout < < endl ;
return 0;
}
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 32 / 60
▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60


▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.
▶ The loop has a much compressed syntax than the while loop, hence it
helps to keep the C++ code well formed and easy to maintain in
many cases.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60


▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.
▶ The loop has a much compressed syntax than the while loop, hence it
helps to keep the C++ code well formed and easy to maintain in
many cases.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60


▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.
▶ The loop has a much compressed syntax than the while loop, hence it
helps to keep the C++ code well formed and easy to maintain in
many cases.


▶ The for loop first performs initialization of the variable(s) specified in
initialization part of its syntax.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60


▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.
▶ The loop has a much compressed syntax than the while loop, hence it
helps to keep the C++ code well formed and easy to maintain in
many cases.


▶ The for loop first performs initialization of the variable(s) specified in
initialization part of its syntax.
▶ After initialization is completed, the loop checks for the result of
condition specified. Only if the condition is evaluated as ‘true’,
operations within the loop will be executed.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60


▶ for loop in C++ is the same as that of the while loop discussed in the
previous section, because for loop is a similar ‘entry control’ type of
loop similar to a while loop.
▶ The loop has a much compressed syntax than the while loop, hence it
helps to keep the C++ code well formed and easy to maintain in
many cases.


▶ The for loop first performs initialization of the variable(s) specified in
initialization part of its syntax.
▶ After initialization is completed, the loop checks for the result of
condition specified. Only if the condition is evaluated as ‘true’,
operations within the loop will be executed.
▶ After the specified operations are fully executed, the loop performs
“increment/decrement”
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 33 / 60
▶ Program to compute 12 + 22 + 32 + 42 + · · · x 2 using for loop

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 34 / 60


▶ Program to compute 12 + 22 + 32 + 42 + · · · x 2 using for loop
▶ # include < iostream >
using namespace std ;
int main ()
{
int k ,x , s ;
s =0;
cout < < " Enter x : " ;
cin > > x ;
for ( k =1; k <= x ; k ++)
{
cout < <k < < " ^2 " ;
if ( k != x )
cout < < " + " ;
else
cout < < " = " ;
s=s+k*k;
}
cout < <s < < endl ;
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 34 / 60


▶ Calculating the series 1/2!+1/4!+1/6!+1/8!...1/n! using for loop.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 35 / 60


▶ Calculating the series 1/2!+1/4!+1/6!+1/8!...1/n! using for loop.
▶ # include < iostream >
using namespace std ;
int main ()
{
int k , n ;
double f , s =0.0 , x ;
cout < < " Enter n : " ;
cin > > n ;
for ( k =2; k <= n ; k +=2)
{
x=k;
f =1.0;
while (x >0)
{
f=f*x;
x - -;
}
s = s +1/ f ;
}
cout < < " Result of the series is " <<s < < endl ;
return 0; }
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 35 / 60
▶ Write a program to take number of rows as input and print the
following pattern:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 36 / 60


▶ Write a program to take number of rows as input and print the
following pattern:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 36 / 60


▶ Write a program to take number of rows as input and print the
following pattern:


▶ For example, if the user enters number of rows as three the output
triangle should contain only three rows as shown below:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 36 / 60


▶ Write a program to take number of rows as input and print the
following pattern:


▶ For example, if the user enters number of rows as three the output
triangle should contain only three rows as shown below:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 36 / 60


▶ Write a program to take number of rows as input and print the
following pattern:


▶ For example, if the user enters number of rows as three the output
triangle should contain only three rows as shown below:


▶ As seen, row number 0 (which is the first row) contains 1 star, row
number 1 (which is the second row) contains 2 starts and so on. The
number of stars required in each row is documented in the table.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 36 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 37 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 37 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 38 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 38 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int i ,j , r ;
// Take number of rows as input
cout < < " Enter the number of rows : " ;
cin > > r ;
for ( i =0; i <= r -1; i ++)
{
// for each row number i , print i +1 stars
for ( j =1; j <= i +1; j ++)
{
cout < < " * " ;
}
// Transfer cursor on new line
// after current row
cout < < endl ;
}
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 39 / 60


▶ Write a program to take number of rows as input and print the
following pattern

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 40 / 60


▶ Write a program to take number of rows as input and print the
following pattern

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 40 / 60


▶ Write a program to take number of rows as input and print the
following pattern


▶ As seen, row number 0(which is the first row) contains four stars, row
number 1(which is the second row) contains three starts and so on.
The number of starts required in each row is documented in the
following table.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 40 / 60


▶ Write a program to take number of rows as input and print the
following pattern


▶ As seen, row number 0(which is the first row) contains four stars, row
number 1(which is the second row) contains three starts and so on.
The number of starts required in each row is documented in the
following table.
▶ From the table, it is clear that in any row number i there are r − i
stars to be printed.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 40 / 60


▶ Write a program to take number of rows as input and print the
following pattern


▶ As seen, row number 0(which is the first row) contains four stars, row
number 1(which is the second row) contains three starts and so on.
The number of starts required in each row is documented in the
following table.
▶ From the table, it is clear that in any row number i there are r − i
stars to be printed.


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 40 / 60

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 41 / 60



▶ for ( i =0; i <= r -1; i ++)
{
Print r - i stars in
each row number i .
cout < < endl ;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 41 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int i ,j , r ;
// Take number of rows as input
cout < < " Enter the number of rows : " ;
cin > > r ;
// Range row numbers from 0 to r -1
for ( i =0; i <= r -1; i ++)
{
// For each row number i , print r - i stars
for ( j =1; j <= r - i ; j ++)
{
cout < < " * " ;
}
cout < < endl ;
}
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 42 / 60


▶ We will now write a program to take number of rows as input and
print the following pattern:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 43 / 60


▶ We will now write a program to take number of rows as input and
print the following pattern:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 43 / 60


▶ The pattern shown above is for the number of rows(r) equal to 4. For
pattern analysis, we can say that each row in the above pattern has x
stars followed by y spaces and then again x stars.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 44 / 60


▶ The pattern shown above is for the number of rows(r) equal to 4. For
pattern analysis, we can say that each row in the above pattern has x
stars followed by y spaces and then again x stars.
▶ Again, we will start numbering the rows from 0. Note that for the
first row which has no spaces hence value of y should be 0 and x
should be 4.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 44 / 60


▶ The pattern shown above is for the number of rows(r) equal to 4. For
pattern analysis, we can say that each row in the above pattern has x
stars followed by y spaces and then again x stars.
▶ Again, we will start numbering the rows from 0. Note that for the
first row which has no spaces hence value of y should be 0 and x
should be 4.
▶ So in summary, the topmost row (row number 0) has 4 stars followed
by 0 spaces and again followed by 4 stars. The next row (row number
1) has 3 stars followed by 2 spaces and the again 3 stars and so on.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 44 / 60


▶ The pattern shown above is for the number of rows(r) equal to 4. For
pattern analysis, we can say that each row in the above pattern has x
stars followed by y spaces and then again x stars.
▶ Again, we will start numbering the rows from 0. Note that for the
first row which has no spaces hence value of y should be 0 and x
should be 4.
▶ So in summary, the topmost row (row number 0) has 4 stars followed
by 0 spaces and again followed by 4 stars. The next row (row number
1) has 3 stars followed by 2 spaces and the again 3 stars and so on.
▶ In general, the ith row has (r − i) stars followed by 2 ∗ i spaces again
followed by (r − i) stars.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 44 / 60


▶ The pattern shown above is for the number of rows(r) equal to 4. For
pattern analysis, we can say that each row in the above pattern has x
stars followed by y spaces and then again x stars.
▶ Again, we will start numbering the rows from 0. Note that for the
first row which has no spaces hence value of y should be 0 and x
should be 4.
▶ So in summary, the topmost row (row number 0) has 4 stars followed
by 0 spaces and again followed by 4 stars. The next row (row number
1) has 3 stars followed by 2 spaces and the again 3 stars and so on.
▶ In general, the ith row has (r − i) stars followed by 2 ∗ i spaces again
followed by (r − i) stars.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 44 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 45 / 60



Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 45 / 60

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 46 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int i ,j , r ;
cout < < " Enter the number of rows \ n " ;
cin > > r ;
for ( i =0; i <= r -1; i ++)
{
for ( j =1; j <= r - i ; j ++)
{
// printing left star
cout < < " * " ;
}
for ( j =1; j <=2* i ; j ++)
{
// printing space
cout < < " " ;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 47 / 60


▶ for ( j =1; j <= r - i ; j ++)
{
// printing right star
cout < < " * " ;
}
cout < < endl ;
}
cout < < endl ;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 48 / 60


▶ for ( j =1; j <= r - i ; j ++)
{
// printing right star
cout < < " * " ;
}
cout < < endl ;
}
cout < < endl ;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 48 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 49 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int choice ,a ,b , c ;
char opt = ’y ’;
do {
cout < < " Welcome to the calculator \ n " ;
cout < < " Please enter your choice \ n " ;
cout < < " 1. Add \ n 2. Substract \ n " ;
cout < < " 3. Multiply \ n " ;
cin > > choice ;
if ( choice ==1)
{
cout < < " enter 2 numbers \ n " ;
cin > >a > > b ;
c=a+b;
cout < < " Addition is " <<c < < endl ;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 50 / 60


▶ else if ( choice ==2)
{
cout < < " enter 2 numbers \ n " ;
cin > >a > > b ;
c =a - b ;
cout < < " Substraction is " <<c < < endl ;
}
else if ( choice ==3)
{
cout < < " enter 2 numbers \ n " ;
cin > >a > > b ;
c=a*b;
cout < < " Multiplication is " <<c < < endl ;
}
else
{
cout < < " This is an incorrect option . " << endl ;
}
cout < < " Do you want to continue ( Y / N ) ? " << endl ;
cin > > opt ;
} while ( opt == ’y ’) ;
return 0;}
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 51 / 60

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 52 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 52 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 53 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int k ;
for ( k =1; k <=10; k ++)
{
if (k >=3 && k <=5)
{
cout < < " Going to next step of loop \ n " ;
continue ;
}
if (k >=7)
{
cout < < " Going out of loop \ n " ;
break ;
}
cout < < " Default loop execution \ n " ;
}
cout < < " Good Bye \ n " ;
return 0;
}
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 54 / 60
▶ Output:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 55 / 60


▶ Output:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 55 / 60


Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 56 / 60


▶ break statement is also used to break the switch block. Hence break
statement, in C/C++ can be used to break the switch block or it can
be used to break the loop.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 57 / 60


▶ break statement is also used to break the switch block. Hence break
statement, in C/C++ can be used to break the switch block or it can
be used to break the loop.
▶ However, continue statement is designed to operate only with loops
and it will make no sense to use it with any of the decision making
control structures like switch block for example.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 57 / 60


▶ break statement is also used to break the switch block. Hence break
statement, in C/C++ can be used to break the switch block or it can
be used to break the loop.
▶ However, continue statement is designed to operate only with loops
and it will make no sense to use it with any of the decision making
control structures like switch block for example.
▶ Write a program to take a number as input from the user and to
check if the number is prime of not.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 57 / 60


▶ break statement is also used to break the switch block. Hence break
statement, in C/C++ can be used to break the switch block or it can
be used to break the loop.
▶ However, continue statement is designed to operate only with loops
and it will make no sense to use it with any of the decision making
control structures like switch block for example.
▶ Write a program to take a number as input from the user and to
check if the number is prime of not.
▶ We know that any number x is a prime number if it is divisible by
exactly two numbers 1 and x itself. Hence, for a given number x we
will generate all the numbers from 2 to x − 1 in our code, and we can
easily conclude that "x is prime" if it is divisible by no number
between 2 and x − 1.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 57 / 60


▶ break statement is also used to break the switch block. Hence break
statement, in C/C++ can be used to break the switch block or it can
be used to break the loop.
▶ However, continue statement is designed to operate only with loops
and it will make no sense to use it with any of the decision making
control structures like switch block for example.
▶ Write a program to take a number as input from the user and to
check if the number is prime of not.
▶ We know that any number x is a prime number if it is divisible by
exactly two numbers 1 and x itself. Hence, for a given number x we
will generate all the numbers from 2 to x − 1 in our code, and we can
easily conclude that "x is prime" if it is divisible by no number
between 2 and x − 1.
▶ There is no point checking the divisibility of number x with any other
number, thus when x is already found to be divisible with one of the
numbers we can conclude that x is not prime and break the execution
of the loop so as to avoid unnecessary iterations.
Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 57 / 60
▶ We therefore need a divisibility indicator or a flag to determine
whether the number x is divisible by at least one number between 2
and x-1 or not, this can be implemented by a character variable flag
which takes two values ‘y’ or ‘n’ such that if flag is ‘y’ it may
represent that the number is prime and if flag is ‘n’ it may represent
that the number is not prime.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 58 / 60


▶ We therefore need a divisibility indicator or a flag to determine
whether the number x is divisible by at least one number between 2
and x-1 or not, this can be implemented by a character variable flag
which takes two values ‘y’ or ‘n’ such that if flag is ‘y’ it may
represent that the number is prime and if flag is ‘n’ it may represent
that the number is not prime.
▶ This would mean that the loop that takes the counter variable i from
2 to (x − 1) can be terminated because of the following two reasons:

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 58 / 60


▶ We therefore need a divisibility indicator or a flag to determine
whether the number x is divisible by at least one number between 2
and x-1 or not, this can be implemented by a character variable flag
which takes two values ‘y’ or ‘n’ such that if flag is ‘y’ it may
represent that the number is prime and if flag is ‘n’ it may represent
that the number is not prime.
▶ This would mean that the loop that takes the counter variable i from
2 to (x − 1) can be terminated because of the following two reasons:
1 The upper bound of variable i is reached, and the number x is not
divisible by any number between 2 and x − 1. In this case, value of
character flag will be retained to ‘y’ at the end of loop, hence the
number will be correctly identified as a prime number by the code.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 58 / 60


▶ We therefore need a divisibility indicator or a flag to determine
whether the number x is divisible by at least one number between 2
and x-1 or not, this can be implemented by a character variable flag
which takes two values ‘y’ or ‘n’ such that if flag is ‘y’ it may
represent that the number is prime and if flag is ‘n’ it may represent
that the number is not prime.
▶ This would mean that the loop that takes the counter variable i from
2 to (x − 1) can be terminated because of the following two reasons:
1 The upper bound of variable i is reached, and the number x is not
divisible by any number between 2 and x − 1. In this case, value of
character flag will be retained to ‘y’ at the end of loop, hence the
number will be correctly identified as a prime number by the code.
2 The divisibility of variable x with some value of i is found; hence the
break statement is executed by the machine. Before executing the
break statement, we set the value of the character flag as ‘n’ indicating
that the number is not prime.

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 58 / 60


▶ # include < iostream >
using namespace std ;
int main ()
{
int x , i ;
char flag = ’y ’;
cout < < " Enter a number \ n " ;
cin > > x ;
// Note that flag is set default to ’y ’
i =2;
while (i <= x -1)
{
if ( x % i ==0)
{
flag = ’n ’;
break ;
}
i ++;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 59 / 60


▶ if ( flag == ’n ’)
{
cout < < " Number is not prime \ n " ;
}
else
{
cout < < " Number is prime \ n " ;
}
return 0;
}

Prof. E. Natarajan MA-211 -Comp. Prog. Appl. 60 / 60

You might also like