Defining A Range

Hello everyone. I am stuck at a point where my program won't go for a loop. I'm trying to define a range of numbers and not with vectors or arrays but with a for loop as I want the number to increment after the desired operation is performed and only be terminated once the condition for it is met, which I've defined to be a limit after which the execution will stop.

Let's say I want to choose a range of numbers, say from 1 to 10. And what I want to do is for every alternate number, I want to perform a different operation. Example - Say for 1, I add 6 so for the other number, I define a different operation such as subtract 6 from the number. So the order of operation for the range 1 to 10 would be like :-

1 = 7
2 = -4
3 = 9
4 = -2
5 = 11
6 = 0
7 = 13
8 = 2
9 = 15
10 = 4


Although I believe that the code will not be needed since the problem is self-sustained, contained and consistent, I will provide the parametric statement, i.e; the for statement with the arguments.
1
2
3
  for (n=1; n<=(2^3); n++) { 
    //conditional functions looped until the desired result is achieved 
  }
Last edited on
the problem is self-sustained, contained and consistent

That's kind of a bizarre statement. If you are trying to say that your problem statement is clear, then that is not the case. I have very little idea what you want to do.

Anyway, you seem to be unaware of what the ^ operator does in C++. It is the "exclusive OR" operator. 2 ^ 3 yields 1. If you want 2 raised to the third power you would say 1 << 3 (1 bitshifted to the left by 3), although you may as well just say 8.
Last edited on
2^3 is 1. Are you trying to raise 2 to the power of 3? Have a look at std::pow: https://en.cppreference.com/w/cpp/numeric/math/pow
Hello RCPP,

Welcome to the forum.

The for loop will work if it was written correctly. For instance "2^3" will produce the answer of 8 not the 10 that you will need. Unless you have a need for a formula keep it simple.

This is a quick thought I had that might solve your problem. I think I understand what you are trying to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (int n = 1; n <= 10; n++)
{
	//conditional functions looped until the desired result is achieved 
	swithc(n)
	{
		case 1:
			// <--- Formula for 1.
			break;
		case 2:
			// <--- Formula for 2.
			break;
		default:
			// <--- Error message. Should not be needed.
	}
}


Hope that helps,

Andy
> For instance "2^3" will produce the answer of 8

Not in C++. ^ is the operator for XOR
@ntchambers, you should say who you are responding to. Usually you would use [quote=username]quote goes here[/quote] for that.

@RCPP, Your example just starts at 7 and alternately subtracts 11 and adds 13, ending when the result is 4. The following code adds a limit to the number of loops just in case the end value is not reached in a reasonable time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>

void out(int i, int n) {
    std::cout << std::setw(3) << i << " = " << std::setw(3) << n << '\n';
}
 
int main() {
    int n = 7, i = 0;
    out(++i, n);
    while (i < 100 && n != 4) {
        out(++i, n -= 11);
        if (n == 4) break;
        out(++i, n += 13);
    }
}

Last edited on
I'm well aware of forum etiquette, but thanks :)
Here's a few options, increasing in flexibility (and obscurity!):

Note (edit): the programs below assume the function to be chosen depending on first, second, third, ... number and NOT on whether n is even or odd.
If your function choice depends on whether n is even or odd instead then you can use n%2 as a switch, as in @Keskiverto's further example below, and you wouldn't need the toggle opt.

Hard-coded:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
   int start = 1, end = 10;
   for ( int n = start, opt = 0;  n <= end;  n++, opt = 1 - opt )    // Update counter AND option
   {
      if      ( opt == 0 ) cout << n << " ==> " << n + 6 << '\n';
      else if ( opt == 1 ) cout << n << " ==> " << n - 6 << '\n';
   }
}
1 ==> 7
2 ==> -4
3 ==> 9
4 ==> -2
5 ==> 11
6 ==> 0
7 ==> 13
8 ==> 2
9 ==> 15
10 ==> 4



With functions (to improve flexibility and avoid repetition in output)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
using namespace std;


int funct0( int x )     // For 1st, 3rd, ... numbers
{
   return x + 6;
}


int funct1( int x )     // For 2nd, 4th, ... numbers
{
   return x - 6;
}


