Infinite rand

So, problem is with this 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<stdlib.h>
#include<time.h>  


using namespace std;


int main()

{
int i,j,a[5];


srand((unsigned)time(0));
for (i=0; i=4; i++)
	{
     a[i]=rand() %100+1;
	 cout<<a[i]<< " ";
	}

for (i=4; i=0; i--)
	{
	 for(j=0; j=4; j++)
		{
		 if (a[j]>a[j+1])
			{
			 int temp=a[j+1];
			 a[j+1]=a[j];
			 a[j]=temp;
                        }
		}
	}

for (i=0; i=4; i++)
	{
	 cout << a[i] << " ";
	}


return 0;
}

It just go on forever writing my a[i].
I have no idea what's wrong.
And I'm new to cpp so it might be something obvius...
= is assignment
== is comparison.

1
2
3
4
5
for (i=0; i=4; i++)

// should be:

for (i=0; i<4; i++)


You have a similar problem with your other loops.
Ok, thanks.
But with that I got next problem:
It will just write twice same thing instead of writing one line in random order and 2nd line in "from smallest to biggest" order
(Sorry for my English)
Last edited on
Did you mess up your 2nd 'i' loop?
Seems like it...
It's my 1st time creating loop like that in c++
I won't be able to see what's going wrong without seeing the updated 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<stdlib.h>
#include<algorithm>
#include<time.h>  


using namespace std;


int main()

{
int i,j,a[5];


srand((unsigned)time(0));
for (i=0; i<=4; i++)
	{
     a[i]=rand() %100+1;
	 cout<<a[i]<< " ";
	}
cout<<""<<endl;
for (i=4; i<=0; i--)
	{
	 for(j=0; j<=4; j++)
		{
		 if (a[j]<a[j+1])
			{
			 int temp=a[j+1];
			 a[j+1]=a[j];
			 a[j]=temp;
                        }
		}
	}

for (i=0; i<=4; i++)
	{
	 cout << a[i] << " ";
	}
cout<<""<<endl;
system("PAUSE");

return 0;
}

Here it is, I did <= instead of < to get 5 elements instead of 4.
you could always just do < 5 :P
Also on line 22 you don't need the "" you can simply put cout << endl;


Your problem is probably on line 23. How can i == 4 but then be less than or equal to 0? Maybe you meant >= 0.
Thank you. Both of you.
So, I had to edit as you said >=0 and in line 25 I had to get ==4, without it it would always start 2nd line with 0.
Thanks once again.
Topic archived. No new replies allowed.