im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out
im new to arrays so any help would be appreciated as well as an feedback on how to improve my code
#include <iostream>
int main()
{
int people[10];
int max = people[0];
std::cout << "please enter number of pancakes eaten by each person.\n";
//lets the user input values for each element
for (int i = 0; i < 10; ++i) {
std::cin >> people[i];
}
//outputs all the elements of the array
for (int i = 0; i < 10; ++i) {
std::cout << people[i] << " ";
}
//finds the largest element in the array
for (int i = 0; i > 10; ++i) {
if (people[i] > max) {
max = people[i];
}
}
std::cout << "\nmax: " << max;
return 0;
}
also i keep getting a warning saying: ill-defined for-loop. loop body not executed. i tried looking this warning up but the warning seems very broad and i couldnt find anything that helped
int people[10];
This declares an array of ten int values. None of the values are explicitly initialized. This is how plain values that get declared in automatic scope work in C++, they are not initialized to any values. It is the code's responsibility to initialize them.
int max = people[0];
This sets the value of max to the first value of the array. Which has not been initialized to any value. This is undefined behavior. From this point on the program's behavior is undefined.
Furthermore, even if peoples values were initialized this will still be broken. The intent of the program is clear: read values into the people array, and then find their maximum value.
However, at this point, nothing has been read from anywhere.
The attempted goal here is to set max, initially, to the first value in the array, the first read value.
But in order for this to make sense, max should be set after the values in the array get read from input, and not before. This should be done after all the values are read in, and not before.
in the line int max = people[0] you are dereferencing the first element of the array. But dereferencing to what? at that point in the program you have not initialised any of the 10 elements in the people array. So taking the value at people[0] at that point in the program and copying it into another int for later comparison is undefined behaviour. Best solution is to simply move int max = people[0] to after you take the user input, and for the comparison loop start with i = 1, because max is already equivalent to the first inputted value.
Related
#include<iostream>
#include<string>
#include <cstring>
using namespace std;
bool b[200][200];
int a[46];
int test_cases;
int n;
int m;
int first;
int second;
int main()
{
cin>>test_cases;
while(test_cases--){
cin>>n;
cin>>m;
for (int i=0;i<2*m;i++){
cin>>a[i];
}
for (int j=0;j<m;j++){
first=a[2*j];
second=a[2*j+1];
b[first][second]=true;
}
}
return 0;
}
Hello. Runtime error seems to occur on the last code 'b[first][second]=true;'
I tried couple of changes and i found if i turn 'b[first][second]=true;' into 'b[second][first]=true;' error doesn't occur, which is simply to change the order of indices.
There is not a possibility of "out of range error" because memory size of b is [200][200] and range of results of a[*] is from 0 to 10.
I can't figure out where the problem is coming from and i need help. Thank you.
There is not a possibility of "out of range error" because memory size of b is [200][200] and range of results of a[*] is from 0 to 10.
The world is littered with buggy code because people made assumptions like this. The first thing you should do is prove this correct. That's as simple as placing something like:
if (first < 0 || first > 199 || second < 0 || second > 199) {
cerr << "Violation, first = " << first << ", second = " << second << "\n";
exit(1);
}
immediately before your line that sets the b[][] element to true.
As an aside, it would also be prudent to check other array accesses as well. Since we don't have your test data, we have no idea what value will be input for n or m but, since those values can result in undefined behaviour (by accessing beyond array bounds), they should also be scrutinised.
If you wanted to be sure that those didn't cause problems, you could dynamically allocate to the correct size as necessary. For example, once you've gotten m from the user:
int *a = new int[m*2];
// Use it as you wish, elements <0..m*2-1> inclusive.
delete [] a;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I don't understand this, the part where it says, "myArray[x] = 42;"
Since when did x even come into myArray? Atleast someone explain me how this script even works?
{ int = myArray[5];
for (int x = 0; x < 5; x++) {
myArray[x] = 42;
cout << x << ":" << myArray[x] << endl;
}
}
C++ arrays are random-access containers. That means that if you want the ith element of the array, you can ask for it (and get it in constant time).
The operator used for array element access is the brackets ([]) operator. It takes a parameter of type std::size_t, which is a typedef to some unsigned integer type that's big enough to index all the memory addresses of your computer's RAM. Thus, if I have an array arr, and I index into it by writing arr[2], I'm asking for the second element of the array.
In the following example, an array is created, and each element is assigned a value equal to the square of its index.
#include <cstdlib>
#include <iostream>
int main() {
constexpr std::size_t length = 10;
int arr[length];
for (std::size_t i = 0; i < length; ++i) {
arr[i] = i * i;
std::cout << "Element " << i << " of arr is " << arr[i] << "." << std::endl;
}
}
Because operator[] returns a reference (in this case an int&), the expression arr[i] can be used for both reading and writing the value.
I'll be specific here, you need to read on basic programming in c++, because you are questioning the fundamental ways the for-loop in c++ works.
I will start by formatting your code so that is is easier to read:
{
int = myArray[5];
for (int x = 0; x < 5; x++)
{
myArray[x] = 42;
cout << x << ":" << myArray[x] << endl;
}
}
Let me point out some errors in your code. Firstly, when you declare a variable in c++, you must also declare its data type along with it. So the following example:
var = 2;
Is invalid, because the data type of the variable var is not specified. The compiler cannot tell what the data type of a variable is by simply looking at the value passed to it in c++. Therefore, we need to add the data type just before the name of the variable when DCLARING IT ONLY. So in the above example:
int var = 2;
Is a valid variable declaration because we have specified that this variable will only store an int value.
Now the problem in your code is that you are trying to do:
int = myArray[5];
This makes no sense. First problem is that you are trying to assign a data type a value as if it were a variable. Second problem is that you never declared myArray before. From your cod, I'm assuming that you intended to do:
int myArray[5];
This makes sense because your for-loop also runs 5 times. In this line, you have declared an array called myArray that stores 5 values of type int.
Now moving on to the for-loop. Lets dissect the header statement of the for-loop:
for (int x = 0; x < 5; x++)
The first statement right after the opening semicolon int x = 0; simply declares a variable ONCE for the entire run of the for loop. This variable x is local to the for loop and cannot ba accessed outside of it. In c++, we refer to it as a counter variable as it stores the number of times we have gone looped through a for-loop.
The next statement x < 5; is a condition for the for-loop. While this condition is true, the for-loop will run; In your case, while x is less than 5, it will run through the loop. As soon as this condition become false; in this code, if x becomes equal to or greater than 5, then the condition is falsified, and the loop is terminated. This way, we ensure that the loop runs through our code only the number of times we want it to.
The final statement x++; simply means that x is incremented at every point. If it is not incremented, then the value of x will never change, and the condition of the loop will never be falsified, making it an infinite loop. Therefore, this statement is crucial.
Now while we are inside the for-loop, we can use the variable x. This is particularily useful in your case as you have an array, and you are trying to fill it up with values. Instead of doing array[a]=n, where a ranges from 0 up till the size of the array minus 1, and n is a random number, we can use a for loop to initialize our values.
In the for loop, how do we do that? We use the counter x, that increments itself after every loop run, to serve as the "a" in array[a]. That's why we use myArray[x] = 42;, simply because x increments itself by 1 after every loop and this number can be used as the address (sorry for my poor choice of words here) of the array. Why it allocates the number 42 is random; it could allocate any number.
If you still need some clarification, or if I made a mistake in my post, please let me know in the comments box.
I have a struct that has two member variables, each is an int.
struct trash
{
int sector;
int weight;
};
I have an array where each element contains one of these structs. All of the data is randomly generated within a set range. In this case, sectors are generated randomly from 1-7. Also, the array is size 15 in this instance. So each sector has a random number of weight variables associated with it. What I am trying to accomplish is printing out what piles belong to each sector. So the format should look like this
Sector 1
Pile 1: xxx
Pile 2: xxx
...
Sector 2
Pile 1: xxx
....
Sector 7
and so on if that makes sense
My attempt at this so far was to sort the array of structs by sector from least to greatest first and then print out the weight variable of each by iterating over the array using for loops. In a nutshell, I just want to print out the array in order after it is sorted by sector but break it up by sector. I can't for the life of me seem to figure out how to accomplish this in a compact, concise way. Below is the loop I have written now that doesnt quite work because the inner loop starts at the same point each time.
for(int i=0;i<NUM_SEC;i++)
{
cout<<"Sector "<<(i+1)<<endl;
for(int j=0;j<num_piles[i];j++)
{
cout<<"Pile "<<(j+1)<<": "<<data[j].weight<<endl;
cout<<endl;
}
}
Any tips would be appreciated, I've already spent hours on just this small aspect of the program and its very frustrating.
Looks like you want to access not data[j], but data[j + previous_piles]. You could then do something like:
int previous_piles = 0;
for(int i=0;i<NUM_SEC;i++)
{
cout<<"Sector "<<(i+1)<<endl;
for(int j=0;j<num_piles[i];j++)
{
cout<<"Pile "<<(j+1)<<": "<<data[j+previous_piles].weight<<endl;
cout<<endl;
}
previous_piles += num_piles[i];
}
You are not keeping record of your progress!!
Look at the following code:
int last_pile = 0; // will keep track of the last printed index
for(int i=0;i<NUM_SEC;i++)
{
cout<<"Sector "<<(i+1)<<endl;
for( int j = 0; j < num_piles[i]; j++)
{
cout << "Pile " << (j+1) << ": " << data[j+last_pile].weight << endl; // sum last_pile to j
}
// updated last printed index
last_pile += num_piles[i];
cout << endl; // empty line 'cause finihes with this sector
}
I created a new variable last_pile which will store the last visited index. Then, inside the loop, I add the value of this variable to the sub-index j so you always get the correct element from the array.
Please pay attention to the comment, I added useful information there.
Well all I had to do was:
user has to enter 20 numbers.
and I should find from array numbers lower than the last number user entered ( 20 numbers )
Example :
User enters:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,4
Output should be:
1,2,3
according to me, my output is correct. But after 1,2,3 alot of 0 come in.
#include <iostream>
using namespace std;
int i,skaitlis,sk2,x;
int masivs[19];
int main() {
for ( i=0; i<=19; i++ )
{
cin >> masivs[i];
skaitlis = masivs[19];
}
for (i=0;i < sizeof masivs; i++){
if ( masivs[i]<skaitlis){
cout << masivs[i] <<endl;
}
}
}
The problem is here:
for (i=0;i < sizeof masivs; i++){
The sizeof operator returns the size of the array in bytes, not in number of elements. On normal modern systems the size of an int is four bytes, meaning sizeof masivs will give you 4*19.
That will lead the loop going massively out of bounds and give you undefined behavior.
Not to mention the other out of bounds you have in the previous loop.
Also, taking about the first loop, why have the assignment to skaitlis inside the loop? After you fix the out-of-bounds indexing, it will just assign zero (because masivs is a global variable and therefore initialized to all zeroes) except in the last iteration. You can move that assignment to be outside the loop.
So, I tried to make an array using input first, then sorting it out from smallest to biggest, then display the array to monitor.
So I come up with this code :
#include <iostream>
using namespace std;
void pancakeSort(int sortArray[], int sortSize);
int main()
{
// Input The Array Element Value
int pancake[10];
for(int i=0; i<10; i++)
{
cout << "Person " << i+1 << " eat pancakes = ";
cin >> pancake[i];
}
// call pancake sorting function
pancakeSort(pancake, 10);
}
void pancakeSort(int sortArray[], int sortSize)
{
int length = 10;
int temp;
int stop = 10;
// this is where the array get sorting out from smallest to biggest number
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
// after that, the array get display here
for(int x=0; x<sortSize; x++)
{
cout << sortArray[x] << " ";
}
}
but the output is weird :
enter image description here
the function is successfully sorting the array from smallest to biggest,
but there is 2 weird things :
1. The biggest value element (which is 96 from what I input and it's the 10th element after got sorted out), disappear from the display.
2. For some reason, there is value 10 , which I didn't input on the array.
So, what happened?
In the loop
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop is the length of the array, and you are iterating through values of j = 0 to stop - 1. When j reaches stop - 1, the next element that is j+1 becomes stop (10 in this case). But since your array has a length of 10, sortArray[10] is not part of the array, but is referring to some other object in memory which is usually a garbage value. The garbage value is 10 in this case. When you swap sortArray[10] and sortArray[9], the garbage value becomes part of the array and the value at index 9 leaves the array. This keeps on happening till the outer loop ends.
The end result is that unless the garbage value < largest element in the array, the garbage value is pushed in the array and the greatest value of the array is put at sortArray[10] which is not part of the array. If the garbage value is greater than all the values of the array, it'll be found at sortArray[10] which is again not part of the array and your code will return the desired result.
Essentially, what you are doing is giving the function an array of 10 (or stop) elements, but the function is actually working with an array of 11 (or stop + 1) elements, with the last element being a garbage value. The simple fix is to change the conditional of the loop to j < stop - 1.
Note that if you had written this code in a managed (or a comparatively higher level) language like Java or C#, it would have raised an IndexOutOfBoundsException.
At index 9, j+1 is out of bounds. So to fix this, you only need to check till index 8
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop-1; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
Look carefully at the inner loop condition j<stop-1