Why can't I get the function to print vector[count]? - c++

//
// main.cpp
// Array
//
// Created by Rusty on 9/21/17.
// Copyright © 2017 Rusty. All rights reserved.
//
Larger Than n
In a program, write a function that accepts three arguments: an array, the
size of the array, and a number n . Assume that the array contains integers. The
function should display all of the numbers in the array that are greater than the number n .
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// prototype
void arrayFunct(int[], int, int);
int main()
{
const int SIZE_OF_ARRAY = 8;
int array[SIZE_OF_ARRAY] = {1,2,3,4,5}; // Unused variable 'array'
int number_n = 2; // Unused variable 'number_n'
cout << "x" << endl; // test print 'x'
int x = 7;
cout << x << endl; // test print variable
void arrayFunct (int array[], int SIZE_OF_ARRAY, int number_n);
return 0;
}
void arrayFunct(int vector[], int sz, int n)
{
cout << sz;
for(int count = 0; count < sz; count++)
{
if (vector[count] > n) // ex: if vector[0] > 2, print
{
cout << vector[count] << endl;
}
}
}

It's have something wrong while u call a function
change this in main
void arrayFunct (int array[], int SIZE_OF_ARRAY, int number_n);
into
arrayFunct(array, SIZE_OF_ARRAY, number_n);
They don't need to assign type for it.

Related

Can we pass an array to any function in C++?

I have passed an array of size 10 to a funtion to sort the array reversely, but it's going wrong after rightly sorting first five elements of the array.
I want to sort the array 'std' reversely here,
# include <iostream>
using namespace std;
int reverse(int a[]); //funtion prototype
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
}
int reverse(int a[]) //funtion defination
{
int index = 0;
for (int i = 9; i >= 0; i--)
{
a[index] = a[i]; //swaping values of the array
cout << a[index] << " ";
index++;
}
}
There's basically three things wrong with your code.
You aren't swapping anything
You have to swap the first half of the array with the second half, not swap the whole array. If you do that then everything gets swapped twice, so that nothing changes
You should print the reversed array after you have finished the reverse, not while you are doing the reverse.
Here's some code that fixes all these problems
# include <iostream>
# include <utility>
void reverse(int a[]);
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
// print the array after reversing it
for (int i = 0; i < 10; ++i)
std::cout << std[i] << ' ';
std::cout << '\n';
}
void reverse(int a[])
{
for (int i = 0; i < 5; ++i) // swap the first half of the array with the second half
{
std::swap(a[i], a[9 - i]); // real swap
}
}
Yes you can.
I usually don't use "C" style arrays anymore (they can still be useful, but the don't behave like objects). When passing "C" style arrays to functions you kind of always have to manuall pass the size of the array as well (or make assumptions). Those can lead to bugs. (not to mention pointer decay)
Here is an example :
#include <array>
#include <iostream>
// using namespace std; NO unlearn trhis
template<std::size_t N>
void reverse(std::array<int, N>& values)
{
int index = 0;
// you only should run until the middle of the array (size/2)
// or you start swapping back values.
for (int i = values.size() / 2; i >= 0; i--, index++)
{
// for swapping objects/values C++ has std::swap
// using functions like this shows WHAT you are doing by giving it a name
std::swap(values[index], values[i]);
}
}
int main()
{
std::array<int,10> values{ 0,1,2,3,4,5,6,7,8,9 };
reverse(values);
for (const int value : values)
{
std::cout << value << " ";
}
return 0;
}

Modify a variable passed by reference

