While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.
"Count positive and negative numbers and compute the average of numbers Write a program that reads an unspecified number of integers , determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a double. where did i go wrong??
#include <iostream>
using namespace std;
int main()
{
int num= 0;
int sum=0;
int pos=0;
int neg=0;
double ave=0;
cout << "Enter an integer, the input ends if it is 0: " ;
cin >> num ;
if (num%10==10) {
while (num!=0) {
num/=10;
if (num%10>0) {
pos++;
}
else if (num%10<0) {
neg++;
}
sum+=num;
}
ave= (double)sum/(pos+neg);
}
cout <<"The number of positives are " << pos <<endl;
cout <<"The number of negatives are " << neg <<endl;
cout <<"The total is " << sum << endl;
cout <<"The average is "<< ave << endl;
return 0;
}
You can use char[] to read input.
I have modified your program as follows;
int main()
{
int sum=0;
int pos=0;
int neg=0;
double ave=0;
char arr[100] = {'\0',};
std::cout << "Enter an integer, the input ends if it is 0: " ;
gets(arr);
int index = 0;
char ch[1];
bool negativeNumber = false;
while(true)
{
ch[0] = arr[index++];
if(ch[0] == ' ') // Check space and continue;
{
continue;
}
else if(ch[0] == '0' || ch[0] == '\0') // check for 0 or NULL and break;
{
break;
}
if(ch[0] == '-') // Set flag if "-ve"
{
negativeNumber = true;
continue;
}
int digit = atoi(ch);
if(negativeNumber)
{
digit *= -1;
negativeNumber = false;
}
if(digit > 0)
{
pos++;
}
else if(digit < 0)
{
neg++;
}
sum += digit;
}
ave= (double)sum/(pos+neg);
cout <<"The number of positives are " << pos <<endl;
cout <<"The number of negatives are " << neg <<endl;
cout <<"The total is " << sum << endl;
cout <<"The sverage is "<< ave << endl;
return 0;
}
Hope this helps.
The purpose of this program is to take an input of an arabic number and return the equivelant roman numeral. it needs to reject input less than 0 and greater than 3999, but also end on an input of ANY NEGATIVE NUMBER. Also needs an input fail catch for entering a letter instead of an integer. (completely clueless on this part?!)
My question is what order should these conditional statement be in so that the program doesnt just return invalid input for a negative number, it ends the program.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string convert(int digit, string low, string mid, string high);
int main()
{
const int MAX_INPUT = 3999, MIN_INPUT = 0, // These constants hold high and low integer numbers,
ARRAY_SIZE = 4; // and the array size declarator.
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
do {
cout << "Enter a negative number to end the program.\n";
cout << "Enter an arabic number between 1 and 3999: ";
cin >> userNum;;
if (userNum < 0)
{
cout << "Exiting program:";
break;
while (userNum <= MIN_INPUT || userNum >= MAX_INPUT)
{
cout << "\nInvalid Value. Number must be between 1 and 3999: ";
cin >> userNum;
}
}
int thous = userNum / 1000;
cout << thous;
int hund = userNum % 1000 / 100;
cout << "hundreds:" << hund;
int tens = userNum % 100 / 10;
cout << "tens:" << tens;
int ones = userNum % 10 / 1;
cout << "Ones: " << ones << endl;
answers[0] = convert(thous, "M", "M", "M");
answers[1] = convert(hund, "C", "D", "M");
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << endl << answers[1] << endl << answers[2];
cout << endl << answers[3] << endl;
} while (userNum > 0);
system("PAUSE");
return 0;
}
string convert(int digit, string low, string mid, string high)
{
cout << digit << endl;
if (digit == 1)
{
return low;
}
if (digit == 2)
{
return low + low;
}
if (digit == 3)
{
return low + low + low;
}
if (digit == 4)
{
return low + mid;
}
if (digit == 5)
{
return mid;
}
if (digit == 6)
{
return mid + low;
}
if (digit == 7)
{
return mid + low + low;
}
if (digit == 8)
{
return mid + low + low + low;
}
if (digit == 9)
{
return low + high;
}
if (digit == 0)
{
return "";
}
}
A possible solution with minimal refactoring of your current code:
int main()
{
const int MAX_INPUT = 3999, MIN_INPUT = 0, // These constants hold high and low integer numbers,
ARRAY_SIZE = 4; // and the array size declarator.
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
do {
cout << "Enter a negative number to end the program.\n";
cout << "Enter an arabic number between 1 and 3999: ";
//cin >> userNum;;
while(!(cin >> userNum) || (userNum < 1 || userNum > 3999)){
if (userNum < 0)
{
cout << "Exiting program:";
return 0;
} else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "\nInvalid Value. Number must be between 1 and 3999. Try again ";
}
}
int thous = userNum / 1000;
cout << thous;
int hund = userNum % 1000 / 100;
cout << "hundreds:" << hund;
int tens = userNum % 100 / 10;
cout << "tens:" << tens;
int ones = userNum % 10 / 1;
cout << "Ones: " << ones << endl;
answers[0] = convert(thous, "M", "M", "M");
answers[1] = convert(hund, "C", "D", "M");
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << endl << answers[1] << endl << answers[2];
cout << endl << answers[3] << endl;
} while (userNum > 0);
system("PAUSE");
return 0;
}
In sudo code:
while (inputVar >= 0) {
try {
inputVar = stoi(inputVar)
} catch {
print("Input error")
}
if in range(min to max) {
roman = romanEquiv(inputVar)
print(roman)
} else {
print("Invalid entry.")
}
}
Try-catch blocks (for catching exceptions you know your program should handle)
std::stoi a function in the cpp library to try and convert a string to an integer
Hope this helps, let me know how it goes.
I revised the beginning of the main method and the beginning of the while loop.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#define MAX_INPUT 3999 // These constants hold high and low integer numbers,
#define MIN_INPUT 1
#define ARRAY_SIZE 4 // and the array size declarator.
string convert(int digit, string low, string mid, string high);
int main()
{
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
string strUserNum;
do {
cout << "Enter a negative number to end the program.\n";
cout << "Enter an arabic number between 1 and 3999: ";
cin >> strUserNum;
userNum = std::stoi(strUserNum);
if (userNum == 0 || userNum > MAX_INPUT)
{
cout << "\nInvalid Value. Number must be between 1 and 3999: " << endl;
continue;
}
else if (userNum < MIN_INPUT)
{
cout << "Exiting program:";
break;
}
int thous = userNum / 1000;
cout << "thousands: " << thous;
int hund = userNum % 1000 / 100;
cout << " hundreds: " << hund;
int tens = userNum % 100 / 10;
cout << " tens: " << tens;
int ones = userNum % 10 / 1;
cout << " ones: " << ones << endl;
answers[0] = convert(thous, "M", "M", "M");
answers[1] = convert(hund, "C", "D", "M");
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << endl << answers[1] << endl << answers[2];
cout << endl << answers[3] << endl;
} while (userNum >= 0);
system("PAUSE");
return 0;
}
string convert(int digit, string low, string mid, string high)
{
cout << digit << endl;
if (digit == 1)
{
return low;
}
if (digit == 2)
{
return low + low;
}
if (digit == 3)
{
return low + low + low;
}
if (digit == 4)
{
return low + mid;
}
if (digit == 5)
{
return mid;
}
if (digit == 6)
{
return mid + low;
}
if (digit == 7)
{
return mid + low + low;
}
if (digit == 8)
{
return mid + low + low + low;
}
if (digit == 9)
{
return low + high;
}
if (digit == 0)
{
return "";
}
}
But I would like to also provide an alternative implementation of the string conversion ( from http://rosettacode.org/wiki/Roman_numerals/Encode#C.2B.2B ):
std::string to_roman(unsigned int value)
{
struct romandata_t { unsigned int value; char const* numeral; };
const struct romandata_t romandata[] =
{
{1000, "M"}, {900, "CM"},
{500, "D"}, {400, "CD"},
{100, "C"}, { 90, "XC"},
{ 50, "L"}, { 40, "XL"},
{ 10, "X"}, { 9, "IX"},
{ 5, "V"}, { 4, "IV"},
{ 1, "I"},
{ 0, NULL} // end marker
};
std::string result;
for (const romandata_t* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
result += current->numeral;
value -= current->value;
}
}
return result;
}
I would suggest you this C++14 code:
#include <utility>
#include <string>
auto toRoman(unsigned arabic)
{
constexpr auto table = {
std::make_pair(1000u, "M"),
std::make_pair(900u, "CM"),
std::make_pair(500u, "D"),
std::make_pair(400u, "CD"),
std::make_pair(100u, "C"),
std::make_pair(90u, "XC"),
std::make_pair(50u, "L"),
std::make_pair(40u, "XL"),
std::make_pair(10u, "X"),
std::make_pair(9u, "IX"),
std::make_pair(5u, "V"),
std::make_pair(4u, "IV"),
std::make_pair(1u, "I")
};
std::string roman;
for (auto& pair: table)
{
while (pair.first <= arabic)
{
arabic -= pair.first;
roman += pair.second;
}
}
return roman;
}
We're only interested in the #'s in the range [0,100]. There may be number outside the range [0, 100], but they aren't part of our calculation (i.e numbers below 0 and above 100 can be inputted but will be ignored in the calculations and counters).
Assume we assign ABCDF as
[85,100]: A
[75,85): B
[65,75): C
[55,65): D
[0,55): F
For each of the five letter grades, output the number of scores with that grade, and also, if the number of scores wasn't 0, output the average score with that grade. Also, if the number of valid scores (in [0, 100]) wasn't 0, output the average of all the scores
I am having trouble with this looping question. When I input multiple scores, it loops them incorrectly and outputs two sets of grades for each input rather than the example answer shown above. Also I am not sure if my break is placed correctly to exit the program when a word is inputted. Any help will be greatly appreciated!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
for (scores; cin >> scores;){
if (scores > 85 && scores <= 100){
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75){
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65){
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55){
grade = 'D';
countD++;
sumD += scores;
}
else{
grade = 'F';
countF++;
sumF += scores;
}
if (!cin){
break;
}
if (countA == 0){
cout << "# A's: 0 " << endl;
}
else {
cout << "# A's: " << countA << " Average = " << sumA/countA << endl;
} if (countB == 0){
cout << "# B's : 0 " << endl;
}
else{
cout << "# B's: " << countB << " Average = " << sumB /countB << endl;
} if (countC == 0){
cout << "# C's: 0 " << endl;
}
else{
cout << "# C's: " << countC << " Average = " << sumC /countC << endl;
} if (countD == 0){
cout << "# D's: 0 " << endl;
}
else {
cout << "# D's: " << countD << " Average = " << sumD /countD << endl;
} if (countF == 0){
cout << "# F's: 0 " << endl;
}
else {
cout << "# F's: " << countF << " Average = " << sumF /countF << endl;
}
}
TL;DR version: Closing brace on the for loop was missing. Loop never ended and caused OP's output code to also loop.
Long version:
Here is working code. The stuff I changed is marked with comments.
#include <iostream> //removed a bunch of unused includes.
using std::cin; // including all of namespace::std is overkill and often
using std::cout; // leads to hard-to-solve bugs. Only use what you need
using std::endl;
int main()
{
double scores;
unsigned countA = 0;
unsigned countB = 0;
unsigned countC = 0;
unsigned countD = 0;
unsigned countF = 0;
char grade;
double sumA = 0, sumB = 0, sumC = 0, sumD = 0, sumF = 0;
cout << "Enter scores: ";
// for (scores; cin >> scores;){
while (cin >> scores) // cleaner
{
if (scores > 85 && scores <= 100)
{
grade = 'A';
countA++;
sumA += scores;
}
else if (scores > 75)
{
grade = 'B';
countB++;
sumB += scores;
}
else if (scores > 65)
{
grade = 'C';
countC++;
sumC += scores;
}
else if (scores > 55)
{
grade = 'D';
countD++;
sumD += scores;
}
else
{
grade = 'F';
countF++;
sumF += scores;
}
// this test is made redundant by the loop condition
// if (!cin)
// {
// break;
// }
} // this was missing. The loop kept going and included all of
// the following code in the loop.
if (countA == 0)
{
cout << "# A's: 0 " << endl;
}
else
{
cout << "# A's: " << countA << " Average = " << sumA / countA << endl;
}
if (countB == 0)
{
cout << "# B's : 0 " << endl;
}
else
{
cout << "# B's: " << countB << " Average = " << sumB / countB << endl;
}
if (countC == 0)
{
cout << "# C's: 0 " << endl;
}
else
{
cout << "# C's: " << countC << " Average = " << sumC / countC << endl;
}
if (countD == 0)
{
cout << "# D's: 0 " << endl;
}
else
{
cout << "# D's: " << countD << " Average = " << sumD / countD << endl;
}
if (countF == 0)
{
cout << "# F's: 0 " << endl;
}
else
{
cout << "# F's: " << countF << " Average = " << sumF / countF << endl;
}
}
Your question is a bit confusing, I assume your main issue is the output part. Currently your code produces this.
As you see we get intermediate output, after every score entered. To change that the loop needs to be split into two loops: One for input, and one for output that runs after the first:
while (/* we get scores */) {
// update the counters and sums
}
for (/* every score */) {
// print count and average
}
To generate the output in a loop you need to store your data in some "loopable" way. Currently you have multiple local variables. Changing that to an array (indexed by the respective grade) allows us to loop over the data:
unsigned counter[5];
double sum [5];
// A -> 0, B -> 1, ..., F -> 4
for (std::size_t it = 0; it < 5; ++it) {
// use sum[it] and counter[it]
}
But raw arrays (as raw pointers) are evil - only use them when absolutely necessary - we use std::array from the standard library. And to ease iteration and improve logical encapsulation it's good to keep sum and count of each grade together:
struct grade_info {
unsigned count = 0;
double sum = 0;
};
// ... later in the main function
std::array<grade_info, 5> grades;
// input
for (auto const & grade : grades) { // C++11 shorthand to iterate over a collection
// use grade.count and grade.sum
}
Concerning your input:
for (scores; cin >> scores;){
This does the right thing, but is a bit strange. Since scores will only be used inside that loop instead of declaring it as local variable of main we only declare it inside the loop:
for (double score; // only a single score is in that variable at any time
cin >> score; // ends the loop on eof or failure to convert to double (when text got entered)
// no step instructions, the above check does that already
) {
Now there's also no need to test cin inside the loop. The operator>> returns (a reference to) its first argument, which is cin, so the test in the for loop already tests cin, no need for if (! cin) { break; }.
Then you have code like this
grade = 'A';
when you never use the value stored in grade. Just remove that.
Last but not least your input validation isn't working (the 101 in my test case is treated as grade B):
if (scores > 85 && scores <= 100) {
// scores between (85, 100]
}
// scores is either <= 85 OR > 100
else if (scores > 75){
// scores is in (75, 85] OR > 100
}
Ideally you should keep input validation and business logic separated:
if (not input_is_valid(score)) {
continue; // the loop
}
// business logic, assuming valid input
So, the final code could be
#include <iostream>
#include <array>
struct grade_info {
unsigned count = 0;
double sum = 0;
char const name;
grade_info(char n) : name(n) {
}
};
bool input_is_valid(double score) {
return (score >= 0) and (score <= 100);
}
std::size_t score_to_grade_index(double score) {
if (score >= 85) {
return 0;
} else if (score >= 75) {
return 1;
} else if (score >= 65) {
return 2;
} else if (score >= 55) {
return 3;
} else {
return 4;
}
}
int main(int, char**) {
std::array<grade_info, 5> grades {'A', 'B', 'C', 'D', 'F'};
for (double score; std::cin >> score;) {
if (not input_is_valid(score)) {
continue;
}
auto index = score_to_grade_index(score);
++(grades[index].count);
grades[index].sum += score;
}
for (auto const & grade : grades) {
std::cout << "# " << grade.name << ": "
<< grade.count;
if (grade.count > 0) {
std::cout << " avg: " << (grade.sum / grade.count);
}
std::cout << std::endl;
}
return 0;
}
Live here
I have problem running my loops.
I have to run a program where user enter 4 digit number, and it will show how many zero appear. This program will run depends on how many times user want it to run. so at the beginning I prompt user to enter the number of times the program will run, then the actual program will run in For loop. but so far, I can only run it once. Can someone help me? Thank you. Here is my code
#include <iostream>
using namespace std;
int main()
{
int numberTimes;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
for (int counter = 0; counter < numberTimes; counter++);
{
int positiveInteger;
//prompt user to enter a positive integer
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
//conditional statement
while((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Please try again.\n";
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
}
cout << "Processing the value " << positiveInteger << ".\n";
int zeroCount = 0;
int firstNumber = positiveInteger%10; //separate the first number
if (firstNumber == 0) //determine if the first digit is zero
{
zeroCount = zeroCount + 1;
}
int digitOne = positiveInteger/10; //omitted first digit number
int secondNumber = digitOne%10; //separate the second number
if (secondNumber == 0) //determine if the second digit is zero
{
zeroCount = zeroCount + 1;
}
int digitTwo = digitOne/10; //omitted the second number
int thirdNumber = digitTwo%10; //separate the third number
if (thirdNumber == 0) //determine if the third digit is zero
{
zeroCount = zeroCount + 1;
}
int digitThree = digitTwo/10; //omitted the third number
int fourthNumber = digitThree%10; //separate the fourth number
if (fourthNumber == 0) //determine if the fourth digit is zero
{
zeroCount = zeroCount + 1;
}
cout << "Your first digit number is " << firstNumber << ".\n";
cout << "Your second digit number is " << secondNumber << ".\n";
cout << "Your third digit number is " << thirdNumber << ".\n";
cout << "Your fourth digit number is " << fourthNumber << ".\n";
cout << "Number of zero appear in your integer is " << zeroCount << ".\n";
if (zeroCount % 2 == 0) //determine if the number is even or odd
{
cout << "Your number zero appear even times.\n";
} else
{
cout << "Your number zero appear odd times.\n";
}
}
cout << "You have run this program " << numberTimes << ".\n";
cout << "Thank you and good bye.";
return 0;
}
The problem is using ; at the end of for line.
for (int counter = 0; counter < numberTimes; counter++);
In such a case that you used, it iterate the loop but do nothing.
In the other word,it is equal to the below program now :
for (int counter = 0; counter < numberTimes; counter++)
{
}
You can also use this program : (Add complementary lines)
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int numberTimes;
int digit;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
while(numberTimes)
{
int zeroRepitation=0;
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
if ((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Try again!\n";
continue;
}
for (int i=1;i<5;i++)
{
digit = positiveInteger % 10;
if (digit=0)
{
++zeroRepitation;
}
positiveInteger = positiveInteger / 10;
}
cout<<"Number of zeros in this number= "<<zeroRepitation;
--numberTimes;
}
You put a semicolon at the end of the for statement. This:
for (int counter = 0; counter < numberTimes; counter++);
should be this:
for (int counter = 0; counter < numberTimes; counter++)