Please explain the difference between the two codes



1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream>
using namespace std;

int main()
{
    int x[10];
    for(int i=0; i<10; i++) {x[i]=i;}
    
    for(int i=0; i<10 && (x[i] !=0); i++) 
    { cout<<x[i]<<" ";}
    
    system("pause");}


and
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    int x[10];
    for(int i=0; i<10; i++) {x[i]=i;}
    
    for(int i=0; i<10 ; i++) 
    { if(x[i])cout<<x[i]<<" ";}
    
    system("pause");
}

The former will terminate the second for loop early at the first number that is zero.

The latter will run both for loops 10 times, no matter what.
1st terminates printing if it encounters 0.
2nd code does not print 0 because of if() statement.
Last edited on
Oh yea...how did I miss it!
Topic archived. No new replies allowed.