Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Unit 4 Assignment B

1. Programming Exercise #6
Write a program that reads a set of integers, and then finds and prints the sum of the even and odd integers. (15
points)
=START CODE=
#include<iostream>
using namespace std;
int main() {
//Set variables.
int evenNums = 0;
int oddNums = 0;
int ckCount = 0;
int count = 0;
int val = 0;
//Prompt for set length.
cout << "How many numbers are in your set of integers?: ";
cin >> count;
DoAgain:
//Prompt for value in set.
cout << "Please enter a number for value #"<< (ckCount+1) << ": ";
cin >> val;
//If the value isn't an integer, then warn user, clear value and try again.
if (cin.fail()) {
cout << "WARNING: You entered an invalid number." << endl;
cin.clear();
cin.sync();
goto DoAgain;
//If the value is within the set length, then do...
} else if (ckCount < count) {
//If the value is even, add to even, otherwise add to odd.
if (val % 2 == 0) {
evenNums = evenNums + val;
} else {
oddNums = oddNums + val;
}
ckCount ++;
//Only if the new length is within the set length, proceed again.
if (ckCount < count) {
goto DoAgain;
}
}
//Print out values.
cout << "The total of the even numbers is : " << evenNums << endl;
cout << "The total of the odd numbers is : " << oddNums << endl;
return 0;
}
=END CODE=

2. Programming Exercise #7
Write a program that prompts the user to input a positive integer. It should then output a message indicating
whether the number is a prime number. (15 points)
=START CODE=
#include <iostream>
using namespace std;
int main() {
int num = 0;
int count = 0;
cout << "Please type a number to check if its a prime: ";
cin >> num;
//Check the number to see if it's prime.
for(int i=2;i <= (num/2);i++){
if(num%i == 0) {
count++;
break;
}
}

Break out if it's not a prime number.

//If the count is zero, then the number is a prime number.


if (count == 0) {
cout << "Yes! " << num << " is a prime number." << endl;
//If the count is greater than zero, then the number isn't a prime number.
} else {
cout << "Sorry! " << num << " isn't a prime number." << endl;
}
return 0;
}
=END CODE=

You might also like