I'm working on a function that finds the smallest element in an array. I'm trying to modify the variable s using pass by reference. I'm brand new to C++ and I'm not sure if I have done pass-by-reference correctly. Can anyone confirm that this is the correct way to do this, or suggest better ways to approach a min value function with pass by reference?
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
using namespace std;
int smallestElm(int numArray[], int length, int &smallest);
int main() {
int n[3] = {2,5,3};
int s = 0;
int length = 0;
cout << smallestElm(n, length, s) << endl;
}
int smallestElm(int numArray[], int length, int &smallest) {
smallest = numArray[0];
length = sizeof (numArray) / sizeof (int);
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
return 0;
}
}
Yes this is correct, as you should be able to tell by yourself, by modifying your main function like this:
int main() {
int s = 0;
// call your function
cout << s << endl; // Here you print 's', thus you confirm whether you are right or not
}
If s wouldn't change its value, then your pass by reference won't be correct (since s does change its value inside the body of the function).
As for the function, it's wrong, since it will return before checking all the elements! So, change that to something like this to check all the elements of the array before saying for certain which the smallest element is:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int &smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int &smallest) {
smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
}
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
2
2
smallest element = 2
Don't forget that STL provides min_element, that you could use like this:
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int n[] = {2,5,3};
int *s = std::min_element(n, n + 3); // 3 size of the array
cout << "smallest element = " << *s << endl;
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
smallest element = 2
Can anyone confirm that this is the correct way to do this
Yes, that is the correct way to declare a reference argument. And yes, you can modify objects through a reference.
or suggest better ways to approach a min value function ...
A better way would arguably be to return the min value, instead of modifying an argument. Right now the function always returns 0, which seems useless.
... with pass by reference
That's a silly idea, but your approach is correct way to pass by reference. The function itself has multiple bugs.
It seems to always return after the first iteration, so it'll always find one of the first 2 element to be "smallest".
The value of int length argument is never used. It is overridden before use.
sizeof (numArray) returns the size of the pointer numArray which is not in any way related to the size of the pointed array.
The function always uses numArray[0] so it will have undefined behaviour if length == 0.
It's correct your code, but there is another way: Using a pointer to int, into the function argument and invoke this with the address of memory of variable s, as the below sample shows:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int *smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, &s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int *smallest) {
*smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < *smallest) {
*smallest = numArray[i];
}
cout << *smallest << endl;
}
}

Caling function that uses array as parameter

I'm having some difficulty with my syntax. The purpose of the below program is to print an array of 20 random numbers, find the max of the array and then print the array and the max. I've got the sections to initialize and create the array without any problem, but my issue is with the find_max function. In the main function, I'm trying to work out the syntax to call my find_max function there so I can print the results. If anyone can help to fix my syntax, I'd really appreciate it.
#include <cstdlib>
#include <iostream>
using
namespace std;
void
init_array(int array[], int size, int range)
{
for (int index = 0; index < size; index++)
array[index] = rand() % range;
}
void print_array(int array[], int size)
{
for (int index = 0; index < size; index++)
cout << array[index] << " ";
cout << endl;
}
int find_max (int array[], int size)
{
int max = array[0];
for (int index = 0; index < size; index++)
{
if (array[index] > max)
max = array[index];
}
return max;
}
int main()
{
// Declare array of integers
const int size = 20;
int array[size] = {0};
int max = find_max(array,size);
// Initialize and print array
init_array(array, size, 100);
print_array(array, size);
cout << "The max is:" << max << endl;
return 0 ;
}
Your call of find_max needs to use your declared variables and that after you call init_array. Otherwise your array is empty.
The call to find_max should look like this:
int max = find_max(data, DATA_SIZE);
You try to find max before the array is initialized. That is not what you want. The following works:
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
print_array(data, DATA_SIZE);
// Find maximum value
int max = find_max(data, DATA_SIZE);
cout << "max = " << max << endl;
return 0;
Well, when declaring the array this way:
int data[DATA_SIZE] = {0};
so all 20 elements in it equals zero.
your main function should look like this:
int main()
{
// Declare array of integers
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
cout<< find_max(data, DATA_SIZE)<< endl;
print_array(data, DATA_SIZE);
return 0 ;
}
you give the 20 elements random values first by calling init_array and then you try finding the Max of them.
You can give your function the start address of your array and the size of array, then you can use pointers to traverse the array. :)

c++ twodimensional array passed to function

