#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main() {
srand(time(NULL));
while (1) {
int n;
bool check_dup = false;
cout << "Please enter a number: ";
cin >> n;
if (n < 2) {
cout << "Wrong number!!!" << endl;
break;
}
cout << "Size of random array: " << n / 2 << endl;
int* arr = new int[n / 2];
cout << "[ Array ]" << endl;
for (int i = 0; i < n/2 / n; i++) {
arr[i] = rand() % n + 1;
cout << arr[i];
}
for (int i = 0; i < n/2; i++) {
for (int j = i+1; j < n/2; j++) {
if (arr[i] == arr[j])
check_dup = true;
}
}
if (check_dup) cout << "Duplicates found" << endl;
else cout << "Duplicates not found" << endl;
delete[] arr;
}
return 0;
}
After inputting n, we dynamically allocated an n / 2 size array and then stored a random number. And when I run it, the rest works fine, but it only outputs the arr value. Where is wrong?
Related
I'm a C++ newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C++ knowledge, so no advanced functions. Here's my code:
#include <iostream>
using namespace std;
int main()
{
int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++) {
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++) {
if (vector[i] % 2 == 0) {
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0) {
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++) {
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++) {
cout << " " << odd[i] << " ";
cout << endl;
}
return 0;
}
If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:
#include <sstream>
#include <stddef.h>
#include <iostream>
int main () {
std::stringstream oddStr;
std::stringstream evenStr;
static constexpr size_t vecSize{100};
int vec[vecSize] = {10, 5, 7, /*other elements...*/ };
for(size_t vecIndex = 0; vecIndex < vecSize; ++vecIndex) {
if(vec[vecIndex] % 2 == 0) {
evenStr << vec[vecIndex] << " ";
} else {
oddStr << vec[vecIndex] << " ";
}
}
std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}
Storing and sorting the elements are always expensive.
Basically, it would be better to sort them first.
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
int mergedArrays[5];
int evenNumbers[5];
int oddNumbers[5];
for(int i=0;i<5;i++){
cin>>numbers[i];
}
int temp=numbers[0];
//bubble sort
for(int i = 0; i<5; i++)
{
for(int j = i+1; j<5; j++)
{
if(numbers[j] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
int nEvens=0;
int nOdds=0;
for(int i = 0; i<5; i++)
{
if(numbers[i]%2==0)
{
evenNumbers[nEvens]=numbers[i];
nEvens++;
}
else if(numbers[i]%2!=0)
{
oddNumbers[nOdds]=numbers[i];
nOdds++;
}
}
int lastIndex=0;
//copy evens
for(int i = 0; i<nEvens; i++)
{
mergedArrays[i]=evenNumbers[i];
lastIndex=i;
}
//copy odds
for(int i =lastIndex; i<nOdds; i++)
{
mergedArrays[i]=oddNumbers[i];
}
return 0;
}
If you have to just output the numbers in any order, or the order given in the input then just loop over the array twice and output first the even and then the odd numbers.
If you have to output the numbers in order than there is no way around sorting them. And then you can include the even/odd test in the comparison:
std::ranges::sort(vector, [](const int &lhs, const int &rhs) {
return ((lhs % 2) < (rhs % 2)) || (lhs < rhs); });
or using a projection:
std::ranges::sort(vector, {}, [](const int &x) {
return std::pair<bool, int>{x % 2 == 0, x}; });
If you can't use std::ranges::sort then implementing your own sort is left to the reader.
I managed to find the following solution. Thanks you all for your help.
#include <iostream>
using namespace std;
int main()
{
int N{0}, vector[100], even[100], odd[100], merge[100], i{0}, j{0}, k{0}, l{0};
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++)
{
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++)
{
if (vector[i] % 2 == 0)
{
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0)
{
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++)
{
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++)
{
cout << " " << odd[i] << " ";
cout << endl;
}
for (i = 0; i < k; i++)
{
merge[i] = odd[i];
}
for (int; i < j + k; i++)
{
merge[i] = even[i - k];
}
for (int i = 0; i < N; i++)
{
cout << merge[i] << endl;
}
return 0;
}
You can use Bubble Sort Algorithm to sort whole input. After sorting them using if and put odd or even numbers in start of result array and and others after them. like below:
//Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Insert In array
int result[100];
if(odd[0]<even[0])
{
for (int i = 0; i < k; i++)
{result[i] = odd[i];}
for (int i = 0; i < j; i++)
{result[i+k] = even[i];}
}else
{
for (int i = 0; i < j; i++)
{result[i] = even[i];}
for (int i = 0; i < k; i++)
{result[i+k] = odd[i];}
}
I am trying to get the height of these slashes to be a certain length based on input. So far, I have:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
I need it to then reverse and go back.
It prints:
//
////
//////
If the user entered 3.
It should print:
//
////
//////
////
//
Can anyone lead me in the right direction? I am new to cpp.
You can use a different kind of loop and add a bool variable to track when the program have reached "n". Then, after the program reaches "n", it sets the bool variable to true and starts to substract until i equals 0
Code below, read comments and ask if you have any further questions:
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You have entered: " << n << "\n";
int i = 1;
bool reachedN = false; // tells if [i] has reached [n]
while (i != 0)
{
// Print required slashes
for (int j = 1; j <= i; j++)
{
cout << "//";
}
cout << '\n'; // new line
// Add until i == n, then substract
if (i == n)
{
reachedN = true;
}
if (reachedN)
{
--i;
}
else
{
++i;
}
}
}
If you enter 3, the output is the following:
This is one way to achieve that:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
for (int i = n - 1; i > 0; i--) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
This is a shorter solution with only two for-loops.
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
n = n * 2 - 1;
int r = 0;
for (int j = 0; j < n; j++)
{
if (j > n / 2) r--;
else r++;
for (int i = 0; i < r; i++)
{
cout << '/' << '/';
}
cout << "\n";
}
return 0;
}
I am trying to filter an array given by the user on basis of whether it is positive even, positive odd, negative even, or negative odd.
And, based on this filtration, I am trying to put them in the respected array but my code is working for the 1st part; i.e. it is taking user array but the problem is: It is not entering my filtration code.
The code is here:
#include<iostream>
#include<limits>
#include <functional>
using namespace std;
int main()
{
int n ;
cout<<"\n Enter the size of array :-";
cin>>n;
int numbers[n];
int peven[n],podd[n],neven[n],nodd[n];
for (int i = 0; i < n ; i++){
cout<<"\n Enter value "<<i+1<<" = ";
cin>>numbers[i];
}
cout<<"\n\n";
for (int i = 0; i < n ; i++){
cout<<" "<<numbers[i];
}
cout<<"\n\n";
for(int j = 0;j<n;j++){
if ( ((numbers[j]%2) == 0) && (numbers[j] > 0) ) {
for(int i = 0; i<1; i--){
cin>>peven[i];
i++;
}
}
else if ( ((numbers[j]%2) == 0) && (numbers[j] < 0) ){
for(int i = 0; i<1; i--){
cin>>neven[i];
i++;
}
}
else if ( ((numbers[j]%2) != 0) && (numbers[j] > 0) ){
for(int i = 0; i<1; i--){
cin>>podd[i];
i++;
}
}
else {
for(int i = 0; i<1; i--){
cin>>nodd[i];
i++;
}
}
}
cout<<"\n The +ve even number array is :- "<<peven[n];
cout<<"\n The +ve odd number array is :- "<<podd[n];
cout<<"\n The -ve even number array is :- "<<neven[n];
cout<<"\n The -ve odd number array is :- "<<nodd[n];
return 0;
}
There are several problems in your code. Here is a list (which is not exhaustive) :
it is forbidden to create a constant size array with an integer which is not constant :
cin>>n;
int numbers[n];
As Sam Varshavchik mentioned, it is not possible to finish this loop :
for(int i = 0; i<1; i--)
You have no reason to read value from cin after you fill the array to filter. Line like this one should be modified :
cin>>peven[i];
Here is a correction :
#include <iostream>
#include <vector>
#include<limits>
#include <functional>
using namespace std;
int main()
{
vector<int> peven, podd, neven, nodd;
int n;
cout << "Enter the size of vector :-" << endl;
cin >> n;
vector<int> numbers(n, 0);
for (int i = 0; i < n; i++) {
cout << "Enter value " << i + 1 << endl;
cin >> numbers[i];
}
cout << endl;
cout << "Your vector contains : [";
for (int i = 0; i < n; i++) {
cout << " " << numbers[i];
}
cout << " ]" << endl;
cout << endl;
for (int j = 0; j < n; j++) {
if (((numbers[j] % 2) == 0) && (numbers[j] >= 0)) {
peven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) == 0) && (numbers[j] < 0)) {
neven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) != 0) && (numbers[j] >= 0)) {
podd.push_back(numbers[j]);
}
else {
nodd.push_back(numbers[j]);
}
}
cout << "\n The +ve even number array is : [";
for (int j = 0; j < (int)peven.size(); j++) {
cout << " " << peven[j];
}
cout << "] " << endl;
cout << "\n The +ve odd number array is : [";
for (int j = 0; j < (int)podd.size(); j++) {
cout << " " << podd[j];
}
cout << "] " << endl;
cout << "\n The -ve even number array is : [";
for (int j = 0; j < (int)neven.size(); j++) {
cout << " " << neven[j];
}
cout << "] " << endl;
cout << "\n The -ve odd number array is : [";
for (int j = 0; j < (int)nodd.size(); j++) {
cout << " " << nodd[j];
}
cout << "] " << endl;
return 0;
}
I have an array of numbers input by the user, the program then sorts it in ascending order. I just need to find a way to get the factors of each number in the array and have it be printed out
#include "stdafx.h"
#include <iostream>
#include <limits>
#define MAX 200
using namespace std;
int arr[MAX];
int n, i, j, k;
int temp;
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of numbers to read: ";
cin >> n;
//check bound
if (n<0 || n>MAX)
{
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++)
{
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
cout << endl;
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
for (i = 0; i<n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << endl;
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl <<endl;
//trying to find factors
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++i)
{
if (arr[i] % k == 0)
cout << k << endl;
}
system ("pause")
return 0;
}
I want it to print each number from the array with
"The factors of (number) are ...'
"The factors of (next number) are ..."
and so on
The final for-loop should be loop with k and you forgot to increment k.
You should also write i-loop:
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
In addition, as pointed out by #LocTran, the upper bound of outer loop should be n-1.
Alternatively, you can easily sort arr using std::sort as follows:
std::sort(arr, arr+n);
Then your code would well work for you:
Live Demo
There are some issues with your source code.
1> Sorting problem with for outer loop
//sorting - ASCENDING ORDER
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
The upper bound of outer loop should be (n-1), not n as following but maybe you're lucky you won't see the problem when n < MAX. In case of n == MAX you will see the problem
//sorting - ASCENDING ORDER
//for (i = 0; i < n; i++)
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
2> The print functionality for entire array, you should add the outer loop for index of your array, and change the i++ by k++ in your loop as well
//trying to find factors
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++i)
{
if (arr[i] % k == 0)
cout << k << endl;
}
should be replaced by
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
//for (k = 1; k <= arr[i]; ++i)
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
Here is my solution based on modified source code
#include <iostream>
#include <limits>
#define MAX 200
using namespace std;
int arr[MAX];
int n, i, j, k;
int temp;
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of numbers to read: ";
cin >> n;
//check bound
//if (n<0 || n>MAX)
if (n<0 || n>MAX)
{
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++)
{
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
cout << endl;
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
//for (i = 0; i < n; i++)
for (i = 0; i < (n-1); i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << endl;
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl << endl;
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
//for (k = 1; k <= arr[i]; ++i)
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
return 0;
}
I have searched many examples and have yet to be able to find where exactly my problem lies. I am trying to implement the merge sort algorithm from the Cormen intro to algorithms book-- here is where I am at so far-- I have tried throwing in print statements to follow how the arrays are getting rebuilt but I am not seeing it... can anyone help?
Code:
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int p = 0;
int q = 0;
int r = 0;
int getRandom()
{
int randNum = 0;
randNum = 1 + rand() % 100;
return randNum;
}
void populateArray(int * array, int size)
{
for (int i = 0; i < size; i++) {
array[i]=getRandom();
}
}
void merge (int * array, int p, int q, int r) // p = start, q = mid, r = end
{
int i = 0; // left array iterator
int j = 0; // right array iterator
int n1 = q - p + 1;
int n2 = r - q;
// int arrayL[n1 + 1];
//int arrayR[n2 + 1];
int arrayL[n1];
int arrayR[n2];
for (i = 0; i < n1; i++) {
arrayL[i] = array[p + i];
}
cout << "TEST ARRAY MS A: ";
for (int count = 0; count < n1; count++) {
cout << arrayL[count] << " ";
}
cout << endl << endl;
for (j = 0; j < n2; j++) {
arrayR[j] = array[q + j + 1];
}
cout << "TEST ARRAY MS B: ";
for (int count = 0; count < n2; count++) {
cout << arrayR[count] << " ";
}
cout << endl << endl;
//arrayL[n1 + 1] = 1000;
//arrayR[n2 + 1] = 1000;
//i = 0;
//j = 0;
for (int k = p, i = j = 0; k <= r; k++) {
if (j >= n2 || (i <= n1 && arrayL[i] <= arrayR[j])) {
array[k] = arrayL[i];
i++;
cout << "TEST ARRAY in loop A: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
else {
array[k] = arrayR[j];
j++;
cout << "TEST ARRAY in loop B: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
cout << "TEST ARRAY in loop: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
}
void mergeSort (int * array, int p, int r)
{
if (p < r) {
q = floor((p + r) / 2);
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
int main(int argc, const char * argv[])
{
unsigned seed = time(0);
srand(seed);
int testArray[5];
populateArray(testArray, 5);
cout << "TEST ARRAY: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
mergeSort(testArray, 0, 4);
cout << "TEST ARRAY after mergeSort: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
return 0;
}