I'm trying to refresh myself in C++ before my college starts again and I ran into some problems. I'm using a bubblesort function given by my professor and I'm struggling to run it in my int main. The function parameters is bubblesort(int *a, int length), so I used bubblesort(a, sizeof(a)/sizeof(*a) ).
The compiler shows an error ' a ' is declared void. I tried searching up for an answer if I made a mistake but I couldn't catch my error. If you understand why I am getting this error can you please explain in detail what I'm missing or doing wrong.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void bubblesort(int *a, int length)
{
int i, temp, finished = 0;
while(!finished)
{
finished = 1;
for( i = 0; i< length-1; i++)
{
if(a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
finished = 0;
}
}
}
}
int main()
{
int a[] = {5,1,7,9,4,3};
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
cout << endl;
void bubblesort(a, sizeof(a)/sizeof(*a));
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
}
You don't need return type in function call.
Remove void from the line
void bubblesort(a, sizeof(a)/sizeof(*a));
and make it
bubblesort(a, sizeof(a)/sizeof(*a));
You can't specify the return type of a function when making a function call, so you need:
bubblesort(a, sizeof(a)/sizeof(*a)); // no void at the beginning
However, you have a fixed-size array, so the call could also simply be:
bubblesort(a, std::size(a));
Also, this loop:
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
can be rewritten like this:
for (int elem : a)
cout << elem;
Related
so I am having a little bit of trouble getting this program to work without it throwing the errors:
"request for member 'insertArray' in 'arr', which is of non-class type 'int [10]' " and
"request for member 'print' in 'arr', which is of non-class type 'int [10]' ".
Both of those errors have to do with using my functions with an array, you can see the code below:
#include <iostream>
using namespace std;
int size = 0;
int *arr;
void insertArray(int val)
{
int i = 0;
while (i < size && arr[i] < val)
i++;
for (int k = size - 1; k >= i; k--)
{
arr[k + 1] = arr[k];
}
arr[i] = val;
size++;
}
void print()
{
cout << "The array is: ";
for (int j = 0; j < size; j++)
{
cout << arr[j];
}
}
int main()
{
int arr[10];
cout << "Please enter 5 values: \n";
for (int i = 0; i < 5; i++)
{
int num = 0;
cin >> num;
arr.insertArray(num); // Error 1: vs code error squiggles say: "expression must have class type"
arr.print(); // Error 2: vs code error squiggles say: "expression must have class type"
}
return 0;
}
I don't know how to fix the errors or what they mean either.
Thanks for the help in advance folks!
arr is just a plain-old C array, you can't define new functions on it. You need to define a class or struct if you want to do that.
What you have here is procedural code, so you're constrained by that model and must pass in arr as an argument.
I've tried to wrangle your original code into this form with as few modifications as necessary:
#include <iostream>
void printArr(const int* arr, const size_t size)
{
std::cout << "The array is: ";
for (int j = 0; j < size; j++) {
std::cout << arr[j];
}
std::cout << std::endl;
}
int main()
{
const size_t count = 5;
int arr[count];
std::cout << "Please enter 5 values: \n";
for (int i = 0; i < 5; i++)
{
std::cin >> arr[i];
}
printArr(arr, count);
return 0;
}
The whole insertArray function was just too confusing so I deleted it presuming what you were trying to do was add things at the end of the array anyway.
I am getting sigabrt error as given below for the given heapsort program. I am new to programming so I apologize for silly mistakes.
error : Abort signal from abort(3) (SIGABRT)
The major parts of the code are as follows
heapify - a program to make a heap out of the given array
heapsort - a function which sorts the array according to a heap and saves the result in the array
main - the driver function
#include <iostream>
#include <math.h>
using namespace std;
void swapper (int first, int second) {
int temp;
temp = second;
second = first;
first = temp;
}
void heapify (int a[], int size) {
for(int i = 0; i < (size/2) ; i++) {
int left = 2*i;
int right = 2*i + 1;
if (a[i] < a[left]) {
swap(a[i], a[left]);
}
else if (a[i] < a[right]) {
swap(a[i],a[right]);
}
}
}
void heapsort(int a[], int size){
int treesize = size;
int i = size;
heapify(a,size);
while (treesize > 0) {
cout << " \t " << a[i];
swap(a[i],a[0]);
i --;
treesize--;
heapify(a, treesize);
}
cout <<"\n";
for(int i = 0; i < size; i++) {
cout <<"\t"<<a[i];
}
}
int main() {
// your code goes here
int a[] = {10,1,2,11,4,57,12,13,44,14,6,7,9,8,15,16,17,98};
int arrsize= sizeof(a)/(sizeof(a[0]));
int pos;
int ele = 7;
heapsort(a,arrsize);
for (int i = 0; i < arrsize; i++){
cout <<"\n "<<a[i];
cout<<"\n"<<arrsize;
}
return 0;
}
I'm not sure about the correctness of the rest of the program, but the reason why you're getting the exception is because you're accessing memory out of bounds. You call heapsort with the array size like this:
heapsort(a, arrsize);
And then you set treesize and i to that size:
int treesize = size;
int i = size;
And then in those lines:
cout << " \t " << a[i];
swap(a[i], a[0]);
i is still equal to arraysize. But it can at most be arraysize-1. This causes undefined behavior when you print a[i], and even worse, undefined behavior in the following line that modifies values outside of the array. On my machine, the former prints rubbish values and the latter causes stack corruption. Instead, you should set those values like this:
int treesize = size-1;
int i = size-1;
This fixes the print and the exception.
Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max
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.
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;