smallest value of array - c++

I'm trying to write a function that will return the smallest value of an array. So far I have this, but all it returns is 0.
I don't see how it would return 0 since I am using a for loop to cycle through the array. Perhaps it is not cycling through the arrays values as I would think it does. Can anyone elaborate on the logic and the fallacy in this code?
#include <iostream>
using namespace std;
int newArray[9] = {4,5,9,3,6,2,1,7,8};
int minArray()
{
int index = 1;
int minimum;
for (int i = 0; i < 9; i++)
{
if (newArray[i] > newArray[index])
{
minimum = newArray[index];
}
index++;
}
return minimum;
}
int main()
{
cout << "original array:\n ";
for (int i = 0; i < 9; i++)
{
cout << newArray[i] << ", ";
}
cout << "minimum value of array: ";
cout << minArray();
return 0;
}

A good idea might be to initialize minimum with an element in the array.
So:
minimum = newArray[0]
In your loop (pseudocode assuming you don't want the answer):
if: newArray[pos] < minimum
minimum = newArray[pos];

I'd do something like this:
#include <iostream>
int minArray(int a[], int size) {
if (size <= 0) return 0; //
int m = a[0];
for (int i = 1; i < size; ++i) {
if (a[i] < m) m = a[i];
}
return m;
}
int main() {
int a[] = { 4, 3, 6, 2 };
std::cout << minArray(a, 4);
return 0;
}

You should initialize minimum with some known value or with maximum integer value.
int minArray()
{
int minimum = newArray[0];
for (int i = 1; i < 9; i++)
{
if (minimum > newArray[i])
{
minimum = newArray[i];
}
}
return minimum;
}
And you are dealing wrong with index (actually you don't need it at all). Example of how index can be used instead of minimum:
int minArray()
{
int index = 0;
for (int i = 1; i < 9; i++)
{
if (newArray[index] > newArray[i])
{
index = i;
}
}
return newArray[index];
}
Both examples should work fine, but I recommend to use first.

The minimum variable should be initially assigned to a value in the array, then compare each element in the array with minimum. If less than, assign minimum with that value:
int minArray()
{
int minimum = newArray[0];
int index = 0;
for (int i = 0; i < 9; i++)
{
if (newArray[i] < minimum)
{
minimum = newArray[i];
}
index++;
}
return minimum;
}

Related

Find unique elements from the given array and print them

Question: Find unique elements from the given array and print them
I have dry run below given code many times but i am not getting what is the problem in the code.
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size)
{
int brray[100];
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++)
{
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++)
{
if (i != j && value == array[j])
{
equal = 1;
break;
}
}
if (equal == 0)
{
brray[i] = value;
count++;
}
}
for (int i = 0; i < count; i++)
{
cout << brray[i] << " ";
}
}
int main()
{
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
i was expecting as an output
1 5 3 7
but when i run the code, getting as output
1 1877357483 1878039440 5
Welcome to SO! Here is the code modified by me:
#include <cstring>
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size) {
int brray[100];
memset(brray, 0, 100); // modified here
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++) {
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++) {
if (i != j && value == array[j]) {
equal = 1;
break;
}
}
if (equal == 0) {
brray[i] = value;
count++;
}
}
for (int i = 0; i < size; i++) { // modified here
if (brray[i] != 0) // modified here
cout << brray[i] << " ";
}
}
int main() {
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
I modified three places in your code:
You should initialize brray when you declare it, the strange values output are because they were in the memory when you defined brray, you should clean the memory before you use it.
The way you store unique number in brray is not very correct, when array[i] is not unique, you will add i, which leave 0 at brray[i], so to fit your code, you should make i from 0 to size. To get more clear about what I'm talking about, you can check the memory of brray.
Since I assume there is no 0 in your test data, so if there is a 0 in barray, you know it is not a valid value, just skip it. Also, you can use a more elegant way to do this, like #Anand Sowmithiran commented:
int brray[100];
memset(brray, 0, 100);
int count = 0;
for (/* conditions... */) {
// if there is a unique number
brray[count++] = unique_number;
}
for (int index = 0; index < count; index++) {
cout << brray[index] << " ";
}
Hope my answer is helpful!

find frequency in array using vector

How can I change my code to get a count for every element?
With my code everything is okay. And it works, but how can I change only that part?
#include <iostream>
#include <vector>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (visited[i] == true)
continue;
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++){
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
And about the result`
input 10
1 1 2 2 3 3 4 4 5 5
output 2 2 2 2 2
but I want to get
output 2 2 2 2 2 2 2 2 2 2
(for every element)
Your function contains extra code that ends up confusing you. The visited variable is essentially unnecessary. Start the count at 0 and make no special case for the "current" cell and you'll find that some very simple code will do what you need:
void countFreq(int arr[], int n)
{
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Count frequency
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
std::cout << count << " ";
}
}
You need to save the result to an array for each number. Then when you find any processed number then print counter from the saved array.
#include <iostream>
#include <vector>
#include <unordered_map>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
std::unordered_map<int, int> counter;
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
{
// Skip this element if already processed
if (visited[i] == true)
{
std::cout << counter[arr[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
visited[j] = true;
count++;
}
}
counter[arr[i]] = count;
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++)
{
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
The issue is that you discard the values already visited.
One possibility is instead to memorize the count when the value is visited the first time,
and to memorize the index value of the first value appearance, when a value is visited the 2nd, 3rd ... time.
#include <iostream>
#include <vector>
void countFreq(const std::vector<int>& arr) {
int n = arr.size();
// Mark all array elements as not visited
std::vector<int> mem_count(n, n);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (mem_count[i] != n) {
std::cout << mem_count[mem_count[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
mem_count[j] = i;
count++;
}
}
mem_count[i] = count;
std::cout << count << " ";
}
}
int main() {
int n;
std::cin>>n;
std::vector<int> arr(n);
for(int i = 0; i < n; i++){
std::cin >> arr[i];
}
countFreq(arr);
return 0;
}
You can find the frequencies of numbers this way if you know the what is your maximum element in the input array. lets say m is maximum number in your array.
so you have to create a new array of size m. you can simply co-relate them as m buckets. from 0 to m. And each bucket will hold the count of each element in the input array. The index of each bucket will refer to element in the input array. This has time complexity O(1) if we know what is the max element the array.
You can do this way:
std::vector<int> frequencey(std::vector<int>& nums){
auto max = *(std::max_element(nums.begin(), nums.end()));
std::vector<int> frequencies(max + 1, 0);
for(int i = 0; i < nums.size(); ++i){
frequencies[nums[i]] +=1;
}
return frequencies;
}
This is very simple
#include <vector>
#include <map>
#include <iostream>
void main()
{
std::vector<int> v { 1,1,2,2,3,3,4,4,5,5 }; // Your input vector
// Count "frequencies"
std::map<int, int> m;
for (auto i : v)
m[i]++;
// Print output
for (auto i : v)
std::cout << m[i] << " ";
}

Sorting through array c++

So I am attempting to do a bubble-like sort. Not a bubble sort because I don't want to exchange every single value that i run into. I simply want to find the smallest value of each index and place it in order. Such as in the arrayVal[3, 5, 2].
Instead of replacing the value 3 with 2 and then replacing 5 with 3. I want to find the smallest number of the entire array and place it at arrayVal[0] and then move to arrayVal[1].
I can't quite figure out how to do this and am kind of stuck.(I took out the <> on the libraries so you could see which libraries I am using)
#include iostream
#include cmath
#include ctime
using namespace std;
int main()
{
const int STARTLOOP = 0;
const int MAXLOOP = 5;
const int MINRANGE = 1;
const int MAXRANGE = 10;
//int temp = 0;
int smallestVal = 0;
int arrayVal[MAXLOOP];
srand(time(0));
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
}
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
cout << arrayVal[i] << endl;
}
cout << "Before the sort" << endl;
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
for (int j = i; j < MAXLOOP; j++)
{
if (arrayVal[j] < arrayVal[i])
{
arrayVal[i] = smallestVal;
}
}
}
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
cout << arrayVal[i] << endl;
}
cout << "After the sort" << endl;
return 0;
I also recognize I'm not using functions, i just wrote up the code because I was trying to figure this out. Thank you in advance.
You're never setting smallestVal to anything from the array. You don't need nested loops. Just go through the array once, comparing each value to smallestVal. If it's smaller, you set smallestVal to that value. You should also have a variable that holds the index of the smallest value, which you update at the same time.
At the end, you swap the first element with the smallest one.
int smallestVal = arrayVal[STARTLOOP];
int smallestIndex = STARTLOOP;
for (int i = STARTLOOP + 1; i < MAXLOOP; i++) {
if (arrayVal[i] < smallestVal) {
smallestVal = arrayVal[i];
smallestIndex = i;
}
}
if (smallestIndex != STARTLOOP) {
// swap it with the first element
int temp = arrayVal[STARTLOOP];
arrayVal[STARTLOOP] = smallestVal;
arrayVal[smallestIndex] = temp;
}
You can then increment STARTLOOP and repeat this.
What you want to achieve is some sort of a modified insertion sort. Check out this implementation :
void sort(int values[], int n)
{
for (int i = 0; i < n; ++i)
{
int min = i;
for ( int j = i ; j < n ; j++)
{
if (values[j]<values[min]) min =j;
}
while(values[min-1]>values[min])
{
if(min==0)
break;
if(values[min-1]!=values[min])
swap (values+min-1,values+min);
min--;
}
}
return;
}
What this function does is that it searches the array every time for the smallest element starting from index i and when it finds this element it keeps on swapping it will all of the previous elements in the array until it reaches a smaller element.

Finding the maximum value of every row in 2D array C++

I've managed to find the minimum value of every row of my 2D array with this
void findLowest(int A[][Cm], int n, int m)
{
int min = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] < min)
{
min = A[i][j];
}
}
out << i << " row's lowest value " << min << endl;
}
}
I'am trying to find the maximum value of every row using the same way,but it only shows me first maximum value
void findHighest(int A[][Cm], int n, int m)
{
int max = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
out << i << " row's highest value " << max << endl;
}
}
I can't find what's wrong with the second function and why is it only showing me the first maximum value it finds. Any help ?
Both functions return the result (maximum or minimum) for the whole array rather than each row, because you set max once rather than once per row. You can get the result for each row as follows:
void findHighest(int A[][Cm], int n, int m)
{
for (int i = 0; i < n; i++)
{
int max = A[i][0];
for (int j = 1; j < m; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
// do something with max
}
}
or, even better, use the standard library function max_element:
void findHighest(int A[][Cm], int n, int m)
{
if (m <= 0) return;
for (int i = 0; i < n; i++)
{
int max = *std::max_element(A[i], A[i] + m);
// do something with max
}
}
This should give you all values which is easy to check:
#include <algorithm>
#include <iostream>
enum { Cm = 2 };
void findHighest(int A[][Cm], int n, int m) {
if (m <= 0) return;
for (int i = 0; i < n; i++) {
int max = *std::max_element(A[i], A[i] + m);
std::cout << max << " ";
}
}
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
findHighest(A, 2, 2);
}
prints 2 4.
If your compiler supports C++11, for concrete arrays you could use the following alternative, that's based on std::minmax_element:
template<typename T, std::size_t N, std::size_t M>
void
minmax_row(T const (&arr)[N][M], T (&mincol)[N], T (&maxcol)[N]) {
for(int i(0); i < N; ++i) {
auto mnmx = std::minmax_element(std::begin(arr[i]), std::end(arr[i]));
if(mnmx.first != std::end(arr[i])) mincol[i] = *(mnmx.first);
if(mnmx.second != std::end(arr[i])) maxcol[i] = *(mnmx.second);
}
}
Live Demo
Your test data is guilty for not clearly showing you the defect.
The row minima occur in decreasing values, so that they get updated on every row.
And the row maxima also occur in decreasing values, so that the first one keeps winning.
As others pointed, your function finds the global minimum/maximum, no the per-row extrema.
Move the initialization of the min/max variable inside the outer loop.
As mentioned your code only shows the maximum element in the whole array.
Here is the code which will help you.
void findHighest(int A[][Cm], int n, int m)
{
int max[n];
max[0]=A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] > max[i])
{
max[i] = A[i][j];
}
}
cout << i << " row's highest value " << max[i] << endl;
}
}
{
int i,j;
int arr[4][2]={(1,2),(3,4),(5,6),(7,8)};
int max;
max=arr[0][0];
for( int i=0; i<4; i++)
{
for(int j=0; j<2; j++)
{
if(max<arr[i][j])
{
max=arr[i][j];
}
}
}
int min;
min=arr[0][0];
for(int i=0; i<4; i++)
{
for(int j=0; j<2; j++)
{
if(min>arr[i][j])
{
min=arr[i][j];
}
}
}
cout<<"maximum number is:"<<max;
cout<<endl;
cout<<"Minimum Number is:"<<min;
}

C++ for loop array assignment. Getting junk returned

I'm trying to generate LIMIT (lets say limit = 1000) prime numbers and store them to an array, but I get junk returned. Here's my code:
#include <iostream>
using namespace std;
void prime_num(int);
int main()
{
int primes[1000];
int n, p, t, LIMIT = 1000;
for(n=2; n <= LIMIT; n++)
{
t=0;
for(p=2; p <= n/2; p++)
{
if (n%p == 0)
{
t = 1;
break;
}
}
if(!t)
primes[p-2] = n;
}
for (int i = 0; i < LIMIT; i++)
cout << primes[i] <<" ";
return 0;
}
Define a variable outside the outer loop:
int count=0;
and then use it here:
primes[count++] = n;
then print as:
for (int i = 0; i < count; i++)
cout << primes[i] <<" ";
Explanation:
You're not generating 1000 prime numbers, rather you're generating all prime numbers less than or equal to 1000.
As #Jerry Coffin commented, your code should be like this:
Note : I'm not talking about correctness, rather the skeleton of the program; so you decide if is_prime() function is correct or not, optimized or not, etc.
bool is_prime(int n)
{
for(int p=2; p <= n/2; p++)
{
if (n%p == 0)
{
return false;
}
}
return true;
}
int main()
{
int primes[1000];
int n, p, t, LIMIT = 1000;
int count=0;
for(n=2; n <= LIMIT; n++)
{
if (is_prime(n) )
primes[count++] = n;
}
for (int i = 0; i < count; i++)
cout << primes[i] <<" ";
return 0;
}
Correctness and Optimization of is_prime():
Now you decide the correctness of is_prime(). Is it correctly written? Is it optimized? Do you really need to check for all integers in the range [2,n/2]?