I have some global variables defined just above my main method. When I try to call the function "fib()" while using those variables, I get incorrect results.
When I move the variables into the local scope of the function, I get correct results.
Why does this happen? Here is the correct code:
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
int sum = 0;
int fib1 = 1;
int fib2 = 0;
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
The incorrect code has the three variables "sum", "fib1", and "fib2" above the main method. Why does this not work, but declaring the variables inside the function does?
Edit: below is the incorrect code. Note that the only difference is the placement of the variables.
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int sum = 0;
int fib1 = 1;
int fib2 = 0;
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
I understand the concept of scope. I thought that making those three variables global(outside main) would make no difference than if they were made local(inside fib() ).
You should try to make your question clearer. Nevertheless I will take a shot in the dark and try to respond to what I believe your question is. Think what happens if you move sum, fib1, and fib2 outside the function fib(), in other words you make them global. They will keep their value across function invocations (technically, they have static storage duration). Hence, when you invoke fib() the second time, sum will be equal to the previous value returned by fib(). However, when you put them inside the function, they are local to that scope, and at each function invocation they start "fresh" and are re-initialized (technically they have automatic storage duration).
Related
The formula is listed in the following article: https://en.wikipedia.org/wiki/Formula_for_primes. I am trying to implement it but to no success, for whatever reason the code is producing number which seem to be nth power of two + 1, which is obviously not what I want to achieve.
#include <iostream>
#include <cmath>
using namespace std;
int nth_prime(int n) {
double s = 1;
for (int i = 1; i <= pow(2, n); i++) {
double c = 0;
for (int j = 1; j <= i; j++) {
double f = (tgamma(j)+1)/j;
c+=floor(pow(cos(M_PI*f), 2));
}
s+=floor(pow(n/c, 1/n));
}
return s;
}
int main() {
int n;
while (cin >> n) {
cout << nth_prime(n) << endl;
}
return 0;
}
I'm writing a function that will find the number with max number of divisors but the function is not returning anything. Can someone point out my mistake?
This is the question
Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main
function). After that, pass that array to a function called “Find_Max_Divisors” using reference pointer.
The function “Find_Max_Divisors” should find (and return) in the array that number which has highest
number of divisors. In the end, the main function displays that number having highest number of divisors.
#include <iostream>
using namespace std;
int main ()
{
int arr[30];
int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i=0; i<30; i++)
{
cin >> arr[i];
}
cout << "Number with most divisors in array is " << endl;
int Find_Max_Divisors (*array);
}
int Find_Max_Divisors (int p[])
{
int count=0, max_divisor, max_counter, prev=0, repeat=0, divisor;
for (int i=2; i<=30; i++)
{
if (p[i]%i==0)
{
count++;
}
if (count > prev)
{
prev = count;
divisor = p[i];
}
if (count==max_counter && max_counter!=0)
{
cout << p[i] <<" has maximum of "<< count <<" divisors.\n";
}
max_counter = prev;
max_divisor = divisor;
repeat++;
}
return count;
}
change
int Find_Max_Divisors (*array);
to
int value = Find_Max_Divisors(arr);
You can get rid of the array variable altogether.
It's quite possible you'll find you need to put your function before main, too.
Firstly, you declare an array that has 30 elements
int arr[30];
But here you make the pointer point to the out of arr.
int* array = &arr[30];
I guess you want to make pointer point to arr, if i am not wrong, you can do as:
int *array = &arr[0]; // or int * array = arr;
Then when you call the Find_Max_Divisors function, you should change to:
int return_value = Find_Max_Divisors(array);
One more thing, int this function:
for (int i=2; i<=30; i++)
When i=30, p[i] go to out of bount again. It should be:
for (int i=2; i< 30; i++)
you don't need pointers to do that this simple code can fix your problem just change the size of your array as you want i am testing with array of size 4 here
#include <iostream>
using namespace std;
int Find_Max_Divisors(int p[])
{
int count = 0, max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 1; j < p[i] / 2; j++) {
if (p[i] % j == 0) {
count++;
}
}
if (count > max)
max = p[i];
}
return max;
}
int main()
{
int arr[30];
// int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i = 0; i < 4; i++) {
cin >> arr[i];
}
int value = Find_Max_Divisors(arr);
cout << "Number with most divisors in array is " << value << endl;
}
There are several mistakes in your code:
First, if your main function should know the funtions it calls, you should declare them previously. Just add a line Find_Max_Divisors (int p[]); Before the main function.
An array in C or C++ is a pointer, when you only call it by it's name. So call Find_Max_Divisors (arr) and get rid of that awful pointer-assignment.
In the last line just try to call the function, but never put it to stdout, you should change it to this:
cout << "Number with most divisors in array is " << Find_Max_Divisors(arr) << endl;
What you actually did with int Find_Max_Divisors (*array); was declaring a new variable and not calling a function.
Screenshot of my code
Hey, I have just started learning C++ and I am trying to get it to sum the series:
K+N−1∑n=K [-1^(n)/(n+1)2]
I have managed to get it to tell me the nth term previously, but now I would like to for each term in the series, starting with the kth and going in sequence to the last (k+n-1st), add this term to the running sum.
I need to use a function direct_up() which uses the function term(). I defined initially and test it in the main.
I know I am missing something and am a bit confused about how to use the functions and that I may have made a few mistakes. So I would be very grateful for some advice or help. I have attached a picture of what I have done so far, as well as typed it below.
using namespace std;
double term(int n) {
double y;
if(n%2==1) {
y = -1.0/((n+1.0)*(n+1.0));
} else {
y = 1.0/((n+1.0)*(n+1.0));
}
return y;
}
double direct_up(int k, int n) {
int startingnumber = k;
for (int i = startingnumber; i <= k+n; i++) {
cout << n << term(n) << endl;
}
return n;
}
int main() {
double n;
int k;
cout.precision(16);
cout << "enter number of terms";
cin >> n;
cout << "enter a value for k";
cin >> k;
cout << "here is the value" << direct_up(k,n);
return 0;
}
This is what you want to do:
double direct_up(int k, int n)
{
int startingnumber = k;
double sum = 0;
for (int i = startingnumber; i <= k+n; i++) {
sum += term(i);
}
return sum;
}
Here's how to do it without keeping your own running sum as you asked in your comment:
#include <vector>
#include <numeric>
double direct_up(int k, int n)
{
int startingnumber = k;
std::vector<double> terms;
for (int i = startingnumber; i <= k+n; i++) {
terms.push_back(term(i));
}
return accumulate(terms.begin(), terms.end(), 0.0);
}
Can someone please help me understand why this code isn't working properly? I know it's very close and I think that I'm just overlooking something. Any help is appreciated. Here is what I have so far:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
long int factorial(int num){
for(unsigned int i = 1; i <= num; i++) {
num *= i;
}
return num;
}
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}
You should move return num; outside the loop. As it is now, control always return after the first number is multiplied.
-- the correct code --
long int factorial(int num){
long int res = 1;
for(unsigned int i = 1; i <= num; i++) {
res *= i;
}
return res;
}
The body of the factorial function is not correct. You can use a recursive method to compute the factorial of a specific number. The corrected program of your version is below:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}
long int factorial(int num){
if (num == 1)
return num;
else
return num * factorial(num-1);
}
That's only part of the problem; it's a case in which proper indentation would make the bug apparent in an instant.
In addition to that, why are you using num inside the loop? You should leave it as-is and declare a new variable to compound and return the result.
long int factorial(unsigned int num) {
int x = 1;
for(unsigned int i = 1; i <= num; i++) {
x *= i;
}
return x;
}
Other things to note:
You shouldn't be using a #define; you should declare a const instead.
You're comparing an unsigned against a signed in the factorial() for loop.
I'm trying some exercise to learn the use of pointers with arrays and functions.
So I tried to code a "strange way" to find out primes within a certain range.
The problem is that the output always add the return value of the function with the algorithm for the primes. if I omit it, it shows is '32767', if I write return *pt, it adds the last number of the range, even if it's not a prime!
Just tried it with number 6: it's not a prime but it pops up!
#include <iostream>
int show_primes(const int * begin, const int * end);
int main()
{
using namespace std;
int i = 0;
int End_Array = 0;
cout << "Write the last number in your range (it always start from number 2)";
cin >> End_Array;
i=End_Array;
int cookies[i];
for(i=-1; i<End_Array; i++)
cookies[i] = i+1;
cout << show_primes(cookies, cookies + End_Array-1);
}
int show_primes (const int * begin, const int * end)
{
using namespace std;
const int * pt;
int z = 0;
for (pt = begin; pt < end; pt++, z=0)
{
for (int n=2; n<=*pt; n++)
if ( *pt%n == 0 )
++z;
if (z==1)
cout << *pt <<endl;
}
return *pt ;
}
Your loop is accessing a value at negative index.
cookies[i] = i+1; //For first iteration, value of i is -1
So for(i=-1; i<End_Array; i++) should be changed to for(i=0; i<End_Array; i++)
Also, you do not need to return from the function as you are printing the values within itself
Although you are using pointers for your learning, a more simpler implementation would be:
#include <iostream>
using namespace std;
void show_primes(int num)
{
bool flag = false;
for (int pt = 2; pt < num; pt++)
{
if ( num%pt == 0 )
{
flag = true;
break;
}
}
if(!flag)
{
cout<<num<<' ';
}
}
int main()
{
int End_Array = 0;
cout << "Write the last number in your range(>2)";
cin >> End_Array;
for(int i=2; i<End_Array; i++)
{
show_primes(i);
}
}
P.S.: Can someone please highlight that is it a bad practice to include std namespace in every functional block as OP has done.(I think it is)
for(i=0; i<End_Array; i++) // Start from zero
cookies[i] = i; //Use i
// Don't use cout
show_primes(cookies, cookies + End_Array-1);