Hey new to C++ and working on a simple problem that takes a sequence of Int's and outputs the sum of the numbers without the smallest and largest number.
If the vector has one or no elements then it is to return 0.
Here is my code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int test(vector<int> numbers) {
typedef vector<int>::size_type vec_sz;
vec_sz size = numbers.size();
if (size <= 1) {
cout << "Vector less than 2" << endl;
return 0;
} else {
sort(numbers.begin(), numbers.end());
int answer;
for (int i=1; i < size-1; i++) {
answer += numbers[i];
}
return answer;
}
}
int main() {
vector<int> vec = {2,1,3,4,6,5,7,9,8,10};
cout << test(vec) << endl;
vector<int> vec_2 = {1};
cout << test(vec_2) << endl;
}
When I run this I get something along the lines of:
3829804
Vector less than 2
0
Why am I getting an absurdly large number when the vector is > 1, when it is just supposed to be returning the sum of 2-8?
When I make the program without the checking for the vector with 1 or less items I have no problem. Thanks for any help!
answer is not initialized in your function and will have indeterminate value.
Any usage will lead to undefined behavior.
int answer; // uninitialized
// answer will have indeterminate value
for (int i=1; i < size-1; i++) {
answer += numbers[i]; // undefined behavior
}
return answer;
As per dcl.init/12:
If no initializer is specified for an object, the object is default-initialized.
When storage for an object with automatic or dynamic storage duration
is obtained, the object has an indeterminate value,
So just initialize answer:
int answer = 0;
Try making answer set to 0 before the for for loop. This should fix the problem since the APU is trying to add a number to an undefined number.
Related
#include <iostream>
using namespace std;
void value(int array[],int size){
int minimum;
int maximum;
minimum = array[0];
for(int x = 0; x < size; x++){
if(minimum > array[x+1]){
minimum = array[x+1];
}
}
maximum = array[0];
for(int x = 0; x < size; x++){
if(maximum < array[x+1]){
maximum = array[x+1];
}
}
cout << "Minimum Value is: " << minimum << endl;
cout << "Maximum Value is: " << maximum;
}
int main(){
int size;
cout << "Number of values you want to input: ";
cin >> size;
cout << "Input " << size << " values" << endl;
int array[size];
for(int x = 0; x < size; x++){
cout << "Input #" << x+1 <<": ";
cin >> array[x];
}
value(array,size);
return 0;
How can I output the maximum value inside the array? whenever I print the value the maximum value always return a number that is not present inside the array but the minimum seems fine, its only the maximum value that I am encountering a problem, I tried every possible answer that I know but it doesn't work, I hope ya'll can help Thank you in advance
for(int x = 0; x < size; x++){
If you have an array with ten values, size will be 10. If you work out, with paper and pencil, what this for loop does, you will see that it iterates for values of x 0 through 9, that's what this says. x starts with 0. When it reaches 10, x < size will be false and the loop ends, so the loop runs with x ranging from 0 to 9.
if(minimum > array[x+1]){
Since x will range from 0-9, it logically follows that x+1 will range from 1 to 10, and so this if statement will check the values in array[1] through array[10].
In C++ array indexes start with 0, not 1. The values in your array are array[0] through array[9]. array[10] does not exist, so the above code is undefined behavior.
Furthermore:
int array[size];
This is not valid C++ either. Your C++ compiler may allow this as a non-standard C++ extension, but array sizes must be fixed, constant sizes in C++, determined at compile time. You can't use a non-constant variable to set the size of an array, C++ does not work this way. If you need to have an array of size that's determined at runtime then you need to use std::vector instead of a plain array, and change the rest of your code accordingly.
Mistake 1
Your example has undefined behavior because of the expression array[x+1]. That is, for the last iteration of the for loop, you're going out of bounds of the array and so have undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
In standard C++, the size of an array must be a compile time constant. So in your code:
int size;
cin >> size;
int array[size]; //NOT STANDARD C++
The statement int array[size]; is not standard C++ because size is not a constant expression.
Additionally you don't need 2 separate for loops when you can achieve the goal in 1 for loop as shown below.
Solution 1
You can use std::vector as shown below:
#include <iostream>
#include <vector>
#include <climits>
//this function take a vector as input
void value(const std::vector<int>& arr)
{
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the vector to find the max and min value
for(const int& element: arr)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num; //return the difference of mx and min value
}
int main()
{
int n;
std::cout<<"elements: ";
std::cin >> n;
//create vector of int of size n
std::vector<int> arr(n);
//take elements from user
for(int i=0; i<n; i++)
{
std::cin >> arr[i];
}
value(arr);
return 0;
}
Demo
Solution 2
You can make the function a function template so that you don't need to pass a separate argument to the function as shown below:
#include <iostream>
#include <climits>
//N is a nontype template parameter
template<std::size_t N>
void value(const int (&array)[N]){
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the array to find the max and min value
for(const int& element: array)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num;
}
int main(){
int array[3] = {};
for(int x = 0; x < sizeof (array) / (sizeof (array[0])); x++){
std::cout << "Input #" << x+1 <<": ";
std::cin >> array[x];
}
value(array); //no need to pass the second argument
return 0;
}
Demo
Also note that with C++17, you can use std::size instead of sizeof (array) / (sizeof (array[0])) to find the length of the array.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
I tried reading other questions to find the answer to my question but I got tired of seeing the answer being in a different coding language. I want to change the amount of numbers in my random error code. I am genuinely new to this so please no rude comments.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int i,j[3];
srand( (unsigned)time( NULL ) );
I set the array for j to 3 so I could try and get a maximum of 3 numbers.
for( i = 0; i < 1; i++ ) {
j[3] = rand();
cout <<"Error code: " << j << endl;
}
return 0;
}
Here is where the error comes in, the output of the code only sends the variable address instead of the random number. I really need help with this before I could continue my project. Please help.
Edit: Variable address is "0x7ffc9b46ed5c"
I can assume you want to set an array of size 3 to random numbers.
I set the array for j to 3
j[3] = rand();
You're not doing that, you're setting the 4th element in your array j as a random number, which happens to be out of bounds and invokes undefined behavior.
cout <<"Error code: " << j << endl;
Outputs the address of the first element in array j. Not the whole array.
How i would do it:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int j[3];
for (int i = 0; i < 3; ++i)
j[i] = rand(); //sets every index of the array to rand()
cout << "Error code: ";
for (int i = 0; i < 3; ++i)
cout << j[i] << '\n'; //outputs all values from the array
return 0;
}
When you declare an array of size 3 by int j[3] you can refer to the first value by j[0], second value by j[1], and the third value by j[2]. If you want to display every value from your array you can use a normal for loop (using j[i]) or a range based for loop:
for(int& i : j)
cout<<i; //this loop will display every component from your array
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a[10], i, index;
int *p, *max;
for (i = 0; i < 10; i++) cin >> a[i];
max = 0;
p = &a[10];
for (index = 0; index < 10; index++) {
if ((p[index]) > *max) {
*max = (p[index]);
}
}
cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
return 0;
}
The code is buggy. First of all, you assign
p=&a[10];
This assigns p to a memory address past a. Furthermore, you then index as p[index], which essentially is the same as a[10 + index].
Also, max is a wild pointer. It does not point to anything. You are assigning values to an undefined memory location.
I would strongly suggest to read up on pointers and to properly understand them before using them. Also, in modern C++, it is not very often than you need pointers.
Also, in idiomatic C++, we would probably write
auto p = std::max_element(a, a + 10);
There are several problems.
First, p should point to the array's first element, so you should have p = &a[0].
You can also rely on implicit conversion and just write p = a;, which is exactly the same.
&a[10] is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.
Next, you want max to point to the maximum element.
It should also start at the beginning of the array, like p.
Then, when you find a new maximum, you should make max point to that element, not change the value max points to.
Lastly, index will always be 10 after the search loop.
(Take a few moments to think about why.)
You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.
int main()
{
int a[10];
for(int i = 0; i < 10; i++)
cin >> a[i];
int* max = &a[0];
int* p = &a[0];
for (int index = 0; index < 10; index++){
if (p[index] > *max){
max = &p[index];
}
}
cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}
I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.
Comments in the code:
#include <iostream>
#include <iterator>
// using namespace std; // don't do this
int main() {
using std::cin, std::cout;
int a[10];
// use a range-based for-loop:
for(int& aref : a) { // aref is a reference to the current element in a
// check that extraction from std::cin actually works
if(!(cin >> aref)) {
std::cerr << "error reading int\n";
return 1;
}
}
// initialize max to point at the first element
auto max = std::begin(a);
// Start at the second element since max is already set to point at the first element.
// Don't use magic numbers. Define a constant or use std::size(<array>)
// ...or use iterators like in this example:
for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
if(*curr > *max) {
max = curr;
}
}
// you can use std::distance ot calculate the index for max:
cout << "Highest value=" << *max << '\n'
<< "is at index=" << std::distance(std::begin(a), max) << '\n';
}
The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.
I tried to make the least amount of changes to the original code:
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *p,*max;
for(i=0;i<10;i++)
cin>>a[i];
max=a; // Initialize max to point to the first item in a
p=a;
for(index=0;index<10;index++){
if((p[index])>*max){
max=(&p[index]); // Now make max point to the new maximum item
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
return 0;
}
Here is the code in ideone:
https://ideone.com/BwE45C
As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *max;
for(i=0;i<10;i++)
cin>>a[i];
max=a;
for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
if(*p>*max){
max=p; // max points to the new maximum
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
return 0;
}
The new ideone link for this is here: https://ideone.com/bk3zoS
I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.
#include<iostream>
using namespace std;
int pent(int num){
int p;
for(int i=1;i<=num;i++){
p=(i*(3*i-1)/2);
}
return p;
}
int main(){
int num;
cin>>num;
int sender=pent(num);
cout<<sender<<endl;
return 0;
}
Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...
The most simple constructor creates a vector with no entries:
std::vector<int> x;
You can reserve space for elements via reserve:
x.reserve(num);
The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.
To add elements to the vector you can use push_back:
x.push_back(42);
Eventually to print all elements of the vector we can use a range-based for loop:
for (auto element : x) std::cout << element << " ";
So you can rewrite your code like this:
#include <iostream>
#include <vector>
std::vector<int> pent(int num){
std::vector<int> result;
result.reserve(num);
for(int i=1;i<=num;i++){
result.push_back(i*(3*i-1)/2);
}
return result;
}
int main(){
int num;
std::cin >> num;
auto sender = pent(num);
for (auto number : sender) std::cout << number << " ";
}
In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.
So there is a way which #asmmo is suggesting, to print in pent() function.
Or you can pass a vector to your pent() function and store values in that and print it in main function.
For your ref:
void pent(int num, vector<int> &arr) {
int p;
for (int i = 1; i <= num; i++) {
arr[i-1] = (i*(3 * i - 1) / 2);
}
}
int main() {
int num;
cin >> num;
vector<int> arr(num);
pent(num, arr);
for (int i = 0; i < num; i++) {
cout << arr[i] << endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int s;
cin>>s;
int t=3;
int maxValue,imax[t],maxIndex,arr[s];
for(int i=0; i<s; i++){
cin>>arr[i];
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if(arr[i]>maxValue){
maxValue=arr[i];
imax[0] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[1] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if (i == imax[1]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[2] = i;
}
}
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
return 0;
}
This program must return tree numbers which is biggest in this arraybut , i do not know why when I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.
In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.
You use uninitialized array values in lines
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.
Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as
int imax[t] = {};
This will zero-initialize all elements of array and will prevent crashing.
Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.
Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int s;
std::cin >> s;
unsigned t = 3;
std::vector<int> max_numbers;
max_numbers.reserve(t + 1);
for (int i = 0; i < s; ++i) {
int number;
if (std::cin >> number) { //Check basic input errors
max_numbers.push_back(number); // Add number to top-3 list
// Sort elements in descending order
std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());
// Remove duplicates
max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
max_numbers.end());
// Remove excess elements
if (max_numbers.size() > t) {
max_numbers.resize(t);
}
}
}
std::cout << "Biggest " << t << " numbers are" << std::endl;
for (int i : max_numbers) {
std::cout << i << std::endl;
}
}