The three biggest numbers in array - c++

#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;
}
}

Related

How to output the maximum value inside an array

#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.

How can I print the numbers in main function?

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;
}

Outputting weirdly large number in C++

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.

Having Trouble With A Simple C++ Program

I'm creating this very simple C++ program.
the program asks the user to enter a few integers and stores them in an array.but when a specific integer(for example 50)is entered,the input is ended and then,all of the integers are displayed on the screen except for 50.
for example:
input:
1
2
88
50
output:
1
2
88
the error i'm getting is when i use cout to print the array,all of numbers are shown,including 50 and numbers i did'nt even entered.
this is my code so far:
#include<iostream>
int main() {
int num[100];
for(int i=0;i<=100;i++) {
cin >> num[i];
if (num[i]!=50) break;
}
for(int j=0;j<=100;j++) {
cout << num[j] << endl;
}
return 0;
}
Change the program the following way
#include<iostream>
int main()
{
const size_t N = 100;
int num[N];
size_t n = 0;
int value;
while ( n < N && std::cin >> value && value != 50 ) num[n++] = value;
for ( size_t i = 0; i < n; i++ ) std::cout << num[i] << std::endl;
return 0;
}
Here in the first loop variable n is used to count the actual number of entered values. And then this variable is used as the upper bound for the second loop.
As for your program then the valid range of indices for the first loop is 0-99 and you have to output only whose elements of the array that were inputed.
A do while loop is more suitable for your problem. The stop condition will check if the number fit inside the array (if k is not bigger than 100) and if number entered is 50.
#include<iostream>
using namespace std;
int main() {
int num[100];
int k = 0;
// A do while loop will be more suitable
do{
cin >> num[k++];
}while(k<100&&num[k-1]!=50);
for (int j = 0; j < k-1; j++) {
cout << num[j] << endl;
}
return 0;
}
Also, a better solution to get rid of 100 limitation is to use std::vector data structure that automatically adjust it's size, like this:
vector<int> num;
int temp;
do {
cin >> temp;
num.push_back(temp);
} while (temp != 50);
Note, you can use temp.size() to get the number of items stored.
You read up to 101 numbers, but if you enter 50 you break the loop and go for printing it. In the printing loop you go through all 101 numbers, but you actually may have not set all of them.
In the first loop count in a count variable the numbers you read until you meet 50 and in the printing loop just iterate count-1 times.
You have allocated an array of 100 integers on the stack. The values are not initialized to zero by default, so you end up having whatever was on the stack previously appear in your array.
You have also off-by-one in both of your loops, you allocated array of 100 integers so that means index range of 0-99.
As the question is tagged as C++, I would suggest that you leave the C-style array and instead use a std::vector to store the values. This makes it more flexible as you don't have to specify a fixed size (or manage memory) and you don't end up with uninitialized values.
Little example code (requires C++11 compiler):
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers; // Store the numbers here
for(int i = 0; i < 100; ++i) // Ask a number 100 times
{
int n;
std::cin >> n;
if( n == 50 ) // Stop if user enters 50
break;
numbers.push_back(n); // Add the number to the numbers vector
}
for (auto n : numbers) // Print all the values in the numbers vector
std::cout << n << std::endl;
return 0;
}
There are just 2 changes in your code check it out :
int main()
{
int num[100],i; //initialize i outside scope to count number of inputs
for(i=0;i<100;i++) {
cin >> num[i];
if (num[i]==50) break; //break if the entered number is 50
}
for(int j=0;j<=i-1;j++)
{
cout << num[j] << endl;
}
return 0;
}
Okay, others already pointed out the two mistakes. You should use i < 100 in the loop conditions instead of i <= 100 and you have to keep track of how many elements you entered.
Now let me add an answer how I think it would be better.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; // a temp variable in the for loop.
numbers.size() < 100 && // check that we have less than 100 elements.
std::cin >> temp && // read in the temp variable,
// and check if the read was a success.
temp != 50) // lastly check that the value we read isn't 50.
{
numbers.push_back(temp); // Now we just add it to the vector.
}
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i]; // Now we just print all the elements of
// the vector. We only added correct items.
}
The above code doesn't even read anymore numbers after it found 50. And if you want to be able to enter any number of elements you just have to remove the check that we have less than 100 elements.
Now I commented the above code a bit much, if you compress it it'll reduce to just:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i];
}
If you can use the C++11 standard it reduces to:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int element : numbers)
std::cout << element;
}
for (auto element : numbers) is new, it basically means for every int 'element' in 'numbers'.

