0% found this document useful (0 votes)
6 views42 pages

Week 06

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)
6 views42 pages

Week 06

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/ 42

CE-116

COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]

Computer Engineering Department


WEEK NO:06

2
C++ Infinite Loop
• C++ Infinite Loop: This loop can also be called as “endless loop”.
This loop in C++ can be defined as a piece of code which lacks
the exit such that it repeats repeatedly. This loop occurs when it is
always executing true. In C++, if you pass true in the do-while
loop it will be known as “infinitive do-while loop”. Even if you
are having an initialization and increment expression but in C++
we use the ‘for(; ;)’ construct to signify the infinite loop.
3
Flowchart – Infinite For Loop
As the condition is never going to be
false, the control never comes out of
the loop, and forms an Infinite Loop as
shown in the above diagram, with blue
paths representing flow of infinite for
loop.

4
C++ Infinite Loop
• In case if you want we can terminate Output:

this loop by pressing the Ctrl + C keys. This loop will never end
#include <iostream> This loop will never end
int main(){ This loop will never end
This loop will never end
using namespace std; This loop will never end
for( ; ; ){ This loop will never end
cout<<"This loop will never end"<<endl; This loop will never end
} This loop will never end
This loop will never end
return 0; This loop will never end
}
5
Infinite For loop with condition=true
• For Loop condition is a boolean #include <iostream>
using namespace std;
expression that evaluates to true or
int main() {
false. So, instead of providing an for (; true; ) {
cout << "hello" << endl;
expression, we can provide the
}
Note: You will see the string hello print
boolean value true, in place of } to the console infinitely, one line after
another. If you are running from
Output
condition, and the result is an command prompt or terminal, to
terminate the execution of the program,
hello
infinite for loop. enter Ctrl+C from keyboard. If you are
hello
running the program from an IDE, click
hello
on stop button provided by the IDE.
hello
6
Infinite For loop with condition that always
evaluates to true
• Instead of giving true boolean value for #include <iostream>
using namespace std;
the condition in for loop, you can also
give a condition that always evaluates int main() {
for (; 1 == 1; ) {
to true. For example, the condition 1 cout << "hello" << endl;
}
== 1 or 0 == 0 is always true. No matter }
how many times the loop runs, the Output
hello
condition is always true and the for hello
hello
loop will run forever. Hello
.
. 7
Infinite For loop with no update to control
variables
• These type of infinite for loops may result when #include <iostream>
you forget to update the variables participating in using namespace std;
the condition.

• In the following example, we have initialized int main() {


for (int i = 0; i < 10; ) {
variable i to 0 and would like to print a string to
cout << "hello" << endl;
console while the i is less than 10. Typically, in the
}
following example, one would increment i in the
}
update section of for loop statement, to print hello Output
10 times. But, if we have not updated i in neither hello
hello
the for loop body nor for loop update section, i hello
would never change. This could make the loop an hello
infinite while loop.
8
C++ Infinite While Loop
To make a C++ While Loop run Flowchart – Infinite While Loop
indefinitely, the condition in the
While loop has to be true forever. To
make the condition always true, there
are many ways.

As the condition is never going to be


false, the control never comes out of
the loop, and forms an Infinite Loop as
shown in the above diagram.

9
Infinite While loop with true for condition
While Loop condition is a boolean #include <iostream>
expression that evaluates to true or using namespace std;
false. So, instead of providing an int main() {
expression, we can provide the while (true) {
boolean value true, in place of cout << "hello" << endl;
condition, and the result is an infinite }
}
while loop. Output Note: You will see the string hello print
hello to the console infinitely. If you are
running from command prompt or
hello terminal, to terminate the execution of
hello the program, enter Ctrl+C from
hello keyboard.
10
Infinite While loop with true for condition
Instead of true, you can also give a non- Output
zero integer. hello
hello
hello
#include <iostream> hello
using namespace std;
Note: You will see the string
int main() { hello print to the console
while (1) { infinitely. If you are running
from command prompt or
cout << "hello" << endl;
terminal, to terminate the
} execution of the program,
} enter Ctrl+C from keyboard.
11
Infinite While loop with condition that always
evaluates to true
Instead of giving true boolean value #include <iostream>
or a non-zero integer in place of while using namespace std;
loop condition, you can also give a int main() {
condition that always evaluates to while (1 == 1) {
true. For example, the condition 1 == cout << "hello" << endl;
1 or 0 == 0 is always true. No matter }
}
how many times the loop runs, the
Output
condition is always true. hello
hello
hello
hello
12
Infinite While loop with no update to control
variables
• These type of infinite while loops may #include <iostream>
result when you forget to update the using namespace std;
variables participating in the while loop
condition. int main() {
• In the following example, we have int i = 0;
initialized variable i to 0 and would like to while (i < 10) {
print a string to console while the i is less cout << "hello" << endl;
than 10. Typically, in the following }
example, one would increment i inside }
Output
while loop body, to print hello 10 times. hello
But, if we forget this update statement in hello
the while body, i is never changed. This hello
could make the loop an infinite while loop. hello
13
Infinite While loop while working with
continue statement
• This also is a typical scenario where we use a include <iostream>
continue statement in the while loop body, using namespace std;
but forget to modify the control variable.
• Extending the previous example, consider we int main() {
have added the increment statement. But, int i = 0;
now we have an additional functionality that while (i < 10) {
the loop has to continue when i becomes 5. if (i == 5) { Output
When continue statement is executed, the continue; hello
executes goes to the while condition, and the } hello
increment statement is not executed. This cout << "hello" << endl; hello
results in the scenario where i is never i++; hello
incremented again. And the while loop } hello
executes infinitely. }
14
C++ Infinite Loop
#include <iostream> Output:
using namespace std;
Output Limit Exceeded
int main() {
do{
cout<<"Infinitive do-while Loop";
} while(true);
}

