avg, biggest and sum in unknown sized array c++ - c++

Im trying to write a console application in c++ that will let the user input a series of numbers and the program should get the sum of all numbers, the average number, the largest and the second largest number.
For example:
Enter a couple of numbers : 10 12 -5 20 -2 15 0
Sum = 50
Average value = 8.3
Largest number = 20
Second largest = 15
#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int a[5];
cout << "We are going to find the max value"<< endl;
int x;
for (x=0; x<5; x++)
{
cout<<"insert values"<<x+1<<endl;
cin>>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<5)
{
if (a[e]>max)
{
max = a[e];
}
e++;
}
cout<<"Max value in the array is.."<<max<<endl;
getch();
return 0;
}
This is my progress so far.
Although, I have some concerns.
How do I let the user input the numbers like in the example and store them in a array with unknown size?
I'll try to figure out a way to count the avg, sum and second largest while waiting for this answer :)
Thanks!

To input an unknown number of elements, you use std::vector, inputting
until the user tells you to stop, typically by inputting an end of file:
std::vector<int> values;
int i;
while ( std::cin >> i ) {
values.push_back( i ) ;
}
If you're looking for some other type a signal for the end, you'll
probably have to read line by line, checking whether the line contains
your end criteron, and then use std::istringstream to parse the
integer.
For the rest: it may not correspond to the goal of the exercise, but
the standard library has a couple of functions which could make things
significantly simpler: std::max_element, for example, or
std::accumulate. And <conio.h> is not very portable, and is
deprecated on the systems which do support it.

If you can't use std::vector, you might want to learn about dynamic memory allocation.
int *a = new int[size];

Related

How to do array

I am trying to learn how to code array.. (i am still a beginner in programming just starting to learn last year) i don't know what's wrong in my code.. the problem is to take 5 integer inputs from user and store them in an array. Again ask user to give a number. Now, tell user whether that number is present in array or not. but my code doesn't recognize my else. Even if i put a number that isn't present in my array it still says "It is present".
int main(){
int num[4];
int i;
int comp;
cout<<"Please input 5 numbers: "<<endl;
for (i=0;i<=4;i++)
{
cin>>num[i];
}
cout<<"Now please input another number to compare: ";
cin>>comp;
if (num[i]=comp){
cout<<"The number you inputted is present in the array";
}
else {
cout<<"It is not present in the array";
}
}
the problem is to take 5 integer inputs from user and store them in an array.
Let's start declaring an array that can hold up to 5 integers.
int numbers[5] = {};
// ^^^ This should be the size of the array, not the maximum index
Since C++11, you can use a proper standard container
std::array<int, 5> numbers{};
Note that in both snippet I initialized those arrays.
Now, the loop that reads all the elements of the array can be written as
for (int i = 0; i < 5; ++i) {
// ^
}
Or use a ranged for
for (auto & number : numbers)
{ // ^^^^^^^^ Loops through the array using `number` as a reference to each element
std::cin >> number;
if (!std::cin) {
std::cerr << "An error occurred while reading.\n";
break;
}
}
The posted loop also goes from 0 to 4 (included), but the array declared in that snippet only has 4 elements, so that it is accessed out of bounds and the program has undefined behaviour.
Another problem, is that the program doesn't check
whether that number is present in array or not
It does only one "check", instead of a loop:
if ( num[i] = comp) {
num[i] = comp is an assignment, not a comparison (you should adequately rise your compiler warning level) and an assignment to an element outside the array (i has value 5, now). It's the result of this assignment, comp, that is used as a condition, which means that the branch is executed whenever comp is not 0.
Or, at least, this is the most likely outcome, given that that assignment is UB too and the compiler could genereate whatever code it decides or your program could seg-fault due to that access out of bounds.
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
int num[4];
int i;
int comp;
int coo;
int flg=0;
std::cout<<"Please input four numbers: "<<"\n";
for (i=0;i<=3;i++)
{
std::cin>>num[i];
}
std::cout<<"Now please input another number to compare: ";
std::cin>>comp;
for (i=0;i<=3;i++)
{
if (num[i]==comp){
flg = 1;
break;
}
}
if (flg) {
printf("The number you inputted is present in the array.\n","%s");
} else {
printf("It is not present in the array\n", "%s");
}
std::cin>>coo;
return 0;
}
Basically, you ommitted to loop through all the array members when comparing the array with the number to be compared and I just added the loop in so that it looped through all array members and compared it with the input number.

how to iterate an array only up to where it is filled without traversing to full length

