

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find largest element from array without using conditional operator in C++
Suppose we have an array A with some elements. We have to find the largest element in the array A, but the constraint is, we cannot use any conditional operator. So if A = [12, 63, 32, 24, 78, 56, 20], then maximum element will be 78.
To solve this problem, we will use the bitwise AND operation. at first we will insert one extra element INT_MAX (where all bit is 1) in array. Then we will try to find maximum AND value of any pair from the array. This obtained max value will contain AND value of INT_MAX and largest element of the original array, and this will be the result.
Example
#include <iostream> #include <vector> using namespace std; int checkBit(int pattern, vector<int> arr, int n) { int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count; } int findLargestElement(int arr[], int n) { vector<int> elements_vector(arr, arr + n); elements_vector.push_back(INT_MAX); n++; int res = 0; for (int bit = 31; bit >= 0; bit--) { int count = checkBit(res | (1 << bit), elements_vector, n); if ((count | 1) != 1) res |= (1 << bit); } return res; } int main() { int arr[] = {12, 63, 32, 24, 78, 56, 20}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Largest element is: " << findLargestElement(arr, n); }
Output
Largest element is: 78
- Related Questions & Answers
- Maximum of four numbers without using conditional or bitwise operator in C++
- C# Program to find the largest element from an array
- C# Program to find the largest element from an array using Lambda Expressions
- Conditional ternary operator ( ?: ) in C++
- C++ Program to Find Largest Element of an Array
- Program to find largest element in an array in C++
- Program to find the Largest Number using Ternary Operator in C++
- What is a Ternary operator/conditional operator in C#?
- Program to find remainder without using modulo or % operator in C++
- Find XOR of two number without using XOR operator in C++
- Find smallest and largest element from square matrix diagonals in C++
- Find the exact match in array without using the $elemMatch operator in MongoDB?
- Python Program to find largest element in an array
- Find size of array in C/C++ without using sizeof
- How to use the ?: conditional operator in C#?
Advertisements