I have written following code which allows user to input an array and give out maximum and minimum value in that array
when i input length of array value = 4 and elements of array as:- 32,152,38 it give output as
max = 1973314801 and min = 24(unexpected values)
for following code:-
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"input length of array = ";
cin>>n;
int array[n];
for(int i=0; i<n;i++)
{
int a;
cout<<"input element "<<i+1<<" = ";
cin>>a;
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
but when i define value of array in code it give expected output (min=3 and max=12)
code(code in which value of array is already defined):-
#include<iostream>
using namespace std;
int main()
{
int array[4]={3,6,9,12};
int max=array[0];
int min=array[0];
for(int i=0; i<4;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
what can be the problem here?
According to the C++ Standard the size of a C++ array must be compile time constant. So your first code example is not correct. That is you cannot take the size of the array from the user as input. You have to explicitly specify the size of the array as you did in your 2nd example.
You can use std::vector for this purpose instead.
You are storing input data in variable a instead of array array and you can't assign array size like that. You have to specify the size as constant before using it.
#include<iostream>
using namespace std;
int main()
{
const int n = 4;
/*cout<<"input length of array = ";
cin>>n;*/
int array[n];
for(int i=0; i<n;i++)
{
cout<<"input element "<<i+1<<" = ";
cin>>array[i];
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
But if you still want to take size as user input then you have to create that array in heap memory
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"input length of array = ";
cin>>n;
int* array = new int[n]; //array in heap
for(int i=0; i<n;i++)
{
cout<<"input element "<<i+1<<" = ";
cin>>array[i];
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
delete [] array;
}
You don't need an array; use a running min and max calculation:
int minimum;
int maximum;
cin >> minimum;
maximum = minimum;
int number;
while (cin >> number)
{
if (number > maximum) maximum = number;
if (number < minimum) minimum = number;
}
cout << "Maximum: " << maximum
<< ", Minimum: " << minimum
<< "\n";
There is no need to store the numbers, only to compare the number to determine the maximum and minimum.
The requirements are still met, because the program is entering an array or bunch, of numbers.
One nice feature of the running min and max, is there is no limit to the quantity of numbers that can be input. The only limit is the range of values that an int can hold.
Related
I tried changing a lot of integers and stuff but it didn't work and it gives me a random number like 53289432 even tho lets say i put in 3:5,1,2 it should output 3 since 5-2 is 3.
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]);
}
{
x[i]=mn;
}
}
for(int i=1;i<n;i++)
{
for(int j=1;j<n;j++)
{
if(x[i]<x[j]);
}
{
x[i]=mx;
}
}
cout<<mx-mn;
}
You don't need an array:
int smallest = 0;
int largest = 0;
std::cout << "Enter quantity: ";
int quantity;
std::cin >> quantity;
if (quantity < 1)
{
std::cerr << "Invalid quantity.\n";
return 1;
}
std::cout << "Enter number: ";
std::cin >> smallest;
largest = smallest;
for (int i = 1; i < quantity; ++i)
{
std::cout << "Enter number: ";
int number;
std::cin >> number;
if (number < smallest) smallest = number;
if (number > largest) largest = number;
}
std::cout << "maximum from minimum: " << (smallest - largest) << "\n";
std::cout << "minimum from maximum: " << (largest - smallest) << "\n";
The above code uses a running minimum/maximum, so no arrays are needed.
No need for variable length arrays or having to figure out the array capacity at compile time.
Your code carries several holes,
Firstly,
for(int i=1;i<n;i++)
{
cin>>x[i];
This won't take n integers, it will only take (n-1) integers as input. You need to initialise i=0, for n integers;
Secondly,
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]); //This will compare with garbage when i=1 and j>1
}
{
x[i]=mn;
}
}
Your comparison, will only be valid for first iteration of i=1 and j=1, after j>1, it will pick garbage value, since, you haven't taken any input yet.
It is suggested, to first take all the inputs, then do the comparison, or other operations.
Here is my solution
I think this is what you are trying to do!
#include <iostream>
#include <climits>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
//First take the inputs in array x
for(int i=0;i<n;i++)
{
cin>>x[i];
}
//Find maximum and store it in mx
mx = INT_MIN; //This stores minimum in mx variable (climits)
for(int j=0;j<n;j++)
{
if(mx<x[j])
mx=x[j];
}
//Find minimum and store it in mn
mn = INT_MAX; //This stores maximum in mn variable (climits)
for(int j=0;j<n;j++)
{
if(mn>x[j])
mn=x[j];
}
int ans = mx - mn;
cout<<ans<<endl;
}
There is a better solution where you don't use extra space(array), and by using only 2 variables, you can find the difference. But I would recommend you to first understand this concept, and take a look, how array works, before moving towards any optimised solution.
This is the complete question:-
All Indices Of Array
You are given a number n, representing the count of elements.
You are given n numbers.
You are given a number x.
You are required to find the all indices at which x occurs in array a.
Return an array of appropriate size which contains all indices at which x occurs in array a.
Sample Input
6
15
11
40
4
4
9
Sample Output
3
4
This is my code:-
#include<iostream>
using namespace std;
int* allIndices(int arr[],int n,int x,int idx,int* fsf){
if(idx==n){
int *q=new int[*fsf];
return q;
}
if(arr[idx]==x){
int* iarr=allIndices(arr,n,x,idx+1,fsf+1);
iarr[*fsf]=idx;
return iarr;
}
else{
int* iarr=allIndices(arr,n,x,idx+1,fsf);
return iarr;
}
}
int main(){
int n;
cin>>n;
int *p = new int[n];
for(int i=0;i<n;i++)
cin>>p[i];
int x;
cin>>x;
int k=0;
int *y=allIndices(p,n,x,0,&k);
for(int i=0;i<k;i++){
cout<<y[i]<<endl;
}
}
This code must be printing an array of index positions but its not printing anything ....
please help!
This does the job quite fine. You might have overcomplicated it a bit.
#include <iostream>
using namespace std;
int* alLIndices(int arr[], int n, int x){
int *y = new int[n];
for(int i=0; i<n; i++){
if(arr[i] == x){
y[i] = i;
}
}
cout<<"Number "<<x<<" occurs at indices: "<<endl;
for(int i=0; i<n; i++){
cout<<y[i]<<endl;
}
}
int main() {
int n;
cout<<"Enter n: ";
cin>>n;
int *p = new int[n];
cout<<"Enter an array of numbers: "<<endl;
for(int i=0; i<n; i++)
cin>>p[i];
int x;
cout<<"Enter x: ";
cin>>x;
alLIndices(p, n, x);
return 0;
}
You just go through the array and see which element of it is equal to the x that you are searching for. If there is any, then you put the index of that element in a new array which you allocated beforehand. Finally, you print out the array containing those indices.
So I am trying to get my even numbers to appear and tell me the result of the user input. Not sure why my function is an error in my main when I tried to just have it output in my even function won't print. Unsure why? also curious should I lock and make my array constant? It isn't changing but might feel like I have to make it constant and lock it in case if I have to change something to check for an even number. Plus I am a beginner and barely learning about arrays.
#include <iostream>
#include <string>
using namespace std;
// putting our voids first to declare be declare and run first
void fillUp(int num[], int size)
{
//user input
cout<<"Enter "<<size<<" and then press the ENTER/RETRUN: ";
for(int i = 0; i < size; i++)
{
cin>> num[i];
}
}
//obtaining user input and totaling them up
int total(int num[], int size)
{
int total = 0;
for(int i = 0; i < size;i++)
{
total += num[i];
}
return total;
}
int EvenElements(int num[], int size, int& evenCounter)
{
for(int i = 0; i<size;i++)
{
if(num[i] % 2 == 0)
{
evenCounter++;
}
}
return(evenCounter);
}
//display the array in a row
void display(int num[], int size)
{
for(int i = 0; i<size;i++)
{
cout<<num[i]<<" ";
}
}
//main function to display the results of the user input
int main()
{
int numOne[4], numTwo[5], numThree[6], evenCounter;
fillUp(numOne, 4);
fillUp(numTwo, 5);
fillUp(numThree, 6);
cout<<"The numbers in the array are: ";
display(numOne, 4);
cout<<" and the total of these numbers is "<<total(numOne, 4)
<<endl;
cout<<"The numbers in the array are: ";
display(numTwo, 5);
cout<<" and the total of these numbers is "<<total(numTwo, 5)
<<endl;
cout<<"The numbers in the array are: ";
display(numThree, 6);
cout<<" and the total of these numbers is "<<total(numThree, 6)
<<endl;
cout<<"This is how many evens were in the array: ";
EvenElements(evenCounter);
}
Your EvenElements() requires three arguments and you're passing only one and therefore, your code as it is will not compile. Try the following (read the comments for the last 3 lines):
#include <iostream>
#include <string>
using namespace std;
// putting our voids first to declare be declare and run first
void fillUp(int num[], int size)
{
//user input
cout<<"Enter "<<size<<" and then press the ENTER/RETRUN: ";
for(int i = 0; i < size; i++)
{
cin>> num[i];
}
}
//obtaining user input and totaling them up
int total(int num[], int size)
{
int total = 0;
for(int i = 0; i < size;i++)
{
total += num[i];
}
return total;
}
int EvenElements(int num[], int size, int& evenCounter)
{
for(int i = 0; i<size;i++)
{
if(num[i] % 2 == 0)
{
evenCounter++;
}
}
return(evenCounter);
}
//display the array in a row
void display(int num[], int size)
{
for(int i = 0; i<size;i++)
{
cout<<num[i]<<" ";
}
}
//main function to display the results of the user input
int main()
{
int numOne[4], numTwo[5], numThree[6], evenCounter;
fillUp(numOne, 4);
fillUp(numTwo, 5);
fillUp(numThree, 6);
cout<<"The numbers in the array are: ";
display(numOne, 4);
cout<<" and the total of these numbers is "<<total(numOne, 4)
<<endl;
cout<<"The numbers in the array are: ";
display(numTwo, 5);
cout<<" and the total of these numbers is "<<total(numTwo, 5)
<<endl;
cout<<"The numbers in the array are: ";
display(numThree, 6);
cout<<" and the total of these numbers is "<<total(numThree, 6)
<<endl;
cout<<"This is how many evens were in the array: ";
// Make sure you initialise evenCounter
evenCounter = 0;
// Call EventElement with the right parameters
EvenElements(numThree, 6, evenCounter);
// Display the result
cout<<evenCounter<<endl;
}
Note: Consider using macros for your sizes
#define SIZE_1 4
#define SIZE_2 5
#define SIZE_3 6
and then replace the hard-coded numbers with the appropriate sizes.
for example, I have to take input in the format:
2 // no of test cases
7 // n->size of an array
9 7 5 9 2 20 3 //n array elements
5 // second test case array size
4 5 8 96 6 // second test case array elements
I don't know what to write in the main function.
void sort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int current =arr[i];
int j;
for(j=i-1;j>=0;j--)
{
if(current<arr[j])
{
arr[j+1]=arr[j];
}
else
{
break;
}
}
arr[j+1]=current;
}
}
int main(){
// what should I write in the main func to test my problem for t no of times
// I have to take all inputs first then print the sorted arrays given by the user
// separated by space and new line for the next sorted array
}
I think this what you want.
const int N = 10;
int main(){
int t, n, arr[N];
cin >>t;
for(int T;T<t;++T){
cin >>n;
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Make sure to put the value if N is the maximum possible size of the array. Or you can declare the array as a dynamic array with the entered n (or use one of the STL like vector)
for example:
int main(){
int t, n;
cin >>t;
for(int T;T<t;++T){
cin >>n;
int * arr = new int [n];
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Or by using Vector:
#include<vector>
using namespace std;
//your sort func here, but make sure to change it to have a vector instead of an array
int main(){
int t, n;
vector<int>arr;
cin >>t;
for(int T;T<t;++T){
arr.clear();
cin >>n;
arr.resize(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
PS: I would recommend to see websites like codeforces, Hackerrank and others to practice on competitive programming question which contains a lot of question that will help (If you're interested)
int main()
{
int t; // number of test cases
std::cin >> t;
while (t--) // repeat t times
{
// what you had before
}
}
to test you can
define an input and a desired output, i.e an array "unsorted" and how it SHOULD look like after sorted
define a method that sorts input "a" and allows you to verify that by eather returning the sorted array or modifying the reference given as parameter.
defined a compare method that takes x1 and x2 as parameter and returns a bool indicating if the operation failed or no. x1 can be the desired sorted array and x2 the array returned from step1
loop in a for with DIFFERENT unsorted arrays and theis according sorted values...
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
cout << endl;
}
return 0;
}
I think this will work
this is a code example for what I mean
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int numOfTest = 0;
std::vector<int>vec;
std::cin>>numOfTest ;
for(int j=; j<=numOfTest; ++j) // loop for num of tests
{
int n=0;
for(int i=0; i<n; ++i) // loop for num of veriabels in one test
{
int var=0;
std::cin >> var;
vec.push_back(var);
}
// option one
int* arr = new int[n] ;
std::copy(vec.begin(),vec.end(),arr);
sort(arr, n);
//option two
sort(&vec[0], n);
//option three
sort(vec.data(), n);
for(int f=0; j<=n ++j)
{
std::cout << arr[f] << " "; // print the sorted array;
}
delete [] arr;
}
return 0;
}
if your choosing option two or three you can using range base loop instead of for loop:
it will look like this:
for(auto& e: vec)
{
std::cout << e << " ";
}
how can I make it say maximum value 5.3 instead of just 5 and also
make it work with the other values and methods??
//main class
#include<iostream>
#include "FloatList.h"
using namespace std;
int main(){
int size;
float element;
cout<<"Enter the maximum number of values to store in the array: ";
cin>>size;
FloatList f1(size);
for(int e=0;e<size;e++){
cout<<"Enter the value you want to store in the position number "<<e+1<<" :";
cin>>element;
f1.setElement(e,element);
}
cout<<endl;
cout<<"The elements in the array are the following: "<<endl;
for(int i=0;i<size;i++){
cout<<f1.getElement(i)<<endl;
}
cout<<"The maximum value in the array is: "<<f1.calculateMaxValue()<<endl;
cout<<"The minimum value in the array is: "<<f1.calculateMinValue()<<endl;
cout<<"The average value in the array is: "<<f1.calculateAverage()<<endl;
cout<<"This is now a copy of the original array:"<<endl;
return 0;
}
//FloatList.h
#ifndef FLOATLIST_H_
#define FLOATLIST_H_
#include<iostream>
#include <cstdlib>
using namespace std;
class FloatList {
private:
int size;
int numElements;
float *list;
bool isValid(int);
public:
FloatList(int=1);
FloatList(FloatList &);
void setElement(int, int); // Sets an element to a value.
float getElement(int); // Returns an element.
~FloatList();
void setNumElements(int numElements);
void setSize(int size);
int getNumElements();
int getSize();
float calculateMaxValue();
float calculateMinValue();
float calculateAverage();
};
#endif /* FLOATLIST_H_ */
//FloatList.cpp
#include "FloatList.h"
FloatList::FloatList(int tempSize):size(tempSize){
list = new float[size];
numElements = size;
for (int i = 0; i < size; i++){
list[i] = 0;
}
}
void FloatList::setNumElements(int numElements) {
this->numElements = numElements;
}
FloatList::FloatList(FloatList& temp) {
size=temp.getSize();
list = new float[size];
numElements = size;
for (int i = 0; i < size; i++){
list[i] = temp.getElement(i);
}
}
int FloatList::getNumElements() {
return numElements;
}
int FloatList::getSize() {
return size;
}
void FloatList::setSize(int size) {
this->size = size;
}
FloatList::~FloatList() {
delete [] list;
}
bool FloatList::isValid(int element)
{
bool status;
if (element < 0 || element >= numElements)
status = false;
else
status = true;
return status;
}
void FloatList::setElement(int element, int value)
{
if (isValid(element))
list[element] = value;
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
float FloatList::getElement(int element)
{
if (isValid(element))
return list[element];
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
float FloatList::calculateMaxValue() {
float maxValue=list[0];
for(int i=1;i<size;i++){
if(list[i]>maxValue){
maxValue=list[i];
}
}
return maxValue;
}
float FloatList::calculateMinValue() {
float minValue=list[0];
for(int i=1;i<size;i++){
if(list[i]<minValue){
minValue=list[i];
}
}
return minValue;
}
float FloatList::calculateAverage() {
float average;
for(int i=0;i<size;i++){
average+=list[i];
}
return average/size;
}
//output:
Enter the maximum number of values to store in the array: 3
Enter the value you want to store in the position number 1 :1.2
Enter the value you want to store in the position number 2 :5.3
Enter the value you want to store in the position number 3 :4.5
The elements in the array are the following:
1
5
4
The maximum value in the array is: 5
The minimum value in the array is: 1
The average value in the array is: 3.33333
This is now a copy of the original array:
1
5
4
how can I make it say maximum value 5.3 instead of just 5 and also
make it work with the other values and methods??`