Professional Documents
Culture Documents
Lab 6:
While and do While loops in programming
OBJECTIVES:
i. Learn about while and do-while loops in C++
WHILE/DO-WHILE LOOPS
PURPOSE
PROCEDURE
1. In the lab students should complete both the “Examples” and “Lab Tasks”.
Before starting this lab, students should read/revise the lectures presented on given topics in the class.
Examples
1. Determine the result of the following code segments. Explain their results.
a)
char letter = 'a';
float total_grade=0.0;
float grade_avg = 0.0;
float grade;
int grade_ctr = 0;
do
{
cout<< “What is your grade? (-1 to end) ``;
cin>> grade;
if (grade >= 0.0)
{
total_grade += grade; // Add to total.
grade_ctr ++;
} // Add to count.
}
while (grade >= 0.0); // Quit when -1 entered.
Task 1
1. Write a program that performs a survey tally on beverages. The program should prompt for the next
person until a sentinel value of –1 is entered to terminate the program. Each person participating in the
survey should choose their favorite beverage from the following list:
1. Coffee
2. Tea
3. Coke
4. Orange Juice
Sample Run:
Please input the favorite beverage of person #1: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
4
Please input the favorite beverage of person #2: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
1
Please input the favorite beverage of person #3: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
3
Please input the favorite beverage of person #4: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
1
Please input the favorite beverage of person #5: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
1
Please input the favorite beverage of person #6: Choose 1, 2, 3, or 4 from the above menu or -1 to
exit the program
-1
#include<iostream>
int main()
int count=0;
int personCount=1;
int choice;
int i=-1;
do
cin>>choice;
cin>>i;
} while(i!=-1);
}
OUTPUT :
Task 2
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13,… , where the first two terms are 0 and 1, and each term
thereafter is the sum of the two preceding terms. Using this information, write a program that calculates
the nth number in a Fibonacci sequence, where n is entered into the program by the user.
SOLUTION :
#include<iostream>
using namespace std;
int main()
{
int n, t1=0,t2=1,nextterm=0;
cout<<"Enter the number of terms :";
cin>>n;
cout<<"Fibonacci series";
for(int i=1 ; i<=n; ++i)
{
//prints the first two terms
if(i==1)
{
cout<<" "<<t1;
continue;
}
if(i==2)
{
cout<<t2<<" ";
continue;
}
nextterm=t1+t2;
t1=t2;
t2=nextterm;
cout<<nextterm<<" ";
}
return 0;
}
OUTPUT :