Trouble finding sum of odd integers cubed [closed] - c++

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 4 years ago.
Improve this question
Tried several times yet still didnt manage to find my mistake: here is my program. i need to find the odd numbers from 1 and integer x and find the sum of them cubed.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;
return 0;
}

Minimally, you should change the compare in while
from
while (i > n)
to
while (i <= n)
There a many numbers where i will be greater than the number entered, n.

You didn't add in your curly brackets for the while loop.
while (i > x)
if (i%2 == 0) {}
needs to be:
while (i > x){
if (i % 2 == 0) {}
}
Plus what are you doing inside of that if statement? You should decrement x, to find if each number is odd.
Plus, your program ends early because i is 1 and if the user enters a number above 1, your while loop won't even run. You're telling the while loop to run ONLY when i is larger than x. Try changing it to less than:
from:
while (i > x){
to:
while (i < x){
Plus you're not doing anything with x. You want to decrement x, not add i. Although, I would recommend using a do-while loop. ( a dowhile loop does one iteration first before incrementation)
do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.
temp = pow(x,3);
//you don't want to take the power of the added sum,
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power. So here we have temp, a
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--; //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar
<< " = " << result << endl;
return 0;
}
note: if-else statements are for flow control, its like true and false, one or the other, so that your data will flow somewhere. I used two if statements because I want to have complete control over the flow.
note2: It's ok to use:
using namespace std;
at first, but eventually you want to start learning what library each command is using. When you get into more complex programming, you start using commands from different libraries than the standard one.

Related

How does increment work in this scenario C++ [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 2 months ago.
Improve this question
I did not write this code.
i'm on my 3rd day of coding in C++ and i'm having a hard time understanding how incremnent works in general.
int main()
{
int antal_ord {};
double medellangd {};
string kort_ord;
string langt_ord;
int min_length {100};
int max_length {};
string S;
cout << "Mata in en text:\n" << endl;
while (cin >> S)
{
if (S.length() > max_length)
{
max_length = S.length();
langt_ord = S;
}
if (S.length() < min_length)
{
min_length = S.length();
kort_ord = S;
}
medellangd+=S.length();
antal_ord++;
}
if (antal_ord == 0)
{
cout << "Inga ord matades in." << endl;
}
else {
medellangd = (medellangd / antal_ord);
round(medellangd);
cout << "Texten innehöll " << antal_ord << " ord." << endl;
cout << "Det kortaste ordet var " << '"' << kort_ord << '"' << " med "
<< kort_ord.length() << " tecken." << endl;
cout << "Det längsta ordet var " << '"' << langt_ord << '"' << " med "
<< langt_ord.length() << " tecken." << endl;
cout << "Medelordlängden var "<< fixed << setprecision(1) << medellangd << " tecken.";
}
return 0;
}
antal_ord is the variable for the amount of words written in this scenario.
In the line where it says "cout << "Texten innehöll " << antal_ord << " ord." << endl;" how does it know how many words have been written? The only time this variable is used before this line is when the variable gets incremented, but how does that let the variable know how many words have been written in total?
and also the .length command, does it basically just count the amount of letters written?
There's really nothing special going on here. Every time you read one word with cin >> S, you increment antal_ord by one. Since you started with zero words written and antal_ord==0, at the end antal_ord will equal the number of words read from cin.
Similarly, S.length() returns the number of letters currently in S. In your case, that is exactly the number of letters read from cin since you didn't chance S after reading. But if you did S += " some extra letters, then S.length() will of course change.
When you'll learn about most programming languages, you'll start off with basics: syntax, data types, declarations (vars + funcs as well as other possible concepts), loops, calls, math operations and other code-control techniques relevant to each programming language.
What you'll see about most (and I;ll try to "rewind" from the generalization I started with and back down to C/C++) is that you have the following type of math operation variations when it comes to addition (let's focus on this, as it's more on point with the question).
result in a separate variable, in our case b: b = a + 1;
result in the same variable: a += 1;
incrementing the value of the variable: a++;
Expanding on it:
In the first case, b will have its value overwritten and is dependent on a different values (in this case the value of a and 1). What you need to focus on here is that a is NOT changed.
In this case, a receives a new value and is incremented by the right-side-value, in our case 1. a is changed by adding one (not incrementing)
In our case, similar to #2, the value of 8a* is updated, but the incrementation is done by 1.
Apart from syntactic sugar or code style preference, the difference between each is also in the way the variables are assigned their values (more formally said, in the assembly code "underneath"). This topic is a lot more complicated for someone that started programming, but focusing on the question, the answer is simply that ++ increments the value by 1.
Also note that there is a difference in certain coding flows between ++a and a++. Mainly in loops. For ++a the value is set before executing the code, using the already incremented value in the code, while a++ uses the current value of a first, then increments it.
Try it like this:
int i = 0;
while (++i < 100)
{
std::cout << i << std::endl;
}
... versus...
int i = 0;
while (i++ < 100)
{
std::cout << i << std::endl;
}
Then count how many lines each case wrote.
There is also a small caveat you should be aware of, it's a bit more advanced, so it's just a little "FYI" for you. There are two C++ techniques called "function overloading" and "operator (re)definition". Let's focus on the second one. You could build your own data type (for example a struct or class) and implement your own operators that do something other than what their arithmetic counterparts do. You'll see this in iterator definitions. In that case ++ is not "actual value incrementation" (so it's not a math calculation), but rather switching to the next item in a list. Once you reach std::vector lessons you'll encounter that.

C++ question: User think a number 1-100, program asks questions no more than 6 times to get answer. can't get correct [closed]

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 2 years ago.
Improve this question
User has to think of a number from 1 - 100. Computer keeps asking not more than 6 times to get what
the user think number. I could not get the logic right, I don't know how to fix anymore. Please somebody help me.
#include "std_lib_facilities.h"
// this program is not correct
// try 24 you will see it
int main()
{
cout << "Think of a number between 1 to 100\n";
int max{100};
int min{0};
int answer{0};
string response{"??"};
while ((max - min) != 1)
{
cout << "Is the number < " << (max + min) / 2 << "?\n";
cin >> response;
if (response == "y" || response == "yes")
{
max = ((max + min) / 2);
if ((max - min) == 1)
answer = min;
}
else if (response == "n" || response == "no")
{
min = (max + min) / 2;
if ((max - min) == 1)
answer = max;
}
else
{
error("Invalid response\n");
}
}
cout << "The answer is " << answer << endl;
keep_window_open();
return 0;
}
Thank you in advance.
As has already been pointed out in the comments section, there are at least 3 bugs in your code:
Your question states that the user should think of a number between 1 and 100, but the variables min and max are initialized to 0 and 100, as if the user was supposed to think of a number between 0 and 100. Therefore, you should initialize min to 1 instead of 0.
When the user replies "yes" to the question whether the number is below a certain value, you set max to this value. This does not make sense, because you know that the number cannot be this value, but must be below this value. Therefore, you should set max to this value minus 1.
When min == 1 and max == 2, it would make sense for the next question your program asks to be whether the number is "< 2", in order to determine whether the number is 1 or 2. However, in that case, your program asks whether the number is "< 1", which does not make sense, because it already knows that the answer to that question is "no". Therefore, instead of asking whether the number is smaller than (max + min) / 2, it would make more sense to ask whether the number is smaller than (max + min + 1) / 2.
I have cleaned up your code a bit and fixed the bugs mentioned above. Here is the code:
#include <iostream>
#include <string>
constexpr int MIN = 1;
constexpr int MAX = 100;
int main()
{
int min{ MIN };
int max{ MAX };
std::string response;
std::cout << "Think of a number between " << MIN << " and " << MAX << "." << std::endl;
while ( min != max )
{
int guess = (max + min + 1) / 2;
std::cout << "Is the number < " << guess << "? ";
std::cin >> response;
if ( response == "y" || response == "yes" )
{
max = guess - 1;
}
else if ( response == "n" || response == "no" )
{
min = guess;
}
else
{
std::cout << "Invalid response" << std::endl;
}
//The following line only exists for debugging purposes and can be disabled
std::cout << "min: " << min << " max: " << max << std::endl;
}
std::cout << "The number is " << min << "." << std::endl;
return 0;
}
I have rearranged the code in such a way that the numbers 1 and 100 are hard-coded only in one place, instead of several places in the program. This allows you to change the range very easily, without having to change the numbers in several places in the program.
One thing that my code does not do is stop asking after 6 questions, because it can take up to 7 questions to find the correct answer. In your question, you specified that it should ask not more than 6 times, but did not specify what should happen if it has not found the answer by then.

C++ - Recursive counter [closed]

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 5 years ago.
Improve this question
I am trying to create a counter. It counts each operation such as multiplication, addition, subtraction, division. Every time I try to cout the counter, it stays as zero.
Can anyone shed any light on what I am doing wrong?
A bulk of my code is missing so I can protect it from other classmates, however I have listed how many operations is in that section where the code would be.
long karatsuba(int num1, int num2, int &counter)
{
if (num1 < 10 || num2 < 10)
{
counter++ // 1 operation
return num1 * num2;
}
/* calculates the size of the number */
... 4 operations
/* split the digit sequences about the middle */
... 4 operations
/* 3 calls made to numbers approximately half the size */
int z0 = karatsuba(..., ..., counter);
int z1 = karatsuba(..., ..., counter);
int z2 = karatsuba(..., ..., counter);
return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
int counter = 0;
cout << karatsuba(123, 456, counter) << " " << counter << endl;
cout << endl;
system("Pause");
return 0;
}
The problem is this line:
cout << karatsuba(123, 456, counter) << " " << counter << endl;
Try instead
cout << karatsuba(123, 456, counter);
cout << " " << counter << endl;
the problem is cout, count is still 0 when it prints.

Print "*" up to n terms in pattern and its reverse

I have a problem that is asking for me to write a C++ program using for loops with less than 3 “cout” statements in your code to print the following pattern (ignore the pipes, the asterisks wouldn't appear without them):
|*
|***
|*****
|*******
|*********
|*********
|*******
|*****
|***
|*
This is my code I used for a fibonacci generator and I feel like it might be similar. I am able to print the "*" symbol but not in horizontal lines. What I need most help with is reversing the output. As in if given number n, I want the series to go n numbers into the series and then back down to 0.
#include <iostream>
using namespace std;
int main()
{
int y = 1, sum = 1, n;
cout << "Enter the number of terms you want" << endl;
cin >> n;
cout << "First " << n << " terms are :- " << endl;
for (int x = 0; x < n; x++) {
cout << "\n" <<endl;
for (int i = 0; i < sum; i++) {
cout << "*" << endl;
}
sum = y + 2;
y = sum;
}
}
It seems this is a homework, so I give some hints instead of a full solution.
For printing the *s in one line, please note that << endl will end the line in the output, i.e. print a line break. (The same does << "\n" by the way.) Not every cout statement has to have an << endl at its end.
For reversing the fibonacci sequence, once you have the last number in the variable sum, just do the reverse computation (i.e. subtraction). This could be done in a second set of loops, however, since you should not use cout statements too often, you better reuse the same loop by using some additional variable holding the current state (i.e. if you are counting up or down) and using an if to decide which computation to do. (I read the requirements such that only the cout statements for printing the pattern count to the "less than three" = 2)

Array returing greatest value with index [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to get the greatest value from the array and its index number also by using a function maxin but my logic somehow isn't working?
#include <iostream>
#include <conio.h>
#include <proceass.h>
void maxin(double[], int);
void main()
{
const int k = 10;
int l = 0;
double num[k];
for (int j = 0; j < k; j++)
{
cout << "Enter the number " << j + 1 << " = ";
cin >> num[j];
if (cin.fail())
{
cout << "Wrong data entered " << "\nTry again";
getch();
exit(0);
}
}
maxin(num, l);
cout << "The Greatest number is = " << num;
cout << "\nIt is " << l << "th number";
getch();
}
void maxin(double k[], int p)
{
int l, s;
l = 10;
s = 0;
double m;
for (int n = 0; n < l; n++)
{
if (k[s] > k[n++])
{
m = k[n];
}
else
{
m = k[n++];
s = ++;
}
}
p = s;
k[s] = m;
}
Your maxin function is invoking Undefined Behavior on your program for causing access to areas beyond the bounds of the array k. This happens because not only is n incremented in the for loop statement, but again in the if statement which is evaluated on each iteration as well. This also happens in the else statement, which is another case of the problem.
When n is 1 less than l, n++ will be >= l, and subsequently dereferencing that address, k[n++], will cause Undefined Behavior. After that, anything can happen to your program, including valid or invalid side effects.
When finding the maximum/minimum value in an array, a variable is usually set to an arbitrary value in the array (typically the first index), and then iteration is performed to check if any other value in the array is smaller/larger than that variable. When that condition passes, the variable is set to the new value in the array.
Furthermore, since you said you needed to set the variable to the index at which the largest value was found, it is necessary that you pass p by reference.
The STL approach:
vector< double > v = {1,2,3,4,5};
auto maxElemIter = std::max_element(begin(v), end(v));
cout << "Max is: " << *maxElemIter;
cout << ", at index: " << distance(begin(v), maxElemIter) << endl;
(I know, this is a cruel suggestion, given code as stated in question above...)