Unused variables & Primary-Expression expected before ']' - c++

I looked at the other answers, but it didn't really help since 1) I don't understand it (especially if it's not exactly my problem) and 2) I noticed that the way my class is learning how to program is vastly different from what I've seen online. For example, we are using std. So I'm sorry for the repetitive question.
Here are my compiler errors:
main.cc: In function ‘int sum_up(std::array)’:
main.cc:21:19: error: expected primary-expression before ‘]’ token
sum+=arr[i,size_t];
^
main.cc:18:9: warning: unused variable ‘size’ [-Wunused-variable]
size_t size = arr.size(); //A size_t is just an unsigned int on this system
^
main.cc: In function ‘int sum_up(std::vector<int>)’:
main.cc:28:9: warning: unused variable ‘size’ [-Wunused-variable]
size_t size = vec.size();
^
Here's my code:
It was actually pre-made by our teacher; our main focus was the functions and how to sum up C style and C++ style arrays/vectors. I did my code exactly like my friend's but for some reason mine won't compile.
Please and thank you for all the help.
#include <iostream>
#include <cstdlib>
#include <array>
#include <vector>
using namespace std;
const size_t ARR_SIZE = 5;
int sum_up(int arr[], size_t size) { //Function to sum up a C-style array
int sum = 0;
for (size_t i = 0; i < ARR_SIZE; i++)
sum += arr[i];
return sum; //Stub
}
int sum_up(array<int, ARR_SIZE> arr) {
size_t size = arr.size(); //A size_t is just an unsigned in
//on this system
int sum = 0;
for (size_t i = 0; i < ARR_SIZE; i++)
sum += arr[i, size_t];
return sum; //Stub
}
int sum_up(vector<int> vec) {
size_t size = vec.size();
int sum = 0;
for (size_t i = 0; i < ARR_SIZE; i++)
sum += vec[i];
return sum; //Stub
}
void die() {
cout << "Invalid input.\n";
exit(EXIT_FAILURE);
}
int main() {
int c_arr[ARR_SIZE] = {}; //Size ARR_SIZE, initialized to zero
array<int, ARR_SIZE> cpp_arr = {}; //Size ARR_SIZE, initialized to zero
vector<int> vec_arr(ARR_SIZE); //Size ARR_SIZE, initialized to zero
cout << "Welcome to the Arrayitizer 2000(tm). Today we will be doing arrays three different ways.\n";
cout << "Please enter " << ARR_SIZE << " integers.\n";
//Now let's read into three arrays
for (size_t i = 0; i < ARR_SIZE; i++) {
int x;
cin >> x;
if (!cin) die();
c_arr[i] = x;
cpp_arr[i] = x;
vec_arr.at(i) = x;
}
//Let's print them out
cout << "You entered (one column for each of the three arrays):\n";
for (size_t i = 0; i < ARR_SIZE; i++) {
cout << c_arr[i] << "\t" << cpp_arr[i] << "\t" << vec_arr.at(i) << endl;
}
cout << "Summming up the three arrays:\n";
//Now lets sum them up and verify they all return the same value
int sum_c = sum_up(c_arr, ARR_SIZE);
int sum_cpp = sum_up(cpp_arr);
int sum_vec = sum_up(vec_arr);
cout << "sum_c: " << sum_c << endl;
cout << "sum_cpp: " << sum_cpp << endl;
cout << "sum_vec: " << sum_vec << endl;
if (sum_c == sum_cpp and sum_c == sum_vec) {
cout << "Congrats, you added up all three arrays the same!\n";
} else {
cout << "Unfortunately, your code for summing up the three arrays returned different results.\n";
}
}

