printing error of array

hi...........

i have the following code written in MSVisual Studio C++ 2008 express edition. As the code says to print 20 but it is printing 27 why???

#include <iostream>

using namespace std;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
	int s[20];
	int count = 0,i=0;
	do	
	{
		i++;
		count++;
		
	}
	while(s[i]!= '\0');
	cout<<count<<endl;
	return 0;
}


I used most of the control statements but it is giving the same value............
thanq if anybody helps me...............
Your local array s[20] is not initialized. So its elements can contain any values that were in memory before the array was allocated.
Also you are trying to compare integer value with a charavcter literal '\0'. It is not an error, but this construction usually is used with character arrays which have terminated zero.
As the code says to print 20


As Vlad has implied, the code says no such thing.
I will show you a more interesting program that does the same. Your compiler shall support C++ 2011

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
#include <iostream>
#include <iterator>
#include <numeric>
#include <algorithm>

using namespace std;

int main()
{
   const int N = 20;
   int a[N];

   iota( begin( a ), end( a ), 0 );
   random_shuffle( begin( a ), end( a ) );

   for ( const auto &i : a ) cout << i << ' ';
   cout << endl;

   int count = 0;

   for ( const auto &i : a )
   {
      if ( i == 0 ) break;
      ++count;
   }

   cout << "count = " << count << endl;

   return ( 0 );
}
Last edited on
Topic archived. No new replies allowed.