1 Replies - 224 Views - Last Post: 18 August 2012 - 10:25 PM Rate Topic: -----

#1 adityasingh95  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 14-July 12

Swapping Array Values: Error in Output

Posted 18 August 2012 - 10:08 PM

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

Is This A Good Question/Topic? 0
  • +

Replies To: Swapping Array Values: Error in Output

#2 jimblumberg  Icon User is online

  • member icon

Reputation: 3055
  • View blog
  • Posts: 9,292
  • Joined: 25-December 09

Re: Swapping Array Values: Error in Output

Posted 18 August 2012 - 10:25 PM

Your problem is contained within the following snippet:
   for (int j = 0; j < n; j++)
   {
      if (a[j] % 10 == 0)
      {
         a[j]=q;
         a[j]=a[j+1];
         a[j+1]=q;

When j is equal to n - 1, you will be referencing an uninitialized element of your array in your last line. Remember arrays start a 0 and stop at size - 1.

Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1