Finding specific repeated digits in a number - c++

I am trying to write a program that will count the number of 5s in a number and display it. So if the user enters:
52315
Then the program should ouptut:
Yes, there are '5's and they're 2
Here is my code but there is something wrong with it.
{
int n,m;
int count = 0;
cout << "Enter an: ";
cin >> n;
int *arr;
arr = new int[count];
// Getting digits from number
while (n > 0)
{
count++;
m = n%10;
n = n/10;
//Trying to put every digit in an array
for (int i = 0; i<count; i++)
{
cin>>arr[i];
arr[i] = m;
cout << arr[i];
}
int even = 5;
//Trying to see if there's a digit 5 in inputed number and how many if so.
for (int j = 0; j<count; j++)
{
if (arr[j]==even)
{
cout << "Yes, there's a digit '5' " << endl;
s++;
}
}
cout << "Count of '5's : " << even;
delete[] arr;
}
return 0;
}

This
for (int i = 0; i<count; i++)
{
cin >> arr[i];
}
You're trying to populate the array with the another user input rather than the existing one.
You also can do it without the array:
int count = 0;
int n;
cin >> n;
do {
if (n%10 ==5) count++;
n /= 10;
} while (n);
cout << "Count of '5's : " << count;

This should do it for every number.
If you only want to know a special number like 5, just remove the for-loop and print count[theNumberYouWantToKnow].
#define BASE 10
void output() {
int givenNumber;
cout << "Please enter a number: ";
cin >> givenNumber;
int count[BASE] = { 0 };
while(givenNumber > 0) {
int digit = givenNumber % BASE;
givenNumber /= BASE;
count[digit]++;
}
for(int i = 0; i < BASE; i++) {
cout << "Found the number " << i << " " << count[i] << " times." << endl;
}
}

Related

Creating a function to find duplicates in array without sorting C++

I've been working on a lottery checking program. The goal is to create a function that finds duplicates and allows the user to choose another number in the case of userTicket, and generate another random number in case of winningNums. So this function must be reusable between the two, or with any array for the matter. I am not familiar with sorting and scanning through the array just yet. I have created a nested for loop to go through each index and compare the two between [i] and [j]. My function only works on the first number for some reason. Any ideas are greatly appreciated.
void getLottoPicks(int userArray[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
cin >> userArray[i];
cin.ignore();
if (noDuplicates(userArray) == true)
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> userArray[i];
}
}
}
void genWinNums(int winArray[])
{
srand((int)time(NULL));
for (int i = 0; i < NUMS; i++)
{
winArray[i] = rand() % 40 + 1;
if (noDuplicates(winArray) == true)
{
winArray[i] = rand() % 40 + 1;
}
}
}
bool noDuplicates(int dupArray[])
{
int temp = 0;
for (int i = 0; i < NUMS; i++)
{
//temp += dupArray[i];
for (int j = 0; j < i; j++)
{
if (dupArray[i] == dupArray[j])
{
return true;
}
else
{
return false;
}
}
}
}
You can use std::set, it's faster and much less code
void getLottoPicks(std::set<int> userArray)
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
int num;
cin >> num;
cin.ignore();
// while the num is already in the set
while (userArray.find(num) != userArray.end())
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> num;
}
}
}
In both cases your calls to noDuplicates() are nested inside the loops which are constructing the array that you pass to noDuplicates(). That won't work. First you need to construct the array, and once you are done constructing it, then you pass it to noDuplicates().

How do I add a search function to array?

I need to add a function to search in the string array and bring up the user with associated phone number. Though Im lost. Any functions created only bring up the persons name without the number. If not found, it needs to say error.
int main(int argc, char** argv)
{
int i, n, j;
string name[100];
string phone[100];
int index[100];
cout << "How many names and phone numbers do you want to enter? " << endl
<< "Entering 0 ends the program." << endl;
cin >> n;
if (n == 0)
return 0;
for (i = 0; i < n; i++) {
cout << "Please enter a name: ";
cin >> name[i];
cout << "Please enter a phone number: ";
cin >> phone[i];
}
for (i = 0; i < n; i++) {
index[i] = i;
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
int temp;
if (phone[index[i]] > phone[index[j]]) {
temp = index[i];
index[i] = index[j];
index[j] = temp;
}
}
}
cout << "These entries are in ascending order by phone number: " << endl;
cout << "Name"
<< " "
<< "Phone Number" << endl;
for (i = 0; i < n; i++) {
cout << name[index[i]] << " " << phone[index[i]] << endl;
}
return 0;
}
This code should work for you (if i understood the question)
int search(string name[], string searchedName){
for(int i=0; i<100; i++){
if(searchedName == name[i])
return i; //Returns the position of the person, which is also the index of his phone number
}
return -1; //If -1 is returned it means there is no such name an "searchedName" in the vector
}
You can call this function like this
int main(){
/* all the stuff you already have inside here */
string nameToSearch;
cout<<"Insert the name of the person you want to see the number of"<<endl;
cin>>nameToSearch;
int position = search(name, nameToSearch);
if(position == -1)
cout<<"Sorry, "<<nameToSearch<<" is not in our list"<<endl;
else
cout<<"The phone number of "<<nameToSearch<<" is "<<phone[position]<<endl;
return 0;
}
Of course this is pretty basic and you can make it better, hope it helps!

