When printing an arrangement of 10 spaces, another number is printed too large

0

I can not understand how it prints that eleventh number .. Would someone with more experience be kind enough to verify it?

#include <iostream>
#include <stdlib.h>
using namespace std;



int ordenarArreglo(int *arr)
{
int i, j, temp = 0;

    for(i = 0; i < (10 - 1); i++)
    {
        for(j = 0; j<(10 - i - 1); j++)
        {
            if(arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j + 1 ]= temp;
            }
        }
    }
temp = 0;
i = 0;
j = 0;


    for(int z = 0;z <= 10;z++)
    {
        cout << " " << arr[z];
    }
}

int main()
{
    //Arreglo de diez numeros a modificar.
    int arr[10] = {15,1,3,4,8,9,7,6,7,4};

    cout << "El arreglo original es: ";

   for(int i=0;i < 10; i++)
    {
        cout << " " << arr[i];
    }

    cout << endl << endl;

    cout << "El arreglo ordenado es: ";

    cout << ordenarArreglo(arr);
    return 0;
}
    
asked by Rubén 12.11.2016 в 02:12
source

3 answers

2

Problem in <= :

for(int z = 0;z <= 10;z++)
{
    cout << " " << arr[z];
}

Change it to < :

for(int z = 0; z < 10; z++)
{
    cout << " " << arr[z];
}

Simple mistake of yours I suppose. The rest of the loops are all good.

And also:

int ordenarArreglo(int *arr);

The return type is int , when in reality you do not return anything. That returns void :

void ordenarArreglo(int *arr);

And additionally, you are also printing the output value of the function (your 11th value, which in particular, will print garbage, I suppose, so I do not know why you are not seeing 12 values instead of 11 taking into account the extra return of <= ):

cout << ordenarArreglo(arr);

Replace it with:

ordenarArreglo(arr);

Which leads me to conclude that you probably want to make the printing loop in main . Complete code (with a couple of extra changes):

#include <iostream>
#include <algorithm> // para swap, o #include <utility> si usas C++11
// #include <stdlib.h> // No lo necesitas

using namespace std;

