C++ double recursion [duplicate] - c++

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Good debugger tutorial for beginners [closed]
(1 answer)
Closed 2 years ago.
Hello i was having some funny with my code lately and i met strange output of double recursion. I was trying to understand it but im not so lucky to know the answer yet. Maybe u ll help me with tis problem . Why this program has so weird output? output : 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1. I figure out that firstly it just do first somefunc call so printing 4321 , next somefunc has output like 1234. firs it decrement 1 so its 0 next decrement 2 by 1 so its 1 and then decrement then 3 decrement by 1 its 2 and 1 , decrement 4 by 1 untill 0 so its 321 its logically output will be 4321 2 1 3 2 1 but i dont understand the rest.
#include <iostream>
using namespace std;
void somefunc(int c)
{
if(c>=1)
{
cout <<c<<" ";
somefunc(c-1);
somefunc(c-1);
}
}
int main()
{
somefunc(4);
return 0;
}

Related

Confused by how stringstream seems to work [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 6 months ago.
I'm new to c++. Currently I'm learning how to read and write to a file. I've created a file "nb.txt" with content like this:
1 2 3 4 5 6 7
2 3 4 5 6 7 9
I'm using a simple program to read this file, looping until reached EOF.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("nb.txt");
while (in) {
int current;
in >> current;
cout << current << " ";
}
}
What I'm expecting is the program will output all of the values.
But what I'm really getting is this:
1 2 3 4 5 6 7 2 3 4 5 6 7 9 9
There's a multiple "9" in the output. I don't understand what's happening! Is it because of the while loop?
Can anyone help me to figure out why there is another "9"? Thanks!
The problem is that after you read the last value(which is 9 in this case) in is not yet set to end of file. So the program enters the while loop one more time, then reads in(which now sets it to end of file) and no changes are made to the variable current and it is printed with its current value(which is 9).
To solve this problem, you can do the following:
int main() {
ifstream in("nb.txt");
int current=0;
while (in >> current) { //note the in >> curent
cout << current << " ";
}
}
The output of the above program can be seen here:
1 2 3 4 5 6 7 2 3 4 5 6 7 9