15
break & continue Statements
• break and continue alter the flow of control
• When the break statement executes in a repetition structure, it immediately exits
• The break statement, in a switch structure, provides an immediate exit
• The break statement can be used in while, for, and do...while loops
• The break statement is used for two purposes:
1. To exit early from a loop
2. To skip the remainder of the switch structure
• After the break statement executes, the program continues with the first statement
after the structure
• The use of a break statement in a loop can eliminate the use of certain (flag)
variables
16
break & continue Statements
• continue is used in while, for, and do…while structures

• When executed in a loop

− It skips remaining statements and proceeds with the next iteration of the loop

• In a while and do…while structure

− Expression (loop-continue test) is evaluated immediately after the continue statement

• In a for structure, the update statement is executed after the continue


statement

− Then the loop condition executes


17
Break Statement Revisited
• break statement can be used with Switch or any of the 3 looping
structures

• it causes an immediate exit from the Switch, while, do-while, or for


statement in which it appears

• if the break is inside nested structures, control exits only the innermost
structure containing it

18
Continue Statement
• is valid only within loops

• terminates the current loop iteration, but not the entire loop

• in a for or while, continue causes the rest of the body statement to be


skipped--in a for statement, the update is done

• in a do-while, the exit condition is tested, and if true, the next loop
iteration is begun

19
The break Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
break;
cout << “j is “ << j<< ‘\n’;
}
cout << “We are out of the loop as j=70.\n”;

20
The continue Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
continue; //skips the 70
cout << “j is “ << j<< ‘\n’;
}//see UseContinue1.cpp
cout << “We are out of the loop” << endl;

21
break and continue

22
Break Statement

23
Continue Statement

24
Break and Continue in While Loop
• You can also use break and continue in 3int i = 0;
while loops: while (i < 10) {
if (i == 4) {
int i = 0;
i++;
while (i < 10) { continue;
cout << i << "\n"; }
i++; cout << i << "\n";
if (i == 4) { i++;
break; }
} Output
} 0
1
2
Output 5
0 6
1 7
2 8
9 25
Exercise:

26
exit( ) function

Today we’ll learn about exit() in C++. We know we can break


out of loops using the built-in break function in C++. Similarly,
we can also break out of a whole C++ program using the exit()
function.

Think of a situation where you are to come to a conclusion in


your program. You get the result and conclude something
before the whole program has been compiled or evaluated.

27
exit( ) function

• Today we’ll learn about exit() in C++. We know we can break out
of loops using the built-in break function in C++. Similarly, we
can also break out of a whole C++ program using the exit()
function.
• Think of a situation where you are to come to a conclusion in your
program. You get the result and conclude something before the
whole program has been compiled or evaluated.
28
How do you terminate the program as soon as you get
your required information or result?

• The answer to the above question is using the built-in exit() function in
C++. So let us take a closer look at the function and how it works.

• Theoretically, the exit() function in C++ causes the respective program


to terminate as soon as the function is encountered, no matter where it
appears in the program listing. The function has been defined under
the stdlib.h header file, which must be included while using the exit()
function.
29
Syntax for the exit() function in C++

• exit( exit_value );

• Here, exit_value is the value passed to the Operating system after


the successful termination of the program. This value can be tested
in batch files where ERROR LEVEL gives us the return value
provided by the exit() function. Generally, the value 0 indicates a
successful termination and any other number indicates some error.
30
Working of the exit() function in C++

• Remember, the function exit() never returns any value. It


terminates the process and performs the regular cleanup for
terminating programs.
• Also, automatic storage objects are not destroyed by calling
this function in C++.
• Look at the example below carefully:
31
Working of the exit() function in C++

