the question is:

Wrtie a program to modify the elements of an array such that the elements that are multiples of 10 swap with the values present in the very next position.

I wrote the following code:

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

void main()
    {
    clrscr();
    int a[20];
    int n,q=0;
    cout<<"How many Numbers would you like to Enter?";
    cin>>n;
    for (int i=0;i<n;i++)
        {
        cout<<"Enter Value for Number "<<(i+1)<<": ";
        cin>>a[i];
        }
    for (int j=0;j<n;j++)
        {if (a[j]%10==0)
            {a[j]=q;
            a[j]=a[j+1];
            a[j+1]=q;
            i++;
            }
        }
    for (int k=0;k<n;k++)
        {cout<<a[k]<<endl;}
    getch();
    }

so if i give the input as:

How many Numbers would you like to Enter? 5
Enter Value for Number 1: 12
Enter Value for Number 2: 10
Enter Value for Number 3: 14
Enter Value for Number 4: 16
Enter Value for Number 5: 18

the output should be
12
14
10
16
18

but instead the output is:
12
14
16
18
3838

Pls tell what i should change in the program so as to get the correct output.

Member Avatar for misi

First of all: Why do you need variables i,j,k?
"i" would be enough then probably you would not increase its value in line 22.

a[j]=q;

Don't you want the opposite: q=a[j] ?

Member Avatar for priesdelly

look is code and read coding comment by me ... :)

int main(int argc, char *argv[])
{
    int a[20];
    for(int i = 0 ; i<20;i++)
    {
            a[i]=0;
    }//clear first
    int n=0,q=0,j=0; //clear first
    cout<<"How many Numbers would you like to Enter? ";
    cin>>n;
    for (int i=0;i<n;i++)
        {
        cout<<"Enter Value for Number "<<(i+1)<<": ";
        cin>>a[i];
        }
    while(j<n)
        {
        if (a[j]%10==0)
            {
                q=a[j]; // your code in line is a[j]=q is not like q=a[j] :)
                a[j]=a[j+1];
                a[j+1]=q;
                q=0; //clear swap variable when end swap job :)
                j++; // jump 2 step when this array can mod 10 :)
            }
        j++;
        }
    for (int k=0;k<n;k++)
       {cout<<"Value Of : "<<(k+1)<<" is :: "<<a[k]<<endl;}
    system("PAUSE");
    return EXIT_SUCCESS;
}

line 22 : should be q=a[j];
and you must be incrementing value of j not i.

Member Avatar for misi

if (a[j]%10==0)

It includes 0(zero) as well.
If you do not want it to be swapped than you may refine your code as:

if (!(a[j]%10) && a[j])

That way 0(zero) will be excluded from swapping.

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.