I like to pass a two dimensional array to a function to print it.
Here is my code so far. As you can see on the comment it does not compile, because of an incompatible type.
QUESTION
How can I pass the two dimensional array to printIt ?
If I adjust it to printIt(int a(*)[50][50]) I get the another error during compilation, because returning array is not allowed
using namespace std;
void printIt(int a[50][50]);
int main(int args, char *argv[])
{
int a[50][50];
int j = 0;
for (int i = 1; i < 6; i++)
{
a[i][j] = i;
// the same should be printed out inside printIt
cout << " " << a[i][j];
// not compiling
// argument of type int is incompatible with int(*)[50]
printIt(a[i][j]);
}
}
void printIt( int a[50][50] )
{
cout << " " << a[50][50];
}
Given
int a[50][50];
a[i][j] evaluates to an int.
a[i] evaluates to int [50], an array of 50 integers. If used as an argument to a function call, a[i] decays to a int* in most cases. In rare cases it converts to int (&)[50].
If used as an argument to a function call, a decays to int (*)[50] in most cases. In rare cases it converts to int (&)[50][50].
In your case, the function declaration
void printIt(int a[50][50]);
is equivalent to
void printIt(int a[][50]);
and
void printIt(int (*a)[50]);
Hence, using
printIt(a);
is the right method of calling the function.
However
Given the way you are using the argument in printIt, you probably meant to use:
void printIt(int num)
{
cout << " " << num;
}
After that, it OK to use:
printIt(a[i][j]);
in main.
Because a[i][j] in an integer, it is a value. You are passing a value not an double array Your code should look like that :
#include <iostream>
using namespace std;
void printIt(int a)
{
cout << " " << a;
}
int main(int args, char *argv[])
{
int a[50][50];
int j = 0;
for (int i = 1; i < 6; i++)
{
a[i][j] = i;
// the same should be printed out inside printIt
cout << " " << a[i][j];
// not compiling
// argument of type int is incompatible with int(*)[50]
printIt(a[i][j]);
}
}

Hi, Just Want to Know What This Error Means

"error C2660: 'storeInitialValues' : function does not take 1 arguments" shows up in the log of my code when I try to build. I've looked at some past errors posted here and I think it might be some kind of initialization error with either/all the usersize, v, dsize, and/or asize. I just want to see the error on the specific calling of storeInitialValues(usersize, v, dsize, asize); that's it. Thank you very much in advance.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
struct vec
{
};
struct arr
{
};
void fillArray(int A[], int size);
void storeInitialValues(int * & arr, int & asize, int & dsize, vector<int>& v, int & usersize);
int main()
{
int usersize, dsize, asize;
vector <int> v;
int * ptr = new int[10];
cout << "How many values in data structures? Please enter values greater than 20." << endl;
cin >> usersize;
while (usersize < 21)
{
cout << "Error, enter values greater than 20!" << endl;
cin >> usersize;
}
cout << "Alright, here are your numbers: " << endl;
storeInitialValues(usersize, v, dsize, asize);
}
// fillArray stores sequential, unique, integer values into an array and
// then randomizes their order
void fillArray(int A[], int size)
{
srand((int)time(0));
for (int i = 0; i < size; i++)
{
A[i] = i + 1;
}
for (int k = size - 1; k>1; k--)
{
swap(A[k], A[rand() % k]);
}
}
// storeInitialValues calls fillArray to produce an array of unique randomly
// organized values and then inserts those values into a dynamically sized
// array and a vector.
void storeInitialValues(int * & arr, int & asize, int & dsize, vector<int>& v, int usersize)
{
int * temp = new int[usersize]; // temporary array for randomized data
fillArray(temp, usersize); // get data
for (int i = 0; i < usersize; i++) // copy data into the dynamic data structures
{
add(arr, asize, dsize, temp[i]);
v.push_back(temp[i]);
}
delete[] temp; // clean up temporary pointer
temp = NULL;
}
void add(int & usersize, int & arr, int & dsize, int & temp[i])
{
}
void remove()
{
}
Nothing about your call to storeInitialValues matches the declaration. I think you might be confused thinking the names of the variables are important. That's not the case. You have to pass variables that match the type of the variables in the function declaration in the correct order, the name are irrelevant.
int * & arr is a very strange declaration. int *arr would be a pointer to an int that you could treat as an array. What exactly are you aiming for with int * &? Mixing * and & requires that you be very careful with your usage. But you are also using vector, which is a very safe way of dealing with arrays. Why not just use vectors? You also declare and allocate ptr in the main function but you don't use it nor do you delete it.