Tools needed:
1.
PC running Windows Operating
System (OS)
2.
DevC++ (installed)
Turn on the PC and log into it using your student
account information.
Note:
The information and concepts discussed in this lab
manual are in sufficient detail but are still not exhaustive. It is assumed
that all these concepts are already taught to you in your ITC theory class.
1. Repetition
Control Structures or Loops
Whenever we need to do any task repetitively, we use
loops. There are 3 types of loops used in C++ -- while loop, for loop and
do-while loop.
while loop:
The structure of a while
loop is:
while(expression)
body of the loop
where the expression
provides an entry condition to the loop, i.e., the loop will be executed only
when the expression evaluates to true. Once the body of the loop is executed, the expression is checked again and if it evaluates to true the body of the loop is executed again. This evaluation of the expression and execution of body of the loop continues until the expression evaluates to false after which the code next to the body of the loop executes.
Each execution of the body of the loop is called an iteration.
If expression
always evaluates to true, such a loop
is known as an infinite loop.
A while loop is usually one of the four main types:
i) Counter-Controlled while
loop:
When we wish a while
loop to execute or iterate N number of times, we use the expression to test a
counter variable value against N and increment the counter each times the body
of loop executes.
counter = 0;
while(counter < N)
{
body of the loop
counter++;
}
}
Example 1:
Find average of 10 positive numbers entered by the
user.
float num, sum = 0;
int i = 0;
while(i++< 10)
{
cin >>
num;
sum += num;
}
cout << "Ave = " << sum/10
<< endl;
ii) Sentinel-Controlled
while loop:
When we do not know how many times to run a loop but
we know that the last entry wll be a special value, called a sentinel, then we
make our expression check that sentinel value to decide when to stop a loop. In
such a case we must read one value before the while loop so that we have a
valid value to test against the sentinel value.
cin >> variable;
while(variable != sentinel)
{
body of the loop
cin >>
variable;
}
Example 2:
Find average of positive numbers entered by the user
until the user enters -1.
float num, sum = 0;
int count = 0;
cin >> num;
while(num != -1)
{
sum += num;
count ++;
cin >> num;
}
cout << "Ave = " << sum/count<<
endl;
iii) Flag-Controlled while
loop:
Sometimes neither do we know the number of times to
run a loop nor is there any sentinel value present in the data to check for.
However, there may a condition which if true will signal the loop to stop. In
this case, use a bool variable as a flag to indicate when that condition has
occurred so that the next time the loop is not executed.
isFound = false;
while(!isFound)
{
body of the loop
if(expression)
isFound
= true;
remaining body
of the loop
}
Example 3:
Find average of first 10 positive even numbers entered
by the user where the user may continue entering both even and odd numbers.
Display the average after the required number of positive even numbers (i.e.
10) has been entered.
Code:
int num, sum = 0; //even and odd is linked to integers
int count = 0;
bool NumReached= false;
while(!NumReached)
{
cin >>
num;
if (num>=0 && num%2==0) {
count++;
sum += num;
}
if(count == 10)
NumReached=
true;
}
cout << "Ave = " <<static_cast<float>(sum)/count<<
endl;
for loop:
A while loop
can be used for any task that requires repetition. However, C++ often provides
optimized ways of writing code structures that are encountered very often by
programmers. A for loop is such an
example. A for loop is just a
specialized form of writing a counter-controlled while loop.
for(initial statement; expression; update statement)
body of the loop
The initial
statement is executed only once before the for loop is entered.
The expression
is just like the expression in while loop which is evaluated and if true the body of the loop is executed.
The update
statement is executed at the end of each iteration.
For example, the following while loop code:
counter = 0;
while(counter < N)
{
body of the loop
counter++;
}
}
can be written as a for loop code as:
for(counter = 0; counter < N; counter++)
{
body of the loop
}
Hence, for
loop is ideally suited where the number of iterations are known. This does not
mean it cannot be used in other situations.
Example 5 (Self Assessment):
Redo code for examples 1 - 4 replacing each while loop
with a for loop.
Challenge:
For example 2 and 4, try to write code such that
everything executes within the for loop without any body of statements!
do-while loop:
A do-while
loop has the following syntax:
do
{
body of the loop
}
while(expression);
Note the reserved word 'do' and the semicolon at the end of while(expression);.
In a do-while
loop, the body of the loop is
executed first and then expression is
evaluated. If the expression
evaluates to true, the body of the loop is executed again, else
the loop is exited.
A do-while
loop will be executed at least once, because contrary to while and for loops, a do-while loop does not have an entry
condition rather an exit condition.
Example 6 (Self Assessment):
Redo code for examples 1 - 4 replacing while loop used
in them with a do-while loop.
2. break and continue statements
Remember the break
statement in a switch-case structure.
It provids an exit from switch
structure. Similarly,break can be
used to exit from a loop.
For example, instead of using a flag in a
flag-controlled while loop:
bool flag = false;
while(!flag)
{
body of the loop
if(expression)
flag =
true;
}
consider the following while loop with a break
statement to do the same job:
while(true)
{
body of the loop
if(expression)
break;
}
Note the loop will iterate infinitely were it not for
the conditional break which will terminate the loop.
The continue
statement when used within a loop means that the remaining part of the body of the loop after the continue statement will be skipped and
the next iteration started.
For example look at this odd use of the continue statement:
while(true)
{
body of the loop
if(!expression)
continue;
break;
}
When the expression
evaluates to false, !expression is true and continue
statement is executed, which immediately takes execution to the start of the loop
body skipping the execution of break
statement.
However, when expression
evaluaes to true, !expression is false and continue
statement is not executed and the break
outside the body of if gets executed, which exits from the loop. Thus this code
is akin to the previous two codes which used flag control and break statement.
Exercise:
Task
# 1: Code file name lab6_1.cpp
Write a program that takes
the the roll # (4-digits) and age (2-digits) of 5 students and display them
accordingly. Do this using both the ‘while’ and ‘for’ loops.
With
FOR loop when while loop is commented out
#include<iostream>
using namespace std;
int main()
{
int
roll;
int
age,i;
// i=1;
// while
(i<=5)
for(i=1;i<=5;i++)
{
cout<<"Enter
Roll no of Student: ";
cin>>roll;
cout<<"Enter
Age of Student: ";
cin>>age;
cout<<"Roll
no of Student no "<<i<<" is
:"<<roll<<endl;
cout<<"Age
of Student is : "<<age<<endl;
// i++;
}
return
0;
}
With
WHILE loop when for loop is commented out
#include<iostream>
using namespace std;
int main()
{
int
roll;
int
age,i;
i=1;
while
(i<=5)
//for(i=1;i<=5;i++)
{
cout<<"Enter
Roll no of Student: ";
cin>>roll;
cout<<"Enter
Age of Student: ";
cin>>age;
cout<<"Roll
no of Student no "<<i<<" is
:"<<roll<<endl;
cout<<"Age
of Student is : "<<age<<endl;
i++;
}
return
0;
}
Task
# 2: Code file name lab6_2.cpp
Write
a program to receive 10 floating point values where each
. If an entered value is not within the required
range, ask the user to enter the value again. Show the sum after the 10th value
has been entered correctly.
#include<iostream>
using namespace std;
int main()
{
float
num,sum=0;
int
i=1;
while(i<=10)
{
cout<<"Enter
Number "<<i<<":";
cin>>num;
if
(num>=0 && num<=1)
{
sum=sum+num;
i++;
}
else
{
cout<<endl<<"The
number entered is not within specified Range ";
cout<<"Try
Again "<<endl;
}
}
cout<<"The Total Sum is : "<<sum<<endl;
return
0;
}
Task # 3: Code file name lab6_3.cpp
Calculate
the power of a number without using cmath library functions. Power can be
positive or negative integer. Take both the base (integer) and exponent
(integer) as input from user.
#include
<iostream>
using namespace
std;
int main ()
{
int exp,base;
cout<<"Enter Base Number : ";
cin>>base;
cout<<"Enter exponent : ";
cin>>exp;
float a=base
;
if (exp==0)
{
cout<<endl<<"The
answer is:"<<1;
}
else
{
if(exp<=0)
{
for(int
i=-1;i>exp;i--)
{
a=base*a;
}
cout<<endl<<"The answer
is:"<<1/a;
}
else
{
for(int i=1;i<exp;i++)
{
a=base*a;
}
cout<<endl<<"The answer
is:"<<a;
}
}
return 0;
}
Task # 4: Code file name lab6_4.cpp
Write
a program for counting digits and displaying their total count at the end of
the program. Output should look like as follow:
Counting Digits Program
Enter a number:12345789
Number of digits are:8
Program Terminated Successfully.
|
#include<iostream>
using namespace std;
int main()
{
int
num;
int
digit;
cout<<"Counting
Digits Program"<<endl;
cout<<"Enter
a number:";
cin>>num;
digit=0;
while (num!=0)
{
num=num/10;
digit++;
}
cout<<"Number
of Digits are:"<<digit<<endl;
cout<<"Program
Terminated Successfully."<<endl;
return 0;
}
No comments:
Post a Comment