Counting different elements in an array [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I got this really easy project however i got stuck in a simple issue.
User enters a number not that is larger than 99 and smaller than 1 000 000.
I am supposed to get the number of digits in that number and how many times each one occurs
E.g: 112233 = 6 digits and 3 different numbers
I was able to do the first part however my second part of part is not working.
Here is the part not working:
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}
if for example my input is 112233 the return value should be 3, however i am getting 12
if input is 1122 the return value should be 2, however i am getting 8
Here is the whole program i have written so far:
/*====================================================================================
Headers and namespace
======================================================================================*/
#include <iostream>
using namespace std;
/*====================================================================================
Prototypes list
======================================================================================*/
int getNum(int); //This function checks how many digits there are in a plate number
int getDiff(int, int); //This function checks how many different numbers are there in the plate number
/*====================================================================================
Global variables list
======================================================================================*/
int PlateNumberArray[6];
int NumberCounter[6];
/*====================================================================================
main Function
======================================================================================*/
int main()
{
//Declaring variables
int CLP;
//End of Vriables Declration
cout << endl
<< "=============================" << endl;
cout << "Enter your vehicle's plate number" << endl;
do {
cin >> CLP;
if (CLP >= 1000000)
cout << "Plate number can be no longer than 6 digits, please re-enter" << endl;
else if (CLP < 100 && CLP >= 0)
cout << "Plate number can not be less than 3 digits, please re-eneter" << endl;
else if (CLP < 0)
cout << "Plate number can not be a negative, please re-eneter" << endl;
} while (CLP >= 1000000 || CLP < 100);
int Num = getNum(CLP);
cout << getDiff(CLP, Num);
return 0;
}
/*====================================================================================
getNum Function
======================================================================================*/
int getNum(int CLP)
{
//Declaring variables
int Num;
//End of Vriables Declration
if (CLP > 99999)
Num = 6;
else if (CLP > 9999)
Num = 5;
else if (CLP > 999)
Num = 4;
else if (CLP > 99)
Num = 3;
return Num;
}
/*====================================================================================
getDiff Function
======================================================================================*/
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}

You need to reset j each time you increment i.

Related

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

Need help displaying min/max values of integers entered by user

I need help with a c++ program that:
"Prompts users for N integers and determines/displays the integer
with the highest and lowest value – use separate functions to return the highest and lowest value. N is a random number from 5 to 10 (both inclusive)."
This is what I have so far:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum(int);
void largestNum(int);
int smallNum;
int largeNum;
int randomNum;
int num[10];
int main()
{
smallestNum(smallNum);
largestNum(largeNum);
system("pause");
return 0;
}
void randNumGenerator()
{
srand(time(0));
randomNum = 5 + (rand() % 10);
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
}
void smallestNum(int smallNum)
{
randNumGenerator();
smallNum = num[randomNum];
for (int i = 0; randomNum <= i; i++)
if (num[randomNum] < smallNum)
{
smallNum = num[randomNum];
}
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(int largeNum)
{
randNumGenerator();
largeNum = num[randomNum];
for (int i = 0; i <= i; i++)
if (num[randomNum] > largeNum)
{
largeNum = num[randomNum];
}
cout << "The largest integer is: " << largeNum << endl;
}
But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!
There are several issues:
First, with randomNum = 5 + (rand() % 10);, you generate random numbers between 5 and 14, inclusive, which may exceed int num[10]. Use randomNum = 5 + (rand() % 6); to get values between 5..10.
In your loops for (int i = 0; randomNum <= i; i++), with random <= i, you exceed array bounds since randomNum can go up to 10 and num[10] is already out of bounds for int num[10]. Write ... randomNum < i instead.
The same problem with smallNum = num[randomNum]; it exceeds array bounds; use smallNum = num[0] instead.
BTW: I'd interpret your assignment such that you enter the numbers once and then find the smallest and largest number in two different functions. In your code, you enter the numbers twice...
And: It's useless passing the smallNum into the function that overrides its value then. I'd rather use a function like int smallestNum() { ... return smallNum; } instead.
Hope it helps.
Try this,
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum();
void largestNum();
void getInput();
int num[11];
int length;
int main(){
smallestNum();
largestNum();
return 0;
}
void randNumGenerator(){
int from = 5;
int to = 10;
srand(time(0));
length = from + (rand() % (to - from));
}
void getInput(){
for (int x = 1; x <= length; x++) {
cout << "Enter the integer num[" << x << "]: ";
cin >> num[x];
}
}
void smallestNum(){
cout << "Finding smallest integer\n";
randNumGenerator();
getInput();
int smallNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] < smallNum)
smallNum = num[i];
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(){
cout << "Finding largest integer\n";
randNumGenerator();
getInput();
int largeNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] > largeNum)
largeNum = num[i];
cout << "The largest integer is: " << largeNum << endl;
}
With above code, I hope you will find your mistakes on your own :)
In addition to the first answer, this loop makes no sense:
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
randomNum is the same every loop, so you just keep overwriting the same array value.
And...
for (int i = 0; i <= i; i++)
This loop is wrong. You are checking i <= i which will always evaluate true.

Determine Amicable Pairs within Confines of Theta(n)

