Questions:
why is the first "cin >>" having "score[0]" saved to it? Since the program is asking for 5 numbers, wouldn't it make sense to save the entered numbers into an array of 5 ("score[4]")?
I also don't understand the syntax of the second "cin >> score[i]." I thought "cin>>" was coupled with "cout<<" when there was data input.
//Enter five scores. Show how much each differs from the highest score.
#include <iostream>
using namespace std;
int main()
{
int i, score[5], max;
cout<<"Enter 5 scores:\n";
cin >> score[0];
max = score[0];
for (i = 1; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
cout <<"Highest score: " <<max<<endl
<<"The scores and their\n"
<<"diff. from highest are:\n";
for (i = 0; i < 5; i++)
cout << score[i] << " off by "
<< (max - score[i]) << endl;
return 0;
}
cin is stdin. This is a UNIX thing. Basically it's the input to your program. If you don't do anything else, it's your console or terminal session.
cout is stdout, another UNIX thing. It's output. Again, your console or terminal session if you don't do anything else with it. They aren't really coupled. It's two separate things, one for input only, one for output only.
Now, let's look at your code:
cin >> score[0];
max = score[0];
for (i = 1; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
This could be simplified. You could get rid of the first two lines and change it to just this:
for (i = 0; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
You'll just have to initialize max to a really negative value.
What cin >> does here is read a SINGLE value -- one score -- and then you stuff it into a single member of score. So you can NOT do something like this:
cin >> score;
That just won't work. Well, you might be able to make it work with operator overloading, but that's an advanced topic, and I've never tried. (I frankly never use the >> operator but find other ways to get input.)
Another thing: score[4] refers not to an array of size 5, but to the 5th item in the array, just like score[0] refers to the first item. It only refers to the size in the initial definition:
int score[5];
That's the only time the [5] is about the size. Otherwise it's an index into the array, starting at 0. So you have score[0] ... score[4].
Related
I wanted to write a code where user will give input the element of the array and then the elements will be print as an array. Here is my code but the code do not give the array as output.
#include<iostream>
using namespace std;
int main(){
int arr[100] , size , i , num ; //Here we are defining the maximum size of array is 100. So user can choose the size of array by him/her but cannot choose more than 100
cout << "Enter the size of array (Maximum array size you can take is 100) : ";
cin >> size;
if (size > 100)
{
cout << "You cannot take the size more than 100" << endl;
}else{
cout << "Inter the elements using space : ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter data you want to insert : ";
cin >> num;
for (int i = size - 1 ; i >= 0 ; i--)
{
arr[i+1] = arr[i];
}
arr[0] = num;
size++;
}
cout << arr[i] << endl;
return 0;
}
Your question isn't entirely clear, but I see two basic problems.
First, you define variable i at the top of your code. That's fine, although there are arguments for variable names being longer than a single character. Think about searching for uses of that variable -- you're going to get it in all sorts of places that have nothing to do with the variable. while has an i. if has an i. Be that as it may.
But here's a real problem. You have some for loops like this:
for (int i = 0; ....)
There's nothing wrong with that, not exactly. It works. HOWEVER, it's considered bad form to reuse a variable inside an inner block that matches a variable from an outer block. It's legal, but it's a common source of bugs. I recommend you don't do it.
Then, at the bottom, you do this:
cout << arr[i] << endl;
At this point, we're back to the original variable i that you declare at the top. But you never actually initialize it, so it's some random value. And you're not doing any sort of loop.
I suspect if you wrap this inside another of your for-loops, you'd get the results you want.
And get rid of declaring i at the top.
I've written a program that returns the median value of a user-defined array. While I've put a few checks in my code (array size can not be negative) I keep running into one issue I simply can not fix (for clarity sake, assume strings and alphabetical characters will not be used).
All of my input values are int however the user could just as easily enter in a float. When they do this (either for size of array or entering in the element) it breaks my code. I've tried multiple things to try and catch this, but it seems like the way my program is getting the value doesn't allow for the catch in time.
#include <iostream>
using namespace std;
void sort(int * a,int n)
{
for(int i=0;i<n;++i)
for(int j=i+1;j<n;++j)
{
if(a[i]>a[j])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}\
}
return;
}
int main()
{
int n;
int check;
int x;
cout<<"Enter length of array:";
cin>>n;
if (n < 0){
while (n < 0){
cout << "Please enter a length greater than 0" << endl;
cin >> n;
}
} else if (n % 1 != 0){
while (n % 1 != 0){
cout << "Whole numbers only! Try again" << endl;
cin >> n;
}
}
if (n == 0){
cout <<"You try to enter numbers, but there's no place to put them." << endl;
cout << ":(";
return 0;
}
int a[n];
cout<<"Enter values one by one:\n";
for(int i=0;i<n;++i){
cin >> x;
a[i] = int(x);
}
sort(a,n);
if (n % 2 == 1){
cout<<"Median is:"<<a[n/2]<<endl;
}
else{
float z = (float(a[n/2]) + float(a[(n/2)-1])) / 2;
cout << "Median is:" << z << endl;
}
return 0;
}
First thing I tried was catching the float like so
`if (n % 1 !=0){
while(n % 1 !=0){
cout << "Enter a whole number"
cin >> n
}
}`
This still broke my program. The odd thing was that I entered a float and then printed the value of n and it only showed the int value.
I tried using typeid.n() with #include <typeinfo>and comparing that to an int type to check it was the correct value, but that slipped through as well.
I tried doing an int cast, something like int(n) immediately after number was stored in n but before it went into a[n] and yet again, it still broke my code.
How can I check against float user-input and loop them until they give me an int?
You're reading into an int:
int x;
...
cin >> x;
So it will read what it can, then stop at e.g. a . and leave the rest on the stream (like if the user enters "123.4" you'll get 123 and then ".4" won't be consumed from the input stream).
Instead, you could read into a float:
float x;
...
cin >> x;
And do the appropriate math.
Alternatively you could read into a string and parse it into a float. That way you won't get stuck at letters and such either.
And the final option is to read into an int but handle any errors and skip the bad input, which is detailed at How to handle wrong data type input so I won't reproduce it here.
Which option you choose really just depends on what you want the behavior of your program to be and how strictly you want to validate input (e.g. round vs. fail if "2.5" is entered but an integer is expected, how do you want to handle "xyz" as input, etc.).
I've written a program that returns the median value of a user-defined array. While I've put a few checks in my code (array size can not be negative) I keep running into one issue I simply can not fix (for clarity sake, assume strings and alphabetical characters will not be used).
All of my input values are int however the user could just as easily enter in a float. When they do this (either for size of array or entering in the element) it breaks my code. I've tried multiple things to try and catch this, but it seems like the way my program is getting the value doesn't allow for the catch in time.
#include <iostream>
using namespace std;
void sort(int * a,int n)
{
for(int i=0;i<n;++i)
for(int j=i+1;j<n;++j)
{
if(a[i]>a[j])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}\
}
return;
}
int main()
{
int n;
int check;
int x;
cout<<"Enter length of array:";
cin>>n;
if (n < 0){
while (n < 0){
cout << "Please enter a length greater than 0" << endl;
cin >> n;
}
} else if (n % 1 != 0){
while (n % 1 != 0){
cout << "Whole numbers only! Try again" << endl;
cin >> n;
}
}
if (n == 0){
cout <<"You try to enter numbers, but there's no place to put them." << endl;
cout << ":(";
return 0;
}
int a[n];
cout<<"Enter values one by one:\n";
for(int i=0;i<n;++i){
cin >> x;
a[i] = int(x);
}
sort(a,n);
if (n % 2 == 1){
cout<<"Median is:"<<a[n/2]<<endl;
}
else{
float z = (float(a[n/2]) + float(a[(n/2)-1])) / 2;
cout << "Median is:" << z << endl;
}
return 0;
}
First thing I tried was catching the float like so
`if (n % 1 !=0){
while(n % 1 !=0){
cout << "Enter a whole number"
cin >> n
}
}`
This still broke my program. The odd thing was that I entered a float and then printed the value of n and it only showed the int value.
I tried using typeid.n() with #include <typeinfo>and comparing that to an int type to check it was the correct value, but that slipped through as well.
I tried doing an int cast, something like int(n) immediately after number was stored in n but before it went into a[n] and yet again, it still broke my code.
How can I check against float user-input and loop them until they give me an int?
You're reading into an int:
int x;
...
cin >> x;
So it will read what it can, then stop at e.g. a . and leave the rest on the stream (like if the user enters "123.4" you'll get 123 and then ".4" won't be consumed from the input stream).
Instead, you could read into a float:
float x;
...
cin >> x;
And do the appropriate math.
Alternatively you could read into a string and parse it into a float. That way you won't get stuck at letters and such either.
And the final option is to read into an int but handle any errors and skip the bad input, which is detailed at How to handle wrong data type input so I won't reproduce it here.
Which option you choose really just depends on what you want the behavior of your program to be and how strictly you want to validate input (e.g. round vs. fail if "2.5" is entered but an integer is expected, how do you want to handle "xyz" as input, etc.).
Hey guys so I just started working with arrays.
Could someone shed some light on this topic please. This was I created, I thought it made sense but I must be missing something.
I get an Debug Error Run-Time Check Failure #2 - S
Type of the Error is the following: Debug Error Run-Time Check Failure #2 - S
#include<iostream>
#include<iomanip>
#include <climits>
//Prototypes:
int lowestAmount(int[]);
int highestAmount(int[]);
using namespace std;
int main() {
const int AMOUNT = 9;
int values[AMOUNT];
int lowest, highest;
cout << "Please Insert 10 Numbers of your Choice: ";
cin >> values[0] >> values[1] >> values[2] >> values[3] >>
values[4] >> values[5] >> values[6] >> values[7] >>
values[8] >> values[9];
cout << endl;
lowest = lowestAmount(values);
highest = highestAmount(values);
cout << "/tThe Lowest out of all of them is: " << lowest <<
endl;
cout << "/tThe Highest out of all of them is: " << highest << endl ;
return 0;
}
int lowestAmount(int val[]) {
int lowest = INT_MAX;
int count = 10;
for (int i = 0; i < count; i++) {
if (val[i] < lowest)
lowest = val[i];
}
return lowest;
}
int highestAmount(int val[]) {
int highest = INT_MIN;
int count = 10;
for (int i = 0; i < count; i++) {
if (val[i] > highest)
highest = val[i];
}
return highest;
}
The code sort of works but not correctly all the time, and I can't figure out what I did wrong? I though I had the logic down??? Could someone shed some light???
Array indices start at zero, which means that the last index is the amount of elements minus one. You want the user to input 10 numbers, and you do read vales[0] up to values[9] but your array doesn't have the room for it.
const int AMOUNT = 9;
int values[AMOUNT];
That means you declare an array big enough for 9 elements, not 10. AMOUNT needs to be 10.
C++ does not automatically do bounds checking. This means that if you write outside of an array, you are going to get unpredictable behaviour, and you cannot even rely on the program always crashing.
There's also a bug in both your higher/lower functions that ignores the last element even as it stands now. Once you fix the array to be for 10 elements, you need to loop until i < 10 after that.
Also in the future, you will get better help by posting specifically what does not work, meaning you should show compiler / debugger errors, not just your code.
Problem: while doesn't work to start loop over when user inputs y.
I have spent hours searching all forums including Stack Overflow for a clue and tried to figure this out (learning C++ on my own). Based on what I have read I have tried: a do loop works when placed at beginning but it incorrectly calculates by multiplying prior numb entry by next entry factorial (flushing problem?), I tried break and it stops calculation but it also stops without getting to cout <<“Do another?”. I have also tried adding/moving braces around statements and if statements (in desperation).
//problem #6 page 127 Robert Lafore OOP Prg C++ 4th ed.
#include <iostream>
using namespace std;
int main()
{
unsigned int numb;
unsigned long fact = 1; //long for larger numbers
char ch;
cout << "Enter a number ";
cin >> numb;
for (int j = numb; j > 0; j--) //multiply 1 by
{
fact *= j;
cout << "Factorial is "<< fact << endl;
cout << "Do another? (y/n)\n";
cin >> ch;
}
while(ch !='n');
return 0;
}
Your logic isn't quite right - you need to perform the operation once, then ask, and redo the entire operation.
Right now, you do a for loop for your operation, then get the character the user types every loop iteration, then just start a while loop that never terminates.
do/while is a good candidate for this:
do
{
fact = 1; // Reinitialize for subsequent loops
cout << "Enter a number ";
cin >> numb;
for(int j = numb; j > 0; j--) //multiply 1 by
{
fact *= j;
}
cout << "Factorial is " << fact << endl;
cout << "Do another? (y/n)\n";
cin >> ch;
}
while (ch == 'y'); // Switched to make anything other than 'y' break out
You need to do this:
do
{
for(int j=numb; j>0; j--) //multiply 1 by
{
fact *=j;
}
cout <<"Factorial is "<< fact<<endl;
cout <<"Do another? (y/n)\n";
cin >> ch;
}
while (ch != 'n');
What's wrong:
Your code goes into a for loop:
for(int j=numb; j>0; j--)
It calculates the factorial...but the code to do another one is in the for loop! Your program flow is like this:
Enter the for loop
Multiply fact by j and store the value in fact
Print the value of fact
Ask to do another
Store the value in ch
Continue the for loop
See the problem? You are asked to do another for each iteration of the for loop. Then, the while loop does this:
Loop while ch isn't equal to 'n'.
But...the loop is infinite! After the last iteration of the for loop, ch doesn't change. So, if the last value was 'y', well, the while loop keeps on looping over...and over...and over...since it has no body, it just continues forever.
You have sort of the right bits of code, but the bits of code are in the wrong places.
Move the output and input for "Do Another" to after the for-loop.
Add do { before cout << "enter a number;`
Add '} beforewhile(ch != 'n');`
Right now, you have a forever loop when ch is not 'n', since nothing changes ch inside the actual loop.