I've been stuck on this for almost two weeks now, could someone guide me? I'm supposed to have the user input an initial start value, and integer they want to end with, and a stepping integer (what the start value will be multiplied by).
EX.
Starting Integer: 10
Ending Integer: 200
Stepping Integer: 20
Output: 10, 30, 50, 70, 90, ...., 200
And when user inputs false values like a smaller ending integer than starting integer, message prompts them to try again.
I got the whole message prompting down I believe, not sure how to get the starting integer to be multiplied by stepping, and stop at ending integer.
This is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int step;
int stop;
int start = -1; //Local variable declaration
cout << "Please enter a positive integer you'd like to start with." << endl; //Starting integer
cin >> start;
if (start < 0)
cout << "Please enter a positive integer.";
if (start >= 0)
cout << "Please enter an integer to end with, it must be bigger than previous number chosen."; //Ending integer
cin >> stop;
if (stop < start)
cout << "Please enter a value that is larger than the previous number chosen." << endl;
if (stop > start)
cout << "Please enter the value you'd like to increase by." << endl; //Stepping integer
cin >> step;
cout << "Integers:";
while (start < stop)
{
cout << start << ", ";
start+=step;
}
return 0;
}
When I run it, it'll go through the entire for loop, and display the while loop but as only the stepping integer the user input, and then exits immediately.
EDIT - Code above is updated from previous code
Thanks for all the help so far! I've taken out the for loop as mentioned, and removed 'cin >> start;' after "Please enter a positive integer." - That was the reason why my program wasn't running through the whole cycle.
The program runs flawlessly if the user follows instructions first time around, however if they input a negative value first, they'll get the results below:
Input: -5
Output: Please put in a positive integer.
Input: 5
Output: Please enter the value you'd like to increase by.
And if they enter a stop value smaller than start value, they'll get the results below:
Input: 5
Output: Please enter a stop value larger....
Input: 3
Output: Integers:.........
How would I get the prompts to continue in order even after the user inputs negative value at first, and/or a smaller stop value than start? I don't think it'd be a cin; command, but please correct me if I'm wrong!
Maybe this can help:
int start = 10;
int stop = 200;
int step = 20;
do
{
cout << start << " ";
start = start + step; // increment. Shorter version: start += step;
} while (start < stop);
When getting the input try something like
int start = -1;
while(start < 0)
{
cout << "Please enter a positive integer you'd like to start with." << endl;
cin >> start;
}
and do something similar for stopand step, for instance
int end = -1;
while(end < start)
{
cout << "Please enter an integer to end with, it must be bigger than previous number chosen."; //Ending integer
cin >> end;
}
Instead of incrementing start by 1, increment it by step.
Also, you need to output the start variable, not step. Outputting step as you did before will just result in:
Integer: 20
Integer: 20
Integer: 20
....
Here are the changes I made:
cout << "Integers: ";
while(start < end)
{
cout << start << ", ";
start+=step;
}
Also, the for loop is not needed, it breaks out of it at the bottom regardless, so just delete the for loop.
Related
I have used a loop for that:
int number1;
int sum=0;
for(int i =1; i<6; i++){
cout<<"Enter number:\n";
cin>>number1;
sum+=number1;
}
cout<<sum;
cout<<"Total Sum is = "<<sum<<"\n";
return 0;
}
My question is how can I print first statement like this ...
"Enter first number"
Enter Second number" and so on
Whenever you are reading numbers (or any value for that matter), you must check the stream-state (see: std::basic_istream State Functions). You have four stream states you must test following every input:
.bad() or .eof(). If badbit is set an unrecoverable error occurred, and if eofbit is set, there is nothing more to read (you can combine both into a single test that exits if either are set)
.fail() is set when a read error occurs, such as the user entering "FIVE" instead of 5 where integer input is expected. You handle failbit being set by calling .clear() to clear failbit and then call ignore() to empty the characters causing the failure before your next read attempt, and finally
.good() - valid input was received from the user, you can proceed to the next input.
By validating your input here, you can Require the user provide 5 valid integer values for you to sum. Do not use a for loop, instead use a while (or do .. while();) and only increment your counter when good input is received.
Putting that altogether, you can do:
#include <iostream>
#include <limits>
int main (void) {
int number = 0,
sum = 0;
const char *label[] = { "first", "second", "third", "fourth", "fifth" };
while (number < 5) /* loop continually until 5 int entered */
{
int tmp; /* temporary int to fill with user-input */
std::cout << "\nenter " << label[number] << " number: ";
if (! (std::cin >> tmp) ) { /* check stream state */
/* if eof() or bad() exit */
if (std::cin.eof() || std::cin.bad()) {
std::cerr << " (user canceled or unreconverable error)\n";
return 1;
}
else if (std::cin.fail()) { /* if failbit */
std::cerr << " error: invalid input.\n";
std::cin.clear(); /* clear failbit */
/* extract any characters that remain unread */
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
else { /* on succesful read of int, add to sum, increment number */
sum += tmp;
number++;
}
}
std::cout << "\nsum: " << sum << '\n';
}
Now your code will gracefully handle an invalid input without exiting just because a stray character was entered.
Example Use/Output
When you write an input routine, go try and break it. Enter invalid data and make sure you handle all error cases correctly. If something doesn't work right, go fix it. Repeat until you input routine can handle all corner-cases as well as the cat stepping on the keyboard:
$ ./bin/sumintlabel
enter first number: 3
enter second number: four five six seven!!
error: invalid input.
enter second number: 4
enter third number: 5
enter fourth number: 6
enter fifth number: 7
sum: 25
Form good habits now regarding handling input, it will pay dividends for the rest of your programming career. Let me know if you have questions.
if you need to print the words "first"... untill "fifth" then I'd do it like this:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int number1;
int sum=0;
string positions[5] = {"first", "second", "third", "fourth", "fifth"};
for(int i = 0; i<5; i++){
cout<<"Enter the " << positions[i] << " number:" << endl;
cin>>number1;
sum+=number1;
}
cout<<"Total Sum is = "<<sum<<"\n";
return 0;
}
I used an array of strings to display the words and changed the for loop to start at 0 so that we can go through the array positions and add the 5 numbers as well. If you just want to use: 1st, 2nd, 3rd... then you could change the for loop to what it was and do:
cout<<"Enter the " << i << "st" << " number:" << endl;
But for this you would have to use the if statement to print the right endings("st", "rd", "nd"). I think it would take longer for it to run but its miliseconds so we wouldn't even notice hahaha.
Hope it helped :)
You can use switch():
#include <iostream>
using std::cin;
using std::cout;
using std::string;
int main() {
int number1;
int sum = 0;
for(int i = 1; i < 6; i++) {
string num;
switch(i) {
case 1:
num = "first";
break;
case 2:
num = "second";
break;
//and 3 4 5 like this
}
cout << "Enter " << num << " number:\n";
cin >> number1;
sum += number1;
}
cout << "Total Sum is = " << sum << "\n";
return 0;
}
or you can use struct or containers like vector (in fact you have to use containers if you want to get a huge number of data.)
So I'm busy with a school project and new to C++ and I'm a bit stuck, so here is the question:
When your program begins, it should prompt the user to enter an integer number greater than or equal to 1. This number should be assigned to a variable called control.
You must create a for loop that iterates a number of times equal to control. Each time it iterates, it must append a numeric digit to a string, with the first digit added being 1, and for each iteration, the next number is the previous number multiplied by the original number input. Additionally, the spaces that would ordinarily be between the numbers must instead be the ”#” symbol.
Once the loop is finished iterating, it must display the string that you have constructed.
As a hint, consider the use of string streams for converting between integer to string.
Examples of this program are below:
Please enter a number: 3
1#3#9
Please enter a number: 5
1#5#25#125#625
Please enter a number: 1
1
And here is my code so far :
int main()
{
int control;
int value;
string final;
int test;
stringstream convert;
cout << "Please enter a number: " << endl;
cin >> control;
if (control >= 1)
{
value = 1;
for (int count = 2; count <= control; count++)
{
value = value * control; <---- SO IM STUCK HERE
convert << value; TRYING TO INSERT "#"
final = convert.str() + "#"; BETWEEN THE VALUES
}
cout << "1#" << final << endl;
}
else
{
cout << "Please enter a valid number!" << endl;
}
system("pause");
return 0;
}
Thanks in advance for the help.
Okay so it seemed to be a very simple fix, I feel like an idiot but thanks for the help.
Old code : convert << value;
New code : convert << '#' << value;
/**
Write a program that reads a series of numbers and stores them in a vector. After the user inputs all the numbers he or she wishes to, ask how many of the numbers the user wants to sum. For an answer N. print the sum of the first N elements of the vector. For example: "Please enter some numbers (press 'I' at prompt to stop ) : " 12 23 13 24 15 "Please enter how many of the numbers you wish to sum, starting from the first:" 3 "The sum of the first 3 numbers : 12, 23, and 13 is 48." Handle all inputs. For exam ple, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector.
**/
#include<iostream>
#include<vector>
using namespace std;
int main()
{
try
{
vector<int> numbers;
int num;
cout<<"Now enter the numbers";
while(cin>>num)
numbers.push_back(num);
int n,sum=0;
cout << "Enter the nth number to find sum of elements till n : ";
cin>>n;
if(n >numbers.size())
throw 66;
for(int i=0;i<n;i++)
sum+=numbers[i];
cout << "sum is "<<sum;
return 0;
}
catch(int k)
{
cerr<<"Error "<<k;
return -1;
}
}
So , when I enter EOF , CTRL+D , the program terminates. I am not sure where it is going wrong. I even tried to debug using gdb(with the help from an online tutorial) . It didn't just work out . can someone tell me what's wrong with the code ?
You are not checking if you actually read anything.
Consider this little test program:
#include <iostream>
int main()
{
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
int n = -42;
std::cin >> n;
std::cout << n << "\n";
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
n = -42;
std::cin >> n;
std::cout << n << "\n";
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
}
The output, when fed with an empty standard input (which is equivalent to immediately declaring its end with ctrl+d) is:
std::cin is ready
-42
std::cin is done
-42
std::cin is done
As you can see, n is never changed, as there is never a new value to change it to! Also, you can easily spot that the state of std::cin reflects if the previous read went past the end.
Since you are only checking the value of your integers without ensuring that they have a sane default (just check what happens to n if it is not set by reading the input), this can easily lead to your program exhibiting unexpected behavior.
Note: The behavior of the test program is different when fed input that simply is not a number.
When you supply cin with EOF it causes cin.failbit to become true. With the failbit set to true, all subsequent cin reads will be ignored. Since n has no default value execution becomes unpredictable from here. In my case the program was crashing because it was throwing 66. Adding cin.clear() after the while loop will fix this, but is not advisable. Two simple solutions would to stop on a magic number/prompt the user after every input if they want to continue.
Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...
Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!