C++/array

Advertisement


Question
#include<iostream.h>
#include<conio.h>
void main()
[
int x[5]={1,2,3,4,5},y[5]={5,4,3,2,1},result[5]={0,0,0,0,0};
int i=0;
while(i++<5)
result[i]=x[i]-y[i];
clrscr();
cout<<"\n content of array:\n";
i=0;
do
{
cout<<'\t'<<x[i]<<'\t'<<y[i]<<'\t'<<result[i]<<'\n';
i++;
}
while(i<5);
getch();
}
O/p:
1 -1 0
2  2 -2
3 3 0
4 2 2
5 1 4
respected sir
que:
how the answer -1 in column pls explain me

Answer
Well I am surprised the code you posted to me does anything at all - as it is illegal C++ - even for pre standard C++ for broken compilers that accept the non-standard void main form of main - it should have been thrown out even by such an old broken compiler, because you start the main function definition with a [ not a {:

   void main()
   [

If you expect me to comment on code then PLEASE POST THE SAME CODE YOU ARE HAVING PROBLEMS WITH!!!

Otherwise obviously my comments may bare little relation to the problem with your actual code as I have not seen it.

You do know how you copy text from one application (e.g. a Visual C++ IDE editing window containing your code) to another (e.g. a web browser open at the All Experts question submission form page) don't you? If not then please learn how to do so now - it is basic GUI usage after all.

OK as I have a more up to date compiler than it seems you have (Microsoft Visual C++ 2008) I re-worked your code slightly viz:

   // ### CORRECTION ###
   // <airstream> ?? Copy, pasted and spell checked to nonsense me thinks - my apologies
   // #include <airstream>    
   // It should of course have been <iostream>:
   #include <iostream>

   using namespace std;

   int  main()
   {
       int x[5]={1,2,3,4,5},y[5]={5,4,3,2,1},result[5]={0,0,0,0,0};
       int i=0;
       while(i++<5)
           result[i]=x[i]-y[i];
       cout<<"\n content of array:\n";
       i=0;
       do
       {
           cout<<'\t'<<x[i]<<'\t'<<y[i]<<'\t'<<result[i]<<'\n';
           i++;
       }
       while(i<5);
   }

I fixed the obvious error and removed uses of non-standard stuff declared in conio.h, as it is not really relevant to the problem. I also applied reasonable indenting as you either did not bother or it got lost posting through AllExperts.

The output I received was (and yes I did copy and paste it from the console window):

    content of array:
           1       5       0
           2       4       -2
           3       3       0
           4       2       2
           5       1       4


Plus, on termination from the Visual Studio debugger an error box with the message:

   Run-Time Check Failure #2 - Stack around the variable 'result' was corrupted.

What is going on? Why does it seem my version only calculated results for index values 1,2,3 and 4? Why is there apparently no result for index 0? (we would expect result[0] to be -4 not 0). Why are my results different from yours?

Well it is your first loop and the way you are updating i:


       while(i++<5)
       // i is incremented by the time it reaches here
           result[i]=x[i]-y[i];

Note the comment. After each iteration through the while statement i has been incremented. So by the time it reaches the line:

           result[i]=x[i]-y[i];

i has been changed. So i starts at 0.

   while(i++<5)

Executes. i's value, 0, is checked to be less than 5. Then i is incremented from 0 to 1

               result[i]=x[i]-y[i];

Executes with an index value, i, of 1 - which explains why there is no result for result[0], the 0 value of i is never used within the loop.

Fast forwarding to the last iterations of the loop, after executing

               result[i]=x[i]-y[i];

For i = 4 we get:

   while(i++<5)

Executes. i's value, 4, is checked to be less than 5. Then i is incremented from 4 to 5.

Note here that i is still less than 5 when its value is used in the comparison, then after being used its value is updated. Hence we go around again with an i index value of 5:

               result[i]=x[i]-y[i];

Executes with an index value, i, of 5 - which explains why the stack memory around result was corrupted, as result[5] is updated but result[5] is one off the end of the result array (which has slots indexed 0,1,2,3,4). This may also explain why my results are different to yours - our stack frames for the main function call may well be different, or the corruption caused by writing off the end of the result array had different effects.

The skipping index zero is due to incrementing within the while statement - using either pre-increment (++i) or post increment (i++).

Note:
   The difference between pre and post increment is whether the value used in
   an expression is the value before or after the increment is applied.
   For example using pre-increment in your loop test viz:

       ++i < 5

   would increment the value of i then use the updated value in the comparison to 5.

   While using post increment, as we have seen,:

       i++ < 5

   Uses the value of i before incrementing in the comparison to 5 then applies
   the increment.
   
   Pre and post decrement work similarly.
-- end note

This could be fixed by initialising the value of i to -1, although this is somewhat non-intuitive - and likely to cause people to go "eh? what's going on?" when reading such code.

To fix the allowing an illegal index of 5 you could either use a value of 4 or use pre-increment - which at least looks like it matches the sizes of the arrays involved so is probably less confusing.

Applying these two changes gives:

       int i=-1;
       while(++i<5)
           result[i]=x[i]-y[i];

However, in C and C++, when doing this sort of iteration over arrays we usually use a for loop.

A for-loop has the form:

   for ( initial-expression ; expression-is_true ; end-expression )
   {
   // repeat the code
   }

It is equivalent to the following:

   initial-expression;

   while ( expression-is-true )
   {
   // repeat the code

       end-expression;
   }

Any or all of the three expressions forming the for-statement may be omitted but the semicolons must remain. If the initial-expression or end-expression is omitted it is as if it were not in the logical while loop equivalent. If the expression-is-true part is omitted then it is taken to be true, so:

   for (;;;)
   {
   // repeat code forever
   }

Will repeat the code in the braces forever, equivalent to:

  while (true)
  {
  // repeat code forever
  }

I have shown the repeated code in braces. In fact if there is only one statement, as per other control flow constructs such as if and while it can follow without braces:

   for (;;;)
       ;// repeat single statement forever

So in your case we could replace your:

       int i=0;
       while(i++<5)
           result[i]=x[i]-y[i];

With a for loop like so:

       int i=0;
       for (; i<5;++i)
           result[i]=x[i]-y[i];

Or, for more modern C++ implementations we are allowed to define the loop variable(s) in the for loop statement:

       for (int i=0; i<5;++i)
           result[i]=x[i]-y[i];

In which i is only defined within the for loop. Older compilers may not support this syntax at all or get the scope of the defined i wrong and allow it to be visible outside of the for loop. The effect of this in your case if trying to use a similar for loop for the output:

       for (int i=0; i<5;++i)
       {
           cout<<'\t'<<x[i]<<'\t'<<y[i]<<'\t'<<result[i]<<'\n';
       }

Would cause such compilers to complain that i was already defined.

Hope this helps.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.