C++ Write a function that takes in 3 arguments: a sorted array, size of the array, and an integer number. It should return the position where the integer value is found. In case the number does not exist in that array it should return the index where it should have been if it were present in this sorted array. Use pointer notation of arrays for this question.
CODE IN C++:
#include<iostream>
using namespace std;
int arg_function(int *arr,int size,int integer)
{
for(int i=0;i<size;i++)
{
if(arr[i]==integer) //searching if the integer is present in the
array
{
cout<<"The integer is present at index : " ;
return i;
}
}
for(int i =0;i<size;i++) //this loop is execute if we are not
able to find the number in the given array
{
if(arr[i]>integer) //checking the index at which the number
should have been present in the array
{
cout<<"Number not found and it should have been at index :
";
return i-1;
}
}
}
int main()
{
int size;
cout<<"Enter the size of array : ";
cin>>size;
cout<<endl;
int *arr = new int(size);
cout<<"Enter the sorted array : ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
cout<<endl;
int integer;
cout<<"Enter integer to be searched : ";
cin>>integer;
int index=arg_function(arr,size,integer);
cout<<index;
}
OUTPUT SNIPPET:
When number is present in the array:
When number is not present in the array:
Please give an upvote if you liked my solution
Thank you :)
Get Answers For Free
Most questions answered within 1 hours.