I am completely newbie to C++. I am doing a practice which consists of building a very simple C++ program.
My teacher emphasizes that it must use recursion with functions and methods. I am wondering how to use recursion within a method in C++. I was looking for some code examples but I haven't find anything. My deep concerns are how a method calls itself without not knowing the name of its class/instance.
class Foo
{
public:
Foo(int offset) : offset(offset) {}
int bar(int x)
{
if (x == 0)
{
return offset; // Base-case
}
return x + bar(x-1); // Recursion
}
private:
int offset;
};
int main()
{
Foo foo(7);
std::cout << foo.bar(5) << "\n"; Prints "22" (5+4+3+2+1+7)
}
Wikipedia: Recursion
I guess your homework is to write a Recursive Descent Parser. A simple example in C:
uBASIC
An example:
#include <iostream>
using namespace std;
int factorial(int n) // 1, 1, 2, 6, 24, 120, 720, ...
{
if (n == 0) return 1;
return n * factorial(n-1);
}
main()
{
int n = 7;
cout << "Enter a non-negative integer: ";
cin >> n;
cout << "The Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
You can find more examples here : http://www.cstutoringcenter.com/tutorials/cpp/cpp6.php
Related
#include <iostream>
using namespace std;
void binary(unsigned a) {
int i;
cout << "0" << endl;
do {
for (i = 1; i < a; i=i/2) {
if ((a & i) != 0) {
cout << "1" << endl;
}
else {
cout << "0" << endl;
}
}
}
while (1 <= a && a <= 10);
}
int main(void) {
binary(4);
cout << endl;
}
I wrote a code about binary numbers. İt should give bits respect to entering number like for
4 (0100) for 2 (10). However my code goes infinity could you explain. I wrote in visual
studio and I cannot use <bits/stdc++.h> because there is no such a library in visual studio
Initially i is 1 but i = i / 2 sets i to 0, where it remains. The inner loop, therfore, loops for ever.
To output an unsigned number a in binary, use
#include <bitset>
#include <climits>
std::cout << std::bitset<sizeof(a) * CHAR_BIT>(a) << '\n';
(There is, at the time of writing no std::bin i/o manipulator cf. std::hex.)
Without using a built-in function, you can write your own function and perform your operation as follows.
Solution-1
#include <iostream>
void binary(unsigned int number)
{
if (number / 2 != 0) {
binary(number / 2);
}
std::cout << number % 2;
}
int main() {
binary(10);
}
Solution-2
#include <iostream>
#include<string>
void binary(unsigned int number)
{
std::string str = "";
while (number != 0) {
str = (number % 2 == 0 ? "0" : "1") + str;
number /= 2;
}
std::cout << str;
}
int main()
{
binary(4);
}
Note : Don't use using namespace std; . Why is "using namespace std;" considered bad practice?
i understand that the conditional operator ? can be used to simplify the if conditional but i'm really having a hard time with it, is it possible to use it as a loop ? for example in the code here it keeps telling me that i can not use r as a function what exactly am i missing ?
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
double r,circle,o;
int rmax =0;
int n;
cout << "enter the number of circles:";
cin >> n;
(n > 1) ? cin >> r (r > rmax) ? rmax = r : r=r: cout<<rmax;
}
The ternary operator (?:) can be easier described using a function:
#include <iostream>
template<typename T>
T &ternary(bool a, T &b, T &c) {
if (a)
return b;
else
return c;
}
int main() {
// The behavior is not completely equivalent
// This example just explains the basic concept of the ternary operator
std::cout << ternary(true, 5, 2) << '\n';
std::cout << (true ? 5 : 2) << '\n';
}
The expression condition ? value1 : value2 returns either value1 or value2 depending on condition.
Of course, value1 and value2 can also be complex expressions but you have to remember to handle the returned values.
#include <iostream>
int main() {
int a;
std::cout << (true ? a = 5 : 2) << '\n';
}
Both possible values must have the same type.
Your expression would look like:
ternary((n > 1), cin >> r ternary((r > rmax), rmax = r, r=r), cout<<rmax);
Now the problem should be obvious.
I am a beginner in programming.I have a problem. I am trying to code the Enigma machine. I have two classes. One for Enigma, one for rotors. Rotors are small parts of the enigma machine, that doesn't matter for the problem. My problem is the error. I cannot cout, the function cout << rotors[0].GetRotor(); which should return my vector of integers. I have no idea why is that. I don't need that to my program, but I'm not sure if my adding rotor to enigma void AddRotor(Rotor rotor) { rotors.push_back(rotor); }function, called in "TakeRotors" function, works right. In my opinion, it should work well, but I can't check it. Debugger, unfortunately, doesn't show any values of vector<Rotor> rotors; permutation so I am not sure :( Any help would be great. Thank You.
Here's my full, needed code :)
#include <iostream>
#include <vector>
using namespace std;
class Rotor {
public:
vector <int> permutation;
int position;
Rotor(vector<int> permutation) {
position = 0;
permutation;
}
vector<int> GetRotor() const {
return permutation;
}
};
class Enigma {
public:
vector<Rotor> rotors;
void AddRotor(Rotor rotor) {
rotors.push_back(rotor);
}
void PrintRotor(const vector<Rotor>& rotors) {
cout << rotors[0].GetRotor(); // Error right here
cout << rotors[0].position;
}
void setupRotor(int index) {
Rotor rotor = rotors[index];
}
void MoveRotor(int index) {
rotors[index].position++;
cout << "Before" << endl;
// cout << rotors[index].permutation.data << ' ';
Enigma::PrintRotor(rotors);
rotate(rotors[index].permutation.begin(), rotors[index].permutation.begin() + rotors[index].permutation.size(), rotors[index].permutation.end());
cout << "After" << endl;
Enigma::PrintRotor(rotors);
}
};
vector<int> take_numbers(int number) {
vector<int> numbers;
for (int i = 0; i < number; i++) {
int number;
cin >> number;
numbers.push_back(number);
}
return numbers;
}
void take_rotors(int number_letters, Enigma* enigma) {
int numberOfRotors;
// int numberOfNotch, positionOfNotch;
cout << "Give number of Rotors" << endl;
cin >> numberOfRotors;
for (int i=0; i < numberOfRotors; i++) {
vector<int> permutation = take_numbers(number_letters);
Rotor Rotor(permutation);
enigma->AddRotor(Rotor); // I am not sure if it adds Rotors fine.
}
}
int main()
{
Enigma enigma;
int number_letters, move_rotor;
cout << "Give number of letters in alphabet" << endl;
cin >> number_letters;
take_rotors(number_letters, &enigma);
// take_reflectors(number_letters, &enigma);
cout << "Which rotor do you want to move (index)" << endl;
cin >> move_rotor;
enigma.MoveRotor(move_rotor);
return 0;
}
There is no operator<<(std::ostream&,const std::vector<int>&) if you want it you need to supply your own. However, overloading operators for types you don't own is not recommended, so I would rather write a function:
void print_vector(std::ostream& out, const std::vector<int>& vect) {
for (int i : vect) {
out << i << '\n';
}
}
That you can call like this
print_vector(std::cout, rotors[0].GetRotor());
Alternatively you can supply an overload for << that prints all the Rotor:
std::ostream& operator<<(std::ostream&,const Rotor& rotor) {
out << rotor.position;
for (auto& i : rotor.GetRotor()) {
out << i;
}
// modify and add more to your likings
return out;
}
Once you have that you can also provide an overload to print a vector of rotors that you can use in Enigma::PrintRotor (which currently only prints the first element of the vector):
std::ostream& operator<<(std::ostream& out,const std::vector<Rotor>& rotors) {
for (const auto& r : rotors) {
out << r << '\n';
}
return out;
}
PS your naming is a little confusing. A Rotor has a GetRotor which returns permutations !?! I strongly suggest to use better names. If I have Rotor r; then r is the Rotor and it is not obvious what a GetRotor will do. Maybe rename it to GetPermutations?
I'm trying to write a program that would print all palindrome in range [a, b]. I've written this so far, but nothing is printed after I input the values for a, b. What is missing?
#include "stdafx.h"
#include <iostream>
using namespace std;
int t = 0, rmd, z, a, b;
int reverse() {
while (z != 0) {
rmd = z% 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin() {
if (a == reverse()) {
return 1;
}
else
return 0;
}
int main() {
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
z = a;
if (palin())
cout << a << endl;
a++;
}
system("pause");
return 0;
}
The problem is that the variable t is not local to your reverse() function. Its value survives to the following invocation, so the result of reverse becomes junk unrelated to the actual call.
You need to make t local to reverse() in order to fix this problem.
In general, it is a good idea to develop a habit of declaring your variables in the innermost scope to which they could belong without breaking your code. In this case, this would be the scope of reverse() function for t, and the scope of main for the remaining variables; palin should take a as its parameter.
Your use of variables is what is confusing you. The actual issue is not setting t to zero every time you call reverse, but you should think about how you use variable scoping and what functions actually do. Right now you have 2 procedures, that perform actions on global data. Instead try to formulate the problem using functions that accept arguments, and return a result.
#include <iostream>
using namespace std;
int reverse(int z) {
int t = 0;
int rmd;
while (z != 0) {
rmd = z % 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin(int z) {
return z == reverse(z);
}
int main() {
int a, b;
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
if (palin(a)) {
cout << a << endl;
}
a++;
}
system("pause");
return 0;
}
I have the following example (simplified) using a struct:
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
struct s_str
{
int a=1,b=2,c=3;
};
int main(void)
{
s_str str;
int sel;
srand(time(NULL)); //initialize random seed
sel = rand() % (3); //generate a random number between 0 and 2
cout << "sel: " << sel << endl;
cout << "str: " << str.??? << endl;//I was wondering to output a, b or c
return 0; //depending whether sel=0,1,2respectively.
}
When the struct "str" is defined, we can access to each element by using the opertor "." followed by the name of the element. For instance "str.c" will give us the number 3.
However in this example we don't know the element of "str" to output when programing because it's randomly selected by sel.
I don't know how to output "str.???" from sel number, that is, str.a if sel=0, str.b if sel=1, and str.c if sel=3.
I tried something like "str.[sel]", but it didn't work. Can you help me?
PD: I don't want to bother too much, but how to solve the same problem but now supposing that a,b and c have different variable type. For example:
int a=1,b=2;
string c="hola";
I tried to do it with two operators, but it didn't compile because they were overloaded.
As mentioned you can't do this without providing a certain mapping and indexing operator. The following should work well:
struct s_str
{
int a=1,b=2,c=3;
int& operator[](int index) {
switch(index) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
default:
throw std::out_of_range("s_str: Index out of range.");
break;
}
}
};
int main() {
s_str s;
cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
// cout << s[42] << endl; // Uncomment to see it fail.
return 0;
}
In general, no.
If the only distinguishing feature of the elements of the struct is their index, define a vector or array in the struct.
If you sometimes want to refer to the elements by name and sometimes by position, define an operator []( int ) for the struct.
Te easiest way, if you have only a couple of ints in your structure is:
struct s_str
{
int a = 1, b = 2, c = 3;
int& operator[] (size_t t) {
assert(t<3); // assumption for the following to return a meaningful value
return (t == 0 ? a : (t == 1 ? b : c));
}
};
You'd access with
cout << "str: " << str[sel] << endl;
and you could even use int to assign, because it's by reference:
str[sel] = 9;
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;