void output( int n, int result )
{
   cout << setw( 3 ) << n << " ==> " << setw( 3 ) << result << '\n';
}


int main()
{
   int start = 1, end = 10;
   for ( int n = start, opt = 0;  n <= end;  n++, opt = 1 - opt )
   {
      if      ( opt == 0 ) output( n, funct0( n ) );
      else if ( opt == 1 ) output( n, funct1( n ) );
   }
}
  1 ==>   7
  2 ==>  -4
  3 ==>   9
  4 ==>  -2
  5 ==>  11
  6 ==>   0
  7 ==>  13
  8 ==>   2
  9 ==>  15
 10 ==>   4



With a switch as alternative to if ... else, and a function pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <iomanip>
using namespace std;


int funct0( int x )          // Code what you want with the 1st, 3rd, ... numbers
{
   return x + 6;
}


int funct1( int x )          // Code what you want with the 2nd, 4th, ... numbers
{
   return x - 6;
}


void write( int n, int f( int ) )
{
   cout << setw( 3 ) << n << " ==> " << setw( 3 ) << f( n ) << '\n';
}


int main()
{
   int start = 1, end = 10;
   for ( int n = start, opt = 0;  n <= end;  n++, opt = 1 - opt )
   {
      switch( opt )
      {
         case 0: write( n, funct0 );   break;
         case 1: write( n, funct1 );   break;
      }
   }
}



Array of function pointers (OK, massive overkill here ...! )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;


int add( int x, int change ){ return x + change; }
int sub( int x, int change ){ return x - change; }
int mul( int x, int change ){ return x * change; }


void write( int n, int c, int f( int, int ) )
{
   cout << setw( 3 ) << n << " ==> " << setw( 3 ) << f( n, c ) << '\n';
}


int main()
{
   vector<int (*)( int, int )> f = { add, sub, mul };   // array of function pointers (only 0 and 1 used here)
   int start = 1, end = 10;
   for ( int n = start, opt = 0;    n <= end;    n++, opt = 1 - opt )
   {
      write( n, 6, f[opt] );
   }
}
Last edited on
One more:
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
   constexpr int start {1}, end {10};
   for ( int n {start};  n <= end;  ++n )
   {
      std::cout << n << " ==> " << n + (n%2 ? 6 : -6) << '\n';
   }
}
Last edited on
Thank you all for your contribution.

@lastchance - I want the calculation to be carried out on the basis of whether the number is odd
or even.

@Keskiverto - Your code is very good but the range is undefined so I am using a variable for it. For now, I do set a limit for which, I required the exponential function/operator but later on, I would let the user set the limit but it will always be 2n.

I am currently using do-while statement. Would it be beneficial to use switch statements instead? And what difference does it make?

And if I may ask one more question. Is there any way to compute with large numbers without using an external library such as GMP? Currently, I am using unsigned long long (no requirement of negative numbers).
@RCCP,
Maybe you will get better answers if you state EXACTLY what your problem says, not what you THINK it says.

You aren't giving enough detail of what you are trying to do.
@lastchance - I had written a good and long explanation of the whole scenario but I left my system to eat and after returning when I updated a little and hit submit, it was all gone. So, I'll summarize everything.

There is no problem from the compiler, but I am facing a problem with huge numbers. I want to compute with gargantuan numbers but I don't know how to do that without using a library like GMP because I have not studied any document on it, I have only glanced at a few.

My program divides an even number by 2 and if the following output or even if the inputted number is odd, it gets converted into an even number either by addition of 1 or subtraction. I have chosen to go with addition of 1 and since it would start to loop after 1 due to the structure, I have set it to terminate the loop as soon as the number reaches 2 and then simply print out 1 to the console as that is the last value. I could also have gone the other way of subtraction and terminated it at one as 1-1 would have given 0, a different value. There certainly are better ways to do it, but this is how I have done it.