I like to fill this array to only up to a[4] and want to traverse only up to 4th position not the enire length.
int main()
{
int a[10],i,j=0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
}
while(a[j]!='\0')
{
cout<<a[j];
j++;
}
}
this code prints 11 numbers
If you can use a special value, such as zero, to indicate the items past the end, the way '\0' is used in C strings, you could use your approach after initializing a to all zeros:
int a[10] = {0};
...
while (a[j]) {
cout << a[j++];
}
The downside to this approach is that the end-marker becomes invalid in the input. In other words, if end-user enters a zero among the four inputs, printing will stop after printing fewer than four items.
That is why these two approaches are more common:
Use a dynamic container, such as std::vector<int> - this approach is valid only in C++
Store the number of items in a separate variable - if you must use a "raw" array, this approach is the most common.
The answer is: You can't. int arrays have nothing like a C style string termination.
An array has a fixed size and the array can't tell how many elements that you have written to. So if you want to use an array for this, you'll have to ad code to count how many elements that you have written, i.e. by using an extra variable for counting.
Like:
int a[10],i,j=0;
int valid_elements = 0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
++valid_elements;
}
for(i=0;i<valid_elements;i++)
{
cout<<a[i];
}
However, that is normally not a good approach.
A much better approach is a vector as the number of elements in a vector is dynamic. You can do something like:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
int i, j;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>j;
a.push_back(j);
}
for (int x : a) // Range based for loop automatic iterates all elements in the vector
{
cout<<x;
}
return 0;
}

Any integer input except one with "6" as the right-most digit works, but any number like ...6 leads to segmentation fault, why?

My C++ program named "coinChange.cpp" reports the number of notes of different figures for changing a given integer amount. The code is
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
cout<<"please enter the amount: ";
int amount;
cin>>amount;
int totalNoOfCoins=0;
int coins[]= {100,50,20,10,5,1};
int noOfCoins[sizeof(coins)]= {0};
int counter=0;
while(amount>0)
{
if(amount>coins[counter])
{
noOfCoins[counter]=amount/coins[counter];
amount-=noOfCoins[counter]*coins[counter];
}
counter++;
}
string output="The amount can be changed by:\n";
for(int i=0;i<sizeof(coins);i++)
{
if(noOfCoins[i]>0)
{
ostringstream oss;
ostringstream oss1;
oss<<coins[i];
oss1<<noOfCoins[i];
if(noOfCoins[i]>1) output+="\t\t\t"+oss1.str()+" nos of "+oss.str()+" taka notes \n";
else output+="\t\t\t"+oss1.str()+" no of "+oss.str()+" taka note \n";
}
}
cout<<output<<endl;
return 0;
}
The result is okay for almost any integers like 34, 37829, ... etc, but the problem arises when the user inputs a number that ends in 6 like 6, x6, xx6, xxx6 etc.
There are 3 issues I see with your code.
First, the obvious one:
You are misusing sizeof:
int noOfCoins[sizeof(coins)]= {0};
This should be:
const int numCoins = sizeof(coins) / sizeof(coins[0]);
int noOfCoins[numCoins]= {0};
Then from there, you can use numCoins for the rest of the code:
for(int i=0;i < numCoins; i++)
The reason why sizeof(coins) did not work is that sizeof returns the size in bytes.
So if you have an array of 6 ints, the sizeof the array is sizeof(int) * 6, which is (assuming you are using 4 byte integers), 24. That goes way beyond the bounds of your array, thus you get undefined behavior.
Second issue: Faulty while() loop condition:
In the while loop condition, you're only testing for amount > 0. But what if amount is a large value? Your while loop will increment counter to beyond the bounds of your array, and you will be using counter as an index in your coins array, thus accessing beyond the bounds of the array.
The while loop should have this condition:
while (amount > 0 && counter < numCoins)
Third issue: Faulty test logic for the right coinage amount
You do this:
if (amount > coins[counter])
But this is wrong. What if the amount entered is simply 100? You miss the check for the 100 note using the above condition. This simply needs to be changed to this:
if (amount >= coins[counter])

How do I drop the lowest value?

