I am learning cpp on my own through a book named Programming with Cpp by John R. Hubbard, Phd. The example below is from the same source.
#include <iostream>
using namespace std;
void read(int [], int&);
void print( int [], int);
long sum (int [], int);
const int MAXSIZE=100;
int main(){
int a[MAXSIZE]={0}, size;
read (a,size);
cout << "The array has " <<size <<" elements: ";
print (a,size);
}
void read(int a[], int& n){
cout <<"Enter integers. Terminate with 0: \n";
n=0;
do{
cout << "a ["<<n<<"]: ";
cin >> a[n];
}
while (a[n++] !=0 && n<MAXSIZE);
--n; //don't count the 0
}
void print (int a[], int n){
for (int i=0; i<n; i++)
cout <<a[i]<<" ";
cout<<endl;
}
Based on the above code, I need to know:
1) Why is the array[MAXSIZE] made equal to 0 in the main() function? Is it ok to use it without initializing it?
2) What is the role of n=0 in the read() function?
1) Why is the array[MAXSIZE] made equal to 0 in the main() function? Is it ok to use it without initializing it?
Only the first element is set to 0.The others are default initialized to 0. In this case is would be ok to use it without initializing it, that is, even without the ={0}, but only if valid integers are provided.
2) What is the role of n=0 in the read() function?
The variable n is used to index through the parameter array a. Since C++ uses zero based indexing the first element of an array is at position 0, and that's why n is set to 0 initially.
Related
This is my first C++ class and I'm not really sure how to proceed in my homework, as understanding arrays has been fairly difficult for me. I've successfully completed the 1st task, but got stuck understanding the 2nd and don't really know how to start it.
The tasks are:
Define a function named harmonicNum() that finds and returns the nth harmonic number using an iteration statement where n is a positive int-typed argument provided by the caller.
Given a valid array index i, define a function named fillHarmonic() that iteratively calls harmonicNum() to initialize the ith element of an array parameter wit the i+1th number of the harmonic series. I must define this function to work on a one-dimensional array of any size.
This is the code that I have so far:
#include <iostream>
#include <cmath>
using namespace std;
double harmonicNum(int n);
int n;
int main()
{
do
{
cout << "Please input a positive integer: " << endl;
cin >> n;
} while (n < 0);
cout << harmonicNum(n) << endl;
return 0;
}
double harmonicNum(n)
{
double harmonic = 0.00
for (int i = 1; i <= n; i++)
{
harmonic = harmonic + 1.00 / i;
}
return harmonic;
}
Something like this?
Method definition:
void fillHarmonic(double &i_elem, int i){
i_elem = harmonicNum(i+1);
}
Call without error checking:
double arr [5];
//TODO init values
for(int i = 0; i < (sizeof(arr)/sizeof(double)); i++ ){
fillHarmonic(arr[i], i);
}
The funcion HIGHEST is all good and accepts variable number of arguments. The problem is how do I do variable amount of input? (idk what terms should be use to describe it, but examples should clear things up...)
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
Duom.txt file if needed (i am now only working with 1st number 4 under it others will follow same/similar thing as 1st row they are not important now)
4
2008 5 2000.00 400.25
2010 5 4000.00 320.25
2009 9 3385.00 254.45
2008 6 1900.00 612.59
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdarg>
using namespace std;
//Variable number of arguments in C++
int highest (int num,...) {
va_list valist;
int max = 0;
int a;
va_start(valist, num);
for (int i = 0; i < num; i++) {
a = va_arg(valist, int);
if(max < a) max = a;
else ;
}
va_end(valist);
return max;
}
int main () {
int n, A[25], B[25];
double C[25], D[25];
ifstream fd ("Duom.txt");
ofstream fr ("Rez.txt");
fd >> n;
cout << n <<endl;
for(int i = 0; i < n; i++){
fd >> A[i] >> B[i] >> C[i] >> D[i];
}
cout << highest(n, ) <<endl;
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
return 0;
}
is there a specific reason you want the function Highest to get all array integers separately? Also - why did you choose to use an array instead of a vector?
Assuming that you want to use an array, I'd suggest to change the function's arguments as follows:
int highest (int num,int *arr);
where arr is the name of your array and in fact a pointer to the first integer of the array.
Then, inside the function, you can just access the array using subscript notation or dereferencing:
first_array_int=*(arr); //dereferencing example
second_array_int=*(arr+1); //dereferencing example
or
first_array_int=arr[0]; //subscript example
second_array_int=arr[1]; //subscript example
note that by doing that you can change the passed array within the function.
Again, I'd suggest to use a vector instead, then define the function:
int highest (int num,vector <int> *A);
if you want to pass a pointer, or:
int highest (int num,vector <int> A);
if you want to pass by value. Ofcourse, don't forget to include the vector library with
#include <vector>
I hope I understood your question well and that this is helpful.
Goodluck!
Guy
I'm learning pointers in but I'm stuck on dynamic allocation of arrays.
The code below provides a function to find the element with the lowest value.
A dynamically allocated array is passed as a parameter to it.
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n);
int main()
{
int *nums = new int[5];
int nums_size = sizeof(*nums);
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(*nums, nums_size);
delete [] nums;
return 0;
}
But it return this error:
error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
How can I pass that array to the function?
Just for curiosity: why the for loop allows me to enter 4 value if my array is made up of 5 elements?
How can I pass that array to the function?
nums is already a type int*, you don't need to dereference it:
findMin(nums, nums_size);
why the for loop allows me to enter 4 value if my array is made up of 5 elements?
int nums_size = sizeof(*nums); does not do what you think it does. It's equivalent to sizeof(nums[0]), which is equivalent to sizeof(int), which happens to be equal to 4 at your machine.
There is no way to extract size of array allocated on the heap, you need to save the size on your own:
int nums_size = 5;
int* nums = new int[nums_size];
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n){
int mn=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<mn){
mn=arr[i];
}
}
return mn;
};
int main()
{
int nums_size = 5;
int *nums = new int[nums_size];
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(nums, nums_size);
delete [] nums;
return 0;
}
The above code works fine. Your error was in passing the array to the function.
Also to add -
Your code made only 4 iterations coz sizeof(*nums) returned the size of base index element pointed by pointer, i.e ,sizeof(num[0]). So I made a minor change and now it works fine.
I am working on program that remove duplicates from an array I am using three functions here: one to take the input such as the size and the number, second function to remove duplicates and return the number without duplicates and the third function just a report show the size and the new number but I am having problem I don't know in what step I think in report or phillip erreur:
In function ‘int main()’: invalid conversion from ‘int*’ to ‘int’,initializing argument 1 of ‘void report(int, int)’
#include <iostream>
using namespace std;
const int size = 100;
void phillip(int[], int & );
/* Preconditions: Array of base type in declared and int varuable declared
postconditions: the array is filled with values supllied by the user at
the keybord. the user is assked how many values they want - this value is
given to the second argument.
*/
int remdubs(int[], int noel);
/* Preconditions: An array of basetype int that has noel values.
postconditions: The number of unique elemts in the array is returned. The function removes all dubplicates inside the array.
*/
void report(int s, int d);
int main()
{
int ruby[size];
int numele, numuniq;
phillip(ruby, numele);
numuniq = remdubs(ruby, numele);
report(ruby, numuniq);
return 0;
}
void phillip(int[], int& )
{
int s;
cout << "\nHow many values you want? ";
cin >> s;
cout << "\nPlease input 10 integers, hitting return after each one \n";
for (int i = 0; i < s; i++)
{
int num;
cin >> num;
}
}
int rembups(int sapphire[], int noel)
{
for (int i = 0; i < noel; i++)
{
for (int j = i + 1; j < noel; j++)
{
if (sapphire[i] == sapphire[j])
{
for (int k = j; k < noel; k++)
sapphire[k] = sapphire[k + 1];
noel--;
j--;
}
}
}
return noel;
}
void report(int s, int d)
{
cout << "\nYou entered " << s << "distinct numbers: " << d;
}
Can't explain it better than your error:
void report (int s, int d);
this function asks for two integer values, you're passing an array to it which, with decayed functionalities, will behave like an integer pointer
int ruby[size];
report (ruby, numuniq);
I'm unsure on the behavior of your program but you should rather do something like
report(ruby[0], numuniq);
that is: access the element of the array and feed it to the function
The error is in the function report, it asks for two integer and you are passing an array and an integer instead
and again i don't think you need 2 parameters in the function report one would solve your purpose
void report(int d)
{
cout << "\nYou entered <<d<<" distinct numbers";
}
that would solve your error but i don't think you would get your desired output
Few problems with the code:
Report function should be expecting an array of integers rather than single integer
Try using human readable variable or function names
remdubs was renamed to rempubs in function definition
phillip function definition didn't have params defined properly
You have const int size but do not use it
remdups has a bug somewhere. I will leave that out as I am trying to fix other issues here.
There are better ways of finding duplicates than remdups. Please look at some other solutions.
I have fixed your code and provided it here on ideone
#include <iostream>
using namespace std;
const int MAX = 1000;
int ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;
void accept(int ArrMix[MAX])
{
cout<<"Enter the number of elements in your array: ";
cin>>r;
for (int i = 0; i < r; i++)
{
cout<<"Enter value:";
cin>>ArrMix[i];
}
}
void process(int &i)
{
if(ArrMix[i] >= 0)
{
ptrArrPos[PosCounter] = &ArrMix[i];
PosCounter++;
}
else
{
ptrArrNeg[NegCounter] = &ArrMix[i];
NegCounter++;
}
}
void display(int &i)
{
cout<<"Your passed array is: " << endl;
cout<<ArrMix[i] << endl;
cout <<"Total number of positive integers is: "<<PosCounter<<endl;
cout<<"Your positive array is: "<<endl;
for (int i = 0; i < PosCounter; i++)
{
cout << *ptrArrPos[i] << endl;
}
cout<<endl;
cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
cout<<"Your negative array is: "<<endl;
for (int i = 0; i < NegCounter; i++)
{
cout << *ptrArrNeg[i] << endl;
}
}
int main ()
{
int *i;
int a = &i;
accept(&ArrMix[MAX]);
process(a);
display(a);
system("pause>0");
}
The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array.
I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?
The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.
Passing an array is as simple as passing any other argument:
accept(ArrMix);
You also have a problem here:
int *i;
int a = &i;
You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.
It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.