Write a C++ program which contains a user-defined functionhaving name isSortedthat returnstrue if the array is sorted,and returns false if thearray is not sorted In main functionask the user to enter 10 integers and store them in array and thencall the function by passing this array. If array is sorted thendisplay message "Array is Sorted" otherwise displaymessage "Array is not Sorted"

Respuesta :

Answer:

#include<iostream>

using namespace std;

//create the function  

bool isSorted(int arrays[]){

   int Array_size=10;//store the size

   //check for condition if array is size 1 or zero

   if(Array_size==1 || Array_size==0){

       return true;

   }

   //traversing the array and check for sort

   for(int i=1;i<Array_size;i++){

       if(arrays[i-1]>arrays[i]){

           return false;

       }

   }

   return true;

}

//main function

int main(){

   //initialization

   int arrays[10];

   cout<<"Enter the 10 numbers: "<<endl;

   //for storing the value in array

   for(int i=0;i<10;i++){

       cin>>arrays[i];

   }

   //call the function and check is true or not and display message

   if(isSorted(arrays)){

       cout<<"Array is Sorted"<<endl;

   }else{

       cout<<"Array is not Sorted"<<endl;

   }

   return 0;

}

Explanation:

Include the library for using the input/output instruction.

create the function 'isSorted' with one parameter arrays and return type id bool. It means the function returns the true or false.

then, declare the variable and check the condition using the if-else statement. if the array size is zero or one, it means the array is sorted. So, the function returns true. otherwise, the program executes the next statement.

After that, take a for loop and traversing the array, an if-else statement is used for checking the previous element is greater than the next element, if condition true, the function returns the false.

after the loop checked all the element and the loop does not return false. It means the array is sorted and the function returns true.

create the main function and declare the array with size 10.

print the message on the screen and then store the element in the array.

we take a for loop and it runs 10 times. so, the user enters the number for every cycle of loop and store in the array.

after that, calling the function with an if-else statement, as we know the function returns the Boolean. So, if the function returns true then if statement executes and print message otherwise else statement executes and prints the appropriate message.

ACCESS MORE