same program gives different outputs everytime I run [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I tried writing a program that outputs "YES" whether every x value or y value is all the same. Otherwise it gives the output "NO". The logic is, if all the x values maximum value is the same as the all the x values minimum value, than this value has never changed, hence all the x values are the same. Same for the y values.
However, the output sometimes give the correct result, sometimes not (for the same input). Moreover, the outputs are not regular. (For example, 2 correct, 3 wrong, 5 correct, 1 wrong etc.)
Here is my code:
#include <iostream>
#include <climits>
using namespace std;
int main(){
int n;
int minX,minY=INT_MAX;
int maxX,maxY=INT_MIN;
cin>>n;
while(n--){ //for the next n line
int x,y;
cin>>x>>y;
maxX=max(maxX,x);
//cout<<maxX<<" "; //comments I write to find out what the heck is happening
minX=min(minX,x); // This value changes irregularly, which I suspect is the problem.
//cout<<minX<<" ";
maxY=max(maxY,y);
//cout<<maxY<<" ";
minY=min(minY,y);
//cout<<minY<<endl;
}
if(maxX==minX||maxY==minY){ //If the x values or the y values are all the same, true
cout<<"YES";
}
else{
cout<<"NO";
}
return 0;
}
Input:
5
0 1
0 2
0 3
0 4
0 5
Output when it Works (with the couts I commented):
0 0 1 1
0 0 2 1
0 0 3 1
0 0 4 1
0 0 5 1
YES
One of the output when it doesn't work(with the couts I commented)
0 -1319458864 1 1 // Not all the wrong outputs are the same, each wrong output is different than the other wrong output.
0 -1319458864 2 1
0 -1319458864 3 1
0 -1319458864 4 1
0 -1319458864 5 1
NO
In these lines
int minX,minY=INT_MAX;
int maxX,maxY=INT_MIN;
^
minX and maxX is never initialized. This is an UB as defined by the standard. Whatever you read is not predictable - it's usually what'l left on that block of memory by another process.
Do note that = has a higher priority than comma, so the expression is evaluated as
int (minX),(minY=INT_MAX);
Actually the comma has the lowest priority among all operators in C++. Change them to these should fix
int minX=INT_MAX,minY=INT_MAX;
int maxX=INT_MIN,maxY=INT_MIN;
^~~~~~~

What does this vector array code do? (C++)

Having difficulty finding an explanation to this.
What does this code do? I understand it creates an array of vector but that's about it.
How can I print the vector array and access elements to experiment with it?
#define MAXN 300009
vector<int>dv[MAXN];
int main()
{
for(int i=1;i<MAXN;i++)
for(int j=i;j<MAXN;j+=i)
dv[j].push_back(i);
}
The code is easy enough to instrument. The reality of what it ends up producing is a very simple (and very inefficient) Sieve of Eratosthenes. Understanding that algorithm, you'll see what this code does to produce that ilk.
Edit: It is also a factor-table generator. See Edit below.
Instrumenting the code and dumping output afterward, and reducing the number of loops for simplification we have something like the following code. We use range-based-for loops for enumerating over each vector in the array of vectors:
#include <iostream>
#include <vector>
#define MAXN 20
std::vector<int>dv[MAXN];
int main()
{
for(int i=1;i<MAXN;i++)
{
for(int j=i;j<MAXN;j+=i)
dv[j].push_back(i);
}
for (auto const& v : dv)
{
for (auto x : v)
std::cout << x << ' ';
std::cout << '\n';
}
}
The resulting output is:
1
1 2
1 3
1 2 4
1 5
1 2 3 6
1 7
1 2 4 8
1 3 9
1 2 5 10
1 11
1 2 3 4 6 12
1 13
1 2 7 14
1 3 5 15
1 2 4 8 16
1 17
1 2 3 6 9 18
1 19
Now, note each vector that only has two elements (1 and an additional number). That second number is prime. In our test case those two-element vectors are:
1 2
1 3
1 5
1 7
1 11
1 13
1 17
1 19
In short, this is a very simple, and incredibly inefficient way of finding prime numbers. A slight change to the output loops to only output the second element of all vectors of length-two-only will therefore generate all the primes lower than MAXN. Therefore, using:
for (auto const& v : dv)
{
if (v.size() == 2)
std::cout << v[1] << '\n';
}
We will get all primes from [2...MAXN)
Edit: Factor Table Generation
If it wasn't obvious, each vector has an ending element (that not-coincidentally also lines up with the subscripts of the outer array). All preceding elements make up the positive factors of that number. For example:
1 2 5 10
is the dv[10] vector, and tells you 10 has factors 1,2,5,10. Likewise,
1 2 3 6 9 18
is the dv[18] vector, and tells you 18 has factors 1,2,3,6,9,18.
In short, if someone wanted to know all the factors of some number N that is < MAXN, this would be a way of putting all that info into tabular form.

What mistake have I made in this code(C++)?

I was solving a problem on codechef:
https://www.codechef.com/NITWMA01/problems/QPALIN.It required to input m number of input cases after getting the value of m from the user. I always used to run a loop of:
while(m--)
{//input test cases}, but in this problem I don't know why the loop is running less than m times when I have to get input cases m times. I tried running the code with the sample input(with m having 6) but main() returned 0 after getting just 4 inputs(and printint respective outputs wherever necessary).
My code is as follows:
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int main()
{
int n,m,op,x,l,r,i,j,xorpair=0;
char k,s[100000];
scanf("%d",&n);
scanf("%s",s);
scanf("%d",&m);
for(j=0;j<m;j++)
{
scanf("%d",&op);
if(op==1)
{
scanf("%d",&x);
scanf("%c",&k);
s[x-1]=k;
}
else
{
xorpair=0;
scanf("%d%d",&l,&r);
for(i=l-1;i<r;i++)
{
xorpair^=s[i]-'0';
}
if(xorpair==0)
{
printf("YES\n");
}
else printf("NO\n");
}
}
return 0;
}
PS: I have replaced cin with scanf. Also I believe I was not able to properly convey what problem actually I am facing. So here's the test case that explains it more clearly:
(What it should be like)
Sample input:
7
abbacca
6
2 1 4
1 1 z
2 1 4
1 4 z
2 1 4
2 5 7
Sample output:
YES
NO
YES
YES
Following is the problem that I am facing:
When I run the program for the above input, this is what appears on the output screen
7
abbacca
6
2 1 4
YES
1 1 z
2 1 4
NO
1 4 z
Process returned 0 (0x0)
I am not able to enter inputs 6 times and after 4th input it returns 0.
scanf("%c" does not do what you seem to expect. It reads just the ' ' before the char you want. Then the next tries at reading op and x fail leaving op still equal to 1, so you do two of operation 1 for every once that you intended to.

Why would a error free code not give the expected result on one machine but yes on the other

I'm having a problem with a part of code. It should work,since it is error free, and it has no logical problems since it does work on someone else pc, but on my computer the result is the same as the input.
code(runnable):
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class RAngle{
public:
int x,y,l;
RAngle(){}
RAngle(int i,int j,int k){
x=i,y=j,l=k;
}
bool operator<(const RAngle& rhs)const{
if(l < rhs.l){
return true;
}
return 0;
}
friend ostream& operator << (ostream& out, const RAngle& ra){
out << ra.x << " " << ra.y << " " << ra.l;
return out;
}
friend istream& operator >>( istream& is, RAngle &ra){
is >> ra.x;
is >> ra.y;
is >> ra.l;
return is ;
}
};
void descrSort(vector <RAngle> &l){
for(unsigned i=0; i<l.size();i++){
cout<<l[i]<<endl;
}
cout << "==================" << endl;
sort(l.begin(),l.end());
reverse(l.begin(),l.end());
for(unsigned i=0; i<l.size();i++){
cout<<l[i]<<endl;
}
}
void readData(vector <RAngle> &l){
RAngle r;
ifstream f_in;
f_in.open("test.txt",ios::in);
for(int i=0;i<10;++i){
f_in >> r;
l.push_back(r);
}
}
int main(){
vector <RAngle> a;
readData(a);
descrSort(a);
return 0;
}
DATA:
1 7 31
2 2 2
3 3 3
4 5 1
10 5 1
1 1 9
10 3 10
4 5 7
5 4 15
2 3 25
1 7 31
The output on other machine(only print part after, the descr sort):
1 7 31
2 3 25
5 4 15
10 3 10
1 1 9
4 5 7
3 3 3
2 2 2
10 5 1
4 5 1
on my computer(hoel output):
1 7 31
2 2 2
3 3 3
4 5 1
10 5 1
1 1 9
10 3 10
4 5 7
5 4 15
2 3 25
==================
1 7 31
2 2 2
3 3 3
4 5 1
10 5 1
1 1 9
10 3 10
4 5 7
5 4 15
2 3 25
This means your code has an error. C and C++ let things compile and run that actually have errors in them. Like this:
int i;
std::cout << i << std::endl;
Will do different things on different machines. I would call it an error. The compiler won't.
Now as for where your error is, here is my "use a debugger" speech. Use a debugger. It will take you less time to use a debugger and have a decent chance of finding the error than it did for me to read your code to see if anything jumped out. Compile with -g. Google "gdb cheat sheet." Run with gdb. Follow the cheat sheet. See where your code does something unexpected.
Seems smart to do this on the machine that is giving the wrong output. And see where it's doing something wrong.
To expand on what #djechlin said, what you most likely have is "undefined behavior".
Most programming languages strictly define what can and can't be done, and compiler writers use that to generate compiler errors. Undefined behavior, on the other hand, means that it is up to the compiler writer and system; anything can happen - it can work correctly, it can erase your boot sector, zombie Alan Turing rise and feast on your brains, etc.
For example, using an uninitialized variable like so:
int i;
std::cout << i << std::endl;
on some compilers will give you a pattern like 0xCECECECE in debug builds to help find uninitialized variables. In release builds it might be set to 0 by the compiler, or it might be garbage data.