Question is:

Declare two arrays of size 5. Get input from the user. Declare a third array of size 10. Put the values of array1 in even indexes of array3 and values of array2 in odd indexes of array3.
Example
Array1
1 2 3 4 5

Array2
6 7 8 9 10


Array3 will be
1 6 2 7 3 8 4 9 5 10


im new in C++
and i have getting a problem in this question..please check my code and help me to sort out the problem.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main()

{clrscr();

int a[5];
int b[5];
int c[10];


int s;

for (s=0;s<5;s++)
{cout<<"Enter Element of array 1";
cin>>a[s];}


for (s=0;s<5;s++)
{
cout<<"Enter element of array 2";
cin>>b[s];
}

for (s=0;s<10;s++)
{
if (s%2==0)
{c[s]=a[s];}

else
{c[s]=b[s];}

}


for (s=0;s<10;s++)
{cout<<c[s]<<endl;}

getch();

}

Recommended Answers

All 6 Replies

There should be a separate index counter for a and b, because you don't want to skip indices:

if (s % 2 == 0)
    c[s] = a[q++];
else
    c[s] = b[r++];

Well, you didn't specify what your problem is, but I suspect you are getting segmentation faults (crashes) at run-time.

The problem is that you are only using "s" as the index of your arrays. If you have 2 arrays containing 5-elements each (elements 0-4). You are going to have memory errors when you try to access elements 5-9.

What you need to do is add 2 additional index variables, perhaps called "i" and "j". You would use one for the current index of array1 and one for the current index of array2. Then, after you perform the required assignment, you increment the appropriate array index, not just "s".

EDIT:
Oops, a little slow, Narue has it covered.

Narue, Fbody can u please write the finalized code by editing my whole program?

There should be a separate index counter for a and b, because you don't want to skip indices:

if (s % 2 == 0)
    c[s] = a[q++];
else
    c[s] = b[r++];

thanks alot it configured ma problem :)

>Narue, Fbody can u please write the finalized code by editing my whole program?
I've already done all of my homework. Why should I do yours too?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.