Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Simulating a Bouncing Ball Using a while Loop

Suppose that when a ball is dropped, it bounces from the pavement to a height one half of its previous height.  Assume that the double variable height contains the height of the ball in meters and that the user has input its initial value. Write a while loop that simulates the bouncing ball.  Each iteration of the loop should calculate and display the height of the ball. 

1. Stop the loop when the height is less than 0.1 meters.

% cat bounce1.cpp
#include<iostream>
using namespace std;
#include<cmath>

int main()
{
  double height;
 
  cout << "Enter the initial height of the ball: ";
  cin >> height;

  while(height > 0.1)
  {
    height = height / 2.0;
    cout << height << endl;
  }

  return 0;
}

% g++ bounce1.cpp
% a.out
Enter the initial height of the ball: 32.0
16
8
4
2
1
0.5
0.25
0.125
0.0625


2. Stop the ball when the absolute value of the difference in the height between two successive iterations is less than 0.1 meters.  You will need variables difference, old_height and new_height.

% cat bounce2.cpp
#include<iostream>
using namespace std;
#include<cmath>

int main()
{
  double old_height, new_height, difference;
 
  cout << "Enter the initial height of the ball: ";
  cin >> old_height;

  difference = 1.0;   // initialization

  while(difference > 0.1)
  {
    new_height = old_height / 2.0;
    cout << new_height << endl;

    difference = fabs(new_height - old_height);
    old_height = new_height;
  }

    return 0;
}

cswanson@mega (~/spring06) % g++ bounce2.cpp
cswanson@mega (~/spring06) % a.out
Enter the initial height of the ball: 100.0
50
25
12.5
6.25
3.125
1.5625
0.78125
0.390625
0.195312
0.0976562



3. Same as part 2 except with a do-while loop

% cat bounce3.cpp
#include<iostream>
using namespace std;
#include<cmath>

int main()
{
  double old_height, new_height, difference;
 
  cout << "Enter the initial height of the ball: ";
  cin >> old_height;

  // use a "post-test" do-while loop

  do
  {
    new_height = old_height / 2.0;
    cout << new_height << endl;

    difference = fabs(new_height - old_height);
    old_height = new_height;
  }
while (difference > 0.1);

    return 0;
}

% g++ bounce3.cpp
cswanson@shemp (~) % a.out
Enter the initial height of the ball: 64
32
16
8
4
2
1
0.5
0.25
0.125
0.0625


 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming