Programme is not executing even not having any comile error - c++

#include <iostream>
using namespace std;
void aUnionB(int A[], int B[], int a, int b)
{
int n = a + b;
int aUb[n]{0}; // n is max num of elements aUb can have
// filling elements of a in aUb
for (int i = 0; i < a; i++)
{
aUb[i] = A[i];
}
int z = sizeof(aUb) / sizeof(aUb[0]);
int temp = z;
// compare element from set B with aUb and if not fount add it in aUb
for (int i = 0; i < z; i++)
{
for (int j = 0; j < b; j++)
{
if (aUb[i] == B[j])
{
continue;
}
else
{
aUb[temp] = B[j];
temp++;
}
}
}
//print a union b
for (int i : aUb)
{
cout << i << " ";
}
}
int main()
{
int TestCases = 1, NoOfElementsInA, NoOfElementsInB, element;
while (TestCases--) //testing for just one test case
{
cin >> NoOfElementsInA >> NoOfElementsInB;
int A[NoOfElementsInA], B[NoOfElementsInB];
//assigning elements in array A
for (int i = 0; i < NoOfElementsInA; i++)
{
cin >> element;
A[i] = element;
}
//assigning elements in array B
for (int i = 0; i < NoOfElementsInB; i++)
{
cin >> element;
B[i] = element;
}
aUnionB(A, B, NoOfElementsInA, NoOfElementsInB);
}
return 0;
}
I am trying for past 1 hour what's the problem but unable to find why the program is not running despite not having any error or warning after execution , I'm not able to pass inputs.
This the numerical question:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consist of three lines. The first line of each test case contains two space separated integers N and M, where N is the size of array A and M is the size of array B. The second line of each test case contains N space separated integers denoting elements of array A. The third line of each test case contains M space separated integers denoting elements of array B.

Related

Write a sum function that returns the sum of all the elements of the array

#include <iostream>
#include<math.h>
using namespace std;
struct Point { //B
double x = 0;
double y = 0;
};
void fillArray(double box[][10]) { //D
cout << "Insert 100 doubles: ";
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
cin >> box[i][j];
}
}
}
int sum(int* arr, int size) { //f
int result = 0;
for (int i = 0; i < size; ++i)
result += arr[i];
return result;
}
int main() {
double box[10][10]{}; //A
cout << "Enter your name:";
//C
string name;
cin >> name;
cout << "Hello " << name << '\n';
fillArray(box);
}
I am having troubles making a couple other functions.
G)Write a difference function that receives as parameter 2 elements of the array and which
returns the difference between element a and element b.
this is the first function I do not understand.
H)Write a product function that receives as parameter 2 elements of the array and which
returns the product of these elements.
This is my advice: Clear your basics and everything will be okay.
This is my code:
Version 1: For summing all elements of the array:
#include <iostream>
double sum(double *arr, std::size_t lengthArr )
{
double sum = 0;
for(int i = 0; i < lengthArr; ++i)
{
sum += arr[i];
}
//return the sum
return sum;
}
int main()
{
//create the array
double arr[] = {1, 10, 13, 43,43,543,63};
std::cout<<"The sum is: "<<sum(arr, sizeof(arr)/sizeof(double));//call the sum fuction passing the arr and its size
return 0;
}
Version 2: For writing a product function that receives as parameter 2 elements of the array and which returns the product of these elements.
#include <iostream>
double product(double &a, double &b )//a and b are passed by reference
{
//return the product
return a * b;
}
int main()
{
//create the array
double arr[] = {1, 10, 13, 43,43,543,63};
std::cout<<"The product is: "<<product(arr[1], arr[3]);//call the product function and pass whichever elements of the array
return 0;
}
I suppose you can modify version 2 for subtraction purpose.
Note that we can also use templates to make this program more general. These samples were just to get you started(or as a reference).

i want to print the non repeated number using hashmap;

// Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> printNonRepeated(int arr[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<int> v;
v = printNonRepeated(arr, n);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
// Function to print the non repeated elements in the array
// arr[]: input array
// n: size of array
vector<int> printNonRepeated(int arr[], int n) {
vector<int> a;
unordered_map<int, int> h;
int count = 0;
int i;
for (i = 0; i < n; i++) {
h[arr[i]]++;
}
int j = 0;
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
}
return a;
}
I want to print the nonrepeating numbers using the function vector<int> printNonRepeated(int arr[],int n). I am trying using hashmap. I am getting segmentation error while compiling. Where am I doing a mistake.
I do not have the permission to change the main function. I can only change the 'printNonRepeated' function.
a[j] = x.first;
j++;
You can't access the jth index of a without having allocated space first. The size of the array needs to be predefined, or you can use push_back so that the vector adds a new element to the end.
a.push_back(x.first);
For starters variable length arrays as this
int n;
cin >> n;
int arr[n];
is not a standard C++ feature.
You may not use the subscript operator with an empty vector.
vector<int> a;
//...
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
Creating vectors is redundant. You could initially store entered values in a container of the type std::map declared in main.

Counting not equal strings in array in C++

I want to count all the different string elements in an array.
So my input would be:
5 Lemon Orange Lemon Mango Lemon
And the output should be this:
3
The problem with my code is, that my code counts all the elements, and not just the different and I can't figure out why.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
string Tname;
string data[N];
int counter = 0;
for(int i = 0; i<N; i++)
{
cin >> Tname;
data[i] = Tname;
}
for(int l = 0; l<N; l++)
{
int k = 0;
while(k<N && (data[l] != data[k]))
{
k++;
}
if(k<N)
{
counter += 1;
}
}
cout << counter << endl;
return 0;
}
The problem is algorithmic: every item is equal to itself, which will end your k loop prematurely. In addition, you only increment when the item is repeated.
I propose you to change the loops, so not to compare every items with every other items, but only items, to items previously processed:
for(int l = 0; l<N; l++)
{
int k = 0;
while(k<l && data[l] != data[k]) // only previous items
{
k++;
}
if(k==l) // if no identical, we can add this one
{
cout<<l<<" "<<data[l]<<endl;
counter += 1;
}
}
Not related: variable length arrays are not legal C++ even if some mainstream compilers accept it. I'd suggest to use a vector to emulate this feature: vector<string> data(N);
Online demo
if i understand well your problem , you want the value that has the max appearances in the array, some modifications are needed to achieve this :
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
string Tname;
string data[N];
int counter = 0;
for(int i = 0; i<N; i++)
{
cin >> Tname;
data[i] = Tname;
}
int tempCounter; // a temporary counter for each item of the array .
for(int l = 0; l < N; l++)
{
tempCounter = 0;
int k = 0;
while(k<N)
{
if(data[l] == data[k])
tempCounter++;
k++;
}
if(tempCounter > counter) // if the new counter is higher than the counter
counter = tempCounter;
}
cout << counter << endl;
return 0;
}
the last if should be if(k+1==N)
because you all the time stop the while before the k reach N
and k must start from l
Your logic is, you add 1 to the counter if it is not in the list's remaining part
But the code check the full list so you never count thw world whitch in the list twice.

Error implementing selection sort in C++

I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
I can't find the error. I'm new to C++.
Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below.
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
The resulting output was as follows:
-5 -4 -3 0 2 3 4 6 100 200
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.

Prime Factoring, no IO

