difference between ( <= ) and (==)

hi dears, i'm beginner in C++.
i had defined counting function in my programm but i surprised when i saw this problem, my programm is so simple but it didn't work as follow mentioned :


#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int counting (int n);
int main(){
int n;
n=30;
counting (n);
system ("pause");
return 0;
}

int counting (int n){
for (int j=0;j==n;j++){
cout<<j<<endl;
}
return n;
}

but when i changed just ( == )with ( <= ) as follow :

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int counting (int n);
int main(){
int n;
n=30;
counting (n);
system ("pause");
return 0;
}

int counting (int n){
for (int j=0;j<=n;j++){
cout<<j<<endl;
}
return n;
}

it works correctly, i didn't understand why this happened!!
what's the difference?
== is equal
<= is less or equal

In first snippet your loop will continue working only if j equals to n
In second snippet your loop will continue working if j less or equal to n
tnx for your attention.

why loop will continue its work with <= but not with ==?
in for loop i wanted to count number from 0 to n! i didn't understand...
Because when you use ==, you are telling the program to only run the code in the loop when j and n are equal. Since j starts at 0, if n is any number other than 0, the loop run at all since that condition starts out false.
The for loop first does the initialisation, in this case sets j = 1.
Next it tests the condition. If it evaluates as true then the body of the loop will be executed. If it is false then the loop terminates

for (int j=0; condition; j++)

After each iteration, control goes back to the top of the loop, the increment, in this case j++ is done. then the condition is re-tested... and so on.

See the tutorial for a full explanation:
http://www.cplusplus.com/doc/tutorial/control/
Topic archived. No new replies allowed.