I have an array generated with random integers from 0 to 9, I have a function that does that. I also have a function that determines what the largest element from the array is. I need to write another function that determine the index of the largest variable. I believe the problem is that I cannot call the function within the function but it could be something else.
The code I have is below:
#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
void initialize(int arr[], int size);
void print(int arr[], int size);
void findLargest(int arr[], int size);
void largestIndex(int arr[], int size);
int main(){
const int SIZE = 10;
int myList[SIZE];
initialize(myList, SIZE);
print(myList, SIZE);
findLargest(myList, SIZE);
largestIndex(myList, SIZE);
return 0;
}
void initialize(int arr[], int size){
srand(time(0));
for(int i = 0; i < size; i++){
arr[i] = (rand() % 10);
}
}
void print(int arr[], int size){
for(int j = 0; j < size; j++){
cout<<arr[j]<< endl;
}
}
void findLargest(int arr[], int size){
for(int i = 0; i < size; i++){
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "The largest element in the array is " << arr[0]<< endl;;
}
void largestIndex(int arr[], int size){
for(int i = 0; i < size; i++){
if(arr[i] == 9){
cout<< "The index of the largest element is " + i <<endl;
}
}
}
Ran it through compiler explorer
https://godbolt.org/z/c9ETjaq3z
Revealing this error message
<source>:69:59: warning: adding 'int' to a string does not append to the string [-Wstring-plus-int]
cout<< "The index of the largest element is " + i <<endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
<source>:69:59: note: use array indexing to silence this warning
cout<< "The index of the largest element is " + i <<endl;
^
& [ ]
This line
cout << "The index of the largest element is " + i <<endl;
Adds i to the pointer to the character string "The index of the largest element is ". The result is that you carve of the beginning of the string instead of showing the value of i.
What you want is
cout << "The index of the largest element is " << i <<endl;
or
cout << "The index of the largest element is " + std::to_string(i) <<endl;
You might want to consider using std::max_element
auto largest = *std::max_element(arr, arr + size);
std::cout << "Largest... = " << largest << std::endl;
Related
I am running a code for finding repeating array elements.
I am doing it using 2 functions, however when I run the code my application immedietaly crashes despite assigning it to random numbers from 1 to 99.
Here is the code. Thank you..
#include <ctime>
#include <iostream>
using namespace std;
int UniqueArray(int arr[], int notunique);
void printarray(int arr[]);
int main() {
int arr[20];
int dup = 0;
printarray(arr);
for (int i = 0; i < 20; ++i) {
UniqueArray(arr, dup);
}
}
int UniqueArray(int arr[], int notunique) {
notunique = 0;
int i, j;
int size = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (arr[i] == arr[j]) {
notunique++;
cout << "Array has duplicates: " << arr[i] << " ";
}
}
}
return notunique;
cout << "There were " << notunique << " Repeated elements";
}
void printarray(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]);
srand(time(0));
arr[20] = rand () % +100;
for (int i = 0; i < 20; ++i) {
cout << arr[i] << " ";
}
}
This line:
arr[20] = rand () % +100;
does not fill an array of size 10 with random values. It indexes the 20th position, which is UB.
You could fill the array with random numbers, using std::generate, like this:
std::generate(arr, arr + 20, [] { return rand() % 100; });
Also, when finding the size of the array, you'll need to deduce the size:
template <size_t N>
void printarray(int (&arr)[N]) {
// ... use N which is the size of arr
or even better, use std::array, which does this for you.
Some minor issues:
Don't use using namespace std;.
In this snippet:
return notunique;
cout << "There were " << notunique << " Repeated elements";
the statement after the return will never get executed.
In this line:
arr[20] = rand () % +100;
you don't need the + operator.
I have this code for bubble sort in c++. At first it generates random numbers and puts them inside an array. After that I call my bubbleSort function, which does the sorting. Everything works fine. However I was curious how can I find a number of total comparisons and number swapping that bubble sort makes?
I created a CountBubbleSort integer for comparisons. However I'm not sure in which part of my code should I increment it. I was thinking to add it after second for loop, inside first one. Hope you understand what I mean. Is it right or not? Number of comparisons defines this formula n*(n-1))/2. And with swaps it is 3*(n-1). But how can I implement it to my code? Thanks for the help guys.
void swap(double *xp, double *yp)
{
double temp = *xp;
*xp = *yp;
*yp = temp;
}
double *Data;
double* A;
double n, temp;
void generate(int _n, const char *_file);
void read(const char *_file);
void printArray(double arr[], int n);
void bubbleSort(double arr[], int n);
int main()
{
int m;
int CountBubbleSort = 0;
srand(time(NULL));
cout << "Amount of random numbers you want: ";
cin >> m;
cout << "Generating random data ..." << endl;
generate(m, "duom.txt");
cout << "Reading data" << endl;
read("duom.txt");
A = new double[n];
for (int i = 0; i < n; i++) {
A[i] = Data[i];
}
cout << "Randomly generated array" << endl;
printArray(A, n);
// Bubble Sort
bubbleSort(A, n);
cout << "Array after bubble sort" << endl;
printArray(A, n);
return 0;
}
void bubbleSort(double arr[], int n)
{
bool swapped;
for (int i = 0; i < n - 1; i++)
{
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
// Should I add CountBubbleSort += i here or not?
if (swapped == false)
break;
}
}
void printArray(double arr[], int n) {
for (int i = 0; i < n; i++) {
cout << A[i] << endl;
}
}
This is a relatively straightforward change:
Increment comparison count before the if statement
Increment the swap counter inside the if statement
Take two int& parameters for the count, like this:
void bubbleSortCounted(double arr[], int n, int& countComparisons, int& countSwaps);
The code incrementing the counters would look like this:
countComparisons++;
if (arr[j] > arr[j + 1])
{
countSwaps++;
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
The call from the main() would look like this:
int cmp = 0, swp = 0;
bubbleSort(A, n, cmp, swp);
std::cout << cmp << " comparisons, " << swp << " swaps" << std::endl;
However I was curious how can I find a number of total comparisons and number swapping that bubble sort makes? I created a CountBubbleSort integer for comparisons. However I'm not sure in which part of my code should I increment it.
There's exactly one line in your bubbleSort() function where you actually compare two elements in the array, so it stands to reason that if you want to count the number of times you compare elements, you should increment the counter either immediately before or immediately after the comparison happens.
So I'm getting a segmentation fault error in the beginning of the code. I've tried running some tests at the different points and the error seems to be when i allocate memory for the array. Ive just started learning about heap and stack memory so I'm not really sure if I'm doing something wrong there. Any help would be appreciated.
#include <iostream>
using namespace std;
//Function Prototypes
void sort(int A[], int n);
int findMin(int A[], int n, int j);
int swap(int& a, int& b);
double median(int A[], int n);
void output1(int median);
void output2(double median);
int main()
{
int size;
int array[size]; //Segmentaion fault here
int i = 0;
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
while(size >= 1)
{
double element;
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
while(i < size)
{
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
}
sort(array, size);
median(array, size);
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
}
delete [] array;
return 0;
}
void sort(int A[], int n)
{
int min;
for(int i = 0; i < n; i++)
{
min = findMin(A,n,i);
//min = findMinIndex(p, size, i);
//if(min )
swap(A[i],A[min]);
//swap(p[i],p[min]);
}
}
int findMin(int A[], int n, int j)
{
int minIndex = j;
for(int i = j+1; i < n; i++)
if(A[i]<A[minIndex])
minIndex = i;
return minIndex;
}
int swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void output1(int median)
{
cout << "The median is " << median << "." << endl;
}
void output2(double median)
{
cout << "The median is " << median << "." << endl;
}
double median(int A[], int n)
{
if(n % 2 == 0)
{
int div1 = n / 2;
int num1 = A[div1];
int num2 = A[div1 -1];
double median = (num1 + num2) / 2;
output2(median);
}
else
{
int div2 = n - 1;
int median = div2 / 2;
output1(median);
}
}
Because you are not initialising size, the value in that variable could literally be anything. If it happens to be excessively large, say 106,840,406, then you won't be able to get an int[] of that size.
So basically, initialise your size variable to something sensible.
Segmentation Fault 11 equals to say "Index out of range"...
Index
0, 1, 2, 3, 4 ,5
Value 5, 6 ,1 ,9 ,8 ,7
Array length is 6, but its last index is 5.. for example, if we control a for cycle with 6 then we got Segmentation Fault 11...
An array in c++ has to be initialized at the with a fixed size. In your case, size is not initialized to any fixed integer value, which is illegal in c++ and will cause the compiler to produce an error message.
If you try the following line just before you initialize the array of size size, you can tell what the size originally is:
cout << size << endl;
I compiled your code with this line and got this int size before the compiler failed:
1995231824 (This differs for every compiler and computer, but every number will be as big and useless as this one)
Trying to have such a big array will naturally lead to a segmentation fault. That's why you would have to initialize the variable size to a fixed number. This will eliminate the segmentation fault.
I am having some issues with an array expansion project and am trying to find where the issue is with getting my array to expand with all zeroes. Here are the requirements:
Array Expander. The program should have an array of integers. It will have a function that has two parameters, the integer array and the array’s size. This function will create a new array that is twice the size of the arguments array. The function should copy the contents of the argument array to the new array, and initialize the unused elements of the second array with 0. The function must return a pointer to the new array. The program will then display the contents of the new array.
Program must have the following functions
• int* expandArray(int[ ], int)
• void showArray(int [ ], int)
I am getting the program to build the first array without issues, however, the second array, while it displays the first array of numbers fine, displays the second array with an assortment of digits. I have been looking at this for hours and am at a loss with how to correct this to work correctly. Here is my code that I have so far:
//Include section
#include <iostream>
#include <cstring>
//Namespace Section
using namespace std;
//Function Prototype Section
int *expandArray(int[], int&);
void showArray(const int[], int);
//Main section: this is the entry point of the program, which controls the flow of execution
int main()
{
int arraySize = 7; //sets the size of the array at 7
int *array = new int[arraySize];
for (int c = 0; c < arraySize; ++c)
array[c] = c + 1;
//the following outputs the initial array of 7 to the user's screen; beginning at 1 and incrementing to 7
cout << "*********************************************************************" << endl;
cout << " The following is the initial array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize);
cout << endl;
cout << endl;
//the following outputs the initial array, plus expands the array by double, initializing the unused elements with zero
cout << "*********************************************************************" << endl;
cout << " The following is the expanded array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize * 2);
cout << endl;
cout << endl;
delete[] array;
system("PAUSE");
return 0;
}
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
expandedArray = new int[arraySize * 2];
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
}
void showArray(const int arr[], int arraySize)
{
for (int index = 0; index < arraySize; index++)
cout << arr[index] << " " << endl;
}
I believe my issue is in the following section of the code, but unsure as to how to fix it:
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
expandedArray = new int[arraySize * 2];
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
Any assistance would be greatly appreciated!
As I see it you forgot to to copy the contents of your initial array into expandedArray in the declaration of your function. You only set all elements with index in between arraySize and arraySize*2 to 0 but never actually copied the values of your argument.
I would include the following:
for(int i=0; i<arraySize; i++) expandedArray[i] = array[i];
right after having declared expandedArray dynamically. Note it is important that you include this piece of code before modifying arraySize as you would get out-of-bounds issues when accessing array[i].
The issue is that you're not copying the original array's contents into the new allocated array space.
A simple solution is to use new[] with brace initialization of 0, and then copy the original contents into the new array. The brace initialization will initialize all the space to 0, so you don't need to write two loop to set the newly allocated space to 0.
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
// allocate and initialize all entries to 0
expandedArray = new int[arraySize * 2]{0};
// copy old elements to new space
for (int index = 0; index < arraySize; index++)
expandedArray[index] = array[index];
// delete old space
delete [] array;
// double array size
arraySize *= 2;
return expandedArray;
}
int *arrayExpander(int arr[], int size)
{
int *expendedArray = new int[size * 2];
// move elements forom original array into the expandedArray
// initilize the rest of the elements to ZERO
for (int i = 0; i < size * 2; i++)
{
if (i < size)
{
// filling firt half
expendedArray[i] = arr[i];
}
else
{
// second half of the array
expendedArray[i] = 0;
}
}
return expendedArray;
}
int main()
{
int size = 5;
int arr[] = { 1,2,3,4,5 };
// Array pointer
int *arrPtr = arrayExpander(arr, size);
// Display
for (int i = 0; i < size * 2; i++)
{
cout << arrPtr[i] << " " << flush;
}
return 0;
}
Actually there are 2 errors in your code:
When you run your code it prints the first 7 elements of your array of type double correctly, but not the other 7. This is because they are not initialized, therefore they are returning garbage values.
Therefore in the function you have to initialize the other 7 elements to 0. The same goes for the first 7 elements and the first matrix.
I rectified the problem. Please have a good look at it:
//Include section
#include <iostream>
#include <cstring>
//Namespace Section
using namespace std;
//Function Prototype Section
int *expandArray(int[], int&);
void showArray(const int[], int);
int *expandedArray;
//Main section: this is the entry point of the program, which controls the flow of execution
int main()
{
int arraySize = 7; //sets the size of the array at 7
int *array = new int[arraySize];
for (int c = 0; c < arraySize; ++c)
array[c] = c + 1;
//the following outputs the initial array of 7 to the user's screen; beginning at 1 and incrementing to 7
cout << "*********************************************************************" << endl;
cout << " The following is the initial array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize);
cout << endl;
cout << endl;
//the following outputs the initial array, plus expands the array by double, initializing the unused elements with zero
cout << "*********************************************************************" << endl;
cout << " The following is the expanded array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
expandArray(array, arraySize);
showArray(expandedArray, arraySize);
cout << endl;
cout << endl;
delete[] array;
return 0;
}
int *expandArray(int array[], int &arraySize)
{
expandedArray = new int[arraySize * 2];
for (int c = 0; c < arraySize; ++c)
expandedArray[c] = c + 1;
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
}
void showArray(const int arr[], int arraySize)
{
for (int index = 0; index < arraySize; index++)
cout << arr[index] << " " << endl;
}
//here is your solution bro..!!
I'm having some problems with this program. It is meant to input random numbers into an array, change its dimensions, sort them, the output the sorted array. For some reason, the array will only fill with one number (-858993460) and I cannot figure out why. Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstring>
using namespace std;
void InputArray(int[][5], int, int);
void OutputArray(int[], int);
void SelectionSort(int[], int);
void CopyArray(int[][5], int, int, int[], int);
int main()
{
int sample_1[80];
int sample_2[16][5];
InputArray(sample_2, 16, 5);
CopyArray(sample_2, 16, 5, sample_1, 80);
cout << "Before sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
SelectionSort(sample_1, 80);
cout << "After sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
return 0;
}
//generate random numbers for a two dimensional array
void InputArray(int array[][5], int m, int n)
{
int i, j;
srand(time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
array[i][j] = rand() % 1000;
}
}
}
//display values in a one-dimensional array
void OutputArray(int array[], int number)
{
int i;
for (i = 0; i < number; i++)
{
cout << array[i] << "\t";
}
}
// selection sort of a one-dimensional array
void SelectionSort(int numbers[], int array_size)
{
int i, j, a;
for (i = 0; i < array_size; ++i) {
for (j = i + 1; j < array_size; ++j) {
if (numbers[i] > numbers[j]) {
a = numbers[i];
numbers[i] = numbers[j];
numbers[j] = a;
}
}
}
return;
}
//x and y and two dimensions of array_2d; n is the dimension of array_1d
//copy values from array_2d[][] to array_1d[]
//assume x*y equals n
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
return;
}
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
}
That's your problem right there. The size of the array_1d is unspecified here. The sizeof() operator does not know the size of the array that's being copied.
In fact, I'm surprised that this even compiles, although I'm too lazy to test it with gcc.
What you need to do is calculate the size of the array yourself, multiply it by sizeof(int), and use that instead of the existing sizeof() operator.