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.
Related
I was struggling on how to move the first value to the las in order like shown in the picture
enter image description here
What should I do?
#include <iostream>
using namespace std;
void rotate(int A[], int n = 5)
{
int x = A[n - 1], i;
for (i = n - 1; i > 0; i--)
{
A[i] = A[i -1];
}
A[0] = x;
}
int main()
{
int A[] = { 1, 2, 3, 4, 5 }, i;
int n = sizeof(A) / sizeof(A[5]);
cout << "Given array is \n";
for (i = 0; i < n; i++)
cout << A[i] << ' ';
for (int j = 0; j < n; j++)
{
rotate(A, n);
cout << "\nStep " << j << " --> ";
for (i = 0; i < n; i++)
{
cout << A[i] << ' ';
}
}
return 0;
}
Your code is still quite "C" like. Here is an example that hopefully will teach you some C++ coding :
#include <algorithm>
#include <iostream>
#include <vector>
// passing arrays is easier using std::vector/std::array (no need to pass size seperately)
void rotate(std::vector<int>& values)
{
// using algorithm's std::swap you can better show WHAT you are doing
// vector and array also have a size() method so you don't
// have to use "C" style sizeof tricks.
for (std::size_t n = 0; n < values.size() - 1; ++n)
{
std::swap(values[n], values[n + 1]);
}
}
int main()
{
// prefer std::vector (or std::array) in C++. Not "C" style arrays
std::vector<int> values{ 1,2,3,4,5 };
rotate(values);
// use range based for loop if you can.
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}
I have been attempting this for hours to no avail, as you can see in my code I have separate functions, they were all together in main, but I am required to turn each into a separate function. However when I try anything I get errors, even when I try to pass parameters. Can someone point me in the right direction?
#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray();
void average();
void largestnumber();
using namespace std;
int main()
{
printarray();
average();
largestnumber();
}
void printarray() {
srand(time(0));
int n[10], tot = 0;
for (int i = 0; i < 10; i++)
{
n[i] = (1 + rand() % 100);
cout << n[i] << endl;
}
}
void average() {
int j, tot = 0, n[10];
for (j = 0; j < 10; j++)
{
tot += n[j];
}
cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber() {
int w = 1, int n[10];
int temp = n[0];
while (w < 10)
{
if (temp < n[w])
temp = n[w];
w++;
}
cout << "The largest number in the array is " << temp << endl;
}
The array you are working with needs to be passed in to each function, so the same array is used everywhere. It is a good idea to pass the size as well, just for flexibility reasons.
Now your functions pretty much work as you wrote them.
#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray(int n[], size_t size);
void average(int n[], size_t size);
void largestnumber(int n[], size_t size);
using namespace std;
int main()
{
const size_t arr_size = 10;
int n[arr_size];
printarray(n, arr_size);
average(n, arr_size);
largestnumber(n, arr_size);
}
void printarray(int n[], size_t size) {
srand((unsigned int)time(0));
int tot = 0;
for (size_t i = 0; i < size; i++)
{
n[i] = (1 + rand() % 100);
cout << n[i] << endl;
}
}
void average(int n[], size_t size) {
size_t j;
int tot = 0;
for (j = 0; j < size; j++)
{
tot += n[j];
}
cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber(int n[], size_t size) {
size_t w = 1;
int temp = n[0];
while (w < size)
{
if (temp < n[w])
temp = n[w];
w++;
}
cout << "The largest number in the array is " << temp << endl;
}
One simple improvement is to break the printarray out into an initarray function that fills the array and printarray that prints the content.
It would also be a good idea to do some checking for things like an empty array (functions assume n[0] exists, for instance).
The next obvious step is to put all this in a class. Also, if you are allowed to, the c array should be replaced with a vector, as that does a great job of keeping all the resource information together.
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.
Here is some random sort program I wrote in C++. It works pretty fine for 10 elements or so. But for 15 elements it works so slow I can't even wait enough to get the result. Is there some way to optimize random sort algorithm?
Here's my code:
// randomsort.h
#ifndef RANDOMSORT_H
#define RANDOMSORT_H
#include <stdlib.h>
#include <time.h>
class RandomSort
{
private:
template <class T>
static bool isOrdered(T*, int);
public:
template <class T>
static int sort(T*, int);
};
template <class T>
bool RandomSort::isOrdered(T* arr, int size)
{
for(int i = 1; i < size; i++)
{
if(arr[i-1] > arr[i])
{
return false;
}
}
return true;
}
template <class T>
int RandomSort::sort(T* arr, int size)
{
int stepAmount = 0;
srand(time(NULL));
while(!isOrdered(arr, size))
{
int i = rand() % size;
int j = rand() % size;
std::swap(arr[i], arr[j]);
stepAmount++;
}
return stepAmount;
}
#endif // RANDOMSORT_H
And main.cpp file
// main.cpp
#include <iostream>
#include "randomsort.h"
int main()
{
int size;
std::cout << "Enter amount of elements to sort: ";
std::cin >> size;
std::cout << std::endl;
int arr[size];
for(int i = 0; i < size; i++)
{
arr[i] = (rand() % (size * 10));
}
std::cout << "Input array: " << std::endl;
for(int i = 0; i < size; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl << std::endl;
int stepAmount = RandomSort::sort(arr, size);
std::cout << "Output array: " << std::endl;
for(int i = 0; i < size; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl << std::endl;
std::cout << "Number of steps: " << stepAmount;
return 0;
}
Any suggestions?
Your code is completely random. So it can swap when it should not. An easy fix would be to swap only if you need it.
int i = rand() % size;
int j = rand() % size;
// to know which should be first
if (i > j)
std::swap(i, j);
if (arr[i] > arr[j])
std::swap(arr[i], arr[j]);
Your array probably will not be sorted immediately, so you could also test if it is sorted only every five steps (for example) instead of every step.
But i think the most important is, you should not expect good performances from such an algorithm.
In my c++ class, i'm supposed to use this " int mymaximum(int a[], int numberOfElements); " function to find the maximum number in an Array. The function should return the largest in this array.
This is the code I have so far without the function I need to use. Thanks in advance and sorry about the messy code, still learning.
#include <iostream>
using namespace std;
int main() {
int Array[] = {23,2,90,53,38};
int mymaximum = 0;
for(int i = 0; i < 5; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
cout << "The Max is: " << mymaximum << "\n";
return 0;
}
Just wrap around the logic to find maximum in a function. Like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = 0;
for(int i = 0; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Aso, in order to support negative numbers, modify your logic like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = a[0];
for(int i = 1; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Note that now I initialize maximum with the first entry in the array!
In main() call your method like this:
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
I'll show the overall structure without solving the homework for you:
#include <iostream>
using namespace std;
int mymaximum(int a[], int numberOfElements) {
int ret = 0;
// compute the maximum and store in `ret'
...
return ret;
}
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
In case you're wondering, sizeof(Array) / sizeof(Array[0]) computes the size of the array so that you don't have to hard-code it here.
Just move your logic into the desired function as follows:
int mymaximum(int Array[], int numberOfElements)
{
int mymaximum = 0;
for(int i = 0; i < numberOfelements; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
return mymaximum;
}
Put that above int main(), then inside main() replace the removed code with:
int mymaximum = ::mymaximum(Array, 5);
(The :: wouldn't be needed if either the local variable or the function had different names).
You should then apply the suggestion in sasha's comment to use [0] as the initial guess at a maximum.
Replace your for loop structure with this:
int max(0);
max = mymaximum(Array, 5);
In the function mymaximum use this code:
int max(a[0]);
for(auto i(1); i < numberOfElements; ++i)
if(a[i] > max)
max = a[i];
return max;