C++ Program Functions

I am having trouble with my functions. When I use a function to manipulate an array, and print it and move on to the next manipulation function, it uses the array that was previously manipulated instead of the original array. For example, when my function converts every negative number to a positive, I call the next function which zeros out all even numbers, and my array prints out all zeros, instead of using the array from the original.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define NUMS_PER_LINE 10 // maximum numbers to be printed on each line.
int numbers[100]; // array to hold upto 100 integer numbers.
int numcnt; // actual count (<=100) of numbers in above array.
// reads file content into array
void read_array_from_file (const char filename[])
{
ifstream inpfile(filename);
if (!inpfile.is_open())
{
cout << "Can't open file : " << filename << endl;
exit(1);
}
numcnt=0; // Initialise count of read numbers
// Read numbers from the file into array.
inpfile >> numbers[numcnt];
while (!inpfile.eof()) // Read until EOF is reached.
{
numcnt++; // Got one more number from input file.
inpfile >> numbers[numcnt];
}
inpfile.close();
return;
}
// Print out all the values in the array
void print_array_content (int numsinaline)
{
int i;
for (i=0; i<numcnt+1; i++)
{
if ((i % numsinaline) == 0)
cout << endl;
cout << numbers[i] << " ";
}
cout << endl << endl;
return;
}
// calculate average
double calculate_average ()
{
int i;
float sum=0;
for (i=0; i<(numcnt-1); i++)
{
sum += numbers[i];
}
return (sum/(numcnt-1));
}
// Find numbers larger and smaller than the average.
void find_numbers_smaller_and_larger_than_average (int &larger, int &smaller, int average)
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < average)
smaller++;
else if (numbers[i] > average)
larger++;
}
return;
}
// Convert negative numbers to positive in the array 'numbers'.
void convert_negative_to_positive ()
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < 0)
numbers[i] *= -1;
}
return;
}
// Convert all even numbers into zero.
void zero ()
{
int i;
for (i=0; i<numcnt; i++)
{
if (numbers[i] > 0)
numbers[i] *= 0;
}
return;
}
First of all, you are using a global variable for your array, so you are never passing it to your function. When you change a global variable in the function, it changes the data in the array. You should be passing that data into the function and NOT using global variables.
Second, while(!inpFile.eof()) is bad! Don't do it.
For file streams:
std::vector<int> numbers;
std::ifstream fin("myfile");
std::copy(std::istream_iterator<int>(fin), std::istream_iterator(), std::back_inserter<vector<int> >(numbers));
Those 3 lines will read the entire file into the vector "numbers".
Third, when declaring your functions, pass the array:
void myFunction(const std::vector<int>& vec); // if you aren't going to change the vector
or
void myFunction(std::vector& vec); // if you are going to change it
and you would call it by simply:
myFunction(numbers);
" it uses the array that was previously manipulated instead of the original array."
Obviously because you have your array declared globally
int numbers[100];
Outside all functions.
When you perform one operation on this array, the element get modified and the new values will be used for next functions.
Instead of this, save of copy of your original array and then use this copy whenever you wish to work on original array
All your operations act on a single global variable, numbers. If you modify it in any of your functions its values will also change in every other occurrence.
Instead, provide a way to tell your functions which array you want to use, how many elements it contains and use several arrays. This also enables you to get rid of the global variable.
Example:
#include <iostream>
using namespace std;
typedef unsigned int array_size_t;
void print_array(int array[], array_size_t size){
for(array_size_t i = 0; i < size; ++i){
cout << array[i] << endl;
}
}
int main(){
int a1[] = {1,2,3,4};
int a2[] = {1,3,3,7,0,0,0,0};
print_array(a1,4);
print_array(a2,8);
}
Remark
If you're allowed use standard containers such as std::vector instead. The solution above is more C than C++-like.
You are using global variable. All your operation on numbers whatever index will change your certain position's value.
Another potential risk is if your input file contains more than 100 integers, you will do
inpfile >> numbers[100];
or some index number greater than 100.
which will cause a segmentation fault.
You should be very careful when using global variables
You are directly manipulating your array inside of your functions since it is defined globally, instead of passing in a copy as a parameter.
void modify(int[] array) {
//Modify copied array here
}
int main() {
int numbers[100];
int copyNumbers[100];
//Copy numbers
memcpy(copyNumbers, numbers, sizeof(numbers));
modify(copyNumbers);
//Use modified array
memcpy(copyNumbers, numbers, sizeof(numbers)); //Set back to original
modify(copyNumbers); //Modify copy again as original
}