Presumably, the following is a typo:
arr[i,size_t]
// ^^^^^^^
The compiler actually pointed you to exactly this code, so you could have spotted this. Or, at least, compared this part of the code with your friend's version (which cannot be "exactly like" yours if it compiles).
The warnings are just that: warnings. And they're warning you about what they say they're warning you about: variables that you declare but never use. So why declare them?
Finally, I don't understand why you say you're not "using std" — assuming you are not referring to the using namespace statement (because you are using that), I can only presume you think you're not using the standard library. Yet, you are! All over the place, in fact! Vectors, C++11 arrays, streams…

The compiler pointed you to the obvious errors:
arr[i, size_t] should be arr[i].
The first function loops ARR_SIZE times instead of using the size argument.
The second function loops ARR_SIZE times instead of using the size variable.
The third function loops ARR_SIZE times also, instead of using size computed as vec.size().
All three functions might produce the correct sum, but only by coincidence.
Here is a corrected version:
int sum_up(int arr[], size_t size) { //Function to sum up a C-style array
int sum = 0;
for (size_t i = 0; i < size; i++)
sum += arr[i];
return sum;
}
int sum_up(array<int, ARR_SIZE> arr) {
int sum = 0;
for (size_t i = 0, size = arr.size(); i < size; i++)
sum += arr[i];
return sum;
}
int sum_up(vector<int> vec) {
int sum = 0;
for (size_t i = 0, size = vec.size(); i < size; i++)
sum += vec[i];
return sum;
}

Related

Issue using functions (c++)

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.

C6385 warning in VS (in regard to dynamic arrays)

My code is supposed to print the Union and Intersection of two sets of integers.
Why do I get this warning?
Is it because I use dynamic arrays and it's size could be anything in runtime?
How can I fix it? My code works fine but this warning really bugs me.
P.S: I know it would be a lot easier to use std::vector but my teacher required to use arrays.
#include <iostream>
using namespace std;
void UnionFunc(int[],int,int[],int,int[],int&);
void IntersectionFunc(int[], int, int[], int, int[], int&);
int main() {
int* A;
int SizeA;
int* B;
int SizeB;
int* Union;
int UnionSize=0;
int* Intersection;
int IntersectionSize=0;
cout << "Enter the Size of First Set : "; cin >> SizeA;
A = new int[SizeA];
cout << "Enter the Size of Second Set : "; cin >> SizeB;
B = new int[SizeB];
Intersection = new int[SizeA >= SizeB ? SizeB : SizeA];
Union = new int[SizeA + SizeB];
for (int i = 0; i < SizeA; i++) {
cout << "Set A[" << i + 1 << "] = ";
cin >> A[i];
}
for (int i = 0; i < SizeB; i++) {
cout << "Set B[" << i + 1 << "] = ";
cin >> B[i];
}
UnionFunc(A,SizeA,B,SizeB,Union,UnionSize);
IntersectionFunc(A, SizeA, B, SizeB, Intersection, IntersectionSize);
cout <<endl<< "Union Set : ";
for (int i = 0; i < UnionSize; i++) {
cout << Union[i] << ",";
}
cout <<endl <<"Intersection Set : ";
for (int i = 0; i < IntersectionSize; i++) {
cout << Intersection[i] << ",";
}
system("pause>n");
return 0;
}
void UnionFunc(int A[],int SizeA, int B[],int SizeB, int Union[],int &UnionSize) {
//Adding First Array to Union Array
for (int i = 0; i < SizeA;i++) {
Union[i] = A[i];
UnionSize++;
}
//Checking if second array's elemnts already exist in union arry, if not adding them
bool exist;
for (int i = 0; i < SizeB; i++) {
exist = false;
for (int j = 0; j < UnionSize; j++) {
if (B[i] == Union[j] ) {
exist = true;
}
}
if (exist == false) {
Union[UnionSize] = B[i];
UnionSize++;
}
}
}
void IntersectionFunc(int A[], int SizeA, int B[], int SizeB, int Intersection[], int& IntersectionSize) {
for (int i = 0; i < SizeA; i++) {
for (int j = 0; j < SizeB; j++) {
if (A[i] == B[j]) {
Intersection[IntersectionSize] = A[i];
IntersectionSize++;
}
}
}
}
Is it because I use dynamic arrays and it's size could be anything in
runtime?
Yes! The compiler doesn't know (and, as your code is written, can't know) that both SizeA and SizeB will be 'valid' numbers - so the size of the three int arrays you create could be less than is required for the Intersection[i] 'read' to be valid.
A 'quick and dirty' fix for this is to provide a visible guarantee to the compiler that the arrays you create will be at least a certain size, like this:
A = new int[max(1,SizeA)]; // Compiler can now 'see' a minimum size
And similarly for the other allocations you make with the new[] operator.
(I have tested this with VS2019, adding the max(1,SizeA) and max(1,SizeB) 'fixes' to just the allocations of A and B and the warning is removed.)

