Computing Fundamentals-1: Jari Abbas & Shahzaib Hayat

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Computing

10/28/2019
Fundamentals-1
Lab # 5

JARI ABBAS & SHAHZAIB HAYAT


The While Loop
Introduction
A repetition statement (Loop) allows the programmer to specify that a program should repeat an action while
some condition remains true. The pseudocode statement:
While there are more items on my shopping list
Purchase next item and cross it off my list

Syntax:
while (expression is true)
{
statement or statements }

Comparison of for and while Loops


The while loop is similar to for loop: the code inside each continues to iterate until a condition becomes false.
The difference between them is in the parentheses following the for and while keywords.

For-Loop-Program While-Loop-Program
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main(void) int main(void)
{ {
for (int num = 1; num <= 10; num++) int num = 1;
{ cout << num << " "; } while (num <= 10)
getchar(); {
return 0; cout << num << " ";
} num++;
}
getchar();
Output: return 0;
}

The parentheses following the for keyword consists of three expressions, initialization, condition, and
update. By contrast, the parentheses following the while keyword consists only of the condition; you have
to take care of any initialization and update elsewhere in the code.

With the while loop, the integer variable num had to be declared and initialized before the loop since this
cannot be done inside the parentheses following the while keyword. Further, num was updated inside the code
of the loop using the increment operator.

The practical comparison of for & while loop comes in the predictability of iterations.

For example, in the following program, the program asks the user to enter a positive number, and in a loop
continues that request until the user does so. The number of times this loop may execute is unpredictable This
program would be more difficult to write with a for loop. While it could be done, the for loop is designed for
situations in which the number of iterations is predictable.
Code:
// A program that lets user enter a number multiple times until he enters a valid number
that is positive integer.

#include <iostream>
using namespace std;
int main(void)
{
int num;
cout << "Enter a positive number: ";
cin >> num;
while (num <= 0)
{
cout << "Number must be positive; please retry: ";
cin >> num;
}
cout << "The number you entered is " << num << " ";
return 0;
}

Here is some sample input and output:

Enter a positive number: 0


Number must be positive; please retry: -1
Number must be positive; please retry: 3
The number you entered is 3

Variations in While Loop


Method # 1 Method # 2 Method # 3
#include <iostream> #include <iostream> #include <iostream>
using namespace std; using namespace std; using namespace std;
int main(void) int main(void) int main(void)
{ { {
int num = 0; int num = 0; int num = 0;
while (num <= 10) while (num <= 10); while (num++ < 10)
{ { {
cout << num << " "; cout << num++ << " "; cout << num << " ";
num++; } }
} getchar(); getchar();
getchar(); return 0; return 0;
return 0; } }
}
Output:

Note that, In Method # 3;

Updating the counter within the condition raises the question: Given the condition num++ < 10, which comes
first, the comparison or the increment? Since the increment is postfix, the answer is the comparison.
The counter also could be updated within the condition using a prefix increment. However, then the condition
should be ++num <= 10 to obtain the desired output.
Flags
A flag is a value that acts as a signal for a function or process. The value of the flag is used to determine the
next step of a program. Flags are often binary flags, which contain a boolean value (true or false).
#include <iostream>
using namespace std;
int main(void)
{
int num;
char choice;
bool quit = false; \\ flag!
cout << "Enter a positive number: ";
cin >> num;
while (num <= 0 && quit == false)
{
cout << "Number must be positive; try again (Y/N): ";
cin >> choice;
if (choice == 'Y')
{
cout << "Enter number: ";
cin >> num;
}
else
quit = true; // flag value updated!
}
\\ Outcome conditional based on the value of flag
if (quit == false)
cout << "The number you entered is " << num << " ";
else
cout << "You did not enter a positive number";
getchar();
return 0;
}

Here is some sample input and output when the user eventually enters a positive number:

Enter a positive number: -3


Number must be positive; try again (Y/N): Y
Enter number: 3
The number you entered is 3

Here is some sample input and output when the user does not enter a positive number but instead decides to
quit. This time the final output is not of the number entered, but rather that the user did not enter a positive
number:

Enter a positive number: 0


Number must be positive; try again (Y/N): Y
Enter number: -1
Number must be positive; try again (Y/N): N
You did not enter a positive number

This program modification, in addition to using the logical && operator, uses a Boolean variable named quit.
This Boolean variable is used as a flag. A flag is a Boolean variable whose value indicates whether a condition
exists.

