Hello all. I am working on this program and having some troubles with it. I have tried lots of different things and can't get it to do what I want. I guess I am not really understanding the code and how to word it properly. I am writing a program that will show the Fibonacci sequence numbers, ask the user to input the amount of numbers they want shone, and print five numbers per line. I want to use a for loop, not show zero, and i'm thinking I should use nested loops to show invalid input for zero. This is what I have so far. Thank you for any help given.

#include <iostream>
#include <iomanip>
using namespace std;

void main()
{
      
	int fib1 = 0;
    int fib2 = 1;      
    int fib3;   
    int numbers;     
    int counter = 0; 
          
    cout << "Please enter the number of Fibonaccis to calculate ==> " ;        
    cin >> numbers; 

	for (numbers >= 1; counter <= numbers; counter++)
	{
		counter++;
		fib3 = fib1 + fib2;
        cout << fib3 << setw(16);
        fib1 = fib2;
        fib2 = fib3; 
	}
     
   /* if (numbers <= 0)     
		cout << "Invalid Input\n";
    do 
	{
        counter++;
        fib3 = fib1 + fib2;
        cout << setw(16) << fib3;
        fib1 = fib2;
        fib2 = fib3;    
    } 
	while (counter <= numbers);
     */
    cout << endl;    
}

Recommended Answers

All 2 Replies

Line 17 is: for ([b]numbers >= 1[/b]; counter <= numbers; counter++) The first slot in the for loop is used for initialization of the counter variable. What you have there is a conditional statement (like the one in the middle slot of the loop) that evaluates to true or false. If you're not using the loop counter for anything beyond the body of the loop, simply declare it in the first slot and it will disappear after the loop ends (and omit line 12). for(int counter = 0;counter<=numbers;counter++) For the variable to remain intact after the loop you can omit the first slot and leave line 12 as it is. for(;counter<=numbers;counter++) For the sake of completeness you could also declare it on line 12

int counter;
//...then on line 17
for(counter=0;counter<=numbers;counter++)

Other than that it seems to be ok (I did not run it). Check that it gives the correct results after making the change.

Also, you are incrementing counter inside the loop! Take the line that increment counter out of for-loop. The for-loop automatically increase the variable counter used for the loop. You are not supposed to increment it yourself unless you want to do certain skipping. Yet, you should use while loop instead if you want to manipulate with the counter.

commented: The eyes glossed over that fact +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.