When I compile and run this program, I get different errors mostly regarding the calling of the function and the sum of arrays - I have tried fixing them myself but whenever I fix one problem I seem to never be able to fix them all as more come in then leave.
/*
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
#include <iostream>
#include <string>
using namespace std;
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total);
int main () {
int arraySize = 2;
int maxNumber = 4000000;
int currentPointer = 1;
int array[2] = {1, 2};
int total = 0;
bool stop = false;
while (not stop) {
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
}
}
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total) {
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
while (newValue < maxNumber) {
arraySize++;
int *array = new int[arraySize];
array[arraySize] = newValue;
if (newValue % 2 == 0) {
total += newValue;
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
}
stop = true;
return total;
}
};
Here are the errors that I am getting:-
error: no matching function for call to 'increaseArray'
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
^~~
note: candidate function not viable: no known conversion from 'int [2]' to 'int' for 1st argument
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total);
^
error: subscripted value is not an array, pointer, or vector
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
~^~~~~
error: subscripted value is not an array, pointer, or vector
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
~^~~~~
error: no matching function for call to 'increaseArray'
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
^~~
note: candidate function not viable: no known conversion from 'int ' to 'int' for 1st argument; dereference the argument with
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total) {
^
4 errors generated.
The problem is in the declaration of increaseArray function.
You want to pass as an argument a whole array, but you declare that the first argument is just an integer.
One solution to the problem would be:
int increaseArray(int * array,....).
I would strongly recommend to learn more about passing arrays to functions.
A good place to start would be: https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm
I hope that helps!
Related
what was i trying to do is a recursion of first 40 fibonacci numbers, when tried to launch a program, it's stopped at return 0;.
#include <stdio.h>
#define SIZE 40
void sum(int arr[], int n1, int n2, int offset);
int main(void)
{
int arr[SIZE] = { 0, 1 };
printf("%d\n", arr[0]);
printf("%d\n", arr[1]);
sum(arr, 0, 1, 2);
return 0;
}
void sum(int arr[], int n1, int n2, int offset)
{
if (offset > SIZE)
return;
arr[offset] = arr[n1] + arr[n2];
printf("%d\n", arr[offset]);
sum(arr, n1 + 1, n2 + 1, offset + 1);
}
Look at this check:
if (offset > SIZE)
return;
That means if offset is equal to SIZE, it passes.
arr[offset] with offset being equal to SIZE refers to the 41 nth element.
This array only have 40 element, hence the corruption.
If you run your program in a debugger, it should stop at the crash and you would be able to look at the value of offset that caused the crash.
A solution for this would be to change the check to if (offset >= SIZE).
I was asked to do sum of numbers in an array using recursion where sample input would be provided and the compiler gave me the following errors (note, I tried three ways and got the corresponding errors). Can someone please explain to me what I was doing wrong here?
Error for Code 1
In file included from Runner.cpp:2:0:
Solution.h: In function 'int sum(int*, int)':
Solution.h:7:32: error: invalid conversion from 'int' to 'int*' [-fpermissive]
totalsum = totalsum + sum(n+1,n-1);
^
Solution.h:1:5: note: initializing argument 1 of 'int sum(int*, int)'
int sum(int input[], int n) {
^
Error for code 2
Solution.h: In function 'int sum(int*, int)':
Solution.h:5:24: error: invalid conversion from 'int' to 'int*' [-fpermissive]
return input[0] + sum(n+1,n-1);
^
Solution.h:1:5: note: initializing argument 1 of 'int sum(int*, int)'
int sum(int input[], int n) {
^
Error for code 3
Runtime error
Code 1
int sum(int input[], int n) {
if (n<=0)
{
return 0;
};
int totalsum;
totalsum = totalsum + sum(n+1,n-1);
return totalsum;
}
Code 2
if (n<=0)
return 0;
return input[0] + sum(n+1,n-1);
Code 3
if (n <= 0)
return 0;
return (sum(input, n +1) + input[n - 1]);
In this function implementation
int sum(int input[], int n) {
if (n<=0)
{
return 0;
};
int totalsum;
totalsum = totalsum + `sum(n+1,n-1)`;
return totalsum;
}
the first parameter declared like int input[] has the type int *. However instead of the array you are passing the integer n + 1 as an argument in the recursive call
sum(n+1,n-1)
The same problem exists in this code snippet
if (n<=0)
return 0;
return input[0] + sum(n+1,n-1);
In the second code snippet it seems there is access memory beyond the array
return (sum(input, n +1) + input[n - 1]);
^^^^
And moreover the call has an infinite recursion because the second argument is always increased: n + 1.
The function can be written like
long long int sum( const int a[], size_t n )
{
return n == 0 ? 0 : a[0] + sum( a + 1, n - 1 );
}
Another approach is the following
long long int sum( const int a[], size_t n )
{
return n == 0 ? 0 :
( n == 1 : a[0] ? sum( a, n / 2 ) + sum( a + n / 2, n - n / 2 ) );
}
Here is a demonstrative program
#include <iostream>
long long int sum( const int a[], size_t n )
{
return n == 0 ? 0
: ( n == 1 ? a[0] : sum( a, n / 2 ) + sum( a + n / 2, n - n / 2 ) );
}
int main()
{
int a[] = { 1, 2,3, 4,5, 6, 7, 8, 9, 10 };
const size_t N = sizeof( a ) / sizeof( *a );
std::cout << sum( a, N ) << '\n';
return 0;
}
Its output is
55
For error for code 1, you are using an integer variable where it is expecting an array. To correct this, you would need to make n an index of some array. so the call would be something like sum(index[n+1], n-1) . Reason being is that arrays are pointers, pointers are arrays. so unless you have a pointer to an int variable, it will not work.
I am trying to read through file that contains series of words and sentences.
Then, needs to Store the unique words and maintain a count of each different word.The words should be ordered by decreasing count and, if there are multiple
words with the same count, alphabetically. (This ordering may be achieved as
the words are read in, partially as the words are read or at the end of all input processing.)In the end, I want to Output the first and last ten words in the sorted list, along with their counts.
How to fix this const char* error. I dont know what is wrong in my code or where and what exactly do I have to change:
[Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
[Error] no match for 'operator<=' (operand types are 'WordType' and 'WordType')
struct WordType
{
int word;
int len, count;
};
const int MaxWords=50000;
char Words[MaxWords*10];
WordType Counters[MaxWords];
int NumWords=0;
bool Compare(WordType &A, WordType &B){
if(A.count<B.count)return true;
if(A.count>B.count)return false;
char w1[50],w2[50];
strncpy(w1,Words[A.word],A.len); //Error comes here
w1[A.len]='\0';
w2[B.len]='\0';
strncpy(w2,Words[A.word],B.len); //Error comes here
return strcmp(w1,w2) < 0 ;
}
int partition (int low, int high)
{
WordType pivot = Counters[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (Compare(Counters[j] <= pivot)) //Error comes here
{
i++;
swap(&Words[i], &Words[j]);
}
}
swap(&Words[i + 1], &Words[high]);
return (i + 1);
}
void quickSort(int low, int high)
{
if (low < high)
{
int pi = partition(low, high);
quickSort(low, pi - 1);
quickSort(pi + 1, high);
}
}
(Whatever your intention with the code, I just looked at the 3 bugs)
This compare function solves the 1st & 2nd compile errors:
#include <string>
bool Compare(WordType &A, WordType &B)
{
if (A.count < B.count)
return true;
if (A.count > B.count)
return false;
std::string w1{ Words[A.word] }, w2{ Words[B.word] }; // Fix
return (strcmp(w1.c_str(), w2.c_str()) < 0);
}
The compare function gets 2 parameters, so I guess you actually want to call it like:
if (Compare(Counters[j], pivot)) // Fix
-
Beside that, I prefer to use std:array & to initialize variables:
#include <array>
struct WordType
{
int word = 0;
int len = 0, count = 0;
};
constexpr int MaxWords = 50000;
std::array<char, MaxWords * 10> Words;
std::array<WordType, MaxWords> Counters;
int NumWords = 0;
// & to call in main():
Words.fill('\0');
if (Compare(Counters[j] , pivot))
strncpy(w2,(const char *)Words[A.word],B.len);
strncpy(w2,(const char *)Words[A.word],B.len);
This is how your error line should look like
So I a little new to C++ and discovery what I can and can't do in comparison to python. Basically I have a function and inside that function I want to parse through an array and some integers run it, and return the output number. But it seems to prove a little tricky. Wondering where I am messing up.
Since the function it contains in is dominated by recursion I can't just make it a global variable where the array values are static.
So here is an outline of the code
void sequenceAlignment(int iStart,int jStart,int kStart, int seqLen1Size, int seqLen2Size, int seqLen3Size) {
int lengthi = seqLen1Size - iStart;
int lengthj = seqLen2Size - jStart;
int lengthk = seqLen3Size - kStart;
/* Sets it as a floor */
int midpoint = (seqLen1Size + iStart) / 2;
/*End the recursion*/
if (lengthi <= 1)
return;
/*We set two scoring arrays and intialize the XY Plane in the 3D */
int forwardScore[2][lengthj + 1][lengthk + 1];
int backwardsScore[2][lengthj + 1][lengthk + 1];
/* Some code */ and then to this
forwardSubscoringCalculation(multidimensionalarray, int, int, int, int, int, int)
The Function that is being called
void forwardSubscoringCalculation(int forwardScore, int scorei, int scorej, int scorek, int scoredArrayi, int scoredArrayj, int scoredArrayk) {
int tempValueHolder = 0;
int subscore[3] = {-10000, -10000, -10000};
subscore[0] = forwardScore[scorei][scorej][scorek] + scoredArray[scoredArrayi][scoredArrayj][scoredArrayk];
}
I am wondering how can I exactly do this. I thought by setting up the array it also acts like a pointer and be passed through but I might screwing that up. Is it possible in this code or can it be quite tricky?
EDIT Minimal Code
void score(int, int, int, int, int, int, int);
void function(int, int ,int, int, int, int)
void function(int i, int j, int k, int l, int m, int n) {
int forward[Number][Number][Number];
for (x = 0; x >= l; x++){
score(forward, i + x, j, k l, m n)
}
}
void score(int array, value1, value2, value3, value4, value 5, value6){
/* Do some stuff with the array */
}
My code is following:
/counting number of digits in an integer
#include <iostream>
using namespace std;
int countNum(int n,int d){
if(n==0)
return d;
else
return (n/10,d++);
}
int main(){
int n;
int d;
cout<<"Enter number"<<endl;
cin>>n;
int x=countNum();
cout<<x;
return 0;
}
i cannot figure out the error,it says that
: too few arguments to function `int countNum(int, int)'
what is issue?
Because you declared the function to take two arguments:
int countNum(int n,int d){
and you are passing none in:
int x = countNum();
You probably meant to call it like this, instead:
int x = countNum(n, d);
Also this:
return (n/10,d++);
should probably be this:
return countNum(n/10,d++);
Also you are not initializing your n and d variables:
int n;
int d;
Finally you don't need the d argument at all. Here's a better version:
int countNum(int n){
return (n >= 10)
? 1 + countNum(n/10)
: 1;
}
and here's the working example.
int x=countNum(); the caller function should pass actual arguments to calling function. You have defined function countNum(int, int) which means it will receive two ints as arguments from the calling function, so the caller should pass them which are missing in your case. Thats the reason of error too few arguments.
Your code here:
int x=countNum();
countNum needs to be called with two integers. eg
int x=countNum(n, d);
Because you haven't passed parameters to the countNum function. Use it like int x=countNum(n,d);
Assuming this is not for an assignment, there are better ways to do this (just a couple of examples):
Convert to string
unsigned int count_digits(unsigned int n)
{
std::string sValue = std::to_string(n);
return sValue.length();
}
Loop
unsigned int count_digits(unsigned int n)
{
unsigned int cnt = 1;
if (n > 0)
{
for (n = n/10; n > 0; n /= 10, ++cnt);
}
return cnt;
}
Tail End Recursion
unsigned int count_digits(unsigned int n, unsigned int cnt = 1)
{
if (n < 10)
return cnt;
else
return count_digits(n / 10, cnt + 1);
}
Note: With tail-end recursion optimizations turned on, your compiler will transform this into a loop for you - preventing the unnecessary flooding of the call stack.
Change it to:
int x=countNum(n,0);
You don't need to pass d in, you can just pass 0 as the seed.
Also change countNum to this:
int countNum(int n,int d){
if(n==0)
return d;
else
return coutNum(n/10,d+1); // NOTE: This is the recursive bit!
}
#include <iostream>
using namespace std;
int countNum(int n,int d){
if(n<10)
return d;
else
return countNum(n/10, d+1);
}
int main(){
int n;
cout<<"Enter number"<<endl;
cin>>n;
int x=countNum(n, 1);
cout<<x;
return 0;
}
Your function is written incorrectly. For example it is not clear why it has two parameters or where it calls recursively itself.
I would write it the following way
int countNum( int n )
{
return 1 + ( ( n /= 10 ) ? countNum( n ) : 0 );
}
Or even it would be better to define it as
constexpr int countNum( int n )
{
return 1 + ( ( n / 10 ) ? countNum( n/10 ) : 0 );
}