while loop condition for fibonacci output - c++

I'm trying to figure out how I can set a conditional statement in the while loop that will take the users input of a desired fibonacci number and calculate the corresponding fib number. User inputs 8 and program outputs 34. Any hint that can point me in the right direction or help me see the problem from a different angle would be appreciated.
#include <iostream>
using namespace std;
int main ()
{
bool exit;
int fib;
int fib1 = 1;
int fib2 = 2;
int fib3 = 0;
cout << "The first Fibonacci number is 1" << endl;
cout << "The second Fibonacci number is 2" << endl;
cout << "what other Fibonacci number would you like? Enter -888 to exit: ";
cin >> fib;
while(fib ) //condition that makes sure output is the fibonacci the user is looking for
{
fib3 = (fib1+fib2);
fib1 = fib2;
fib2 = fib3;
cout << "...and the Fibonnaci is..... " << fib << endl;
}
if(fib == -888)
{
exit = true;
}
return 0;
}

Two possible answers.
One is to calculate the Fibonacci number using the closed form solution, which is \frac{(\frac{1 + \sqrt{5}}{2})^n - (\frac{1 - \sqrt{5}}{2})^n}{\sqrt{5}}.
Another is to use a loop structure, which is how you are doing it. I do not want to answer the question for you, but you need a counter variable in your loop structure. Start it at 1 and count up until you reach the desired iteration of the fibonacci number.
Something like
i = 1;
while(i < n)
{
i++;
//code
}

Related

c++ numbering the inputs for simple program

so im new to c++ and im doing a program that takes user inputs for any amount number say 5 so i will get 5 inputs from user and calculate the sum of it ,i did make the program but what i want for the output is say
"Enter Input 1:xx
"Enter Input 2:xx
so on and on as the user input say 5 so it goes on for 5 times however my program takes the user input and i enter it, it dosnt say enter input 1 ,so i want to show the enter input 1 enter 2 part hope someone can help me with this sorry for my poor explanation
#include<iostream>
using namespace std;
int main() {
while (true) {
// prompts the user to ask how many inputs they want
int x;
cout << "Enter input : ";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1)
break;
// get the input from above and calculate the total of the input
int sum = 0;
for (int i = 0; i < x; i++) {
int value;
cin >> value;
sum += value;
}
// Output the total
cout << "Output total: " << sum << endl;
}
system("pause");
return 0;
}
Okay to start out, there are times when to use break and there are times not to. This scenario is not meant for them. Although, I used one in my code I did it because I am rushing. I would recommend to take the code snippet, learn from it, and see how to optimize it :)
Also, just for future purposes its important to understand your task at hand and be able to communicate it well so others can help debug and answer your question.
Heres what I think your question is:
"I want to make a program in cpp that allows the user to first submit how many numbers they would like to input. From there I would then ask them for the indicated number of inputs. After gathering all inputs I will then add those numbers together and output the sum. If at any point they decide to type in -1, I will stop asking for inputs and give their sum on the spot."
#include<iostream>
using namespace std;
int main() {
bool runProgram = true;
cout << "Hi welcome to my sum calculator program!\n";
cout << "This program will prompt you for a number of inputs and then calculate the total of them.\n";
cout << "If you no longer want to be prompted for numbers at any time type in -1!\n";
cout << "Press enter to begin!\n";
cin.get();
while (runProgram) {
// prompts the user to ask how many inputs they want
int x;
cout << "How many inputs?\n";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1){
runProgram = false;
}else{
// get the input from above and calculate the total of the input
int sum = 0;
int val = 0;
for (int i = 0; i < x; i++) {
cout<< "Input #" << i+1;
cin >> val;
if(val == -1){
runProgram = false;
break;
}
sum += val;
}
// Output the total
cout << "Your Output total is " << sum << endl;
}
}
system("pause");
return 0;
}

Simple while loop not terminating (beginner)

