Iteration counter not incrementing [closed] - c++

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 8 years ago.
Improve this question
I wrote a program in c++ to print all the primes up to 100, but it just writes "hello world", and then hangs. Why is that?
#include <iostream>
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
for(int i = 2; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
int increase(int i)
{
return i++;
}
int main()
{
std::cout << "hello world!!" << std::endl;
int i = 1;
while(i < 100)
{
i = increase(i);
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}
}

return i++; this statement would return the original value of i, not the incremented one.
You need return ++i; or return i + 1 (thanks to #interjay for pointing that). The later return i + 1; makes it clear that only the return value matters, and not the new value of i.
The effect of post increment i++ would be visible on the next line (or usage of i).
Not really sure, if you need a separate method for incrementing your variable i, you can do that at in your while loop.
while(i < 100)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
i++;
}
You can also use a for loop, instead of while since you are working with a range of values.
for(i = 1; i < 100; i++)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}

Try this:
int increase(int i)
{
return ++i;
}
to get the incremented value of i else you will get the original value of i which will lead you to infinite loop.
The better approach would be to use(for clarity):
int increase(int i)
{
return i+1;
}

You are calling i++. i++ remembers what value i had and returns that. Try to call ++i.

return i++; returns i then increase i in function stack,
use return ++i; instead.
remember doing something on X++ first do something then increase X.

the problem is that ur increase function keeps returning 1. To fix the issue, change i++ to ++i, the second one modify i by adding 1 before returning

why create a function to increase i. just i = i+1;
The problem is with i++; should be change to ++i;
i++ evaluates i and then increments i, whereas it should be increment i before you evaluate..
Another problem start from 5 instead of 2 since you already handled the case
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
if(num == 2 || num == 3)
{
return true;
}
for(int i = 5; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
Another way of doing prime numbers:
bool is_prime(int num)
{
while(1)
{
int div = x-1;
if(x%div==0)
return false;
else
if(div != 1)
div--;
else
return false;
}
}

I++ increments I after executing the line. ++I increments I before executing the line.
You may check operator precedence (it works for c++ also)
c operator precedence
Note 2 explains why return I++ does not work.

Related

Loop does not continue correctly

I have been programming in C++ for the past 3 years, and I have always used the continue keyword in loops with success. But right now, a simple code of mine with continue is not working properly. Here is the code that is showing the problem:
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
else
{
continue;
}
num++;
}
cout << "The result is: " << result << endl;
return 0;
}
As stated above, this does not print anything on the console. When I remove the else statement with continue in it, it successfully calculates the result and prints the said result. Does anyone have any idea why the given code is not working correctly (or why the loop in it does not break)? Any sound answer would be much appreciated.
Loop is indeed continuing (continue works properly) correctly
Initially, num = 2, so if condition fails and goes to else. So it will call continue. Then again the loop starts from the beginning with num = 2. This continues forever.
In short, num value is not changing and if condition always fails.
It's a very simple issue. Look at this block of code properly:
else
{
continue;
}
Due to continue, n++ is never called because due to the non-changing value of n, num % 2 != 0 is always false. This is resulting in an infinite loop.
So to fix this issue, just remove the above block of code:
#include <iostream>
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
/*else
{
continue;
}*/
num++;
}
std::cout << "The result is: " << result << std::endl;
return 0;
}
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.
You just have to remove your else part because of no use and terminated cause of continue keyword.
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
num++;
}
std::cout << "The result is: " << result << std::endl;
return 0;
}
Since continue is just a thinly disguised goto, rewriting the loop with explicit gotos might make it clearer:
start:
if (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
else
{
goto start;
}
num++;
goto start;
}
Now you see clearly that num isn't incremented when num % 2 != 0 is false.
Just remove the else branch.

Why does the if/else if approach give a wrong answer for the Roman To integer conversion question? This is a question from leetcode

This is the question that I am referring to:
https://leetcode.com/problems/roman-to-integer/
And this is the code that I have used for the following:
int romanToDecimal(string &str) {
int num=0;
for(int i=0; i<str.size(); i++){
//three special cases given
if(str[i]=='I' and str[i++]=='V'){
num=num+4;
str.substr(i+2);
}
else if(str[i]=='I' and str[i++]=='X'){
num=num+9;
str.substr(i+2);
}
else if(str[i]=='X' and str[i++]=='L'){
num=num+40;
str.substr(i+2);
}
else if(str[i]=='X' and str[i++]=='C'){
num=num+90;
str.substr(i+2);
}
else if(str[i]=='C' and str[i++]=='D'){
num=num+400;
str.substr(i+2);
}
else if(str[i]=='C' and str[i++]=='M'){
num=num+900;
str.substr(i+2);
}
else if(str[i]=='I'){
num=num+1;
}
else if(str[i]=='V'){
num=num+5;
}
else if(str[i]=='X'){
num=num+10;
}
else if(str[i]=='L'){
num=num+50;
}
else if(str[i]=='C'){
num=num+100;
}
else if(str[i]=='D'){
num=num+500;
}
else if(str[i]=='M'){
num=num+1000;
}
}
return num;
}
It always ends up giving a wrong answer, not iterating and adding the numbers further. Why?
i++ and ++i and i + 1 does three different things.
And because how i++ works, str[i]=='I' and str[i++]=='V' will actually the equivalent to str[i]=='I' and str[i]=='V', which is always false.
And i++ (or ++i) is totally wrong here, you need i + 1 and then an increment inside the body of the if. As is the call to substr which isn't needed, and which returns the sub-string anyway, so it doesn't actually do anything useful.
Like for example:
if(str[i] == 'I' and str[i + 1] == 'V') {
num=num + 4;
++i;
}
As for why i++ (and ++i) is wrong inside the condition itself, think about if the condition str[i]=='I' is true but str[++i]=='V' is false... Then you will increase i before the next condition is checked:
// Begins with i == 0
if(str[i]=='I' and str[++i]=='V') { ... }
// If the above condition is false, this will be checked
// BUT! Here i might be equal to 1 because of the above increment
else if(str[i]=='I' and str[++i]=='X') { ... }
...
i is increased each if
this is how it should be
for(int i=0; i<str.size(); ){
.......
else if(str[i]=='X' and str[i + 1]=='C'){
num += 90;
...
i += 2;
}
..........
else i++;
}