In this program, the while loop continues to loop as long as the data entered is invalid and the user wants to
keep going. Accordingly, the while keyword is followed by two conditions, joined by the logical && operator.
Integrating While Loop with Unconditional Branching:
Break Statement: Continue Statement:
#include <iostream> Develop a baker’s dozen program, which states that
using namespace std;
int main(void)
for every dozen item you buy, you get one free.
{ That is every 13th item is free. And each item cost’s
int num; the same price.
char choice;
cout << "Enter a positive number: "; #include <iostream>
cin >> num; using namespace std;
while (num <= 0) int main(void)
{ {
cout << "Number must be positive; int num, counter = 0, total = 0;
try again (Y/N): "; cout << "How many items do you want to
cin >> choice; buy: ";
if (choice == 'Y') cin >> num;
{ while (counter++ < num)
cout << "Enter number: "; {
cin >> num; if (counter % 13 == 0)
} continue;
else total += 3;
break; }
} cout << "Total for " << num << " items
cout << "The number you entered is " is $" << total;
<< num << " "; getchar();
getchar(); return 0;
return 0; }
}

Here is some sample input and output when the user


eventually enters a positive number:
Output:
Enter a positive number: 0
Number must be positive; try again (Y/N):
Y
Enter number: -1 Normally 39 items would cost 39 * 3 =
Number must be positive; try again (Y/N): 117$
Y But since every 13th item is free, 39/13 =
Enter number: 3 3, that is 3 out of 39 items are free due
The number you entered is 3 to this deal.
Hence 117 – 9 = 108$ net total.
Here is some sample input and output when the user
does not enter a positive number but instead decides
to quit:

Enter a positive number: -2


Number must be positive; try again (Y/N):
N
The number you entered is -2
The Infinite Loop:
Consider the program,

int num = 1;
while (num <= 10)
{
cout << num << " ";
}

Forgetting to update the value of the variable you are using in the condition is a common mistake with a while
loop. As the condition will always remain true no matter the case, the loop would run indefinitely.

While (true)

Similar to for ( ; ; ), There is a variation for while loop that allows it to run for infinite times. An infinite loop
can be terminated by using the break keyword tagged with a condition inside the loop.

Initializing an infinite while loop:

1. While (true) 3. int num = 1;


{ statement/s } while (num)
{ statement/s }
2. While (1)
{ statement/s } 4. bool choice = true;
while (choice)
{ statement/s }
For Example:

/* A program that asks user to enter a positive number, if user keeps giving the wrong input, the program iterates via
infinite while loop. */
#include <iostream>
using namespace std;
int main(void)
{
int num;
char choice;
bool quit = false;
while (true)
{
cout << "Enter a positive number: ";
cin >> num;

if (num > 0)
{ break; }

else
{
cout << "Number must be positive; try again (Y/N): ";
cin >> choice;
if (choice != 'Y')
{
quit = true;
break;
}
}
}
if (quit == false)
cout << "The number you entered is " << num << " ";

else
cout << "You did not enter a positive number";
getchar();
return 0;
}

Sample Outputs:

The major problem in the above program is that the user is trapped inside the loop until they enter a positive
number. That is not a good programming design. While the user should be required to enter good data if they
are going to enter any data at all, they should have the option, when told the data entered was not valid, of
quitting the data entry.

Nesting While Loops


In the previous Lab, nested for loops with a program that prints 5 rows of 10 X characters. The following is a
modification of that program using nested while loops.

#include <iostream>
using namespace std;
int main(void)
{
int x = 0;
while (x++ < 5)
{
int y = 0;
while (y++ < 5)
cout << "X";
cout << '\n';
}
return 0;
}
Flow-Chart:

Do While Loop
do...while statement tests the loop-continuation condition after the loop body executes; therefore, the loop body
always executes at least once. When a do...while terminates, execution continues with the statement after the while
clause.

Syntax:
do
{
statement
} while ( condition );

// do...while repetition statement.


#include <iostream>
using namespace std;

int main()
{
int counter = 1; // initialize counter

do
{
cout << counter << " "; // display counter
counter++; // increment counter
} while ( counter <= 10 ); // end do...while

cout << endl; // output a newline


getchar();
return 0; // indicate successful termination
} // end main

1 2 3 4 5 6 7 8 9 10

A Do While Loop Example


