We input n numbers and the program must type the ones that have exactly 2 ‘9’ in them. (for instance, if we input 9193 then the program will type it, but if we write 73999 or 256 it will not give any output).
So I wrote this code
int main(){
int a, n, i, count=0, y;
cin>>n;
for(i=1; i<=n; i++){
cin>>a; y=a;
while(y>0){
if(y%10==9) count++;
y=y/10;
}
if(count==2) cout<<a<<endl;
}
return 0;
}
But I cannot understand why this does not work.
If I change it and write this way it works.
int main(){
int a, n, i, count, y;
cin>>n;
for(i=1; i<=n; i++){
count=0;
cin>>a; y=a;
while(y>0){
if(y%10==9) count++;
y=y/10;
}
if(count==2) cout<<a<<endl;
}
return 0;
}
Will much appreciate if you explain this to me.
Just read as string (or convert it to) and count:
for(i=1; i<=n; i++){
std::string numstr;
std::cin >> numstr;
if( std::count( numstr.begin(), numstr.end(), '9' ) == 2 )
std::cout << numstr << std::endl;
}
If you don't reset count to 0 each time through the main loop, you're adding the count in the new number to the count from the previous number.
So if you type 19 for the first number, you'll set count to 1. Then if you type 939 for the second number, it will set count to 3, and the test if (count == 2) will not succeed, even though there were 2 nines in that number. After this, count will never become 2, because you'll keep adding to it.
You need to start counting from the beginning for each number.
Note that your algorithm won't work for negative numbers. -9 % 10 is -9, not 9.
We need to initialise count=0 for every case.
Related
#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...
while(i <= N)
2 <= 5 is true, so we loop
if(i%2 == 0)
2 % 2 == 0 is true, so we enter this branch
sum = sum + i;
Update sum, then head back to the top of the loop
while(i <= N)
Neither i nor N have changed, so 2 <= 5 is still true. We still loop
if(i%2 == 0)
2 % 2 == 0 is still true, so we enter this branch again...
Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?
Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to
int sum = 0;
You're looping infinitly when i is even because you don't increase it.
Better option would be this if you want to use that while loop :
while(i<=N)
{
if(i%2 == 0)
sum = sum + i;
i=i+1;
}
cout << sum;
If you don't need to do anything when the condition is false, just don't use an else.
No loops are necessary and sum can be evaluated at compile time if needed too
// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
unsigned int m = (n / 2);
return m * (m + 1);
}
int main()
{
// compile time checking of the function
static_assert(sum_of_even_numbers_smaller_then(0) == 0);
static_assert(sum_of_even_numbers_smaller_then(1) == 0);
static_assert(sum_of_even_numbers_smaller_then(2) == 2);
static_assert(sum_of_even_numbers_smaller_then(3) == 2);
static_assert(sum_of_even_numbers_smaller_then(7) == 12);
static_assert(sum_of_even_numbers_smaller_then(8) == 20);
return 0;
}
int main(){
int input; //stores the user entered number
int sum=0; //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1) //this check the number to be bigger than one means must be positive integer.
goto repeat; // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
if(i%2==0){
sum=sum+i;
int j=0;
j=j+1;
cout<<"Number is: "<<i<<endl;
}
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}
Copy this C++ code and run it, it will solve your problem.
There are 2 problems with your program.
Mistake 1
The variable sum has not been initialized. This means that it has(holds) an indeterminate value. And using this uninitialized variable like you did when you wrote sum = sum + i; is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.
This is why it is advised that:
always initialize built in types in local/block scope.
Mistake 2
The second problem is that you're not updating the value of variable i.
Solution
You can solve these problems as shown below:
int main(){
int i = 1;
int sum = 0; //INITIALIZE variable sum to 0
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1; //update(increase i)
}
cout << sum;
}
1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.
I am trying to solve a problem where every letter has a respective number such as a-1,b-2....z-26.
Now given a number, in how many ways can the number be decoded is the question. consider an example where 25114 can be decoded as 'BEAN',‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. this could be decoded in 6 ways.
I have written code in c++ but I am getting the wrong answer. Please correct my code.
#include<bits/stdc++.h>
using namespace std;
int total = 0;
int arr[100001];
void func(int start,int end,int factor){
if(start==end)
return;
int j =start;
if(factor==2&&j==end-1)//if j is the last element and factor is 2,accessing j+1 element is illegual
return;
if(factor==2){
if((arr[j]*10+arr[j+1])>26)
return;
else{
total++;
func(start+2,end,1);
func(start+2,end,2);
}
}
else{//factor is 1
total++;
func(start+1,end,1);
func(start+1,end,2);
}
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int p;
cin>>p;
arr[i]=p;
}
func(0,n,1);
func(0,n,2);
cout<<total<<endl;
return 0;
}
essentially what my code is doing is that it fixes one number from the given array(using one digit or two digits from the the given array) and recurses until all the combinations are covered. for example considering the above case, I first choose '2' as my first digit and decode it as 'B'(factor = 1) and then choose '25' and decode it as 'E'(factor = 2).
**following are the input and output from the following code
input : 25114
expected output : 6
my output : 15
input : 3333333333(10 digits)
expected output : 1
my output : 10
Based on the original program from the question I suggest to count the encodings when you reach the end only (if(start==end)).
As func will always be called twice with factor=1 and factor=2, I can freely choose either condition for counting.
Here is the modified code:
#include<bits/stdc++.h>
using namespace std;
int total = 0;
int arr[100001];
void func(int start,int end,int factor){
if(start==end) {
if(factor == 1) total++; // count once when reaching the end
return;
}
int j =start;
if((factor==2) && (j==end-1))//if j is the last element and factor is 2,accessing j+1 element is illegal
return;
if(factor==2){
if((arr[j]*10+arr[j+1])>26)
return;
else{
//total++;
func(start+2,end,1);
func(start+2,end,2);
}
}
else{//factor is 1
//total++;
func(start+1,end,1);
func(start+1,end,2);
}
return;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int p;
cin>>p;
arr[i]=p;
}
func(0,n,1);
func(0,n,2);
cout<<total<<endl;
return 0;
}
This calculates the expected results from the example input in the question.
$ echo 5 2 5 1 1 4|./program
6
$ echo 10 3 3 3 3 3 3 3 3 3 3|./program
1
There is room for improvement.
Instead of modifying a global variable I would return the number of combinations from func and add the values in the higher level.
I would also handle the distinction between 2-digit and 1-digit numbers in the called func instead of in the caller.
Something like this pseudo code:
int func(int start, int end)
{
if(remaining length is <2) {
// we reached the end, so this is one combination
return 1;
}
if(two-digit number is >26) {
// only a 1-digit number is possible, count remaining combinations
return func(start+1, end);
}
// both a 1-digit or 2-digit number is possible, add the remaining combinations for both cases
return func(start+1) + func(start+2);
}
Your question is tagged as "dynamic-programming", but it is anything but.
Instead, think about the state space and its boundary conditions:
The empty string has zero encodings;
A single digit has a single encoding;
An n-digit string has as many encodings as an (n-1)-digit substring plus as many encodings as an (n-2)-digit substring if the first two digits are <= 26.
Thus, we can walk the string from back to front and store the intermediate results for reuse:
uint64_t solve(std::vector<int>& digits) {
const int n = digits.size();
std::vector<int> encodings(n+1);
encodings[n] = 1;
for (int i = n-1; i >= 0; i--) {
bool two_digits_fit = (i < n - 1) && (digits[i] * 10 + digits[i+1]) <= 26; // What if digits[i] == 0?
encodings[i] = encodings[i+1] + (two_digits_fit ? encodings[i+2] : 0);
}
return encodings[0];
}
i have to convert values from 1 to 63(decimal to binary) in such a way that it store in table in 6 place.
for instance, if i enter 2 it convert it into binary: 10 , but i want it to show it in 6-places like 000010. and store it in a table.
i am unable to find a code which convert decimal to binary and show 6 places..what should i do to do this...??
#include <iostream>
using namespace std;
int main()
{
int a[10], n, i;
cout<<"Enter the number to convert: ";
cin>>n;
for(i=0; n>0; i++)
{
a[i]=n%2;
n= n/2;
}
cout<<"Binary of the given number= ";
for(i=i-1 ;i>=0 ;i--)
{
cout<<a[i];
}
}
i tried this but i convert it into the specified bit like convert 2 in 10, and 3 in 11 same as for others, but i want to convert it into 3=000011.
So the one way to solve your problem is: First, initialize the array of 6 elements with zeros...
also you dont have to use an array of 10 as you mentioned clearly that numbers are 1 to 63
int a[6], n, i;
So you can just add this before your input1
for (i = 0; i < 6; i++) {
a[i] = 0;
}
Now the loop you had run doesn't make much sense to me as a programmer, although I know it is correct... because the condition is on n but increment is on i. So I'd change it like this
while (n > 0) {
a[i] = n % 2;
n = n / 2;
i++;
}
And change the i-1 to 5 (OR MAX_CAP - 1; where MAX_CAP is 6)
for(i=5 ;i>=0 ;i--)
{
cout<<a[i];
}
But According to me, you should use vectors instead of arrays to get rid of that initialization
vector<int> a(6,0);
I'm writing a program for finding whether a given number is an Armstrong Number:
int main()
{
int n,rem,sum=0;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
while(n!=0)
{
rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
When I run it, it always reports "It's not a armstrong number", regardless of input.
I changed the code as follows, and got the correct result. But I don't understand why I need to assign input to n1 and do the operation - why can't I directly do the operation with n?
int main()
{
int n,rem,sum=0,n1;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
n1=n;
while(n1!=0)
{
rem=n1%10;
sum=sum+(rem*rem*rem);
n1=n1/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
In the line if (sum==n) your program compares sum and n. In the second program n is initial number entered by user. But in the first program n==0 (see the loop above it).
So, in the first program the check if (sum==n) works as if (sum==0). But value of sum is never 0 (except user entered 0). So, first program always returns "It's not a armstrong number".
And about style: It is much better to use functions instead of putting the whole logic into one main() function. For instance, you can create a function for calculation of the intermediate sum for cheching of Armstrong Number:
int getSumOfCubesOfDigits(int n)
{
int sum = 0;
while (n)
{
const int rem = n % 10;
sum += rem * rem * rem;
n = n / 10;
}
}
In this case your program will be much simpler and it will be hard to make the mistake you have in the first program of your question:
int main()
{
int n;
cout << "Enter the Number for checking" << endl;
cin >> n;
if(getSumOfCubesOfDigits(n) == n)
cout<<"Armstrong Number"<<endl;
else
cout<<"It's not a armstrong number";
return 0;
}
In the first program, the original number is entered into 'n'. The only problem in your logic is, you forgot that by the time you exit from the while loop, 'n' will no longer be your original number since you are repeatedly doing n=n/10, and hence 'sum==n' never satisfies even for an Armstrong number.
So before you enter the while loop, save the original number into another variable, say n1 (as done in the second program you provided), and only use n1 for operations, ie, n1=n1/10. Leave n alone so that, in the end 'n' will still contain the original number, which you can finally compare with 'sum' to find your answer.
Which number do you compare ? , in first program in while loop , n value is changed ( in this variable you get the input) and finally check with sum == n , so it always get condition fail.
So temp (n1) variable is required , to compare the final result
Your code is different in the second code block, you are still testing if sum=n.
In the second code block, if you tested if(sum=n1), I would suspect it would work the same.
I got this solution for finding an Armstrong Numbers
int main() {
for (int i=10; i<=9999; i++) {
int k = i,z = 1, s = 0, n = i;
while ((k/=10) > 0) z++;
for (int t = z; t; t--, n/=10) {
s += pow(n % 10, z);
}
if (i == s) cout << i << endl;
}
return 0;
}
Example: Let’s say your user input is 6.
Then the number of sequences that sum up to 6 is 11 (including 6 itself). This is shown clearly below:
6
5+1
4+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1
2+2+1+1
3+2+1
4+2
2+2+2
3+3
You SHOULD NOT have any sequences that repeat. You cannot have 2+2+1+1 and 1+1+2+2 as two different combinations!!
CODE:
#include <iostream>
using namespace std;
int sum(double number, int min, int & counter)
{
int temp=0, n;
n=number+temp;
if ((number>=(n/2)) & (number!=0))
{
number --;
temp ++;
while (number>=(n/2))
{
cout << number << "+"<< temp << "\n";
number --;
temp ++;
counter ++;
}
}
else if (number==0)
{
return 0;
}
sum(n-min, 1,counter);
return 0;
}
int main()
{
int number, counter=1;
cout << "Please enter the number: ";
cin >> number ;
cout << "\n";
sum(number, 1, counter);
cout << counter;
return 0;
}
My output is
6
5+1
4+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1
2+2+1+1
3+2+1
3+1+2
2+3+1
4+2
2+2+2
3+3
0+1
Total out is 13.
Real output which is a shorter version for those of you who dont like whats posted above.
5+1
4+2
3+3
4+1
3+2
2+3
3+1
2+2
2+1
1+2
1+1
0+1
13
Where 1+2 and 2+3 are doubles as listed above.
Any ideas what is wrong here?
I guess it would be easier if you'd sum so that the first summand is always highest possible and you don't allow that of two adjacent summands the second one is greater than the first one.
Just a thought...
I've already posted a solution to it in your previous question:
void sum_r(int n, int m, int cnt, int* nums){
for (;n >= m; m++)
sum_r(n-m, nums[cnt] = m, cnt+1, nums);
if (!n) for (int i=0; i<cnt; i++) printf("%d%c",nums[i],(i==cnt-1)?'\n':'+');
};
void sum(int n){
int nums[100];
return sum_r(n, 1, 0, nums);
};
int main(){
sum(6);
return 0;
};
EDIT: I'll try to explain it better. The main idea is to impose an order on the generated sequence, it will help in avoiding repetition.
We will use the min parameter for that, it will be the smallest possible term we can use from now on in the sequence.
The function sum_r just prints the sequence of values of min at each recursion level.
The num term is used as a kind of accumulator, or the value left "to spare".
We can write a simplier function, that just counts the number of such sequences:
int sum_c(int n, int m){
if (!n) return 1; // termination condition. end of sequence reached with "perfect match". this means we have found 1 additional sequence. Note that it's the only way of adding new values to result.
int comb_cnt = 0;
while (n >= m) { // we need a stop condition, and there is no point in having negative value of (n - m)
comb_cnt += // here we accumulate all the solutions from next levels
sum_c(n-m, m); // how many sequences are for current value of min?
m++; // trying a larger `min`
};
return comb_cnt; // number of sequence fond at this level
};
Here's a hint: The problem is to compute the partitions of the input number. See also: partition function
Well the logical AND operator in C++ is &&, not & as you have in this line:
if ((number>=(n/2)) & (number!=0))