Homework 7

Due: 3/25/04

Task: For problems 1-3, create a table that contains the intial values of a and x, and their values at the end of each time through the loop. How many times does the loop run? What are the values of a and x when the loop finishes?

1.

int x = 256;
int a = 1;
while( x > 0 )
{
	a = a * 3;
	x = x/2;
}


2.
int x = 0;
int a = 0;
while( x <= 10 )
{
	if(x%2 == 0)
	{
		a = a + x;
	}
	else
	{
		a = a * x;
	}
	x++;
}


3.
int x = 0;
int a = 1;
while ( x < 100 )
{
	if( a % 3 == 0 )
	{
		a = a*a-2;
		x = x*2;
	}
	else
	{
		a = 2*a + 1;
		x++;
	}
}


4. What is the output of the following program?

#include <iostream>

using namespace std;

int main()
{
	int	x=1, num, out=1;

	cout << "Enter a number." << endl;
	cin >> num;

	while( x <= num ) 
	{
		if(num%x == 0)
		{
			cout << x << " is a factor of " << num << endl;
		}
		x++;
	}
}


5. What is the output of the following program?

#include <iostream>

using namespace std;

int main()
{
	int	x=0, num, pow=1;

	cout << "Enter a number." << endl;
	cin >> num;

	while( x <= num )
	{
		cout << "2 to the " << x << " power is " << pow << endl;
		pow = 2 * pow;
		x++;
	}
}
			


Purpose: After grading the midterms, it is obvious that we need more practice analyzing programs. This assignment will, hopefully, give you that practice.