CSCI 240 - Loops Worksheet 2

C++ Solutions

Note the similarities in the loops.

1a.	int i, sum;
	sum = 0; 
	for (i = 1; i < 11; i++) 	// or use i <= 10 
	  { 
	  sum += i;
	  cout << "\nCurrent sum is " << sum);
	  }
1b.   	Change for statement to
	for (i = 1; i < 51; i++)
1c.   	Change for statement to
	for (i = 1; i < 101; i++)
2.	int i, sum; 
	sum = 0; 
	for (i = 2; i < 10; i++)
	  { 
	  sum += i; 
	  cout << "\nCurrent sum is " << sum;
 	  }
3a.	int i;
	for (i = 3; i <= 20; i+=3)
	  {
	  cout << "\n" << i;
	  }

Here you start with the first multiple and increment by the number that you are finding multiples of. You must know the first multiple.

		OR
	for  (i = 1; i <= 20; i++)
	  {
	  if (i % 3 == 0)
	    cout << "\n" << i;
	  }

Here you increment by 1, but only print it if it is a multiple.

3b.	int i;
	for (i = 100; i <= 200; i++)
	  { 
	  if (i % 3 == 0) 
	    cout << " " << i);
	  }

By using the 2nd version, you do not need to know the first multiple.

3c.	int i, begin, end; 
	cout << "\nEnter the beginning of the search range: "; 
	cin >> begin; 
	cout << "\nEnter the end of the search range: "; 
	cin >> end; 
	for (i = begin; i <= end; i++)
	  {
	  if (i % 3 == 0)
	    cout << " " << i;
	  }
4.	#include ...
	#include ...
	void main() 
	  { 
          int i, begin, end, base;  
          cout << "\nEnter the beginning of the search range: "; 
	  cin >> begin; 
	  cout << "\nEnter the end of the search range: "; 
	  cin >> end; 
	  cout << "\nEnter the integer whose multiples you want: "; 
	  cin >> base; 
	  for (i = begin; i <= end; i++) 
	    { 
	    if (i % base == 0) 
	      cout << " " << i;
	    }
          }