Upon completion this program will output all prime numbers up to 1000, it is a fairly simple program and although I have read and re-read over the syntax many times at this point it is still not working
The code has been edited since the original post, it now runs with 0 errors, however it will not display the correct result, instead it displays 008D1389 over and over again.
this is the code in its entirety:
#include <iostream>
using namespace std;
//funtion prototypes
int output_number, number = 1, value = 1, i;
bool is_this_number_prime(int number_in_question);
bool does_it_have_factors(int numerator, int denominator);
int prime_number_sender();
int prime_number_output();
//function definitions
int prime_number_output()
{
int value;
value = prime_number_sender();
return value;
}
int prime_number_sender()
{
int value = number;
if (is_this_number_prime(number) == true)
return value;
else
return 0;
}
bool is_this_number_prime(int number_in_question)
{
bool answer = true;
int i;
for (i = 2; i <= number; i++)
{
if (does_it_have_factors(number, i) == true)
answer = false;
}
return answer;
}
bool does_it_have_factors(int numerator, int denominator)
{
bool result = false;
if (numerator % denominator == 0){
bool result = true;
}
return result;
}
int main() {
bool is_this_number_prime(int number_in_question);
bool does_it_have_factors(int numerator, int denominator);
int prime_number_sender(int number_in_question);
int prime_number_output();
int output_number = prime_number_output();
int i;
for (i = 2; i <= 1000; i++)
{
cout << prime_number_output << endl;
number++;
}
return 0;
}
If anyone can shed any light as to why the code is not working I will be extremely grateful. Thankyou.
Your code is generating quite a few errors for me.
main.cpp|48|error: too few arguments to function 'int prime_output(int)'|
You have prime_output declared as int prime_output(int value) but you promptly shadow the parameter value with a local variable value. You might as well drop the parameter, it's not doing you any good.
main.cpp|52|error: too few arguments to function 'int perfect_output(int)'|
Same issue as above. It looks like you're trying to modify the parameter directly, though, which is a no-no the way you're doing it. Try using a reference:
int perfect_output(int& value)
The function itself is weird as heck though. You don't output anything or do any calculations. I feel like you may not have finished writing that yet.
main.cpp||In function 'void user_selection()':|
main.cpp|59|error: a function-definition is not allowed here before '{' token|
This is probably where you're getting the error your question mentions. Your formatting makes it difficult to see this directly; fortunately Code::Blocks tells me where the problem is.
void user_selection()
{
You never close this. (More accurately, your closing brace is all the way at the end of the file, where it triggers another mismatch error.)
main.cpp|87|error: expected declaration before '}' token|
See above. This is the closing brace that somehow got detached from user_selection. Try to be more careful with your code formatting; the easier you can read it, the easier you can see things like this before the compiler does.
main.cpp|63|error: expected primary-expression before '<' token|
Your if statement is formatted oddly. Change = < to <= like this:
for (i = 2; i <= 1000; i++)//if numbers are 1 off, make i = 1.
Related
Context: Preparing for the Fall semester, I whipped up a quick code file to check if you can call a function as a parameter of another function. However, before I could compile the code and check - this error happened.
C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g
\wsl$\kali-linux\home\tyrael\Foundry\morga.cpp -o
\wsl$\kali-linux\home\tyrael\Foundry\morga.exe
'\wsl$\kali-linux\home\tyrael\Foundry'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
In file included from
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:39,
from \wsl$\kali-linux\home\tyrael\Foundry\morga.cpp:1:
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ostream:681:49:
error: expected unqualified-id before '-' token
__rvalue_ostream_type<_Ostream>>::type - operator<<(_Ostream&& __os, const _Tp& __x)
^
Build finished with error(s).
The terminal process failed to launch (exit code: -1).
Terminal will be reused by tasks, press any key to close it.
I had tried moving around the #include statement, didn't work.
I tried to isolate the cause of the error by commenting out huge swaths of the code, but the error still there.
My only guess as far as what the issue could be is that the compiler is very angy that I am trying to call a function as a parameter for another function, but I can't verify that.
I'm truly at a loss, I just don't know what it could be. Any help would be much appreciated!
This is the code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
// Forward declaration of my functions
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
// simple function that takes numbers and combines them into one total sum
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
// simple function that takes a number and multiples by 5
int main (int argc, char** argv) {
combiner();
int final = multiplier(combiner());
cout << "This is our final number: " << final;
return 0;
}
// putting it all together, using a function as a parameter for another function
I remembered that you can't pass a func as a parameter for another func in C, but you can in other langs. However, even when I get rid of that process - I still hit the error. Here's the new code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
int main (int argc, char** argv) {
int tiago = combiner();
int final = multiplier(tiago);
// Storing return value of combiner() into a int variable, using that var as
// parameter instead for 2nd function - multiplier
cout << "This is our final number: " << final;
return 0;
}
EDIT: In the vein of investigating my compiler, here are some screenshots to show what my compilation process looks like on VS Code.
Selecting the compiler type
Select the actual compiler, the one I want is g++
#include <iostream>
using namespace std;
int i = 0;
int binarySearch(int arr[],int left, int right, int item)
{
int midpoint;
bool found{false};
if(left < right && !found)
{
midpoint = left + (right - left)/2;
if(arr[midpoint]<item)
{
binarySearch(arr,midpoint+1,right,item);
}
else if(arr[midpoint]>item)
{
binarySearch(arr,left,midpoint-1,item);
}
else
{
found = true;
return midpoint;
}
}
}
int main()
{
int arr[] = {10,20,30,40};
int x = binarySearch(arr,0,3,40);
cout << x ;
}
How is it returning the correct value of the item searched for although its not even reaching the return statement.
It is reaching the base case when it is only one element in the array, but it should not reach the return statement, thus it should return garbage, but it is returning the correct index every time.
In most cases you don't return any value so you get whatever happens to be in the result register or stack slot at the time. This can work by accident, if you are unlucky.
Turn on compiler warnings and always fix them. Best to turn warnings into errors.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've tried to make sure my function prototype and definitions are good. The compiler doesn't show me any errors with those. And I've looked up in my textbook to make sure I'm writing my function call properly, but it still doesn't work. What am I missing? (VERY new to programming here. Please be kind.)
#include <iostream>
using namespace std;
bool noNegatives(int intArray[], int arraySize);
int main()
{
int mainArrSize = 5;
int mainArr[] = {7, 12, 4, 69, -2};
bool funcResult;
funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work
if (funcResult = true)
{
cout << "The array did not contain any negative"
<< " integers." << endl;
}
else
cout << "The array contained negative integers." << endl;
return 0;
}
bool noNegatives(int intArray[], int arraySize)
{
bool result = false;
int index;
for (index = 0; index < arraySize; index++)
{
cin >> intArray[index];
if (intArray[index] < 0)
return false;
}
return result;
}
Actually the compiler does warn about this line.
if (funcResult = true)
Perhaps you meant to compare
if (funcResult == true)
Always compile with at least -Wall, and take any warnings you see seriously. In fact, treat them like errors. You can even enforce this by compiling with -Werror.
1. Enable warnings and do not ignore them.
Here, the important part of the warning was "note: use '==' to turn this assignment into an equality comparison". (Note: this is the warning which Clang provides, other compilers will have different warning texts. All compilers will warn about this mistake.)
<source>:16:20: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (funcResult = true)
~~~~~~~~~~~^~~~~~
<source>:16:20: note: place parentheses around the assignment to silence this warning
if (funcResult = true)
^
( )
<source>:16:20: note: use '==' to turn this assignment into an equality comparison
if (funcResult = true)
^
==
1 warning generated.
2. Create and assign at the same time
This is your code:
bool funcResult;
funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work
if (funcResult = true)
I would declare and initialize the variable at the same time. I would write it like this:
bool funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work
if (funcResult = true)
Because if I do this, I can also make the variable const! And then, the little mistake would not compile, which would tell us about the problem earlier.
const bool funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work
if (funcResult = true) // Now this line won't compile anymore
3. Use C++ containers not C-style arrays
The (int intArray[], int arraySize) signature is dangerous (memory unsafe!) and can be replaced by either a std::vector<int> (if the size is not fixed at compile-time), or by std::array<int, 5> (if the size is known at compile-time).
Here's how your code would look like, after making this change:
#include <iostream>
#include <vector>
bool noNegatives(std::vector<int> const &intArray) {
bool result = false;
for (int index = 0; index < intArray.size(); index++) {
if (intArray[index] < 0)
return false;
}
return result;
}
int main() {
const std::vector<int> mainArr = {7, 12, 4, 69, -2};
const bool funcResult =
noNegatives(mainArr); // Here's the call that wont work
if (funcResult == true) {
std::cout << "The array did not contain any negative"
<< " integers.\n";
} else {
std::cout << "The array contained negative integers.\n";
}
return 0;
}
Minor changes there:
1. Do not use "using namespace std".
2. Moved the declaration and definition of noNegatives to the same place, just to make it a bit cleaner.
3. Do not use std::endl, prefer \n + std::flush. And in case the std::flush isn't needed, drop the flush.
4. If something is constant, just mark it as such. That's just a good habit. In this case, mainArr is constant.
4. Use modern C++ range-based for-loops
Instead of raw array access using indices, it is better to use a range-based loop. So we transform this code:
for (int index = 0; index < intArray.size(); index++) {
if (intArray[index] < 0)
return false;
}
into this:
for (int value: intArray) {
if (value < 0)
return false;
}
5. Optional: Use std::all_of
C++11 and later provides many great algorithms, so that you don't have to write your own. You are checking that a condition ("is Positive") holds for all elements in a container.
For this, std::all_of exists.
After including <algorithm>, we can make the noNegatives function be a single line:
bool noNegatives(std::vector<int> const &intArray) {
return std::all_of(array.begin(), array.end(), [](int x) { return x >= 0.; });
}
[](int x) { return x >= 0.; } is a lambda function and defines a function which takes an int x and then returns whether it is positive.
6. Optional: Get rid of iostreams
std::cout creates a lot of extra code when compiled. For fixed strings, you can use puts("Hello\n"); from #include <cstdio>. A more generic solution is to use fmt, but you'd have to install this on your system.
std::cout << "The array contained negative integers.\n"; becomes
puts("The array contained negative integers.\n");.
Final result:
https://godbolt.org/z/4FVyOw
#include <algorithm>
#include <array>
#include <vector>
#include <cstdio>
int main() {
const std::array<int, 5> mainArr {7, 12, 4, 69, -2};
const bool allPositive = std::all_of(mainArr.begin(), mainArr.end(), [](int x) { return x >= 0.; });
if (allPositive) {
puts("The array did not contain any negative integers.\n");
} else {
puts("The array contained negative integers.\n");
}
return 0;
}
Note, I replaced the vector<int> with std::array<int, 5> because then the compiler can optimize this to nothing. Here's the generated Assembly code:
main: # #main
push rax
mov edi, offset .L.str.1
call puts
xor eax, eax
pop rcx
ret
.L.str.1:
.asciz "The array contained negative integers.\n"
here is the codes In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number
#include <string>
std::string highAndLow(const std::string& numbers)
{
int big,small;
int a;
a = numbers.length();
big = numbers[0];
small = numbers[0];
for(int i=0;i<a; i++)
{
if(big<numbers[i+1])
big = numbers[i+1];
}
for(int i=0;i<a;i++)
{
if(small > numbers[i+1])
small = numbers[i+1];
}
std::cout<<big<<" "<<small;
}
Your function has a return type of std::string, so the compiler will require that you return one. In the case that you have some sort of branching (e.g. if-else statements), then it must also be the case that you return one by the end of each branch. If any of the above is violated, you will receive this error message. In this case, you can either change your function to be a void function (and then having no return is completely acceptable) or you can update it to return a std::string.
I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.