Repeating Array elements

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.

Function is not returning any value | C++

I'm writing a function that will find the number with max number of divisors but the function is not returning anything. Can someone point out my mistake?
This is the question
Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main
function). After that, pass that array to a function called “Find_Max_Divisors” using reference pointer.
The function “Find_Max_Divisors” should find (and return) in the array that number which has highest
number of divisors. In the end, the main function displays that number having highest number of divisors.
#include <iostream>
using namespace std;
int main ()
{
int arr[30];
int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i=0; i<30; i++)
{
cin >> arr[i];
}
cout << "Number with most divisors in array is " << endl;
int Find_Max_Divisors (*array);
}
int Find_Max_Divisors (int p[])
{
int count=0, max_divisor, max_counter, prev=0, repeat=0, divisor;
for (int i=2; i<=30; i++)
{
if (p[i]%i==0)
{
count++;
}
if (count > prev)
{
prev = count;
divisor = p[i];
}
if (count==max_counter && max_counter!=0)
{
cout << p[i] <<" has maximum of "<< count <<" divisors.\n";
}
max_counter = prev;
max_divisor = divisor;
repeat++;
}
return count;
}
change
int Find_Max_Divisors (*array);
to
int value = Find_Max_Divisors(arr);
You can get rid of the array variable altogether.
It's quite possible you'll find you need to put your function before main, too.
Firstly, you declare an array that has 30 elements
int arr[30];
But here you make the pointer point to the out of arr.
int* array = &arr[30];
I guess you want to make pointer point to arr, if i am not wrong, you can do as:
int *array = &arr[0]; // or int * array = arr;
Then when you call the Find_Max_Divisors function, you should change to:
int return_value = Find_Max_Divisors(array);
One more thing, int this function:
for (int i=2; i<=30; i++)
When i=30, p[i] go to out of bount again. It should be:
for (int i=2; i< 30; i++)
you don't need pointers to do that this simple code can fix your problem just change the size of your array as you want i am testing with array of size 4 here
#include <iostream>
using namespace std;
int Find_Max_Divisors(int p[])
{
int count = 0, max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 1; j < p[i] / 2; j++) {
if (p[i] % j == 0) {
count++;
}
}
if (count > max)
max = p[i];
}
return max;
}
int main()
{
int arr[30];
// int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i = 0; i < 4; i++) {
cin >> arr[i];
}
int value = Find_Max_Divisors(arr);
cout << "Number with most divisors in array is " << value << endl;
}
There are several mistakes in your code:
First, if your main function should know the funtions it calls, you should declare them previously. Just add a line Find_Max_Divisors (int p[]); Before the main function.
An array in C or C++ is a pointer, when you only call it by it's name. So call Find_Max_Divisors (arr) and get rid of that awful pointer-assignment.
In the last line just try to call the function, but never put it to stdout, you should change it to this:
cout << "Number with most divisors in array is " << Find_Max_Divisors(arr) << endl;
What you actually did with int Find_Max_Divisors (*array); was declaring a new variable and not calling a function.

How do i find the maximum number in an Array using a function

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;