Problem with while C++

Asked

Viewed 136 times

0

I’m starting to learn programming in C++ and I’m having trouble solving an exercise through repetition. The exercise has such a statement:

Make a program that reads 5 integers. The program must then determine whether or not the numbers are sorted (ascending order). If ordered, the program must write 1, otherwise it must write 0.

Input example: 1 2 3 4 5 Output: 1

Input example: 1 3 2 4 5 Output: 0

I was able to solve the problem with this code, without using the while function:

#include  using namespace std;

int main() { int num1, num2, num3, num4, num5;

cin >> num1 >> num2 >> num3 >> num4 >> num5; if (num1<=num2 and num2<=num3 and num3<=num4 and num4<=num5) { cout << 1 << endl; } else { cout << 0 << endl; } return 0; }

However, I don’t know how I would solve it with the while function or the logic behind using that function.

1 answer

0


#include<iostream>
#include<vector>

int main()
{
    std::vector<int> valores;       // Declara vetor de int

    for(int k = 0; k <= 4; k++)     // Grava 5 número no vetor valores
    {

        int temp;
        std::cin >> temp;

        valores.push_back(temp);

    }

    for(int k = 0; k <= 4; k++)     //Executa a verificação
    {
        if(valores[k] > valores[k+1])   // Verifica a posição seguinte, se for maior, significa desordenado
        {
            return 0;   // Não ordenado

        }
    }

    return 1;   // Ordenado

}

Explanation in comments in the code.

  • Thanks for the reply, I will use yours as a basis to try to perfect my code!

  • Dispose, colleague.

  • 1

    @Fourzerofive is not advisable to use main to return values in this way, since if main returns 0 indicates to the system that called it that everything went well and a return other than 0 indicates that something out of the ordinary happened.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.