#include <iostream>
using namespace std;
int main(void)
{
int num;
char choice;
bool quit = false;
do {
cout << "Enter a positive number: ";
cin >> num;
if (num <= 0)
{
cout << "Number must be positive; try again (Y/N): ";
cin >> choice;
if (choice != 'Y')
quit = true;
}
} while (num <= 0 && quit == false);
if (quit == false)
cout << "The number you entered is " << num << " ";
else
cout << "You did not enter a positive number";
return 0;
}

The following are sample inputs and outputs. The first one has the user successfully enter a positive number the
first time.

Enter a positive number: 4


The number you entered is 4

The next sample input and output has the user enter a positive number after two unsuccessful tries.

Enter a positive number: 0


Number must be positive; try again (Y/N): Y
Enter a positive number: -1
Number must be positive; try again (Y/N): Y
Enter a positive number: 4
The number you entered is 4

The final sample input and output has the user quit after two unsuccessful tries.

Enter a positive number: 0


Number must be positive; try again (Y/N): Y
Enter a positive number: -1
Number must be positive; try again (Y/N): N
You did not enter a positive number
Comparison of the Do While and While Loop
As a general rule, A do while loop is preferred over a while loop in those situations in which the loop must
execute at least once before a condition may be tested, simply because under these circumstances it seems
illogical to test the condition prematurely on the first iteration of the loop.

Consider a program in which a menu is displayed

Menu
====
1. Add an entry
2. Edit an entry
3. Delete an entry
4. Exit

If the user chooses options 1, 2, or 3, the program performs the indicated operation (add, edit, or delete) and
then again displays the menu for the user’s next choice. If the user chooses option 4, the program ends.

In this menu example, the menu always displays at least once; the user cannot choose to exit before being given
that choice. Accordingly, a do while loop normally is preferable to a while loop when choosing a loop to
display a menu.

Scope
With a do while loop, it is important that a variable used in the condition following the while keyword not be
declared inside the loop.

int num; char choice;


char choice; do {
bool quit = false; int num;
do { bool quit = false;
// statements // more statements
} while (num <= 0 && quit == false); } while (num <= 0 && quit ==
false);

Flowchart
Task Test Data
Input number: 7
Expected Output:
1. Write a program in C++ to display n terms of
Input is a prime number.
natural number and their sum.
Test Data: 7
6. Write a program in C to display the pattern like
Expected Output:
right angle triangle with a number, with the number
The first 7 natural number is:
of lines defined by user.
1234567
The Sum of Natural Number upto 7 terms: 28
The pattern like:

1
2. Write a program in C++ to read 10 numbers from
12
keyboard and find their sum and average.
123
Test Data:
1234
Input the 10 numbers:
Number-1 :2 7. Write a C++ program to calculate the factorial of
... a given number.
Number-10 :2 Test Data :
Expected Output: Input the number : 5
The sum of 10 no is: 55 Expected Output :
The Average is: 5.500000 The Factorial of 5 is: 120

3. Write a program in C++ to display the 8. Write a program in C++ to print the Fibonacci
multiplication table of a given integer. series (x[n] = x[n-1] + x[n-2]), such that the number
Test Data: of outputs is defined by the user. Note that x[0] = 0
Input the number (Table to be calculated) : 15 and x[1] = 1 in all cases.
Expected Output : Test Data:
15 X 1 = 15 Input number: 9
... Expected Output:
... 0 1 1 2 3 5 8 13 21
15 X 10 = 150

4. Write a program in C++ to check if the input is a


prime number.
9. Write a program in C to find the prime numbers Input 2nd number for LCM: 20
within a range of numbers. Expected Output:
Test Data: The LCM of 15 and 20 is : 60
Input starting number of range: 1
Input ending number of range: 50 12. Write a C++ program to find the length of an
Expected Output : integer without using the library function.
The prime number between 1 and 50 are : Test Data:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Input an integer: 51923
Expected Output:
10. Write a C++ program to find HCF (Highest The integer contains 5 digits.
Common Factor) of two numbers.
Test Data: 13. Write a program in C++ to convert any two digit
Input 1st number for HCF: 24 integer (0 – 99) to words using no more than 3
Input 2nd number for HCF: 28 switch-case scenarios.
Expected Output: Test Data:
HCF of 24 and 28 is : 4 Input an integer: 25
Expected Output:
11. Write a program in C++ to find LCM of any Twenty Five
two numbers.
Test Data: 14. Rewrite the calculator program from previous
Input 1st number for LCM: 15 lab using switch-case statements.

You might also like