So, I tried to make an array using input first, then sorting it out from smallest to biggest, then display the array to monitor.
So I come up with this code :
#include <iostream>
using namespace std;
void pancakeSort(int sortArray[], int sortSize);
int main()
{
// Input The Array Element Value
int pancake[10];
for(int i=0; i<10; i++)
{
cout << "Person " << i+1 << " eat pancakes = ";
cin >> pancake[i];
}
// call pancake sorting function
pancakeSort(pancake, 10);
}
void pancakeSort(int sortArray[], int sortSize)
{
int length = 10;
int temp;
int stop = 10;
// this is where the array get sorting out from smallest to biggest number
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
// after that, the array get display here
for(int x=0; x<sortSize; x++)
{
cout << sortArray[x] << " ";
}
}
but the output is weird :
enter image description here
the function is successfully sorting the array from smallest to biggest,
but there is 2 weird things :
1. The biggest value element (which is 96 from what I input and it's the 10th element after got sorted out), disappear from the display.
2. For some reason, there is value 10 , which I didn't input on the array.
So, what happened?
In the loop
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop is the length of the array, and you are iterating through values of j = 0 to stop - 1. When j reaches stop - 1, the next element that is j+1 becomes stop (10 in this case). But since your array has a length of 10, sortArray[10] is not part of the array, but is referring to some other object in memory which is usually a garbage value. The garbage value is 10 in this case. When you swap sortArray[10] and sortArray[9], the garbage value becomes part of the array and the value at index 9 leaves the array. This keeps on happening till the outer loop ends.
The end result is that unless the garbage value < largest element in the array, the garbage value is pushed in the array and the greatest value of the array is put at sortArray[10] which is not part of the array. If the garbage value is greater than all the values of the array, it'll be found at sortArray[10] which is again not part of the array and your code will return the desired result.
Essentially, what you are doing is giving the function an array of 10 (or stop) elements, but the function is actually working with an array of 11 (or stop + 1) elements, with the last element being a garbage value. The simple fix is to change the conditional of the loop to j < stop - 1.
Note that if you had written this code in a managed (or a comparatively higher level) language like Java or C#, it would have raised an IndexOutOfBoundsException.
At index 9, j+1 is out of bounds. So to fix this, you only need to check till index 8
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop-1; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
Look carefully at the inner loop condition j<stop-1
Related
let's say I have an array
arr[5]={5,2,3,2,5} and i wrote following program for it
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter Length of Elements= ";
cin>>n;
int arr[50];
for(int i=0;i<n;i++)
{
cout<<"Enter Number=";
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
int countNum=1;
for(int j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
if(i>0)
{
int countNum2=0;
for(int k=0;k>i;k++)
{
//bool repeat=false;
if(arr[i]==arr[k])
{
//repeat=false;
}
else
{
countNum2++;
}
}
if(countNum2==i)
{
countNum++;
}
}
else
{
countNum++;
}
}
else
{
for(int k=0;k<i;k++)
{
if(arr[k]==arr[i])
{
}
else
{
countNum=1;
}
}
}
}
cout<<arr[i]<<" has appeared "<<countNum<< "Times"<<endl;
}
return 0;
}
but why I am getting
5 has appeared 2 Times
2 has appeared 1 Time
3 has appeared 1 Time
2 has appeared 1 Time
5 has appeared 1 Time
instead of
5 has appeared 2 Times
2 has appeared 2 Times
3 has appeared 1 Times
so how to fix my program
help!
That's what you exactly need (amount of each number in array):
// we'll store amounts of numbers like key-value pairs.
// std::map does exactly what we need. As a key we will
// store a number and as a key - corresponding counter
std::map<int, size_t> digit_count;
// it is simpler for explanation to have our
// array on stack, because it helps us not to
// think about some language-specific things
// like memory management and focus on the algorithm
const int arr[] = { 5, 2, 3, 2, 5 };
// iterate over each element in array
for(const auto elem : arr)
{
// operator[] of std::map creates default-initialized
// element at the first access. For size_t it is 0.
// So we can just add 1 at each appearance of the number
// in array to its counter.
digit_count[elem] += 1;
}
// Now just iterate over all elements in our container and
// print result. std::map's iterator is a pair, which first element
// is a key (our number in array) and second element is a value
// (corresponding counter)
for(const auto& elem : digit_count) {
std::cout << elem.first << " appeared " << elem.second << " times\n";
}
https://godbolt.org/z/_WTvAm
Well, let's write some basic code, but firstly let's consider an algorithm (it is not the most efficient one, but more understandable):
The most understandable way is to iterate over each number in array and increment some corresponding counter by one. Let it be a pair with the first element to be our number and the second to be a counter:
struct pair {
int number;
int counter;
};
Other part of algorithm will be explained in code below
// Say that we know an array length and its elements
size_t length = // user-defined, typed by user, etc.
int* arr = new int[length];
// input elements
// There will be no more, than length different numbers
pair* counts = new pair[length];
// Initialize counters
// Each counte will be initialized to zero explicitly (but it is not obligatory,
// because in struct each field is initialized by it's default
// value implicitly)
for(size_t i = 0; i < length; i++) {
counts[i].counter = 0;
}
// Iterate over each element in array: arr[i]
for(size_t i = 0; i < length; i++)
{
// Now we need to find corresponding counter in our counters.
size_t index_of_counter = 0;
// Corresponding counter is the first counter with 0 value (in case when
// we meet current number for the first time) or the counter that have
// the corresponding value equal to arr[i]
for(; counts[index_of_counter].counter != 0 && counts[index_of_counter].number != arr[i]; index_of_counter++)
; // Do nothing here - index_of_counter is incrementing in loop-statement
// We found an index of our counter
// Let's assign the value (it will assign a value
// to newly initialized pair and won't change anything
// in case of already existing value).
counts[index_of_counter].number = arr[i];
// Increment our counter. It'll became 1 in case of new
// counter, because of zero assigned to it a bit above.
counts[index_of_counter].counter += 1;
}
// Now let's iterate over all counters until we reach the first
// containing zero (it means that this counter and all after it are not used)
for(size_t i = 0; i < length && counts[i].counter > 0; i++) {
std::cout << counts[i].number << " appeared " << counts[i].counter << " times\n";
}
// correctly delete dynamically allocated memory
delete[] counts;
delete[] arr;
https://godbolt.org/z/hN33Pn
Moreover it is exactly the same solution like with std::map (the same idea), so I hope it can help you to understand, how the first solution works inside
The problem with your code is that you don't remove the duplicates or assign an array which effectively stores the count of each unique element in your array.
Also the use of so many loops is completely unnecessary.
You just need to implement two loops, outer one going through all the elements and the inner one checking for dupes first (using an array to check frequency/occurence status) and counting appearance of each element seperately with a variable used as a counter.
Set a counter array (with the corresponding size of your taken array) with a specific value (say zero) and change that value when same element occurs while traversing the array, to trigger not to count for that value again.
Then transfer the count value from the counter variable to the counter array (the one which we set and which distinguishes between duplicates) each time the inner loop finishes iterating over the whole array. (i.e. place it after the values are counted)
With a little bit of modification, your code will work as you would want it to:
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter Length of Elements = ";
cin>>n;
int arr[50];
for(int i=0;i<n;i++)
{
cout<<"Enter Number = ";
cin>>arr[i];
}
int counter[50];
for(int i=0; i<n; i++)
counter[i]=0;
// Our counter variable, but counts will be transferred to count[] later on:
int tempcount;
for(int i=0; i<n; i++)
{ // Each distinct element occurs once atleast so initialize to one:
tempcount = 1;
for(int j=i+1; j<n; j++)
{
// If dupe is found:
if(arr[i]==arr[j])
{
tempcount++;
// Ensuring not to count frequency of same element again:
counter[j] = 1;
}
}
// If occurence of current element is not counted before:
if(counter[i] != 1)
counter[i] = tempcount;
}
for(int i=0; i<n; i++)
{
if(counter[i] != 0)
printf("%d has appeared %d times.\n", arr[i], counter[i]);
}
return 0;
}
I used a variable tempcount to count occurence of each element and a zero-initialized array count to get the dupes checked (by setting it to 1 for a duplicate entry, and not counting it if it qualifies as 1) first. Then I transferred the counted occurence values to counter[] from tempcount at each outer loop iteration. (for all the unique elements)
I was given the integers 15, 16, 17 ,18 ,19 and 20.
I am supposed to put only the numbers divisible by 4 into a vector and then display the values in the vector.
I know how to do the problem using arrays but I'm guessing I don't know how to properly use pushback or vectors.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> arrmain; int i,j;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
//output the elements in the vector
for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}
}
}
return 0;
}
wanted output: Numbers divisible by 4: 16, 20
As already mentioned in the comments, you have a couple of problems in your code.
All which will bite you in the end when writing more code.
A lot of them can be told to you by compiler-tools. For example by using -Weverything in clang.
To pick out the most important ones:
source.cpp:8:10: warning: declaration shadows a local variable [-Wshadow]
for (int i = 15; i <=20 ; i++)
and
source.cpp:6:26: warning: unused variable 'i' [-Wunused-variable]
vector arrmain; int i,j;
Beside those, you have a logical issue in your code:
for values to check
if value is ok
print all known correct values
This will result in: 16, 16, 20 when ran.
Instead, you want to change the scope of the printing so it doesn't print on every match.
Finally, the bug you are seeing:
for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}
This bug is the result of poor naming, let me rename so you see the problem:
for(innercounter=0; innercounter<=arrmain.size(); innercounter++)
{
cout <<arrmain[outercounter]<< " "<<endl;
}
Now, it should be clear that you are using the wrong variable to index the vector. This will be indexes 16 and 20, in a vector with max size of 2. As these indexes are out-of-bounds for the vector, you have undefined behavior. When using the right index, the <= also causes you to go 1 index out of the bounds of the vector use < instead.
Besides using better names for your variables, I would recommend using the range based for. This is available since C++11.
for (int value : arrmain)
{
cout << value << " "<<endl;
}
The main issues in your code are that you are (1) using the wrong variable to index your vector when printing its values, i.e. you use cout <<arrmain[i] instead of cout <<arrmain[j]; and (2) that you exceed array bounds when iterating up to j <= arrmain.size() (instead of j < arrmain.size(). Note that arrmain[arrmain.size()] exceeds the vector's bounds by one because vector indices are 0-based; an vector of size 5, for example, has valid indices ranging from 0..4, and 5 is out of bounds.
A minor issue is that you print the array's contents again and again while filling it up. You probably want to print it once after the first loop, not again and again within it.
int main()
{
vector<int> arrmain;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
}
}
//output the elements in the vector
for(int j=0; j<arrmain.size(); j++)
{
cout <<arrmain[j]<< " "<<endl;
}
return 0;
}
Concerning the range-based for loop mentioned in the comment, note that you can iterate over the elements of a vector using the following abbreviate syntax:
// could also be written as range-based for loop:
for(auto val : arrmain) {
cout << val << " "<<endl;
}
This syntax is called a range-based for loop and is described, for example, here at cppreference.com.
After running your code, I found two bugs which are fixed in code below.
vector<int> arrmain; int i, j;
for (int i = 15; i <= 20; i++)
{
//checking which numbers are divisible by 4
if (i % 4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
//output the elements in the vector
for (j = 0; j < arrmain.size(); j++) // should be < instead of <=
{
cout << arrmain[j] << " " << endl; // j instead of i
}
}
}
This code will output: 16 16 20, as you are printing elements of vector after each insert operation. You can take second loop outside to avoid doing repeated operations.
Basically, vectors are used in case of handling dynamic size change. So you can use push_back() if you want to increase the size of the vector dynamically or you can use []operator if size is already predefined.
I'm a Computer Science student. This is some code that I completed for my Data Structures and Algorithms class. It compiles fine, and runs correctly, but there is an error in it that I corrected with a band-aid. I'm hoping to get an answer as to how to fix it the right way, so that in the future, I know how to do this right.
The object of the assignment was to create a binary search. I took a program that I had created that used a heap sort and added a binary search. I used Visual Studio for my compiler.
My problem is that I chose to read in my values from a text file into an array. Each integer in the text file is separated by a tabbed space. In line 98, the file reads in correctly, but when I get to the last item in the file, the counter (n) counts one time too many, and assigns a large negative number (because of the array overflow) to that index in the array, which then causes my heap sort to start with a very large negative number that I don't need. I put a band-aid on this by assigning the last spot in the array the first spot in the array. I have compared the number read out to my file, and every number is there, but the large number is gone, so I know it works. This is not a suitable fix for me, even if the program does run correctly. I would like to know if anyone knows of a correct solution that would iterate through my file, assign each integer to a spot in the array, but not overflow the array.
Here is the entire program:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
#define MAXSIZE 100
void heapify(int heapList[], int i, int n) //i shows the index of array and n is the counter
{
int listSize;
listSize=n;
int j, temp;//j is a temporary index for array
temp = heapList[i];//temporary storage for an element of the array
j = 2 * i;//end of list
while (j <= listSize)
{
if (j < listSize && heapList[j + 1] > heapList[j])//if the value in the next spot is greater than the value in the current spot
j = j + 1;//moves value if greater than value beneath it
if (temp > heapList[j])//if the value in i in greater than the value in j
break;
else if (temp <= heapList[j])//if the value in i is less than the value in j
{
heapList[j / 2] = heapList[j];//assigns the value in j/2 to the current value in j--creates parent node
j = 2 * j;//recreates end of list
}
}
heapList[j / 2] = temp;//assigns to value in j/2 to i
return;
}
//This method is simply to iterate through the list of elements to heapify each one
void buildHeap(int heapList[], int n) {//n is the counter--total list size
int listSize;
listSize = n;
for (int i = listSize / 2; i >= 1; i--)//for loop to create heap
{
heapify(heapList, i, n);
}
}
//This sort function will take the values that have been made into a heap and arrange them in order so that they are least to greatest
void sort(int heapList[], int n)//heapsort
{
buildHeap(heapList, n);
for (int i = n; i >= 2; i--)//for loop to sort heap--i is >= 2 because the last two nodes will not have anything less than them
{
int temp = heapList[i];
heapList[i] = heapList[1];
heapList[1] = temp;
heapify(heapList, 1, i - 1);
}
}
//Binary search
void binarySearch(int heapList[], int first, int last) {//first=the beginning of the list, last=end of the list
int mid = first + last / 2;//to find middle for search
int searchKey;//number to search
cout << "Enter a number to search for: ";
cin >> searchKey;
while ((heapList[mid] != searchKey) && (first <= last)) {//while we still have a list to search through
if (searchKey < heapList[mid]) {
last = mid - 1;//shorten list by half
}
else {
first = mid + 1;//shorten list by half
}
mid = (first + last) / 2;//find new middle
}
if (first <= last) {//found number
cout << "Your number is " << mid << "th in line."<< endl;
}
else {//no number in list
cout << "Could not find the number.";
}
}
int main()
{
int j = 0;
int n = 0;//counter
int first = 0;
int key;//to prevent the program from closing
int heapList[MAXSIZE];//initialized heapList to the maximum size, currently 100
ifstream fin;
fin.open("Heapsort.txt");//in the same directory as the program
while (fin >> heapList[n]) {//read in
n++;
}
heapList[n] = heapList[0];
int last = n;
sort(heapList, n);
cout << "Sorted heapList" << endl;
for (int i = 1; i <= n; i++)//for loop for printing sorted heap
{
cout << heapList[i] << endl;
}
binarySearch(heapList, first, last);
cout << "Press Ctrl-N to exit." << endl;
cin >> key;
}
int heapList[MAXSIZE];//initialized heapList to the maximum size, currently 100
This comment is wrong - heapList array is declared not initialized, so when you had read all data from the file, index variable n will point to the uninitialized cell. Any attempt to use it will invoke an undefined behavior. You could either: initialize an array before using it, decrement n value, since it greater than read values number by one, or better use std::vector instead of array.
You populate values for heapsort for indices 0 to n-1 only.
Then you access heaplist from 1 to n which is out of bounds since no value was put in heapsort[n].
Use
for (int i = 0; i < n; i++) //instead of i=1 to n
Question is: write a function that takes an array A of length n and an index i into A, and rearrange the elments such that all elements less than A[i] appear first, followed by elements equal to A[i], followed by elements greater than A[i].
explanation for my code:
Ask user for n numbers, which is 11. And ask him what the index that he wants to rearrange the elements with. It takes it to function1, and creates a for loop and does an if else statement. if A[i] < A{index} , place it in the begining, else if it's less, place it at the end, or place it in the middle:
Here is my code
#include <iostream>
using namespace std;
void function1(int a[], int ind);
int main()
{
int a[11];
int index;
cout << " enter the numbers: " << endl;
for(int i=0; i < 11; i++)
cin >> a[i];
cout << "what is the index ? " << endl;
cin >> index;
function1(a,index);
}
void function1(int a[], int ind)
{
int x = a[ind];
int newArray[11];
for(int i=0; i < 11; i++)
{
if(a[i] < x)
{
newArray[i] = a[i];
}
else if(a[i] > x)
{
newArray[10-i] = a[i];
}
else
{
newArray[10/2] = a[i];
}
}
for(int i=0; i<11; i++)
cout << newArray[i] << " ";
}
The output that I am expecting to get is the rearrangement of the new array which will probably look similar to this:
a[0....x....n-1], where x is the index that represents a[i]
however I am getting incorrect output with numbers randomly scattered across
what is wrong with my logic ?
The problem is that (like Olaf Dietsche pointed out) you take just one index where two are necessary. Further you can't know if the element that is neither smaller not bigger than a[ind] (means equal to a[ind]) is to be inserted in the middle of the new array. (Imagine 3 2 1 and index 3 results in 2 1 3 but 3 isn't in the middle!)
Updated Version (allows for multiple elements with same value as pivot element)
void rearange(int* data, int size, int pivot)
{
int* temp_data = new int[size];
int start_index = 0, end_index = size - 1;
for (int i = 0; i < size; i++)
{
if (data[i] < data[pivot]) // -> insert 'before' pivot element
{
temp_data[start_index] = data[i];
start_index++;
}
else if (data[i] > data[pivot]) // -> insert 'behind' pivot element
{
temp_data[end_index] = data[i];
endIndex--;
}
// else: skip pivot(s)
}
// insert pivot element(s)
for (int i = start_index; i <= end_index; i++)
{
temp_data[i] = data[pivot];
}
for (int i = 0; i < size; i++)
{
std::cout << temp_data[i] << " ";
}
delete[] temp_data;
}
Input:
11 10 9 8 7 7 7 6 5 4 3
5
Output
6 5 4 3 7 7 7 8 9 10 11
As you see, all elements smaller than element 5 (with value of 7) are before, all elements greater are behind the pivot element. All other elements with same value as pivot are wrapped around position 5, wherever there's free space. However the rearranged elements are not yet sorted (apart from being positioned relative to pivot element)!
You use the same index i for the smaller and larger values. This means, if only the last value a[10] is larger than x, you will write it in the first location newArray[10 - 10], even though you already filled all places up to the 10th. Another problem is, when you have multiple middle values. They will all be stored into newArray[5].
What you want to achieve is called partitioning, as used in the quicksort algorithm.
You need to maintain two indexes (pointers), one for the smaller (left) and one for the larger (right) values.
You have to determine the size of your array at the beginning and pass the fixed size of the array to the function as a parameter.
I have no idea what to do. Please help me with code or tell me what textbook to look up or something; I need code to finish this program and I would love an explanation of what I'm looking at..
#include<iostream>
using namespace std;
int main()
{
short num[100], size, //declare an array of type short that has 100 elements
unique[100], number, // declare a second array to help solve the problem; number counts the number of unique values
k; // loop control variable; may need other variables
cout<<"enter the number of values to store in the array\n";
cin>>size;
cout<<”enter the “<<size<<” values to be used as data for this program\n”;
for(k=0; k<size; k++)
cin>>num[k];
// print the contents of the array
cout<<"\nthere are "<<size<<" values in the array\n";
for(k=0; k<size; k++)
cout<<num[k]<<’ ‘; // there is one space between each number in the display
cout<<endl; // cursor moved to next output line
cout<<"the program will count the number of different (distinct) values found in the array\n";
//************************************************************
//Put the code here that counts the number of unique values stored in the
//array num. The variable number will contain the count.
//************************************************************
cout<<endl<<number<<" unique values were found in the "<<size<<" element array\n";
// pause the program to see the results
system("pause");
//return 0;
}
I have to do one of these two things and I don't know what they mean?
Algorithm – unique array is used to help find the solution, used to avoid counting any value more than one time
Set number to 0 - this represents the number of distinct values in the data set; also used as a subscript in the unique array
Loop from 0 to size by one, proceeding through successive elements of the data (num) array
Store value of current array element in non-array variable (SV)
Set event_flag to 0
Loop from 0 to number by one, proceeding through successive elements of unique array
If SV is equal to current element of unique array
Set event_flag to 1
Break (stop) inner loop
End of inner loop
If event_flag is equal to 0 (value not found in unique array and not previously counted)
Store SV in element number of unique array
Increment the value of number
End of outer loop
Solution – the variable number contains the count of distinct values in the data array
Alternate Algorithm
Algorithm that does not use the event_flag (loop control variable can be used to determine if event occurred)
Algorithm – unique array is used to help find the solution, used to avoid counting any value more than one time
Set number to 0 - this represents the number of distinct values in the data set; also used as a subscript in the unique array
Loop from 0 to size by one, proceeding through successive elements of the data (num) array
Store value of current array element in non-array variable (SV)
Loop from 0 to number by one, proceeding through successive elements of unique array
If SV is equal to current element of unique array
Break (stop) inner loop
End of inner loop
If loop control variable of inner loop is equal to value of number (SV not found in unique array and not previously counted)
Store SV in element number of unique array
Increment the value of number
End of outer loop
Solution – the variable number contains the count of distinct values in the data array
I put this in mine:
//************************************************************
//Put the code here that counts the number of unique values stored in the array num. The variable number will contain the count.
for(k=0; k<size; k++)
num=SV;
event_flag=0;
for(k=1; k<number; k++)
if(SV=unique)
return true;
return false;
//************************************************************
It's not working, obviously.
This is my code, it seems to work
//************************************************************
//Put the code here that counts the number of unique values
//stored in the array num. The variable number will contain the count.
number = 0;
for (k = 0; k < size; ++k)
{
short sv = num[k];
short event_flag = 0;
for (int i = 0; i < number; ++i)
{
if (sv == unique[i])
{
event_flag = 1;
break;
}
}
if (event_flag == 0)
{
unique[number] = sv;
++number;
}
}
For the alternative ,
his is my code, it seems to work
//************************************************************
//Put the code here that counts the number of unique values
//stored in the array num. The variable number will contain the count.
number = 0;
for (k = 0; k < size; ++k)
{
short sv = num[k];
int i;
for (i = 0; i < number; ++i)
if (sv == unique[i])
break;
if (number == i)
{
unique[number] = sv;
++number;
}
}
You are roughly asked to do the following:
#include <iostream>
using namespace std;
int main()
{
// This is the given array.
int given_array[5] = { 1, 1, 2, 2, 3 };
// This is the array where unique values will be stored.
int unique_array[5];
// This index is used to keep track of the size
// (different from capacity) of unique_array.
int unique_index = 0;
// This is used to determine whether we can
// insert an element into unique_array or not.
bool can_insert;
// This loop traverses given_array.
for (int i = 0; i < 5; ++i)
{
// Initially assume that we can insert elements
// into unique_array, unless told otherwise.
can_insert = true;
// This loop traverses unique_array.
for (int j = 0; j < unique_index; ++j)
{
// If the element is already in unique_array,
// then don't insert it again.
if (unique_array[j] == given_array[i])
{
can_insert = false;
break;
}
}
// This is the actual inserting.
if (can_insert)
{
unique_array[unique_index] = given_array[i];
unique_index++;
}
}
// Tell us how many elements are unique.
cout << unique_index;
return 0;
}
Try out this one...
You can insert cout statements wherever required.
#include <iostream>
using namespace std;
int main()
{
int Input[100], Unique[100], InSize, UniLength = 0;
cin >> InSize;
for (int ii = 0 ; ii < InSize ; ii++ )
{
cin >> Input[ii];
}
Unique[0] = Input[0];
UniLength++;
bool IsUnique;
for ( int ii = 1 ; ii < InSize ; ii++ )
{
IsUnique=true;
for (int jj = 0 ; jj < UniLength ; jj++ )
{
if ( Input[ii] == Unique[jj] )
{
IsUnique=false;
break;
}
}
if ( IsUnique )
{
Unique[UniLength] = Input[ii];
UniLength++;
}
}
cout<<"We've "<<UniLength<<" Unique elements and We're printing them"<<endl;
for ( int jj = 0 ; jj < UniLength ; jj++ )
{
cout << Unique[jj] << " ";
}
}
I hope this is what you were looking for.....
Have a nice day.
Here is my approach. Hope so it will helpful.
#include<iostream>
#include<algorithm>
int main(){
int arr[] = {3, 2, 3, 4, 1, 5, 5, 5};
int len = sizeof(arr) / sizeof(*arr); // Finding length of array
std::sort(arr, arr+len);
int unique_elements = std::unique(arr, arr+len) - arr;
std::cout << unique_elements << '\n'; // The output will 5
return 0;
}