arrays and functions

I was wondering if there is a way to use a function to define the contents of an array with a function. I am trying to do something with the Fibonacci sequence so I would like to define a[0] as 1 and a[1] as 1. Then I would add those two together and continue by adding a[i] to a[i-1] or something like that is there anyway you can do that this book isnt helping very much.
Yes, that's possible.

First of all, you need to give your function access to the array. In the case of a normal variable you would need pointers or return-values, but considering array's as being constant pointers you can simply pass the the array itself. Eg:
1
2
3
4
5
void giveValues(int array[],int size);
...
int myArray[5];
giveValues(myArray,5);
//at this point myArray has the values you gave array[] in giveValues() 


About the fibonacci sequence: you could use recursion, aldo there're other way's to do this. A recursion function is a function that calls (under some condition) itself. You will need someting to keep track wich element is given a value: you could use a static variable or a argument "count". A simple example of a recursion function:
1
2
3
4
5
6
7
void function Display (int limit, int count=0)
{
    cout<<count<<endl;
    if (count == limit)
        return;
    Display (limit,count+1)
}
Last edited on
Is there anyway that i can take a single input and split it into two if say they were separated by a space? like 3 5 would become 3 and 5?
Yes. You would need strings. You can store the input in a string using getline: http://www.cplusplus.com/forum/articles/6046/. Then you can use string.find() to search for spaces and string.substr() to seperate the string:
http://www.cplusplus.com/reference/string/string/find.html
http://www.cplusplus.com/reference/string/string/substr.html
After the string is seperated into substrings, you can use stringstream (see first link, where Zaita explains how get number from the user) to get the integervalues if you want.

I understand your first problem is solved?
ok so now im trying to import a file turn each line into an integer and then sort those integers into ranges like say if i have 132 135 140 145
ill have 2 in range 139 and 2 in range 145 and ideas?
i know i could do find and stuff but i was hoping i could sort an array into increments and output how much was in each
Last edited on
Topic archived. No new replies allowed.