Computing Fundamentals-1: Jari Abbas & Shahzaib Hayat
Computing Fundamentals-1: Jari Abbas & Shahzaib Hayat
10/28/2019
Fundamentals-1
Lab # 5
Syntax:
while (expression is true)
{
statement or statements }
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;
}
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:
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:
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; }
}
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.
/* 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.
#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 );
int main()
{
int counter = 1; // initialize counter
do
{
cout << counter << " "; // display counter
counter++; // increment counter
} while ( counter <= 10 ); // end do...while
1 2 3 4 5 6 7 8 9 10
The following are sample inputs and outputs. The first one has the user successfully enter a positive number the
first time.
The next sample input and output has the user enter a positive number after two unsuccessful tries.
The final sample input and output has the user quit after two unsuccessful tries.
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.
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