Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am not getting correct output

What I have tried:

C++
void main()
{
int a[5][5],i,j,k,t;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
cin>>a[i][j];
}
for(k=0;k<25;k++)
{
a[k]=a[i][j];
}
}
for(k=0;k<25;k++)
{
if(a[k]>a[k+1])
{
t=a[k+1];
a[k+1]=a[k];
a[k]=t;
}
}
for(k=0;k<25;k++)
{
cout<<a[k]<<\t;
}
getch();
}
Posted
Updated 7-Jul-17 9:04am

The initialization of the matrix is incorrect (not complete). Moreover your sort routine is flawed.
Try
C++
#include <iostream>
using namespace std;
int main()
{
  int a[5][5],i,j,k,t;
  int * b = reinterpret_cast<int*>(a);
  for(i=0;i<5;i++)
  {
    for(j=0;j<5;j++)
    {
      cin>>a[i][j];
    }
  }
  for(i=0;i<24;i++)
  {
    for(j=i+1;j<25;j++)
    {
      if(b[i]>b[j])
      {
        t=b[i];
        b[i]=b[j];
        b[j]=t;
      }
    }
  }
  for(k=0;k<25;k++)
  {
    cout<<b[k]<<"\t";
  }
  cin.get();
}
 
Share this answer
 
First of all, indent your code properly, it helps reading.
C++
void main()
{
    int a[5][5],i,j,k,t;
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            cin>>a[i][j];
        }
        // this loop is very confusing and lake no sens to me
        for(k=0;k<25;k++)
        {
            a[k]=a[i][j];
        }
    }
    for(k=0;k<25;k++)
    {
        if(a[k]>a[k+1])
        {
            t=a[k+1];
            a[k+1]=a[k];
            a[k]=t;
        }
    }
    for(k=0;k<25;k++)
    {
        cout<<a[k]<<\t;
    }
    getch();
}

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900