I have been given some integers and I have to count the frequency of a specific digit in the number.
example input:
5
447474
228
6664
40
81
The first number says number of integers in the list. I am finding frequency of 4 in this case. I tried to change the integer to an array, but it is not working.
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main() {
int n;
cin>>n;
for (int i=0; i<n; i++)
{
int x;
cin>>x;
int frequency=0;
int t=log10(x);
int arr[t];
for (i=t; i>0; i--)
{
arr[i]=x%10;
x=x/10;
}
for(int i=0; i<t; i++)
{
if(arr[i]==4)
{
frequency++;
}
}
std::cout << frequency << std::endl;
}
return 0;
}
No need to create an array, or to determine the number of digits. Just loop until the number reaches zero.
int digitCount(int n, int d) {
if(n < 0) n = -n;
int count = 0;
for(; n != 0; n /= 10)
if(n % 10 == d) count++;
return count;
}
Test:
cout << digitCount(447474, 4) << endl;
cout << digitCount(-447474, 4) << endl;
Output:
4
4
Your code uses VLAs which are not standard C++. See Why aren't variable-length arrays part of the C++ standard?.
log10(x) is not the number of digits. For example log10(1234) == 3.09131516 but it is 4 digits. Also you are accessing the array out of bounds in the first iteration of the loop: arr[t]. Valid indices in an array of size t are 0,1,2,...,t-1. Trying to access arr[t] is undefined behavior.
Actually you dont need any array. Instead of storing the digits in an array you can immediately check whether it is a 4 and count.
Even simpler would be to read the user input as a std::string:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::cout << std::count(input.begin(),input.end(),'4');
}
Perhaps you should add some checks to verify that the user input is actually a valid number. However, also when reading an int you should validate the input.
Related
So I need to combine a specific number (not string) of digits from a vector of possible ones (all 0-9, not characters) in an N-digit number (not binary, then). However, I cannot have any extra permutations appear: for example 1234, 4321, 3124... are now the same and cannot be all outputed. Only one can be. This is hard because other questions cover these permutions by using std::next_permutation, but I still need the different combinations. My attempts at trying to remove permutations have failed, so how do you do this? Here is my current code with comments:
#include <iostream>
#include <vector>
using namespace std;
#define ll long long
int n = 0, m = 0, temp; //n is number of available digits
//m is the length of the desired numbers
//temp is used to cin
vector <int> given;
//vector of digits that can be used
vector <int> num;
//the vector to contain a created valid number
void generate(vector <int> vec, int m) {
//recursive function to generate all numbers
if (m == 0) {
for (int x : num) {
cout << x;
}
cout << '\n';
return;
}
for (int i = 0; i < given.size(); i++) {
num.push_back(given[i]); //add digit to number
int save = given[i];
given.erase(given.begin() + i);
//no repeating digits, save the used one and delete
//however, permutations can still pass, which is undesirable
generate(vec, m - 1);
//recursive
num.pop_back();
//undo move
given.insert(given.begin() + i, save);
//redo insert deleted digit
}
}
int main () {
cin >> n;
//input number of available digits
for (int i = 0; i < n; i++) {
cin >> temp;
given.push_back(temp); //input digits
}
cin >> m;
//input length of valid numbers
generate(given, m); //start recursive generation function
return 0;
}
I tried deleting permutations before printing them and erasing more digits to stop generating permutations, but they all failed. Lots of other questions still used std::next_permutation, which was not helpful.
Unlike some people who suggested binary strings in some comments, you can begin by having a recursive function that can go two ways as an on/off switch to decide whether or not to include a given digit. I personally like using a recursive function to do this and a check for length at the end to actually print the number of the desired len, demonstrated in the code below:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int givencount = 0, temp = 0, len = 0;
vector <int> given;
string creatednum;
void generate(int m) {
if (m == givencount) {
if (creatednum.length() == len) {
cout << creatednum << '\n';
}
return;
}
for (int i = 0; i < 2; i++) {
if (i == 1) {
generate(m + 1);
continue;
}
creatednum = creatednum + ((char) ('0' + given[m]));
generate(m + 1);
creatednum.erase(creatednum.begin() + creatednum.length() - 1);
}
}
int main () {
cin >> givencount;
for (int i = 0; i < givencount; i++) {
cin >> temp;
given.push_back(temp);
}
cin >> len;
generate(0);
return 0;
}
Given a two-digit number n, print both the digits of the number.
Input Format:
The first line indicating the number of test cases T.
Next T lines will each contain a single number ni.
Output Format:
T lines each containing two digits of the number ni separated by space.
Constraints
1 <= T <= 100000
10 <= ni <= 99
Error: Runtime Error (SIGSEGV)
I'm not able to pinpoint, where the problem is in the code as it is working fine for a two numbers while it gives the runtime error for 4 or more numbers.
Is there another way of doing this problem other than using for loop twice?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
Fist, you declare t, but do not initialize it, so it is uninitialized. Trying to use the value leads to undefined behavior.
Second, VLA is not valid C++, see here. You have to use std::vector instead.
Third, you don't need to use an int.
So, you should do:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}
I wrote this piece of code, which has t test cases, and for every test cases it would input 3 digits. I want this program to then identify the minimum element among those three inputs, and then print the minimum element. What should I do?
int main()
{
int t;
cin>>t;
while(t--)
{
for(int i=0;i<3;i++)
{
int n;
cin>>n;
}
}
return 0;
}
Here's a example of finding the minimum of three digits, using a running minimum:
#include <iostream>
int main()
{
unsigned int test_case_quantity = 0U;
std::cin >> test_case_quantity;
while(test_case_quantity--)
{
char minimum;
std::cin >> minimum;
char digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cout << " minimum: " << minimum << "\n";
std::cin.ignore(100000, '\n'); // Synchronize to next line.
}
return 0;
}
For a more robust program, you can add validation that the character read is actually numeric.
We can make use of an extra variable say small and when we are inputting the very first number, we can assign that first number to the small and in all other cases we can compare whether the current number is less than small, if yes then update small.
Finally outside the loop we can print the value of small and this will be our answer.
int main()
{
int t;
cin>>t;
while(t--)
{
int small;
for(int i=0;i<3;i++)
{
int n;
cin>>n;
if (i == 0)
small = n;
else {
if (n < small)
small = n;
}
}
cout<<"Smallest number is :" << small;
}
return 0;
}
input :
1
10 2 3
output :
Smallest number is :2
Flow :
At first the value 10 will be assigned as small, then for the next element 2, we compare whether 2 is less than small which is 10 in that case, and reassign small to 2. Then this small is checked with 3, but 2 < 3, so small value remains unchanged.
I assume there will be only integer values as input.
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.
I know how to do that without using a function ,for example for any n numbers I have the following program:
#include<stdio.h>
int main()
{
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
return 0;
}
Or this one which do that using arrays:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
But is it possible to use functions?if yes then how? thank you so much for helping.
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
In fact a complete example can require only a dozen or so additional lines, e.g.
#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n; /* temporary integer */
std::vector<int> v {}; /* vector of int */
while (std::cin >> n) /* while good integer read */
v.push_back(n); /* add to vector */
std::cout << "\naverage: " << avg(v) << '\n'; /* output result */
}
Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).
Example Use/Output
$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333
(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)
It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array
#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}
This is an example meant to give you an idea about what needs to be done. You can do this the following way:
// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main()
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
how to do that without using a function
Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?
The list of numbers (array of numbers)
Total numbers (n)
So let's first get the input from the user and put it into the array, you have already done it:
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}
Now, lets make a small function i.e., calculateAverage():
int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}
There are a few important points to note here.
When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,
pass the size information in the function, like we passed total
Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array
A few problems with your code:
using namespace std;
Don't do this. Instead if you want something out of std, for e.g., cout you can do:
using std::cout
using std::cin
...
or you can just write std::cout everytime.
int n, i;
float num[100], sum=0.0, average;
Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};
int n{}, i{};
float num[100]{}, sum=0.0, average{};
It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.
I'm creating this very simple C++ program.
the program asks the user to enter a few integers and stores them in an array.but when a specific integer(for example 50)is entered,the input is ended and then,all of the integers are displayed on the screen except for 50.
for example:
input:
1
2
88
50
output:
1
2
88
the error i'm getting is when i use cout to print the array,all of numbers are shown,including 50 and numbers i did'nt even entered.
this is my code so far:
#include<iostream>
int main() {
int num[100];
for(int i=0;i<=100;i++) {
cin >> num[i];
if (num[i]!=50) break;
}
for(int j=0;j<=100;j++) {
cout << num[j] << endl;
}
return 0;
}
Change the program the following way
#include<iostream>
int main()
{
const size_t N = 100;
int num[N];
size_t n = 0;
int value;
while ( n < N && std::cin >> value && value != 50 ) num[n++] = value;
for ( size_t i = 0; i < n; i++ ) std::cout << num[i] << std::endl;
return 0;
}
Here in the first loop variable n is used to count the actual number of entered values. And then this variable is used as the upper bound for the second loop.
As for your program then the valid range of indices for the first loop is 0-99 and you have to output only whose elements of the array that were inputed.
A do while loop is more suitable for your problem. The stop condition will check if the number fit inside the array (if k is not bigger than 100) and if number entered is 50.
#include<iostream>
using namespace std;
int main() {
int num[100];
int k = 0;
// A do while loop will be more suitable
do{
cin >> num[k++];
}while(k<100&&num[k-1]!=50);
for (int j = 0; j < k-1; j++) {
cout << num[j] << endl;
}
return 0;
}
Also, a better solution to get rid of 100 limitation is to use std::vector data structure that automatically adjust it's size, like this:
vector<int> num;
int temp;
do {
cin >> temp;
num.push_back(temp);
} while (temp != 50);
Note, you can use temp.size() to get the number of items stored.
You read up to 101 numbers, but if you enter 50 you break the loop and go for printing it. In the printing loop you go through all 101 numbers, but you actually may have not set all of them.
In the first loop count in a count variable the numbers you read until you meet 50 and in the printing loop just iterate count-1 times.
You have allocated an array of 100 integers on the stack. The values are not initialized to zero by default, so you end up having whatever was on the stack previously appear in your array.
You have also off-by-one in both of your loops, you allocated array of 100 integers so that means index range of 0-99.
As the question is tagged as C++, I would suggest that you leave the C-style array and instead use a std::vector to store the values. This makes it more flexible as you don't have to specify a fixed size (or manage memory) and you don't end up with uninitialized values.
Little example code (requires C++11 compiler):
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers; // Store the numbers here
for(int i = 0; i < 100; ++i) // Ask a number 100 times
{
int n;
std::cin >> n;
if( n == 50 ) // Stop if user enters 50
break;
numbers.push_back(n); // Add the number to the numbers vector
}
for (auto n : numbers) // Print all the values in the numbers vector
std::cout << n << std::endl;
return 0;
}
There are just 2 changes in your code check it out :
int main()
{
int num[100],i; //initialize i outside scope to count number of inputs
for(i=0;i<100;i++) {
cin >> num[i];
if (num[i]==50) break; //break if the entered number is 50
}
for(int j=0;j<=i-1;j++)
{
cout << num[j] << endl;
}
return 0;
}
Okay, others already pointed out the two mistakes. You should use i < 100 in the loop conditions instead of i <= 100 and you have to keep track of how many elements you entered.
Now let me add an answer how I think it would be better.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; // a temp variable in the for loop.
numbers.size() < 100 && // check that we have less than 100 elements.
std::cin >> temp && // read in the temp variable,
// and check if the read was a success.
temp != 50) // lastly check that the value we read isn't 50.
{
numbers.push_back(temp); // Now we just add it to the vector.
}
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i]; // Now we just print all the elements of
// the vector. We only added correct items.
}
The above code doesn't even read anymore numbers after it found 50. And if you want to be able to enter any number of elements you just have to remove the check that we have less than 100 elements.
Now I commented the above code a bit much, if you compress it it'll reduce to just:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i];
}
If you can use the C++11 standard it reduces to:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int element : numbers)
std::cout << element;
}
for (auto element : numbers) is new, it basically means for every int 'element' in 'numbers'.