Here is the code :-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cmath> 
using namespace std;
int main(){
    
    unsigned long long n; 
    unsigned long long number = 1; 
    do {
        number++; 
        n = number; 
    cout << "Evaluating for - " << n << endl; 
    if (n>1) { 
   
        do {
            //even operation 
            if (n % 2==0)
            do {
              for (; n % 2==0; n = n/2)
                cout << n << endl; 
            } while (n % 2==0);
            
            //odd operation     
            if (n>1 && n % 2!=0)
            do {
              for (; n % 2!=0; n++)
                cout << n << endl; 
            } while (n % 2 !=0); 
            } while (n>2); 
    } cout << 1 << endl; 
    } while (number<(pow(2,6))); 
    return 0;
} 


It's a console application for now and for now, I have set a limit on line 30th. But later on, I would allow the user to be able to input the limit. The number can be anything and I want my program to be prepared for it. And I will set a limit which the user's value will have to stay within, or else it would be rendered invalid. I will be adding a check for that as well as other invalid inputs such as negative numbers or strings later on after grounding the foundation. My current limit is 2^6 but that's only so that my computer doesn't freeze. But even when selecting the limit, I want to keep some headroom available. So for example, I'm working with unsigned long long which goes upto 2^62 but I will set it to be 2^60 or 2^50 or anything less than the actual limit of the data type. But I want to go beyond 2^62, way beyond it. I can manually set a number instead of using an algebraic expression, an equation to define it but I that would be unorthodox. I don't think there is a way to simply allot 1024 bytes to a certain variable as I believe the operations and manipulation of the bits on the bit-wise level pertains to and remains the same regardless of the byte-size, which I think is what all the operations are predicated upon. I don't know how to work with big numbers. That is the problem that I'm facing. The problem I had before was regarding the exp() function, or the exponential function which learnt was given by pow() in C++. But that is moot now, and so, I marked this thread as solved.

And interestingly enough, on line 30, less than acts the same as less than equal to. What could be causing that? And my writing may not be very elegant but this is how I've done it, bear with it.
Last edited on
Try recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

using INT = unsigned long long;


void sequence( INT n )
{
   cout << n << '\n';
   if ( n != 1 ) 
   {
      if   ( n % 2 ) sequence( n + 1 );
      else           sequence( n / 2 );
   }
}


int main()
{
   INT n;
   cout << "Input n: ";   cin >> n;
   sequence( n );
}

Last edited on
@lastchance - Thank you so much! That is such a neat solution! I remember studying a little bit about containers but I hadn't made my way up there. This is very elegant and very pleasing to look at as well.

May I ask what the 4th line does? Is that a method to give name to a container?
@lastchance - There is one more thing. As I was talking about the user inputting the limit, I don't want the operation to be carried out on n, but instead, I want the operation to be carried out from 1 or 2 upto n. I'm not quite sure how to modify your code for that.
rcpp wrote:
May I ask what the 4th line does? Is that a method to give name to a container?

Not at all. It's an alias to (a) save having to write unsigned long long a lot; and (b) readily change to other types of integers.


There is nothing to do with "containers" here - it is just "recursion" - literally, calling itself/chasing its tail.


rcpp wrote:
I want the operation to be carried out from 1 or 2 upto n. I'm not quite sure how to modify your code for that.

Instead of asking the user for a single value of n, just put a loop round the following line.
using in this sense is like a typedef, or if you don't know that concept, it renames something awkward to something simple. Its a bit annoying to keep typing unsigned long long over and over, so he renamed it to INT which is much shorter.
Last edited on
@lastchance @jonnin - Yes, I am aware of typedef, but I was not aware that aliases to data types could be assigned in this way. It's very fascinating. I thought of it as a container because I was studying constructors and I felt that the void function and constructors are very similar, although they may not be in reality.

@lastchance - Thank you again.

Last but not the least, what should I do if I want numbers bigger than what the standard data types have to offer?
you need something bigger than 264 - 1 ?
rcpp wrote:
Last but not the least, what should I do if I want numbers bigger than what the standard data types have to offer?


@icy rather took the words out of my mouth. If you really need to go bigger than what an unsigned long long will provide then, in C++ and most languages, you will need a big number library - either use boost's, or write your own with enough functionality to (a) represent the number (a vector or even string would do) and (b) do the operations of adding 1 and dividing by 2.

Apparently, python will do big numbers "out of the box", but numbers many times the world's population, share price of Apple or the size of Donald Trump's ego are probably big enough for anyone.
Last edited on
Topic archived. No new replies allowed.