#include<iostream> cout<<"ERROR!"; //the program exists if the value is 0


using namespace std; exit(0); }
cout<<"The input was : "<<i;
int main() }
{ Output:
Enter a non-zero value: 0
int i;
ERROR!
cout<<"Enter a non-zero value: "; //user input
• Since the user input for the above code
cin>>i;
provided is zero(0), the else part is executed for
if(i) // checks whether the user input is non-zero the if-else statement. Further where the
or not compiler encounters the exit() function and
{ terminates the program.
cout<<"Valid input.\n"; • Even the print statement below the if-else is not
} else executed since the program has been
{ terminated by the exit() function already.
32
Now let us look at another example where we try to
determine whether a number is prime or not.
#include<iostream> cout<<"\nNot a prime number!";
using namespace std; exit(0);
int main() }
{
}
int i,num;
cout<<"Enter the number : ";
cout<<"\n It is a prime number!";
cin>>num;
for(i=2;i<=num/2;i++) return 0;
{ }
if(num%i==0) Output:
{ Enter the number : 26
Not a prime number!
33
Further for the above code:

• firstly we took a user input for the number. We need to check whether this number, num is
prime or not.
• After that, we apply a for loop which works from 2 to n/2. This is because we already know
that all numbers are divisible by 1 as well as a number is indivisible by numbers above its half.
• Inside the for loop, we check whether the number is divisible by the loop iterator at that instant.
If so, we can directly conclude that the number is not prime and terminate the program using
the exit() function,
• Else, the loop goes on checking. After the execution of the whole loop structure, we declare the
number as a prime one.

34
Flow-diagram of exit statement in C++

• C++ provides a way to leave a


program early (before its
natural finish) with the exit()
function. The format of exit()
is as follows:
exit(status);

35
Flow-diagram of exit statement in C++

//Program exits itself


• Header File: stdlib.h (C) or
cstdlib (C++) //Note that the example would terminate
anyway
• Explanation: Exit ends the #include <cstdlib>
program. The ExitCode is
#include <iostream>
returned to the operating
system, similar to returning a using namespace std;
value to int main. int main()
{ cout<<"Program will exit";
exit(1); // Returns 1 to the operating
system
cout<<"Never executed";
} 36
Postfix Operators

• Post-increment operator:
A post-increment operator is used to increment the value of a variable
after executing the expression in which the operator is used. With the
post-increment operator, the value of the variable is first used in an
expression and then incremented.
int x = 10;
int a;
a = x++;
• The value of a will be 10 because the value of x is assigned to a and then
x is incremented
37
Post-decrement operator:

• A post-decrement operator is used to decrement the value of a


variable after executing the expression in which the operator is
used. With the post-decrement operator, the value of the
variable is first used in an expression and then decremented.
int x = 10;
int a;
a = x--;
• The value of a will be 10 because the value of x is assigned to a and then
x is decremented.

38
Prefix Operators

• Pre-increment operator:
A pre-increment operator is used to increment the value of a
variable before using it in a expression. With the pre-increment
operator, the value of the variable is first incremented and then
used in an expression.
int x = 10;
int a;
a = ++x;
• The value of a will be 11 because the value of x is incremented before it is
assigned to a. 39
Pre-decrement operator:

• A pre-decrement operator is used to decrement the value of a


variable before using it in a expression. With the pre-decrement
operator, the value of the variable is first decremented and then
used in an expression.
int x = 10;
int a;
a = --x;

• The value of a will be 9 because the value of x is decremented


before it is assigned to a.
40
Other Differences

• The postfix operators #include <iostream> OUTPUT


using std::cout; Value of x is 7
have a higher using std::endl; Value of x is now 7
precedence than the int main()
Value of x is now 8
Value of x is now 9
prefix operators, as well { Value of x is now 9
as a different int x = 7;
associativity. The postfix cout << "Value of x is " << x << endl;
cout << "Value of x is now" << x++ << endl;
operators are evaluated cout << "Value of x is now " << x << endl;
left-to-right while the cout << "Value of x is now " << ++x << endl;
prefix operators are cout << "Value of x is now " << x << endl;
evaluated right-to-left. return 0;
}
41
Other Differences

• The postfix operators #include <iostream> OUTPUT


using std::cout; Value of x is 7
have a higher using std::endl; Value of x is now 7
precedence than the int main()
Value of x is now 8
Value of x is now 9
prefix operators, as well { Value of x is now 9
as a different int x = 7;
associativity. The postfix cout << "Value of x is " << x << endl;
cout << "Value of x is now" << x++ << endl;
operators are evaluated cout << "Value of x is now " << x << endl;
left-to-right while the cout << "Value of x is now " << ++x << endl;
prefix operators are cout << "Value of x is now " << x << endl;
evaluated right-to-left. return 0;
}
42

You might also like