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?
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.