Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've just started learning C++ and I came across a simple problem but couldn't solve. Help me please,
In geometric progression, b1=2, r=3.
Create recursive function that outputs initial n sequences of progression. n should be input.
Assuming b1 is the initial number and r is the multiplier (ratio?), that would give 2, 6, 18, 54, ....
The pseudo-code for such a beast would be:
def geometric (limit, current, multiplier):
if limit <= 0: return
print(current)
geometric(limit - 1, current * multiplier, multiplier)
def main():
b1 = 2
r = 3
n = input("How many terms? ")
geometric(n, b1, r)
The reason it's pseudo-code is that I tend to prefer for educational questions since people learn a lot more by converting it rather than just being given an answer.
So, in terms of how the recursive function works, you pass it the number of terms remaining along with the current term and the multiplier.
Provided it hasn't reached its base case (number of terms remaining is zero), it prints the current term then recursively calls itself, adjusting the arguments so as to approach the base case.
Once it has reached the base case, it will return (from all recursive levels).
Turning that into C++ is an exercise I'll leave for the reader, but I can provide something similar so you will see the approach taken.
Let's say you wanted to sum all the numbers between 1 and a given number. It has the same features as any recursive solution, including the one posed in your question:
an operation that can be defined in terms of a simpler operation; and
the base case.
In C++, a complete program to do that would be something like:
#include <iostream>
void recurse(int number, int sum) {
// Base case for printing and returning.
if (number <= 0) {
std::cout << "Sum is " << sum << '\n';
return;
}
// Recurse to next level.
recurse(number - 1, sum + number);
}
int main() {
int myNum;
std::cout << "Enter your number: ";
std::cin >> myNum;
recurse(myNum, 0);
}
Some sample runs:
Enter your number: 3
Sum is 6
Enter your number: 4
Sum is 10
Enter your number: 5
Sum is 15
Enter your number: 6
Sum is 21
Enter your number: 100
Sum is 5050
The explanatory text on your specific question, along with the C++ code showing how to do it for a different question, should hopefully be enough for you to work it out.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
The problem I am having is how to say if(//code=Whole) I dont know how to tell the program if the number equals whole number because if its a number like 39 9 divided 3 equals a whole number if a number is not divisible it will go to the decimals which is how I am willing to solve the problem by saying if digit 1 or 2 divisible by the other digit is whole then cout<<Divisible
I tried searching up didnt work heres my code
#include <iostream>
using namespace std;
int main()
{
int x,z,n;
cin>>x;
x%10=z;
x/10=n;
if(z/n==int)
{
cout<<"YES";
}
else if(n/z==int)
{
cout<<"YES"
}
else
{
cout<<"NO";
}
}
I dont know how to say if it equals whole So i dont know what to put there plus there might be something wrong in the program other than that.
This is your code.
int main()
{
int x,z,n;
cin>>x;
x%10=z;
x/10=n;
if(z/n==int)
{
cout<<"YES";
}
else if(n/z==int)
{
cout<<"YES"
}
else
{
cout<<"NO";
}
}
A few things. First, please use whitespace to make your code readable. It's going to safe you from a wide variety of bugs over the years.
Next, this is bad code:
x%10=z;
x/10=n;
So is this:
if(z/n==int)
The first few lines of your main method should be like this:
int x;
cin >> x;
int z = x % 10;
int n = x / 10;
Note that I've done two things. First, I moved where the variables are declared to as late as possible so that they aren't hanging around, uninitialized for a while. This is just good practice. Define them and assign them at the same time.
Next, the way you wrote that code doesn't make sense. An assignment statement can't be written backwards the way you did it.
In your head, you could say, "z becomes x % 10" if you have to.
This line won't compile:
if(z/n==int)
If you want to see if z divides evenly by n:
if ( z % n == 0 )
You have the same problem in the else-if a few lines later.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
For my CS class I am supposed to design a program that says:
Write a program that asks the user how many integers they would like to enter. You can assume they will enter a number >= 1. The program will then prompt the user to enter that many integers. After all the numbers have been entered, the program should display the largest and smallest of those numbers (no, you cannot use arrays, or any other material we haven't covered). When you run your program it should match the following format:
How many integers would you like to enter?
4
Please enter 4 integers.
-4
105
2
-7
min: -7
max: 105
I dont know how to assign the different number of user input variables their own values.
The assignment is due on the 21st of january 2018.
any help would be appreciated.
edit: I am not allowed to use array or the conditional operator (?)
assign the different number of user input variables their own values
You do not have to do this. You need only two variables: min and max. When first number is entered, assign both variables to that value. Then, after reading every next number (if any!), compare it with both those values. If that number (let's call it current) is greater than max, do max = current. If it is smaller than min, do min = current.
After all numbers are processed max and min will contain largest and smallest value, respectively.
Something like:
int n = 0;
int min, max;
// read number of variables from user and store it in n
for (int i = 0; i < n; ++i)
{
int current;
// read next number and store it in current
if (i == 0) // first number
{
min = max = current;
}
else
{
if (current > max) max = current;
if (current < min) min = current;
}
}
std::cout << "Max: " << max << ", min: " << min << std::endl;
That code should illustrate you the general idea. Code the essential parts yourself (reading input) and that's all.
Small note: since you can assume that n is >= 1, you could move the first read outside the loop and change it to start from i = 1 (loop will not be executed at all if user enters only one value). That will also allow you to avoid the if (i == 0) condition which is true only during the first run. But since that's just an exercise, I went for simplicity.
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 6 years ago.
Improve this question
I have an assignment to create a C++ program to find all the possible mathematic equation with operators. Below shows the question:
Given a set of numbers, for example {5, 3, 7, 3, and 11}. Find all the possible mathematic equation with operators such as +, - ,*, / in such a way that the equation will produce the given answer. For example, 5+7-3/3=11.
I need an idea how to start with the code. Is it like brute force algorithm ? I have no idea how to interchange the operators to create the possible equation. I'm not asking for full solution, just an idea how to start the coding.
You could think about it like this. +,-,*,/ can be treated as 1,2,3,4 respectively. Now, if you were to try all the different combinations for whatever size array of numbers you get, you could look at it like this.
example. 4 numbers.
1,1,1,1 1,1,1,2 1,1,1,3 1,1,1,4
1,1,2,1 1,1,2,2 1,1,2,3 1,1,2,4
and so on and so forth. Hope this might help!
I would like to state that this is not my original idea. I will add the reference below.Please find the C++ code below. It might be of some help to you as it has been to me.
#include <iostream>
#include<string>
using namespace std;
void cntdwn(double sum, double previous, string digits, double target, std::string expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
std::cout<<expr << " = " << target;
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = std::stod(digits.substr(0, i));
string remaining = digits.substr(i);
cntdwn(sum + previous, current, remaining, target, expr + " + " + std::to_string(current));
cntdwn(sum, previous * current, remaining, target, expr + " * " + std::to_string(current));
cntdwn(sum, previous / current, remaining, target, expr + " / " + std::to_string(current));
cntdwn(sum + previous, -current, remaining, target, expr + " - " + std::to_string(current));
}
}
}
void f(string digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
string current = digits.substr(0, i);
cntdwn(0, std::stod(current), digits.substr(i), target, current);
}
}
int main() {
// The digits go as concatenated string
f("5373",11);
return 0;
}
Output:
5 * 3.000000 - 7.000000 + 3.000000 = 11
References:
Generate all combinations of mathematical expressions that add to target (Java homework/interview)
https://math.stackexchange.com/questions/459857/using-operators-and-4-4-4-4-digits-find-all-formulas-that-would-resolve
https://www.careercup.com/question?id=5735906000502784
Additional Note
a) This code will not make any combinations for the digits. For example if we give (4,4,4,4) as numbers and 10 as target then it will not give any result as the solution in that case should be [(44-4)/4] {this example has been picked from second reference].
b) And this problem is a classic algorithmic problme popularly known as "Countdown Problem" picked from famous UK game.
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
You are required to write your own algorithm for computing square root. Write a
pseudocode rst before you go on and write the C++ program. Do not use the
sqrt function from the math library to compute the square root. Create your own
square root algorithm.
2. Your program should cater for all non-perfect square numbers as well as negative
integers that the user inputs. In these cases the program should prompt the user
that a perfect square has not been entered.
3. The program should allow the user three chances to enter a perfect square. If the
user is not able to enter a perfect square within the three chances then the program
should exit.
4. You are to use functions in your C++ program. Create a user dened function
by the name sqroot. This should be the function where you implement your own
square root algorithm. This function should return an integer and accept only one
input argument, that too of type integer.
i have tried but got stuck pliz help
#include <iostream>
#include <cmath>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main (){
int test;
int square;
int answer;
int i=0;
cout << "enter a perfect sqare ";
cin >> square;
answer = pow(square, 0.5);
test = square % answer;
if (test==0){
cout << "the square is: " << answer;
}
if (test!=0){
cout << "enter a perfect sqare ";
cin >> square;
answer = pow(square, 0.5);
test = square % answer;
cout << "the square is: " << answer;
}
return 0;
}
See Newton-Raphson algorithm.
From Wikipedia: "a method for finding successively better approximations to the roots (or zeroes) of a real-valued function".
Lets say you are trying to find the root of 'a'.
Then basically, you are trying to find the roots of the function:
f(x) = x^2 - a
Also this method is known to be very fast.
If you really want to impress da' Prof, you could use the binomial expansion approximation with a power of 1/2:
=
a is the next perfect square from your input number (I'm sure it'll be easy for you to compute that, and its square root). Sub it into the formula, with x as your input number, not forgetting to use floating point variables for the fractions, and do what you like with the answer (in your case round it to an integer).
I know it's only an approximation but it should be more than good enough for integer answers.
http://en.wikipedia.org/wiki/Binomial_theorem
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to know whether there is a way in which we can print the number alphabetically i.e
123 should be printed as one two three.
The only condition is that we should not reverse the number and we should not use array.
I only know these two ways:
"Reverse the number", that is, taking the last digit and cutting it off. For each cut-off digit, one can use an array to look up the correct string.
using switch and a lot of cases
Any ideas?
for hundreds place:
int hundreds = my_num / 100 //Needs "/", NOT "%"
if(hundreds == 0)
cout << "zero";
else if(hundreds == 1)
cout << "one";
//repeat for 2-9
This process could be tweaked to do the other digits as well. It is also worth mentioning that the if/else block a) could be done with a switch/case if preferred, and b) could pretty easily be made into a separate function to avoid having to repeat the block of code over and over, I just wrote out as much as I did for clarity's sake. Note that this assumes the number you're "translating" is an integer. With integers the "/" operator will return the full quotient WITHOUT the remainder, e.g. 123 / 100 = 1, not 1.23
Not necessarily the easiest route, but you can make a function, say DigitToWord which will take a digit 0, 1, 2, ...etc to its word with a switch statement. Then I recommend using a for loop over the number, continuously dividing by 10 and taking the mod for the loop:
int num; //my number i want to print
int div = pow(10, (int)log10(num)); //find the largest power of 10 smaller than num
while(num > 0) {
int remainder = num%div;
int digit = num/div;
DigitToWord();
num = remainder;
}