Selected-Programming-Exercises-Ch5
Selected-Programming-Exercises-Ch5
ExProg1: Write a program that reads a set of integers and then finds
and prints the sum
of the even and odd integers.
Solution:
#include <iostream>
#include <iomanip>
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
cout << "Please enter " << N << " integers" << endl;
cout << "The numbers you entered are: " << endl;
if (number % 2 == 0)
sumEvens = sumEvens + number; //update even sum
else
sumOdds = sumOdds + number; //update odd sum
}
Sample Run:
ExProg2: Write a program that uses while loops to perform the following
steps:
a) Prompt the user to input two integers: firstNum and secondNum
(firstNum must be less than secondNum).
b) Output all odd numbers between firstNum and secondNum.
c) Output the sum of all even numbers between firstNum and
secondNum.
d) Output the numbers and their squares between 1 and 10.
e) Output the sum of the square of the odd numbers between firstNum
and secondNum.
f) Output all uppercase letters.
Solution:
#include <iostream>
#include <iomanip>
int main()
{
int firstNum, secondNum;
int sumEven = 0;
int sumSquareOdd = 0;
char chCounter;
int counter;
//Part a
cout << "Enter two numbers." << endl;
cout << "First number must be less than "
<< "the second number you enter" << endl;
cout << "Enter numbers: " << flush;
cin >> firstNum >> secondNum;
cout << endl;
//Part b
if (firstNum % 2 == 0)
counter = firstNum + 1;
else
counter = firstNum;
cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;
//Part c
if (firstNum % 2 == 0)
counter = firstNum;
else
counter = firstNum + 1;
cout << "Sum of even integers between " << firstNum << " and "
<< secondNum << " = " << sumEven << endl;
//Part d
cout << "Number Square of Number" << endl;
counter = 1;
while (counter <= 10)
{
cout << setw(4) << counter << setw(18)
<< counter * counter << endl;
counter++;
}
//Part e
if (firstNum % 2 == 0)
counter = firstNum + 1;
else
counter = firstNum;
while (counter <= secondNum)
{
sumSquareOdd = sumSquareOdd + counter * counter;
counter = counter + 2;
}
//Part f
cout << "Upper case letters are: ";
chCounter = 'A';
while (chCounter <= 'Z')
{
cout << chCounter << " ";
chCounter++;
}
cout << endl;
return 0;
}
Sample Run:
Enter two numbers.
First number must be less than the second number you enter
Enter numbers: 9
10
Solution:
#include <iostream>
#include <iomanip>
int main()
{
int townAPop;
int townBPop;
double growthRateTownA;
double growthRateTownB;
int numOfYears = 0;
cout << "After " << numOfYears << " year(s) the population of town A "
<< "will be greater than or equal to the population of town B." <<
endl;
cout << "After " << numOfYears << " population of town A is "
<< townAPop << endl;
cout << "After " << numOfYears << " population of town B is "
<< townBPop << endl;
cin.ignore();
cin.get();
return 0;
}
Sample Run: