I have this program that finds the largest integer in an array using recursion, but it keeps returning the last number entered no matter what the value instead of the largest number. How do i fix this?
#include <iostream>
using namespace std;
int maximum(int digits[], int size, int largest, int i);
void main()
{
const int size = 3;
int digits[size];
int n = 0, x = 0;
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[n];
}
cout << "\nThe largest digit is, " << maximum(digits, size, 0, 0) << ", thank you!\n";
cout << endl;
}
int maximum(int digits[], int size, int largest, int i)
{
if ( i < size )
{
if ( largest < digits[i])
largest = digits[i];
maximum( digits, size, largest, i + 1);
}
return largest;
}
First use the index variable properly in main()
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[a];//-->Use the index varible correctly.
}
int maximum(int digits[], int size, int largest, int i)
{
if(i==size-1)
return digits[i]; //The base case is specified here.
if ( i < size )
{
int temp= maximum( digits, size, largest, i + 1);
if ( digits[i] < temp)
largest =temp;
else
largest=digits[i];
}
return largest;
}
Please check out the changes. Carefully read the code. You will understand your mistakes.
When designing recursion think of few things first-
The base condition. (This stops the recursion).
The recursive step. (Where you will calculate something based on previous calculation)
Combine step- You have to combine them (value at this stage and value got from recusive step) to get the correct answer. This step is not required in some cases.
It should be return maximum( digits, size, largest, i + 1);
Live example.
int biggestOne(int integerArray[], int lengthOfArray, int max)
{
if (lengthOfArray==0) return max;
if (max < integerArray[lengthOfArray-1]) max = integerArray[lengthOfArray-1];
return biggestOne(integerArray,lengthOfArray-1,max);
}
int main()
{
int array[] = {7,2,9,10,1};
int arrSize = sizeof(array)/sizeof(array[0]); //returns length of the array
cout <<"Biggest number in the array: " << biggestOne(array,arrSize,0) << endl;
return 0;
}
Related
I have to find the elements in a given array, and I found a program in other site, but when I try to interpret the code in my way, I have error.
That is from the other site:
#include <iostream>
using namespace std;
// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
int sum = 0; // initialize sum
// Iterate through all elements
// and add them to sum
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Sum of given array is " << sum(arr, n);
return 0;
}
That's mine:
#include <iostream>
using namespace std;
int Function(int arr[], int Broi)
{
int suma = 0;
for (int i = 0; i < Broi; i++) {
cin >> arr[Broi];
suma += arr[i];
}
return suma;
}
int main()
{
int arr;
int Broi = sizeof(arr) / sizeof(arr[0]);
cout << "Srednoto Aritmetichno e: " << Function(arr[], broi);
return 0;
}
Also the first programe gives the numbers of the array, but I want the user to cin>> them when u write the length of the arr.
Your code is not declaring an array at all. It is declaring a single int.
You said in comments that:
The task is to read 10 numbers, and to put them in array
So, you should declare a 10-int array in main() and fill it with user values before passing it to Function(), similar to how the original code was doing. The user input doesn't really belong in Function() to begin with.
Try something more like this instead:
#include <iostream>
using namespace std;
int Function(int arr[], int Broi)
{
int suma = 0;
for (int i = 0; i < Broi; i++) {
suma += arr[i];
}
return suma;
}
int main()
{
int arr[10];
cout << "Enter 10 numbers: ";
for(int i = 0; i < 10; ++i){
cin >> arr[i];
}
cout << "The sum is: " << Function(arr, 10);
return 0;
}
The line arr[Broi] is accessing the array out of bounds, causing undefined behavor, because the array consists only of a single element. Even if it consisted of Broi elements, it would be accessing the array out of bounds, because valid indexes would be 0 to Broi - 1.
In the comments section (but not in the question), you stated that you are supposed to read 10 numbers from the user. If arr were pointing to an array of 10 elements instead of 1 element, then it would make sense to write arr[i] instead of arr[Broi].
The simplest solution to the problem would be to not use arrays at all:
#include <iostream>
constexpr int NUM_INPUTS = 10;
int main()
{
int input;
int sum = 0;
for ( int i = 0; i < NUM_INPUTS; i++ )
{
//prompt user for input
std::cout << "Please enter integer #" << i + 1 << ": ";
//attempt to read integer from user
if ( ! ( std::cin >> input ) )
{
std::cout << "Input failure!\n";
return 1;
}
//add user input to sum
sum += input;
}
//print sum
std::cout << "\nThe sum of all numbers is: " << sum << ".\n";
return 0;
}
However, since you stated in the comments section that you are supposed to use arrays, then you are probably supposed to first read all 10 numbers from std::cin into an array of 10 elements and then calculate the sum afterwards:
#include <iostream>
#include <cstdlib>
constexpr int NUM_INPUTS = 10;
void input_array( int arr[] )
{
for ( int i = 0; i < NUM_INPUTS; i++ )
{
//prompt user for input
std::cout << "Please enter integer #" << i + 1 << ": ";
//attempt to read integer from user
if ( ! ( std::cin >> arr[i] ) )
{
std::cout << "Input failure!\n";
std::exit( EXIT_FAILURE );
}
}
}
int calculate_sum( int arr[] )
{
int sum = 0;
for ( int i = 0; i < NUM_INPUTS; i++ )
{
sum += arr[i];
}
return sum;
}
int main()
{
int arr[NUM_INPUTS];
//fill array with user input
input_array( arr );
//print sum
std::cout << "\nThe sum of all numbers is: " << calculate_sum( arr ) << ".\n";
return 0;
}
Both programs have the following output:
Please enter integer #1: 20
Please enter integer #2: 30
Please enter integer #3: 10
Please enter integer #4: 5
Please enter integer #5: 31
Please enter integer #6: 17
Please enter integer #7: 6
Please enter integer #8: 14
Please enter integer #9: 18
Please enter integer #10: 50
The sum of all numbers is: 201.
The simple fix without too many complicated features would be like below:
#include <iostream>
int Function( int* const array, const std::size_t elementCount)
{
int suma { };
for ( std::size_t idx = 0; idx < elementCount; ++idx )
{
std::cin >> array[ idx ];
suma += array[ idx ];
}
return suma;
}
int main( )
{
int myArray[ 4 ] { };
int suma = Function( myArray, sizeof( myArray ) / sizeof( *myArray ) );
std::cout << "Srednoto Aritmetichno e: " << suma << '\n';
return 0;
}
That's it. You can change the size of myArray to anything that fits onto stack memory.
I have a little problem with check for multiplicity for 3. It says that my arr must be integer, but in objective I need to have a float massive. How to make this check "arr[i] % 3 == 0" for float numbers.
thanks.
#include <iostream>
#include <cmath>
using namespace std;
float minElement(float arr[], int length) {
float minElement = arr[0];
for (int i = 0; i < length; i++)
{
if (minElement > arr[i])
minElement = arr[i];
}
return minElement;
}
float multiplyArr(float arr[], int length) {
float multiply = 1;
for (int i = 0; i < length; i++)
{
if (arr[i] != 0 && arr[i] % 3 == 0)
multiply *= arr[i];
}
return multiply;
}
int main()
{
float length;
cout << "Enter integer value: ";
cin >> length;
float* p_darr = new float[length];
cout << "Enter values: " << endl;
for (int i = 0; i < length; i++) {
cin >> p_darr[i];
}
cout << "Max. element: " << minElement(p_darr, length) << endl;
cout << "Multiply: " << multiplyArr(p_darr, length) << endl;
delete[] p_darr;
return 0;
}
Assuming
float massive
to mean "large value". You cannot perform this operation, as it would be meaningless. Comments (and other answers) will suggest fmod. I'll advise against.
If I give you the value 3.6x10^12 and ask you what's the remainder after division by 3, you can't give me a meaningful answer.
3600000000000 % 3 is 0. 3600000000001 % 1 is 1. 3600000000002 % 2 is 2.
But all three values are 3.6x10^12.
If you need integer modulo values, it typically means you need integer precision. Float values won't offer it.
Rather, you should read your input as a string, parse it character by character, and compute the modulo so far. This is a typical first assignment in a computer theory class (as I used to TA).
suppose the array is a[]={123,34533,21123}.How do i calculate the length of element at index 1?I know i am doing it all wrong but i dont know how to approach this
#include<iostream>
using namespace std;
int main()
{
int a[]={123,231,23},j=0,num,last_digit,sum;
int size_of_array=sizeof(a)/4;
int pos;
cin>>pos;
num=a[pos];
for(int i=0;i<size_of_array;i++)
{
last_digit=num%10;
sum=sum+last_digit;
num=num/10;
}
cout<<sum;
}
"i want to calculate sum of the digits of the element for which i need its length "
Confusing. If you want to convert the element to a string and then take its length, you would do this:
std::cout << "Length: " << std::to_string(a[i]).size() << std::endl;
Where i is the index into array a[].
However, if you want to calculate the sum of the digits, then I suppose you are trying to do this:
int sumCell = 0;
int cellValue = a[i];
while(cellValue > 0) {
sumCell = cellValue % 10;
cellValue /= 10;
}
Sum is in the variable sumCell.
Are you looking for one of these two solutions, or another?
Just like an ordinary int
#include<iostream>
int main() {
int a[]={123,231,23};
size_t pos; // use size_t for index and size
std::cin >> pos;
int elm = a[pos];
int cnt = 1;
while ( elm /= 10) {
++cnt;
}
std::cout << cnt << std::endl;
return 0;
}
Enter the index and get the length.
#include<iostream>
using namespace std;
int main()
{
int a[] = { 123, 231, 23 }, j = 0, num, last_digit, sum = 0, count = 0;
size_t size_of_array = sizeof(a) / 4;
size_t index;
cin >> index;
num = a[index];
while (num != 0) {
last_digit = num % 10;
sum = sum + last_digit;
num = num / 10;
count = count + 1;
}
cout << sum << endl; //sum
cout << count; //number of digits
}
Im trying to implement the Quick Select Algorithm on a Array that has randomly generated numbers. Now after writing the algorithm in code, it does not sort the array from lowest to highest nor am i able to find the kth smallest element. I would appreciate the help i get. Thank you.
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void printArray(int *myArray, int n){
for(int i = 0; i < n; i++){
cout << myArray[i] << " ";
}
}
int Partition(int *myArray, int startingIndex, int endingIndex){
int pivot = myArray[endingIndex];
int partitionIndex = startingIndex;
for(int i = startingIndex; i<endingIndex; i++){
if(myArray[i]<= pivot){
swap(myArray[i],myArray[partitionIndex]);
partitionIndex++;
}
}
swap(myArray[partitionIndex],myArray[endingIndex]);
return partitionIndex;
}
int QuickSelect(int *myArray, int startingIndex, int endingIndex, int KthElement){
/*if(startingIndex < endingIndex){
int partitionIndex = Partition(myArray, startingIndex,endingIndex);
QuickSelect(myArray,startingIndex,partitionIndex-1);
QuickSelect(myArray,partitionIndex+1,endingIndex);
}*/1
if (startingIndex < endingIndex){
int partitionIndex = Partition(myArray, startingIndex, endingIndex);
if(KthElement == partitionIndex)
return KthElement;
if(KthElement < partitionIndex)
QuickSelect(myArray, startingIndex, partitionIndex - 1, KthElement);
else
QuickSelect(myArray, partitionIndex + 1, endingIndex, KthElement);
}
}
int main(){
int numOfElements;
int KthElement;
srand(time(NULL));
cout<<"Enter The Amount Of Numbers You Wish To Use: ";
cin >> numOfElements;
int myArray[numOfElements];
cout << "Array Before Sorting: ";
for(int i = 0; i< numOfElements; i++){
myArray[i] = rand() %10;
}
printArray(myArray, numOfElements);
cout << endl;
cout << endl;
cout <<"Enter The Index Of The Kth Element You Wish To Retrieve: ";
cin >> KthElement;
QuickSelect(myArray, 0,numOfElements,KthElement);
cout << "Array After Sorting: ";
printArray(myArray, numOfElements);
cout << endl;
cout <<"The " <<KthElement<<" Smallest Element Is: " << QuickSelect(myArray,0,numOfElements,KthElement);
}
For numOfElements as 5, array extends from 0 to 4.
Your endingIndex assumes that its the last index of the array.
Fix:
QuickSelect(myArray, 0,numOfElements-1,KthElement);
Problems with your code:
Your program accesses out of bound array locations in
int pivot = myArray[endingIndex];
Have a check for k<1 and k>(num_of_elements).
Check your code for num_of_elements = 1 as well.
Check what k means for the array, i.e For k=1 , arr[0] should be returned not arr[1];
We had a project that asked us to Write a program that allows a user to enter a series of numbers "read numbers into an array for further processing, user signals that they are finished by entering a negative number (negative not used in calculations), after all numbers have been read in do the following, sum up the #'s entered, count the #'s entered, find min/max # entered, compute average, then output them on the screen. So the working version of this that I made looks like so
/* Reads data into array.
paramater a = the array to fill
paramater a_capacity = maximum size
paramater a_size = filled with size of a after reading input. */
void read_data(double a[], int a_capacity, int& a_size)
{
a_size = 0;
bool computation = true;
while (computation)
{
double x;
cin >> x;
if (x < 0)
computation = false;
else if (a_size == a_capacity)
{
cout << "Extra data ignored\n";
computation = false;
}
else
{
a[a_size] = x;
a_size++;
}
}
}
/* computes the maximum value in array
paramater a = the array
Paramater a_size = the number of values in a */
double largest_value(const double a[], int a_size)
{
if(a_size < 0)
return 0;
double maximum = a[0];
for(int i = 1; i < a_size; i++)
if (a[i] > maximum)
maximum = a[i];
return maximum;
}
/* computes the minimum value in array */
double smallest_value(const double a[], int a_size)
{
if(a_size < 0)
return 0;
double minimum = a[0];
for(int i = 1; i < a_size; i++)
if (a[i] < minimum)
minimum = a[i];
return minimum;
}
//computes the sum of the numbers entered
double sum_value(const double a [], int a_size)
{
if (a_size < 0)
return 0;
double sum = 0;
for(int i = 0; i < a_size; i++)
sum = sum + a[i];
return sum;
}
//keeps running count of numbers entered
double count_value(const double a[], int a_size)
{
if (a_size < 0)
return 0;
int count = 0;
for(int i = 1; i <= a_size; i++)
count = i;
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int INPUT_CAPACITY = 100;
double user_input[INPUT_CAPACITY];
int input_size = 0;
double average = 0;
cout << "Enter numbers. Input negative to quit.:\n";
read_data(user_input, INPUT_CAPACITY, input_size);
double max_output = largest_value(user_input, input_size);
cout << "The maximum value entered was " << max_output << "\n";
double min_output = smallest_value(user_input, input_size);
cout << "The lowest value entered was " << min_output << "\n";
double sum_output = sum_value(user_input, input_size);
cout << "The sum of the value's entered is " << sum_output << "\n";
double count_output = count_value(user_input, input_size);
cout << "You entered " << count_output << " numbers." << "\n";
cout << "The average of your numbers is " << sum_output / count_output << "\n";
string str;
getline(cin,str);
getline(cin,str);
return 0;
}
That went fine, the problem I am having now is part 2. Where we are to "copy the array to another and shift an array by N elements". I'm not sure where to begin on either of these. I've looked up a few resources on copying array's but I was not sure how to implement them in the current code I have finished, especially when it comes to shifting. If anyone has any thoughts, ideas, or resources that can help me on the right path it would be greatly appreciated. I should point out as well, that I am a beginner (and this is a beginners class) so this assignment might not be the 'optimal' way things could be done, but instead incorporates what we have learned if that makes sense.
for(int i = 0; i < n; ++i){
int j = (i - k)%n;
b[i] = a[j];
}
Check it. I'm not sure
If this works you could improve it to
for(int i = 0; i < n; ++i)
b[i] = a[(i - k)%n];//here can be (i +/- k) it depends which direction u would shift
If you only want to copy the array into another array and shift them
ex : input = 1, 2, 3, 4, 5; output = 3, 4, 5, 1, 2
The cumbersome solution is
//no template or unsafe void* since you are a beginner
int* copy_to(int *begin, int *end, int *result)
{
while(begin != end){
*result = *begin;
++result; ++begin;
}
return result;
}
int main()
{
int input[] = {1, 2, 3, 4, 5};
size_t const size = sizeof(input) / sizeof(int);
size_t const begin = 2;
int output[size] = {0}; //0, 0, 0, 0, 0
int *result = copy_to(input + begin, input + size - begin, output); //3, 4, 5, 0, 0
copy_to(input, input + begin, result); //3, 4, 5, 1, 2
return 0;
}
How could the stl algorithms set help us?
read_data remain as the same one you provided
#include <algorithm> //std::minmax_element, std::rotate_copy
#include <iostream>
#include <iterator> //for std::begin()
#include <numeric> //for std::accumulate()
#include <string>
#include <vector>
int main(int argc, char *argv[]) //don't use _tmain, they are unportable
{
const int INPUT_CAPACITY = 100;
double user_input[INPUT_CAPACITY];
int input_size = 0;
double average = 0;
cout << "Enter numbers. Input negative to quit.:\n";
read_data(user_input, INPUT_CAPACITY, input_size);
auto const min_max = std::minmax_element (user_input, user_input + input_size); //only valid for c++11
std::cout << "The maximum value entered was " << min_max.second << "\n";
std::cout << "The lowest value entered was " << min_max.first << "\n";
double sum_output = std::accumulate(user_input, user_input + input_size, 0);
cout << "The sum of the value's entered is " << sum_output << "\n";
//I don't know the meaning of you count_value, why don't just output input_size?
double count_output = count_value(user_input, input_size);
cout << "You entered " << count_output << " numbers." << "\n";
cout << "The average of your numbers is " << sum_output / count_output << "\n";
int shift;
std::cout<<"How many positions do you want to shift?"<<std::endl;
std::cin>>shift;
std::vector<int> shift_array(input_size);
std::rotate_copy(user_input, user_input + shift, user_input + input_size, std::begin(shift_array));
//don't know what are they for?
std::string str;
std::getline(std::cin,str);
std::getline(std::cin,str);
return 0;
}
if your compiler do not support c++11 features yet
std::minmax_element could replace by
std::min_element and std::max_element
std::begin() can replace by shift_array.begin()
I don't know what is the teaching style of your class, in my humble opinion, beginners should
start with those higher level components provided by c++ like vector, string, algorithms
and so on.I suppose your teachers are teaching you that way and you are allowed to use the
algorithms and containers come with c++(Let us beg that your class are not teaching you "c with classes" and say something like "OOP is the best thing in the world").
ps : You could use vector to replace the raw array if you like