I am doing a simple program to calculate the first 15 fibonacci numbers and also placing an asterisk next to even numbers. My output should look like this:

``````1
1
2*
3
5
8*
13
21*
34*
55
89
144*
233
377
610*
``````

I can calculate the numbers easily enough but I can't seem to get the asterisks next to the even numbers. My code so far is:

``````package assign4;

/**
*
*
*/
public class Main {

/** Creates a new instance of Main */
public Main() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) { //a method
int num1 = 1; //first number in fibonacci sequence
int num2 = 1; //second number in fibonacci sequence
int num3 = 2; //provides summation of previous two numbers

System.out.println("The first 15 fibonacci numbers are: ");
System.out.println(num1);
System.out.println(num2);

while( num3 <= 377){ //loop ends after calculating the first 15 fibonacci numbers
num3 = num1 + num2;
System.out.println(num3);
num1=num2;
num2=num3;

}

if ( num3 % 2 == 0 );
System.out.println(num3 + "*");
num1 = num2;
num2 = num3;
``````

It is a very basic program and I'm sure I look like a fool by overlooking an obvious flaw, but I'm only in my first year of Computer Science so I'm still new to this. If anyone could lead me in the right direction it would be greatly appreciated.

It's simple.

Before displaying that number check whether it an even number

``````while( num3 <= 377){ //loop ends after calculating the first 15 fibonacci numbers
num3 = num1 + num2;
if ( num3 % 2 == 0 )
System.out.println(num3 + "*");
num1=num2;
num2=num3;
}
``````

not after …

## All 2 Replies

It's simple.

Before displaying that number check whether it an even number

``````while( num3 <= 377){ //loop ends after calculating the first 15 fibonacci numbers
num3 = num1 + num2;
if ( num3 % 2 == 0 )
System.out.println(num3 + "*");
num1=num2;
num2=num3;
}
``````

not after displaying
No need for this code fragment

``````/*if ( num3 % 2 == 0 );
System.out.println(num3 + "*");
num1 = num2;
num2 = num3; */
``````

greetings
Parthiban

Here is the Code as per your requirement.

``````#include <stdio.h>

int main(){
int terms, lastNumber=1,secondLast=0,currentNumber=0,counter;
printf("Enter number of terms in Fibonacci series: ");
scanf("%d", &terms);
/*
*  Nth term = (N-1)th therm + (N-2)th term;
*/
for(counter = 0; counter < terms; counter++){
if(counter < 2){
currentNumber = counter;
} else {
currentNumber = lastNumber + secondLast;
secondLast = lastNumber;
lastNumber = currentNumber;
}
if(currentNumber%2 == 1) // Odd number
printf("%d\n", currentNumber);
else
printf("%d *\n", currentNumber);
}

return 0;
}
``````
Be a part of the DaniWeb community

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