If and else if in a while loop

Hi there
I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main(){
	int number;
	int a=0;
	srand(time(0));
	while(a!=5){
		cout << "Enter something" << endl;
		cin >> a;
		number=rand()%3;
		cout << number << endl;
		if(number=0){
			cout << "0" << endl;
		}
		else if(number=1){
			cout << "1" << endl;
		}
		else if(number=2){
			cout << "2" << endl;
		}
	}
	return 1;
}


Whenever i enter some input and press enter i first get my random number from 0-2 (bold in the code).

The program then goes on to only output 1 (in italics) although my if condition would result in an output of (0-2) (the same i get in the first output).

This is not the case though. If I comment out the first "else if" and leave the second "else if" the program only chooses to show the 2 (underlined) neglecting my random number.

Is there any way to make the program work as intended?
greetings

//EDIT:
On another note for exercise 8 here:
http://www.cplusplus.com/forum/beginner/3473/

8. Create a program which generates Fibonacci series till a number 'n' where 'n' is entered by the user. For eg. if the user enters 10 then the output would be: 1 1 2 3 5 8 (Beginner)


do i need an array for this exercise?
Last edited on
closed account (zb0S216C)
Your if statements are doing something completely different from what you think.

The first thing to note is that you're not testing for equality, instead, you're assigning a new value to number. After the assignment, number is evaluated to a Boolean. This mistake is common amongst beginners. Alls' you have to do is change number = 0 to number == 0. For instance:

1
2
3
4
if(number == 0) // Equality
    // ...

if(number = 0) // Assignment, not equality 

Wazzak
Last edited on
Oh lol this just happened to me on another program as well. This is kind of obvious then...Thank you ^^
Last edited on
Topic archived. No new replies allowed.