Printing 1 to n using Fibonacci recursion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to print Fibonacci series from 1 to n in my function.
I know that I can do it by writing a regular Fibonacci and using it in a for block to print 1 to N. Like this:
#include <iostream>
using namespace std;
int fibo(int);
int main(){
for (int i = 0; i < 5; i++)
cout << fibo(5);
system("pause");
return 0;
}
int fibo(int n){
if (n == 1 || n == 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
but my problme is that I can't do it without for,IN my function
I mean I want to Print it with a recursive algorithm
Here is my code up to now
#include <iostream>
using namespace std;
int fibo(int, bool);
int main(){
fibo(5, false);
system("pause");
return 0;
}
int fibo(int n, bool IsPrinted){
if (n == 1 || n == 2){
if (!IsPrinted)
cout << 1 << endl;
return 1;
}
else{
int temp = fibo(n - 1, IsPrinted) + fibo(n - 2, IsPrinted);
if (!IsPrinted){
cout << temp << endl;
IsPrinted = true;
}
return temp;
}
}
long fibo(int N, bool print) {
long value = 0;
if(1 == N)
value = 1;
if(1 < N)
value = fibo(N-1, print) + fibo(N-2, false);
if(print)
std::cout << N << " => " << value << std::endl;
return value;
}
int main(){
fibo(5, true);
return 0;
}
What you should realize is that the calls to the fibo function makes a tree. The root of the tree is the call to fibo(5, true) in the main(). As you only want to print each value once, the solution is to decide to print the value of the function only on the leftmost branch of that tree. The rule is then simply:
never print when on a right branch (hence the call to fibo(N-2, false)
never print if the parent didn't print (to avoid printing when on a child left branch of a right branch)
A common solution is to use memoization:
int fibo(int n)
{
static std::map<int,int> memo;
auto it=memo.find(n);
if(it!=std::end(memo))
{
return it->second;
}
int ret=1;
if (n > 2)
{
ret = fibo(n - 1) + fibo(n - 2);
}
memo[n]=ret;
return ret;
}
Then you can safely loop over the input parameters without recomputing the values over and over again:
for(int i=0;i<20;++i)
{
std::cout<<i<<" "<<fibo(i)<<std::endl;
}
Note that this is not only advantageous in printing but also for the calculation itself (at least as long as you call the function more than once).
Beside the above, you should also consider using long or double for the return type, as int will overflow more quickly.
EDIT: Ok, after your edit I don't know whether my answer exactly fits to your question, but I think it's a good advice anyway.
But here is another quick alternative which comes close, I guess:
int fibo(int n, bool first=true)
{
int ret=0;
if(n>2)
{
ret=fibo(n-1,false)+fibo(n-2,false);
}
else
{
ret=1;
}
if(first)
{
std::cout<<ret<<std::endl;
}
return ret;
}
DEMO

bool function for prime numbers

I have the following code for checking whether the first 20 positive numbers are prime using a bool function.
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int);
/*
function to evaluate whether a positive integer is prime (true)
or not prime (false)
*/
int main()
{
for(int x=1; x<=20; x++)
{
cout << x << " a prime ? (1 yes, 0 no) "
<< prime(x) << endl;
}
return 0;
}
bool prime(int x)
{
for(int i=2; i<= sqrt(x); i++)
{
if ((x%i) != 0)
return true;
else
return false;
}
}
It works for all numbers 1 to 20 apart from 2 and 3 where the output is 0 instead of 1. I think I know why. For x = 2 and 3 there is no i in the for loop such that i<=sqrt(2) or i<=sqrt(3).
How could I modify the code so it would work for these values too?
Also there is an error message "Control may reach end of non-void function". Why is this?
Thanks.
Modify your prime function to the following
bool prime(int x)
{
if (x < 2) return false;
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0) return false;
}
return true;
}
The Control may reach end of non-void function error message tells you that your prime function does not return in all cases (When you pass 1 to your function, it does not go in the for loop, and so exit without explicitly returning anything, which could lead to undefined-behavior). In general, you want to have a return instruction outside of any conditionnal structure.
You return in the wrong place in your prime function.
bool prime(int x) {
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0)
return false;
}
return true;
}
In your existing function you only test the very first i. The compiler warning refers to how if the loop finishes without returning (although this is easy for us to see it never will), then control will reach the end of prime without returning a value.
Extract return true result from cycle!
bool prime( int _x )
{
double x = sqrt( _x );
for( int i = 2; i <= x; ++i )
if ( !( _x % i ) )
return false;
return true;
}
you can also use this without need to sqrt function , there it is
bool prime (int num){
int i,temp;
for (i=2; i<=num/2) && temp; i++)
if (num%i==0)
temp = 0;
return temp;}

Recursive/iterative functions

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}
Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);
You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!
I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}
void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.
the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}
To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.