I am attempting to implement a program that reads a positive integer from the user and outputs all the perfect numbers between 2 and userNum. It also outputs all the pairs of amicable numbers that are between 2 and userNum. Both numbers must be within the range. I am seriously struggling with this.
Requirements:
1) calls to AnalyzeDivisors must be kept to theta(userNum) times all together. 2) Function void AnalyzeDivisors must take the following arguments int num, int& outCountDivs, int& outSumDivs. 3) Function bool IsPerfect must take the following argument int num.
I am honestly at a loss for how to do this within that efficiency range. I currently am able to determine all the perfect numbers in the range by bending the rules as far as parameters to the IsPerfect Function, but how can I determine amicable pairs without calling Analyze Dividors an inordinate amount of times each iteration of the for loop in main?
Any help would be greatly appreciated! Code below:
main
int main()
{
int userNum;
//Request number input from the user
cout << "Please input a positive integer num (>= 2): " << endl;
cin >> userNum;
for (int counter = 2; counter <= userNum; counter++)
{
//Set variables
int outCountDivs = 0, outSumDivs = 0, otherAmicablePair = 0;
bool perfectNum = false, isAmicablePair = false;
//Analyze dividors
AnalyzeDividors(counter, outCountDivs, outSumDivs);
//determine perfect num
perfectNum = IsPerfect(counter, outSumDivs);
if (perfectNum)
cout << endl << counter << IS_PERFECT_NUM;
}
return 0;
}
AnalyzeDividors
void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
{
//both counter and num/divisorCounter
outSumDivs += divisorCounter + (num / divisorCounter);
outCountDivs += 2;
}
else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
{
//Just divisorCounter
outSumDivs += divisorCounter;
outCountDivs += 1;
}
}
}
IsPerfect
bool IsPerfect(int userNum, int outSumDivs)
{
if (userNum == outSumDivs)
return true;
else
return false;
}
I think I found a solution that fits the requirements. I found amicable numbers by storing every number and sum of divisors in a map. If a number's sum of divisors is entered in the map, and the sum of divisor's sum of divisors was the current number, then they are amicable.
Because the results are saved each time, you only call AnalyzeDivisors once per number.
Pardon the lazy variable naming.
#include <iostream>
#include <map>
#include <cmath>
void AnalyzeDivisors(int num, int& divc, int &divs)
{
divc = 1;
divs = 1;
for (int x = 2, y = std::sqrt(num); x <= y; ++x)
{
if (num % x == 0)
{
++divc;
divs += x;
if (num / x != x)
{
++divc;
divs += num / x;
}
}
}
}
bool IsPerfect(int num)
{
static std::map<int, int> amicable;
int divc = 0, divs = 0;
AnalyzeDivisors(num, divc, divs);
if (amicable.find(divs) != amicable.end() && amicable[divs] == num)
std::cout << num << " and " << divs << " are best bros for life.\n";
amicable[num] = divs;
return num == divs;
}
int main()
{
int num;
std::cout << "Pick a number: ";
std::cin >> num;
for (int x = 2; x < num; ++x)
{
if (IsPerfect(x))
std::cout << x << " is perfect in every way!\n";
}
}

How can I display only prime numbers in this code?

I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)

Taking in multiple inputs at once and then giving out output at once [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So my question is how to efficiently write a program where in we are able to take multiple inputs (the amount of inputs given is determined by the user) and then give the outputs at once. Lets consider a program which gives gives the sum of its digits. Eg - 12345 = 15.
//Single input single output
#include <iostream>
using namespace std;
int main()
{
int T, N;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
cout << "Enter the value of N : " << endl;
while (T > 0)
{
cin >> N;
int ans = 0,temp1,temp2;
while(N!=0)
{
temp1= N %10;
N = (N - temp1)/10;
ans = ans + temp1;
}
cout << ans << endl;
T--;
}
return 0;
}
// Taking in all inputs then giving out all outputs ( Not working properly)
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase, int t);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int *Ans(new int[T]);
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i, T);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
delete[] Ans;
return 0;
}
int SumCal(int Number, int TestCase, int t)
{
int temp1, temp2 = 0;
int *AnsTemp(new int[t]);
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
AnsTemp[TestCase] = (temp1 + temp2);
while (temp2 > 10)
{
AnsTemp[TestCase] = (AnsTemp[TestCase] + temp1);
temp2 = temp2 / 10;
temp1 = temp1 % 10;
}
return AnsTemp[TestCase];
delete[] AnsTemp;
}
// This will work properly for multiple inputs multiple outputs
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int Ans[1000] = {};
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
return 0;
}
int SumCal(int Number, int TestCase)
{
int temp1, temp2 = 0;
int ans;
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
ans = (temp1 + temp2);
while (temp2 > 10)
{
ans = (ans + temp1);
temp2 = temp2 / 10;
temp1 = temp2 % 10;
}
return ans;
}
These are the codes I could think of. The first one is a simple one, which takes in an input and then gives out a output. In the second one I tried to use dynamic memory allocation but the program gives error. ( I know I haven't made proper use of * and & in it but I already tried using it in various manners and failed). The third program is successful but as we are setting up a large constraint value to the array, (i.e int Ans[1000]) it makes the program a bit inefficient.
So my question is how would one dynamically allocate memory during runtime successfully to take in multiple inputs and then give multiple outputs at once.
It's very hard to work with your code. I just took the 1st example, minimized the code and did what you should have done:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int T;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
int *buf = new int[T](); // buffer to hold the answers
for(int i = 0; i < T; ++i)
{
int N;
cout << "Enter the value of N : " << endl;
cin >> N;
while(N)
{
buf[i] += N % 10; // calculate on the buffer element
N /= 10;
}
}
for(int i = 0; i < T; ++i)
cout << buf[i] << endl; // print the buffer
delete [] buf; // delete buffer
return 0;
}
There's not much to do for managing the dynamically allocated array here, but take a look at std::vector and its uses.