I'm pretty new to C++, and I need help figuring out the code for dropping the lowest value of a randomly generated set of numbers. Here is my code so far:
//Create array and populate the array with scores between 55 and 10
// Drop lowest Score
#include <iostream>
#include <cstdlib>//for generating a random number
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
//function prototype
int *random (int);
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
//random function, generates random numbers between 55 and 100 ??
int *random(int num)
{ int *arr; //array to hold numbers
//return null if zero or negative
if (num <= 0)
return NULL;
//allocate array
arr = new int[num];
//seed random number generator
srand(time (0));
//populate array
for (int count = 0; count < num; count++)
arr[count] = (rand()%(45) +55);
//return pointer
//
return arr;
}
For this piece of code, how would I sort or find the lowest score to drop it after the function returns the random numbers?
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
Your suggestions are appreciated!
In general, to find the lowest value in an array, you can follow this psuedo-algorithm:
min = array[0] // first element in array
for (all_values_in_array)
{
if (current_element < min)
min = current_element
}
However, you can't "drop" a value out of a static array. You could look into using a dynamic container (eg. vector), or swapping the lowest value with the last value, and pretending the size of the array is 1 less. Another low level option would be to create your own dynamic array on the heap, however, this is probably more complicated than you are looking for.
Using an vector would be much easier. To drop the lowest element, you just have to sort in reverse order, then remove the last element. Personally, I would recommend using a vector.
The obvious approach to find the smallest element is to use std::min_element(). You probably want to use std::vector<T> to hold your elements but this isn't absolutely necessary. You can remove the smallest value from an array like this:
if (count) {
int* it = std::min_element(array, array + count);
std::copy(it + 1, array + count--, it);
}
Assuming you, reasonable used std::vector<int> instead, the code would look something like this:
if (!array.empty()) {
array.erase(std::min_element(array.begin(), array.end()));
}
First find the index of the lowest number:
int lowest_index=0, i;
for (i=0; i<20; i++)
if (arr[i]<arr[lowest_index])
lowest_index=i;
Now that we know the index, move the numbers coming after that index to overwrite the index we found. The number of numbers to move will be 19 minus the found index. Ie, if index 2 (the third number, since the first is at index 0) is lowest, then 17 numbers comes after that index, so that's how many we need to move.
memcpy(&arr[lowest_index],&arr[lowest_index+1],sizeof(int)*(19-lowest_index))
Good luck!
Sort the array ascending.
The lowest value will be at the beginning of the array.
Or sort the array descending and remove the last element.
Further to what others have said, you may also choose to use something like, perhaps a std::list. It's got sorting built-in, also offering the ability to define your own compare function for two elements. (Though for ints, this is not necessary)
First, I typically typedef the vector or list with the type of the elements it will contain. Next, for lists I typedef an iterator - though both of these are merely a convenience, neither is necessary.
Once you've got a list that will holds ints, just add them to it. Habit and no need to do otherwise means I'll use .push_back to add each new element. Once done, I'll sort the list, grab the element with the lowest value (also the lowest 'index' - the first item), then finally, I'll remove that item.
Some code to muse over:
#include <cstdio>
#include <cstdlib>
#include <list>
using namespace std;
typedef list<int> listInt;
typedef listInt::iterator listIntIter;
bool sortAsc(int first, int second)
{
return first < second;
}
bool sortDesc(int first, int second)
{
return first > second;
}
int main (void)
{
listInt mList;
listIntIter mIter;
int i, curVal, lowestScore;
for (i=1; i<=20; i++)
{
curVal = rand()%45 + 55;
mList.push_back(curVal);
printf("%2d. %d\n", i, curVal);
}
printf("\n");
mList.sort();
// mList.sort(sortAsc); // in this example, this has the same effect as the above line.
// mList.sort(sortDesc);
i = 0;
for (mIter=mList.begin(); mIter!=mList.end(); mIter++)
printf("%2d. %d\n", ++i, *mIter);
printf("\n");
lowestScore = mList.front();
mList.pop_front();
printf("Lowest score: %d\n", lowestScore);
return 0;
}
Oh, and the choice to use printf rather than cout was deliberate too. For a couple of reasons.
Personal preference - I find it easier to type printf("%d\n", someVar);
than cout << someVar << endl;
Size - built with gcc under windows, the release-mode exe of this example is 21kb.
Using cout, it leaps to 459kb - for the same functionality! A 20x size increase for no gain? No thanks!!
Here's an std::list reference: http://www.cplusplus.com/reference/stl/list/
In my opinion the most optimal solution to your problem would be to use a linked list to store the numbers, this way you can use an algorithm with complexity O(N) = N to find the smallest element in the list, it is a similar finding method given by user1599559 or Mikael Lindqvist, you only need stored together with the minimum value the pointer to the Item(ItemX) in the linked list that store it, then to eliminate Item X just tell Item X - 1 points to Item X + 1 and free memory allocated by Item X

Get the maximum number from an integer array in C++

I have another task for my school and it is:
Write a program which will output the largest from three inputed numbers
So far I have done this:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int* numbers = new int[3];
for(int i = 0; i < 3; i++) {
cout << "Input number no. " << (i + 1);
cin >> numbers[i];
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Is there a helper function/method in C++ which will find a largest number in my numbers array?
There's an algorithm that finds the maximal element in a container (std::max_element), but that's inappropriate. Your situation can be solved with constant memory consumption, so you don't need to store all numbers. At any given point, you just need to remember the current maximum.
Imagine you had to process one gazillion numbers. Then storing them all would not be desirable.
Of course, internally the max_element algorithm does the same as I just suggested, but it assumes that you already have the container anyway. If you don't, then just update the maximum on the fly. The boost.accumulators library has something to do that, but I'm sure you can write this yourself — it should only take one or two lines.
In the following code snippet, max will contain the highest number from the list:
int i;
int max=numbers[0];
for(i=1;i<3;i++)
{
if(numbers[i]>max) max=numbers[i];
}
Note: Your array looks too small - it has a size of two and I'm pretty sure you want a size of three.
You don't need an array here. Just look at the numbers as they come in:
int largest = std::numeric_limits<int>::min();
for (int i = 0; i < 3; ++i) {
int value;
std::cin >> value;
if (largest < value)
largest = value;
}