Dear StackOverflow community,
I am trying to write code that accepts a "primefactorized" array, each element originally describing their final multiplicational product.
The code I'm trying to write then reads this array and turns it to the exponentiation of prime numbers, each index of the array corresponding to the next prime number, and each element on the index the power to which it must be raised. I believe I have done so, but I cannot for some reason get my IO working. For some reason when I switched the inner for-loops last incrementation part to an "i++" instead of the correct "j++", it would display the loop.
Relevant snippet
// Next stage: Take the array and turn in into the form described earlier
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = result[i];
tempcounter = 1; // counter to control the loop.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
{
if(result[j]+1 == temppower)
{
tempcounter++;
result[j+1] = 0;
}
}
result[i] = tempcounter;
}
for(unsigned int i = 0; i < sizeof(result); i++)
{
cout << result[i] << " ";
}
cout << endl;
Full code
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
#include "fact.h"
/** eartosthenes constructs an up-to-n primes array of length len .
* #param n call-by-value, top value for construction of primes.
* #param &len call-by-reference, the finished size of the array of primes.
* #return int* pointer to the first element of the array of primes.
* Description:
* The eartosthenes method of calculating primes are efficient for relative low primes (up to 10 million or so).
* You can read about the method at http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
* You can use wolfram-alpha https://www.wolframalpha.com/ and run Prime(start)...Prime(end) to get the primes
* between start and end, e.g. Prime(1)...Prime(10) yield {2,3,5,7,11,13,17,19,23,29}.
*/
int * eratosthenes(int n, int & len){
// computes all prime numbers up to n
// returns the prime numbers as an array
// the len parameter will be set to the length of the array
bool *isPrime=new bool [n+1]; // construct [n+1] booleans
len=0;
// initialize every value from 1..n to true.
for(int i=2; i<=n; i++){
isPrime[i]=true;
}
// now we'll start at 2, and for every number of multiplicity 2.
// e.g. 2*{1,2,3,4...n} is then set to false, as they are dividable by 2.
// then we increment to 3, during the same.
for(int i=2; i<=n; i++){
if(isPrime[i]){
len++; // for each such iteration, we increase our desired length.
for(int j=2*i; j<=n; j+=i){
isPrime[j]=false; // set every(n) multiplicity of 2 to false.
}
}
}
// having used erathosthenes formula, we now construct our array.
int *result=new int[len];
// now we need to return the primes-filled array.
for(int i=0, j=2; i<len; i++){
// if it's not a prime, then we spin the value up.
while(!isPrime[j]) j++;
// when the while-loop no longer hold, we'll have the iterations desired prime
// we then set it, and the for-loop will continue to the next.
result[i]=j++;
}
delete [] isPrime; // always delete what you have allocated with new.
// we say these allocation are on the heap or free store (c-syntax)
return result;
}
#include "fact.h"
factrep new_factrep()
{
factrep result;
result = new int[len];
return result;
}
factrep primfact(int n)
{
factrep result;
result = new int[len];
int m; // still to factorize number
int f; // current factor
int index = 0; // index of factrep array
int temppower = 0; // index for the power
int tempcounter = 0; // counter to help the power determine its size
m=n;
f=2;
// 0-initialize the result array
for(unsigned int i = 0; i < sizeof(result); i++)
{
result[i] = 0;
}
// continue until nothing to factorize
while(m != 1){
// while the factor divides m, go on
while(m % f == 0){
if(m!=1)
{
m=m/f;
result[index] = f;
index++;
}
else
{
result[index] = f;
break;
}
}
// increment factor
f++;
}
// Next stage: Take the array and turn in into the form described within
// the exercise handout,
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = result[i];
tempcounter = 1; // counter to control the loop.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
{
if(result[j]+1 == temppower)
{
tempcounter++;
result[j+1] = 0;
}
}
result[i] = tempcounter;
}
for(unsigned int i = 0; i < sizeof(result); i++)
{
cout << result[i] << " ";
}
cout << endl;
return result;
}
factrep mult(factrep f1, factrep f2)
{
factrep result;
result = new int[len];
for(int i = 0; i < len; i++)
{
result[i] = f1[i]+f2[i];
}
return result;
}
int getint(factrep f)
{
int result = 0;
// int *temparray = new int[len];
for(int i = 0; i < len; i++)
{
result *= pow(primes[i],f[i]);
}
return result;
}
// these are our global variables
// so in our header we called extern
// which basically tells c++, that we'll define them in another file.
int *primes;
int len;
int main(){
// construct our primes array with maximum integer value
primes=eratosthenes(sqrt(INT_MAX),len);
// len now contains the length of the primes.
// TEST VALUES
// these are our test values.
int n=60;
int m=25;
int l=640;
// first check for non-negative content
if ( n < 0 || m < 0 || l < 0){
cout << "values must be positive (n > 0)" << endl;
return 1;
}
// construct 3 prime-factorized arrays by the values (60,25,640)
factrep fn=primfact(n);
factrep fm=primfact(m);
factrep fl=primfact(l);
// Verify that these are indeed constructed with those values
cout << getint(fn) << " " << getint(fm) << " " << getint(fl) << endl;
// multiply: fn = fn*fm, fm = fl*fl, fl = fn*fm
// 1500 = 60*25, 409600 = 640*640, 614400000 = 1500*409600
fn=mult(fn,fm);
fm=mult(fl,fl);
fl=mult(fn,fm);
// Verify that our functions work as expected by printing out their values now.
cout << getint(fn) << " " << getint(fm) << " " << getint(fl) << endl;
/* Expected output:
60 25 640
1500 409600 614400000
*/
// and again, if we construct something on the heap/free-store we better delete it again
// otherwise we might have a memory-leak on our hands.
delete [] primes;
delete [] fn;
delete [] fm;
delete [] fl;
return 0;
}
Update
The error was pointed out to me: I had put an i variable reference within the inner-most loop instead of the j variable I was using. (facepalm).
In the meantime this realization quickly helped me to solve my original problem which I will paste below in case anyone might run into a similar problem (primes[] is an array of primes, one per element, established outside of the factrep functions)
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = primes[i];
tempcounter = 0; // counter to control the loop.
for(unsigned int j = 0; j < sizeof(result); j++)
{
if(result[j] == temppower)
{
tempcounter++;
}
}
result[i] = tempcounter;
}
Line 116 : A loop is endless.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
i never changes in the inner loop where j is increasing, thus preventing your program from advancing further and printing anything.