How do I implement an exception handler for strings and doubles in my bubble sort?

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int hold;
int swapNumber=0;
int compare=0;
int array[10];
for(int i=0; i<10; i++)
{
cout<<"Enter 10 numbers: "<<endl;
cin>>array[i];
}
cout<<endl;
// what user inputed
cout<<"Originally entered array by the user is: "<<endl;
for(int k=0; k<10; k++)
{
cout<<array[k];
cout<<endl;
}
cout<<endl;
//begin bubblesort method
for(int i=0; i<9; i++)
{
for(int k=0; k<9; k++)
{
compare++;
if(array[k]>array[k+1])
{
hold=array[k];
array[k]=array[k+1];
array[k+1]=hold;
swapNumber++;//adding swap count by 1
}//end of if
} //end of for j
} // end of for i
//when sorted sm to large
cout<<"Sorted Array is: "<<endl;
for(int i=0; i<10; i++)
{
cout<<array[i]<<endl;
}
//how many times numbers are swapped
cout<<"Number of times Swapped: "<<swapNumber<<endl;
//how ,many times numbers are compared
cout<<"Number of times Compared: "<<compare<<endl;
getch();
}
My assignment is to add an exception handler which states "Error! ONLY INTEGER INPUT ALLOWED ".The handler is supposed to catch doubles and strings. I've tried try and catch method but i don't know quite where to place it so that it'll work. I've also read about the catch all method, which seems like what i need to do. I've just now completed my counter methods for swap and comparisons which I do believe are working fine.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int hold, swapNumber = 0, compare = 0, array[10];
const string Error = "Error! ONLY INTEGER INPUT ALLOWED!";
cout << "Enter 10 numbers: " << endl;
try
{
for ( int i = 0; i < 10; i++ )
{
cin >> array[i];
if ( !cin ) // Error in reading input stream
{
throw Error;
}
}
}
catch ( const string& E )
{
cout << E << endl;
return 0;
}
cout << endl;
cout << "Originally entered array by the user is: " << endl;
for ( int k = 0; k < 10; k++ )
{
cout << array[k] << endl;
}
cout << endl;
for ( int i = 0; i < 9; i++ )
{
for ( int k = 0; k < 9; k++ )
{
compare++;
if ( array[k] > array[k + 1] )
{
hold = array[k];
array[k] = array[k + 1];
array[k + 1] = hold;
swapNumber++;
}
}
}
cout << "Sorted Array is: " << endl;
for ( int i = 0; i < 10; i++ )
{
cout << array[i] << endl;
}
cout << endl;
cout << "Number of times Swapped: " << swapNumber << endl;
cout << "Number of times Compared: " << compare << endl;
getch();
}

send dynamic array of pointer to function in c++

I trying to send array to function, but my program gets stuck
int main()
{
int n, i;
bool random;
cout << "number of elements in array:"; cin >> n;
cout << "use random values?"; cin >> random;
int* arr = new int[n]; //create int array with n size
init_array(random, n, arr); //fill array using function
for (i = 0; i <= n; i++) //display array
cout << " " << arr[i];
return 0;
}
This function should fill array with random number or input from keyboard
void init_array(bool random, int n, int* arr)
{
int i;
if (random)
{
srand(time(0)); //initialize random;
for (i = 0; i < n; i++)
arr[i] = rand() % 100;
}
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
}
Is there any way send dynamic array to function?
When you do not use brackets after your for-loop, only the first statement is used as a loop:
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
This loop will attempt to print "arr[#]" n times, and then ask for an input (which will attempt to be placed in the item 1 after the last element in your array (UB).
What you want is this:
else
{
for (i = 0; i<n; i++)
{
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
}
You also have a problem with your output:
for (i = 0; i < n; i++) // <= would attempt to print 1 more item than exists in the array
And just for completeness, most of these issues go away when you use a container that does all of this for you:
int main()
{
int n = 0;
bool useRandom = false;
std::cout << "number of elements in array:";
std::cin >> n;
std::cout << "use random values?";
std::cin >> useRandom;
std::vector<int> arr(n);
init_array(useRandom, arr);
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
void init_array(bool useRandom, std::vector<int>& vec)
{
::srand(time(0)); //initialize random;
int n = 0;
std::transform(vec.begin(), vec.end(), vec.begin(), [&](int i)
{
if (useRandom)
{
i = rand() % 100;
}
else
{
std::cout << "arr[" << n++ << "]: ";
std::cin >> i;
}
return i;
});
}
Your code is asking for a number at the end because of last cin>>n
fix else part in init_array as:
else
for (i = 0; i<n; i++)
{ //Notice braces
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
Also fix:
for (i = 0; i < n; i++) //display array from index 0 to n-1
cout << " " << arr[i];

how to process an array of even numbers from a users input and display them with spaces in C++

I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}