C++/c++ looping
Expert: vijayan - 12/11/2010
QuestionSir, I have a question related to arrays and loop in c++ its
a real simple question you will agree with me but the
problem I am facing is with the results. The question is
this:
WAP to enter two arrays of five elements each and find the
sum of the array such that C[1]=A[1]+B[1].
I get the results correct for first four value of both
arrays that I enter but the fifth result is some garbage
value.I am providing the code below hope you will look into
it and please answer.
WAP to enter two arrays of five elements each and find the
sum of the array such that C[1]=A[1]+B[1].
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k,a[5],b[5],c[5];
clrscr();
for(i=1;i<=5;i++)
{
cout<<"Enter the "<<(i)<<" element of the array ONE : ";
cin>>a[i];
}
for(j=1;j<=5;j++)
{
cout<<"Enter the "<<(j)<<" element of the array TWO : ";
cin>>b[j];
}
for(i=1;i<=5;i++)
{
for(j=i;j<=i;j++)
{
for(k=i;k<=i;k++)
{
c[k]=a[i]+b[j];
cout<<"The sum of array ONE "<<(i)<<" element and array TWO
"<<(j)<<" is : "<<c[k]<<endl;
}
}
}
getch();
}
I hope you will please answer.
regards,
Prakash Kumar
AnswerThe first element of an array has the subscript zero (0). The expression a[4] refers to the last element in an array containing five elements. For an array containing N elements, the valid subscripts are: 0, 1, 2, .... N-1.
So your loops should be: for( i=0 ; i<5 ; ++i )