Mishal Rehaj
Mishal Rehaj

Reputation: 1

C++ Array swapping and find smallest element

I am trying to find first smallest array but my code does not display any output. There are no errors or warnings. Actually, I am trying to check an algorithm that I got as an assignment from my university.

#include <iostream>
using namespace std;
int main(){

    int arr[7]= {8,4,6,9,2,3,1};
    int n = sizeof(arr)/sizeof(arr[0]);

    int smallest = 0;
    for(int j = 1; j = (n-1); j = (j + 1) )
    {
        smallest= j ;
        for(int i = (j+1); i = n ; i = (i + 1))
        {
            if (arr[i]<arr[smallest])
            {
                smallest = i;
                int swaper = arr[j];
                arr[j] = arr[smallest];
                arr[smallest] = swaper;
            }
        }
    }
    for(int a = 1; a = n; a = (a + 1))
    {
        cout<<arr[a];
    }   
    return 0;
}  

Upvotes: 0

Views: 514

Answers (2)

PaulP1
PaulP1

Reputation: 125

# include <iostream>
using namespace std;
int main ()
{
  int  a[100][100],n,k,i,j,aux,mi=0;
 cin>>n>>k;
for(i=1;i<=n;i++)
       for(j=1;j<=k;j++)
             cin>>a[i][j];

for(i=1;i<=n-1;i++)
     for(j=i+1;j<=n;j++)
          if(a[i][k]>a[j][k])
              {aux=a[i][k];
               a[i][k]=a[j][k];
               a[j][k]=aux;
             } //until here you are sorting the 2D array

             for(i=1;i<=n;i++) {
                for(j=1;j<=k;j++) {
                cout<<a[i][j]<<" ";
                }
                cout<<endl;
             }
cout<<endl;
  mi=a[1][1];
  for (i=1; i<=n; i++)
    {
        for (j=1; j<=n; j++)
            if (mi<a[i][j])
            mi=a[i][j];
    } //here you're finding the smallest element
    cout<<mi;
    return 0;
  }

The Code doesn't compile, but the idea should solve 90%, you just have to write the code.

Upvotes: 0

There are three errors with this code:

    for(int a = 1; a = n; a = (a + 1))
    {
        cout<<arr[a];
    }

Firstly, arrays start from zero, not one. So the first part of the for statement should be int a = 0;.

Secondly, you are not comparing a and n, you are assigning n to a, (and the value is non-zero, so you always keep going). The equality test is ==, but you don't want that anyway!

Thirdly, the loop condition is for when to keep going, not when to stop. So you need either < or != (either will work, people have long arguments about which is preferable).

The normal way to write a loop over a range of integers in C++ is:

    for (int a = 0; a < n; a++)

You are at least consistent, and have made the same mistake in every loop. You will need to fix it in every loop.

Upvotes: 4

Related Questions