Here's what I want my program to do. Prompt the user to input 10 integers. Then my program adds up the even integers, adds up the odd integers, then displays both sums. Simple beginner's exercise. To do this, I'm using a while loop with a control variable. Here is the entirety of my code:
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << endl;
cin >> num;
while (control <= 10)
{
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
cin >> num;
}
cout << "The sum of the even integers is " << evenSum << endl;
cout << "The sum of the odd integers is " << oddSum << endl;
return 0;
}
To test this code, I'm using as input the first 10 positive integers, 1-10. However, I'm having a couple headaches. First, control never passes from the while loop, i.e. the program never gets to the point where it displays the evenSum and outSum variable values. I'm having a hell of a time figuring out why the while loop never terminates. As I've written it, the while condition will become false as soon as control = 11, and the control variable is incremented at the end of the while body, so it should not keep going. Yet it does.
My second headache (probably related) is that the sum of the even numbers in my input should be 30, and the sum of the odd numbers should be 25. However, while my program gets the oddSum correct, it only sums the evens up to 20, so it is not counting the last number (10) for some reason.
I have walked through this program carefully several times on paper. Also, I've had it display the variable values as it goes, so I can track what it is doing with each while loop. Eventually, it just stops displaying output, but without ever actually terminating. And it sums the evens and odds correctly, just without adding that last number.
It seems to me there is at least one off-by-one error here, possible 2 that are compounding each other. But I have tried adjusting my various values and it's nothing doing. My other thought is that I'm suspicious of the way I have set up my input stream. I.e. I'm unsure of what value will be assigned to num in the final iteration of the while loop.
Can anyone shed some light on either of these problems?
Read at the top of your loop (after checking the count)
// cin >> num;
while (control <= 10)
{
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
// cin >> num;
}
Try to trace the code execution. Manually. That is the best way to learn how computers think.
You’ll realize, that the loop condition is broken. You start counting from 0, continue up to 10 including, stop at 11. 0..10, that’s 11 numbers!
Furthermore, you are reading input once at the beginning and then once at the end of each iteration. That makes 12 reads.
When trying to read more input than supplied, the program blocks and waits for more input. A program in infinite loop is active, it consumes all your CPU resources. In this case the program is blocked and uses close to no resources.
ask to enter numbers inside the loop,its easy to understand when to input particular number
int control = 1;
while (control <= 10)
{
cout << "Enter integer at position:"+Control << endl;
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
}
I could not see an error. Only the issue that you have to put 11 numbers instead of 10. Have you tried to type 11 numbers?
hey i am also a beginner but i tried to answer your question. you could also use compound assignment i.e. += instead of repeating evenSum and oddSum twice.
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << "\n";
while (control <= 9 )
{
cin >> num;
if (num % 2 == 0)
{
evenSum += num;
}
else
{
oddSum += num;
}
control++;
}
cout << "The sum of the even integers is: " << evenSum << "\nThe sum of the odd integers is: " << oddSum << "\n";
return 0;
}

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!

C++ Perfect Number With Nested Loops Issue

What I am trying to do is search for a perfect number.
A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.
Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.
My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.
What can be wrong?
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main()
{
int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;
cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;
for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
{
if (isAFactor(outer_loop, inner_loop) == true)
{
inner_loop += perfect_number;
}
}
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
else
{
cout << "There is no perfect number." << endl;
}
}
system("PAUSE");
return 0;
}
bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
return true;
}
else
{
return false;
}
inner_loop += perfect_number; should be perfect_number += inner_loop;.
There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.
I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.
after the if statement:
cout << perfect_number;
cout << outer_loop;
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
and see what values they have
Updated:
What is the value of your endval? is 0?, and thats why the loop ends so early
Oh, so many issues.
The variable perfect_number never changes. Did your compiler flag
this?
The outer loop will be one more than the ending value when it exits;
did you know this?
You don't need to compare bool values to true or false.
You could simplify the isAFactor function to return (outer %
inner) == 0;.
You could replace the call to isAFactor with the expression
((outer % inner) == 0).

What is wrong with my recursive fibonacci program?

I am unsure what the fault in my logic is. Sample output:
How many terms of the Fibonacci Sequence do you wish to compute?
1
1
1
--How many terms of the Fibonacci Sequence do you wish to compute?
5
5
5
5
5
5
5
Why is it doing this?
// Recursive Fibonacci Sequence
#include <iostream>
using namespace std;
double fib(double number);
int main(void) {
double number;
cout << "How many terms of the Fibonacci Sequence do you wish to compute?" << endl;
cin >> number;
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
} // end main
// function fib definition
double fib(double number) {
if((number == 0) || (number == 1))
return number;
else
return fib(number - 1) + fib(number - 2);
} // end function fib
Look at your loop:
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
Notice how the body of the loop doesn't use i... it always calls fib(number). Changing that to fib(i) will fix it.
(It's not terribly efficient, in that you'll end up recalculating values each time, but that's a separate matter. While you could put the printing in fib, that mixes the concerns of "what to do with the results" and "computing the Fibonacci sequence".)
You should just pass 'i' as the parameter in your for loop not 'number'
Make it:
for(int i = 0; i <= number; ++i)
cout << fib(i) << endl;