Count the occurence of a particular digit in a range of number - c++

I was trying to count the number of digit 2 in an range of number (say 2-22, the answer would be 6: 2,12,20,21,22 as 22 contribute twice). This is the code that I came up with, yet it fails to run after value input. Any ideas?
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int lowerbound,upperbound,sum=0;
int nofNum(int num);
scanf("%d %d",&lowerbound,&upperbound);
for (int i=lowerbound;i<=upperbound;++i){
sum+=nofNum(i);
}
printf("%d",sum);
return 0;
}
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
num/=10;
}
}
return count;
}

you are using c not c++. Your mistake is that nofNum wasn't declared before you used it. It has to be declared before the line you use it.
int nofNum(int num);
would declare it.
You will still need to implement it, which you allready did.
alternatively you can move the implementation st. it is above main, where you used it.
EDIT: i just saw you declared it inside main, which is uncommon at best. you really should not do that.
EDIT2:
you messed up that if statement in numOf
int nofNum(int num){
int count=0;
while(num!=0){
if (num%10==2){
count++;
}
num/=10; // may not be inside if, since num would not be adjusted
// if the last digit isnt a 2
}
return count;
}
EDIT3:
you can use input and output streams in c++ to replace scanf and printf:
scanf("%d %d",&lowerbound,&upperbound);
becomes
std::cin >> lowerbound >> upperbound;
and
printf("%d",sum);
becomes
std::cout << sum << std::endl;
Edit4:
suggested form:
// declarations - this is what would belong to the *.h file later on.
int nofNum(int num);
followed by
int nofNum(int num) { /*implementation*/ }
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
or
// this is valid because we allready heard of nofNum through declaration
int main(int /*argc*/, char* /*argv*/[]) { /*implementation*/ }
int nofNum(int num) { /*implementation*/ }
the upper form doesn't require the declarations because each function allready is implemented before you use them, therefore the compiler allready knows what nofNum is supposed to be.

Related

global vairable did not initialize correctly between running multiple test cases in c++

I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.
The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2 int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
cout<<n<<endl;
return n;
}
int main()
{
return 0;
}
Here is the code to run test case #2:
int main()
{
const string s = "26";
dfs(s,0);
cout<<n<<endl;
return 0;
}
If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.
Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.
#include <iostream>
#include <string>
using namespace std;
int n=0;
void dfs(const string& s, int i){
if (i==s.size()){
n++;
return;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
dfs(s, i+2);
}
int decodeVariations(const string& s)
{
dfs(s,0);
return n;
}
int main(int argc, char **argv){
for (int i=1;i<argc;i++)
cout<<decodeVariations(argv[i])<<endl;
}
run with ./test 26 26 26
output:
2
4
6
Quick fix is to get rid of global variable
#include <iostream>
#include <string>
using namespace std;
//int n=0;
int dfs(const string& s, int i){
int ans = 0;
if (i==s.size()){
return 1;
}
if ( 0<s[i]-'0' && s[i]-'0'<10)
ans += dfs(s, i+1);
if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
ans += dfs(s, i+2);
return ans;
}
int decodeVariations(const string& s)
{
// your code goes here
int n;
n = dfs(s,0);
cout<<n<<endl;
return n;
}

What is the problem with the following code using constructors for sorting strings?

#include <iostream>
#include <string.h>
using namespace std;
class sorting
{
private:
char str[10];
public:
sorting() {
int i;
for(i=0;i<10;i++) {
cin>>str[i];
}
}
void sort() {
int i,j;
char temp;
for(i=0;i<10;i++) {
for(j=i+1;j<10;j++) {
if(strcmp(str[j],str[j+1])>0) {
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
for(i=0;i<10;i++) {
cout<<str[i];
cout<<"\n";
}
}
};
int main() {
sorting s1;
cout<<s1.sort();
return 0;
}
This is a code I have written to sort strings using constructors. It gives me error in the if condition of the code where I have used strcmp. Please review this for I could not get the desired output and it gives me errors.
Problem 1
Like someone already pointed out, you cant use strcopy on chars. If you want to create a string array i would suggest using either char** or std::string*.
Problem 2
In your nested loop you will get an index out of bounds error, due to the fact that once i reaches a value of 8, j will be 9, which means that when you try to access str[j+1] which evaluates to str[10], you will get said error.

Id returned 1 exit status. C++

I'm very new to C++, so I've probably made some really stupid mistakes. But I've looked online to solutions for this error, and I tried all I can think of.
I'm trying to have my whole program in one function, because it's going to be merged with other programs. The id error is the only error I have so far.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std;
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
void BookingSystem(int time, int k);
int time;
int k = 0;
int main()
{
BookingSystem(time, k);
{
while (k==0)
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
scanf("You have selected to book your meal for %d", &time);
if (time!=7||time!=9)
{
printf("Sorry, that was an incorrect time");
time = 0;
}
}
return 0;
}
system ("pause");
return 0;
}
Any help is much appreciated, I've spent a long time trying to fix this on my own with no luck.
Thank you!
You make many mistakes in your program:
1) You mix C & C++ syntax.
using namespace std, is C++
2) You include useless header files
3) You declare variables that I don't understand what for
Why do you need this?
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
You don't use the variables above anywhere !!!!
4) You try to write a function inside main (this is not Pascal).
So, if I understand what you want, look at this:
#include <stdio.h>
void BookingSystem() // this is the function who does all job
{
int time = 0;
while ((time != 7) && (time != 9))
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
printf("\nYou have selected to book your meal for ");
scanf("%d", &time); // read the time
scanf("%*[^\n]"); // consume all caracters until the newline
scanf("%*c"); // consume the newline
if (time == 7)
{
printf("You have selected to book your slot at 7PM\n");
}
else if (time == 9)
{
printf("You have selected to book your slot at 9PM\n");
}
else
{
printf("You have selected an incorrect time, please try again\n");
}
} // end while
} // end function
int main(int argc, char *argv[])
{
BookingSystem(); // this is the calling to your function
return 0;
}
If I understand what you want, this works fine.
you can not to Define Function in to the main ..
you must to do like this...
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std;
int ninebooking(int , int , int ); //just say data type int or ....
int sevenbooking(int , int , int );
void BookingSystem(int , int);
int main() //and in to main just call he...
{
int time;
int k = 0;
BookingSystem(time, k);//call ....and send parameter time and k
system ("PAUSE");
return 0;
}
void BookingSystem(int time,int k)
{
while (k==0)
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
scanf("You have selected to book your meal for %d", &time);
if (time!=7||time!=9)
{
printf("Sorry, that was an incorrect time");
time = 0;
}
}
// return 0;//if this function is void he can not to return any thing!!!!
}
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0)
{
//......
}
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0)
{
//........
}

combinations of k-tuple from n elements set by recursive

#include <vector>
#include <iostream>
using namespace std;
void SubSetNum(bool * select, int*a, int selectk, int k, int selectn, int n )// depthk to
{
if(k>n) return;
if(selectn==n)
{
if(selectk==k)
{
for(int i=0;i<n;i++)
if(select[i]==true)
cout<<a[i];
cout<<endl;
}
return;
}
select[selectk]=false;
SubSetNum(select,a,selectk,k,selectn+1,n);
select[selectk]=true;
SubSetNum(select,a,selectk+1,k,selectn+1,n);
}
int main()
{
int k=3;
int n=5;
int a[]={1,5,8,10,13};
//while(cin>>k)
{
bool *select=new bool[n];
memset(select,0,sizeof(bool)*n);
SubSetNum(select,a,0,k,0,n);
delete []select;
}
return 0;
}
This a question, that I want to get k elements from n elements set.
But it prints out incorrect answer? I am always confused when I design recursive algorithms...Especially the parameter of functions, if or not return value, and so on, thus I always try to forcely remember the code in textbook.
Your mistake is here:
select[selectk]=false;
...
select[selectk]=true;
It should be this:
select[selectn]=false;
...
select[selectn]=true;
I believe the cause of the mistake was a failure to remember what the variables represent. The variable selectn is the index of the element being included or excluded. The variable selectk is the number of elements already included. It does not make sense to use selectk as an index into a.

C++ Int getting random value after function that isn't supposed to change it

Okay - yes, this is homework, but it isn't mine. I have a friend taking an introductory C++ course who asked me for help, and I helped them write this program, but there is one weird bug that I can't figure out. Any helpful suggestions would be greatly appreciated. Thanks!!
The following is the code. The problem is that after the add_loop function, the int loop_size gets a random value. Within the function, it has the value it is supposed to have, but afterwards, it changes.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define STRING_SIZE 50
void get_template (char StemLoop [])
{
char Template [STRING_SIZE];
cout<<"Please enter a template for the stem:";
cin>> Template;
strcpy (StemLoop, Template);
}
void add_loop (char StemLoop[], int loop_size)
{
char random_loop [STRING_SIZE];
int random_array[STRING_SIZE];
for (int i=0; i<loop_size; i++)
{
random_array[i] = rand() % 4;
if (random_array[i]==0)
random_loop[i]='A';
else if (random_array[i]==1)
random_loop [i]='U';
else if (random_array[i]==2)
random_loop [i]='G';
else if (random_array[i]==3)
random_loop [i]='C';
}
strcat (StemLoop, random_loop);
}
void add_complement(char StemLoop[], int loop_size)
{
int x =strlen(StemLoop);
int j=0;
char complement [STRING_SIZE]="";
for (int i=0; i<(x-loop_size); i++)
{
if (StemLoop[i]=='A')
complement[j]='U';
else if (StemLoop[i]=='U')
complement[j]='A';
else if (StemLoop[i]=='G')
complement[j]='C';
else if (StemLoop[i]=='C')
complement[j]='G';
j++;
}
strcat(StemLoop,complement);
}
void main()
{
int loop_size=0;
cout<<"Please enter the size of the loop: ";
cin>>loop_size;
char StemLoop [STRING_SIZE];
//Part1: the template
get_template (StemLoop);
//This is supposed to be the function that adds the loop of random "genes".
//It works, and within it the int loop_size is the correct value...
add_loop (StemLoop, loop_size);
/*...but here it is a random number. It's as if the random value generated
within the function is getting assigned to it. And of course, it's throwing off the
entire program.
*/
//Part#3: the complement
add_complement (StemLoop, loop_size);
cout<<"The complete stem-loop strand is:"<<StemLoop<<endl;
}
You're not 0-terminating random_loop before you use it in strcat, so strcat can write all over your stack. Try this:
random_loop[i] = 0;
strcat (StemLoop, random_loop);
A more serious problem could be that you're not checking you have enough room to strcat.