int ordenarArreglo(int *arr, int n) // Pasa el tamaño manualmente
{
    int i, j, temp = 0;

    for(i = 0; i < n - 1; ++i) // Mejor preincrementos
        for(j = 0; j < n - i - 1; ++j)
            if(arr[j] > arr[j + 1])
               std::swap(arr[j], arr[j + 1];
}

int main()
{
    //Arreglo de diez numeros a modificar.
    int arr[] = {15,1,3,4,8,9,7,6,7,4}; // El tamaño se calcula solo
    int n = sizeof(arr); // Aquí recuperas tu '10'. Así puedes añadir valores a 'arr' con libertad.

    cout << "El arreglo original es: ";

    for(int i = 0; i < n; ++i)
        cout << " " << arr[i];

    cout << endl << endl;

    cout << "El arreglo ordenado es: ";

    ordenarArreglo(arr, n);

    for(int i = 0; i < n; ++i)
        cout << " " << arr[i];

    cout << endl;

    return 0;
}

If you use C ++ 11, the% co_of% is simplified:

int main()
{
    int arr[] = {15,1,3,4,8,9,7,6,7,4};

    cout << "El arreglo original es: ";

    for(int v : arr)
        cout << " " << v; // 'v' "itera" sobre los contenidos de 'arr'.

    cout << endl << endl << "El arreglo ordenado es: ";

    ordenarArreglo(arr, sizeof(arr));

    for(int v : arr)
        cout << " " << v;

    cout << endl;

    return 0;
}
    
answered by 12.11.2016 / 02:15
source
1

First error

As indicated by @ Peregring-lk, in the cycle with which you are printing the values, you are leaving the limit of the array, you should change:

for(int z = 0;z <= 10;z++)

By

for(int z = 0;z < 10;z++)

Second error

The call to the function, you are doing it within a cout, you have it like this:

cout << "El arreglo ordenado es: ";

And you should be like this

ordenarArreglo(arr);

This should be what is causing a large number to be printed, even after you fix the first error.

    
answered by 12.11.2016 в 02:42
0

The problem, as you have been told, is in the last ordenarArreglo loop:

for(int z = 0;z <= 10;z++)
{
    cout << " " << arr[z];
}

In that loop you are iterating in the range (0.10), when the valid range is (0.9).

The simplest solution is to change <= by < :

for(int z = 0;z < 10;z++)
{
    cout << " " << arr[z];
}

However, the value 10 repeats everywhere. A good habit is to prevent these types of values from being replicated by the code like rabbits. Imagine that to do tests you prefer to use a low value (for example 10) but then in the real environment you have to use a larger value (it means 500). Are you going to locate all the apparitions to replace them one by one? I hope your answer is not affirmative.

The solution to this problem is to use constant variables. This way of working provides two great advantages:

  • It is very easy to change the value. You edit it in one place and all the code adapts to the new value.
  • Names are usually more descriptive than numbers. When finding errors it is not the same to find a literal and try to deduce if this value is correct than to find a constant and, based on its name, know if you are using the correct constant.

Example:

const int TamVector= 10;

int ordenarArreglo(int *arr)
{
  int i, j, temp = 0;

  for(i = 0; i < TamVector - 1; i++) // <<--- AQUI!!!
  {
    for(j = 0; j<(TamVector - i - 1); j++) // <<--- AQUI!!!
    {
      // ...
    }
  }

  // ...

  for(int z = 0;z < TamVector;z++) // <<--- AQUI!!!
  {
    cout << " " << arr[z];
  }
}

int main()
{
  //Arreglo de diez numeros a modificar.
  int arr[TamVector] = {15,1,3,4,8,9,7,6,7,4}; // <<--- AQUI!!!

  cout << "El arreglo original es: ";

  for(int i=0;i < TamVector; i++)
  {
    cout << " " << arr[i];
  }

  // ...
}

And would not it be better to use #define ?

The truth is that not since #define does not have a strong typing, which can cause if you do not take into account that small but crucial detail.

Another silly detail of your code is the initialization of temp , i , and j in the middle of ordenarArreglo . That code is directly redundant since those variables have no use. I take this paragraph to also tell you that these variables should be declared within the corresponding loop (as you already do in other sections of the code):

for(int i = 0; i < TamVector - 1; i++)
{
    for(int j = 0; j<(TamVector - i - 1); j++)
    {
        if(arr[j] > arr[j + 1])
        {
            int temp = arr[j];
            arr[j] = arr[j+1];
            arr[j + 1 ]= temp;
        }
    }
}

It is highly recommended to reduce the scope of the variables to the minimum to avoid foolish mistakes when programming. Creating a variable int in each iteration of the loop has no cost and, in addition, the compilers can do wonders when optimizing the code ... while unnecessarily lengthening the life of a variable can lead to rather complicated problems to find out what it happens if you reuse a variable without realizing it and assume that it is initialized to a value that is not what it really has?

Another detail we find here:

temp = arr[j];
arr[j] = arr[j+1];
arr[j + 1 ]= temp;

That can be replaced quietly by this:

std::swap(arr[j],arr[j+1]);

Another problem that your code has is found here:

int ordenarArreglo(int *arr)
{
  // ...

  // ¿Y el return?
}

If you indicate that the function returns an integer you should necessarily put a return somewhere (preferably at the end of the function), however this instruction is absent.

This generates an added problem and is that it allows the following statement to be valid:

cout << ordenarArreglo(arr);

Do you really want to print an additional integer after displaying the resulting vector on the screen? I guess not.

In short, the function should have the following signature:

void ordenarArreglo(int *arr)

And in the penultimate instruction of your program there is a cout :

ordenarArreglo(arr);
return 0; // También puedes poner return EXIT_SUCCESS; que queda más elegante
    
answered by 12.11.2016 в 02:44