You are here:

C++/c++ looping

Advertisement


Question
Sir, 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

Answer
The 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 )

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

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