Why dοes this code output 1? - c++

I'm trying to figure out this C++ code line by line.
Can anyone explain it for me? Why is the output 1?
int main() {
int sum = 0;
for (int i=0; i<10; i++)
if (sum%2==0)
sum += i;
else
continue;
cout << sum << endl;
}

The code can be roughly translated to the English:
Start with a sum of zero then, for every number from 0 to 9 inclusive, add it to the sum if and only if the current sum is even.
So, you'll add zero to the sum (because the sum is currently even) after which the sum will still be zero (hence even).
Then you'll add one to the sum (because the sum is currently even) after which the sum will be one (hence odd).
Then you'll never add anything to the sum again (because it's odd and will remain so because you're not adding anything to it).
That's why it outputs one.
You may find it more instructive to simply modify your program to output what it's "thinking". The following changes will hopefully make it easier to understand:
#include <iostream>
using namespace std;
int main(void) {
int sum = 0;
for (int i = 0; i < 10; i++) {
cout << "Processing " << i
<< ", sum is " << sum
<< ((sum % 2 == 0) ? " (even):" : " (odd): ");
if (sum % 2 == 0) {
sum += i;
cout << "adding " << i << " to get " << sum;
} else {
cout << "leaving at " << sum;
}
cout << '\n';
}
cout << "Final value is " << sum << '\n';
}
Running that code will show you the steps along the way:
Processing 0, sum is 0 (even): adding 0 to get 0
Processing 1, sum is 0 (even): adding 1 to get 1
Processing 2, sum is 1 (odd): leaving at 1
Processing 3, sum is 1 (odd): leaving at 1
Processing 4, sum is 1 (odd): leaving at 1
Processing 5, sum is 1 (odd): leaving at 1
Processing 6, sum is 1 (odd): leaving at 1
Processing 7, sum is 1 (odd): leaving at 1
Processing 8, sum is 1 (odd): leaving at 1
Processing 9, sum is 1 (odd): leaving at 1
Final value is 1

I created a table trying to simulate the debug steps for you to understand the logic of your code and see why the result is evaluated to 1
Recommendation: learn how to debug. Depending on the IDE you are using they approach code debugging differently. Debug come in handy when you want to understand how your code is being executed.
About your code:
Try to use curly braces when possible, this helps your code to be clean and more understandable;
else continue: you don't need this line of code because there's nothing to skip in your loop after else condition;

Exchanging the comparison from
if (sum%2==0)
to
if (i%2==0)
would make sense.
This would sum up the even numbers 0+2+4+6+8 -> 20.

Related

Can someone explain this output? (C++)

Hello can someone please explain the output of the following C++ code espacially the numbers after the output of the first one 43211223334444
Here is the code:
void rek(int i) {
if (i > 0){
cout << i;
rek(i-1);
for (int k=0; k < i; k++)
cout << i; }
}
int main(){
rek(4);
return 0;
}
Here is the output:
the output is: 43211223334444
All the trouble comes from the fact that your output didn't introduce any separation in values cout << i; prints.
You actually getting the following at first:
4, 3, 2, 1
We got this out of these two statements:
// ...
cout<< i;
rek(i-1);
// ...
Where each call to the rek(i) prints its current i and then calls rek(i-1), which in turn before proceed through the function body has to print its i-1 and then call rek((i-1)-1)... And so on, until it hits the i < 0 case.
The remaining part is brought to you by the output of 1 one time, 2 two times, 3 three times, and 4 four times. All because of the for loop:
for (int k=0; k < i; k++) // print the value of i, i times
cout << i;
Thus, you essentially have the following:
4
3
2
1 // We hit base case on next rek() call, so no print out of there
1 // Here the for loop comes in
2 2
3 3 3
4 4 4 4
By the way, please note that the placement of brace(s) in your code is somewhat counterintuitive.
We can write the dynamic stack development down manually. Below I have pseudo code with an indentation of four per stack level. The commands are on the left, the resulting output, in that order, on the right. I have replaced i with the respective number to make even more transparent what's going on.
rek(4)
cout << 4; 4
rek(3)
cout << 3; 3
rek(2)
cout << 2; 2
rek(1)
cout << 1; 1
rek(0)
if(i>0) // fails, rek(0) returns
rek(1) continues
for (int k=0; k < 1; k++)
cout << 1; 1
rek(1) returns
rek(2) continues
for (int k=0; k < 2; k++)
cout << 2; 2
cout << 2; 2
rek(2) returns
rek(3) continues
for (int k=0; k < 3; k++)
cout << 3; 3
cout << 3; 3
cout << 3; 3
rek(3) returns
rek(4) continues
for (int k=0; k < 4; k++)
cout << 4; 4
cout << 4; 4
cout << 4; 4
cout << 4; 4
rek(4) returns
main() continues
return 0;
Lets break your output string: "43211223334444" into 2 parts:
Part 1: "4321"
This is the result of
cout << i;
rek(i-1);
You are printing i and recursively calling same function by passing the (i-1) as argument and function performs the operation till (i > 0).
This prints the numbers from 4 to 1, i.e. "4321"
Part 2 "1223334444"
This is the result of code section:
for (int k=0; k < i; k++)
cout << i;
This section gets called in reverse order from number 1 to 4.
This code section basically prints the number i, for the i times.
For i=1 it prints: 1
For i=2 it prints: 22
For i=3 it prints: 333
For i=4 it prints: 4444
That makes the string: "1223334444"
Hope this explains you the total output string: "43211223334444"
you are doing recursive function and then a for-loop
and you're function is going deep in the recursion and then the for loop is working from the deepest point of the recursion that's why you see this output
You start with going "down in the recursive tree", first you complete printing the numbers from i=4 to i=1 and therefore you print: 4321.
After that you go "up the recursive tree" and start printing from i=1 to i=4 using the loop you wrote, therefore the order is now for i=1 you print 1 and for i=2 you print 22 which result in printing 1223334444 at the end of the line.

Why does my code give me different answers when I initialize a variable compared to when I add a simple value like 0? [duplicate]

This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 2 years ago.
Below you have two different codes. The difference between the two is simply for the variable sum, sum was initialized compared to giving sum the value 0 sum =0;
#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";
}
cout << endl;
// variable was initialized
int sum;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;
}
This Code outputs:
The natural numbers are:
1 2 3 4 5 6 7 8 9 10
The sum of first 10 natural numbers: 32821
Program ended with exit code: 0
#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";
}
cout << endl;
// here I gave the value 1... this time it worked
int sum =0;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;
}
This Code outputs:
The natural numbers are:
1 2 3 4 5 6 7 8 9 10
The sum of first 10 natural numbers: 55
Program ended with exit code: 0
Why does the code do this? Can someone please explain to me why they gave me two different sums?
If you do not initialize sum it has an indeterminate value and there's no way you can tell what operations on it will do. Reading an uninitialized variable is undefined behaviour and doing so renders your entire program invalid.
Btw; you seem to be confused about what initialization is. int sum; does not initialize sum, it just declares it - it does not give it an initial value and you may not read it or use it in computations until you have assigned it a known value. int sum = 0; does initialize sum - that is, it gives it an initial value and you can now validly read it and use it in computations.
Actually in the first set of code the compiler took a random value of variable sum. In your case I think the compiler took value of of sum as 32766. This value 32766 is "garbage value".
So see in second case you gave sum a initial value hence compiler knows that user has given a value. So accordingly it will perform your given operation. Inside the loop sum will start from 0 and keep performing the given operation until it exit the loop.
The operation for this Case2 codes is given below :
sum = sum + i; //(here value of "i" increase by 1 with iteration of the given loop)
/* 1 = 0 + 1
3 = 1 + 2
6 = 3 + 3
10 = 6 + 4
15 = 10 + 5
21 = 15 + 6
28 = 21 + 7
36 = 28 + 8
45 = 36 + 9
55 = 45 + 10
As you can see the value of "sum" after the loop is 55
*/
But in first case you didn't give sum initial value, so compiler don't know whether the value of sum is 0, 6, 15, 7 or 10. So, compiler took a random value for it, in your case it is 32766. Inside the loop it start from 32766 and continue its given operation.
The operation for the Case1 codes see below :-
sum = sum + i; //(like previous case here too value of "i" increase by 1 with iteration of the given loop)
/* 32767 = 32766 + 1
32769 = 32767 + 2
32772 = 32769 + 3
32776 = 32772 + 4
32781 = 32776 + 5
32787 = 32781 + 6
32794 = 32787 + 7
32802 = 32794 + 8
32811 = 32802 + 9
32821 = 32811 + 10
Here you can see the value of "sum" after the operation is 32821
*/
Okay! summing up everything, your logic and code looks fine to me but in first case the value of sum was allotted by compiler randomly, so here everything went wrong for the first case.
Activate the compiler flag -Wuninitialized.
In the first program, the sum is kept uninitialized and contained garbage value. Thus, you get the error. OTOH, in the second program, the value of sum is initialized to 0, which is exactly a zero and thus, the count did successful.
When you write int sum; in c++, a space in the memory is reserved for this variable, because it's not only a declaration, but also a definition. As sum is not set to any value yet, then, in this case, it gets any crazy value stored in it's space of memory that was already stored there before. Hope it helped :) Here are some useful links about this:
link1;
link2

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

For Example: Input: 982
Outputs: 9 8 2
Your Total sum is: 19
I see people using input_number % 10 in a loop and then input_number / 10 but I still do not get it. If i did 982 % 10 I would get 2 and then they add it to the sum which is 0 + 2 = 2 and how would that get 19???? and then the input number which is 982/10 is equal to 9.82 how does lead me to my solution of 19?? I am just super confused can someone please explain it to me and try to work out the problem and make it into a simple solution. I appreciate it and try to use the basic stuff like including namespace std and then not using arrays just loops and simple math equations thank you.
int n,sum=0;
cin>>n;
while(n!=0)
{
sum=sum+(n%10);
n=n/10;
}
/*
Since your n is an integer it will drop the value after decimal.
Therefore, 982 will run as
Iteration 1 n=982
sum=2
n=982/10=98
Iteration 2
sum=2+(98)%10 = 10
n=98/10= 9
Finaly in iteration 3
n=9/10=0 hence loop will terminate and sum be 19*/
You should input the number as a characters, that you convert into the digits and then individual numbers, that are easy to add or print or whatever. Avoid complicated math when you can totally live without it.
std::string str;
std::cin >> str;
int sum = 0;
for( int i=0; i<str.length(); i++) {
if( isdigit(str[i]) ) {
std::cout << str[i] << " ";
sum += int(str[i] - '0') // convert a char to int
}
}
std::cout << std::endl;
std::cout << "Total sum: " << sum << std::endl;
or something like that. Haven't programmed in C++ for a while, there might be minor mistakes in the code, but you get the general idea.

Sum finder not consistent

My code here finds the sum of some given multiples less than or equal to a certain number. It uses a modified version of a formula I read about on the internet a while ago (the one for finding the sum of all the numbers less than or equal to 100, or 1000 or something- when I wrote my formula while I was waiting to be picked up at the ymca so it might not look like the one from the internet). So for me I used (n+x)(n/x/2), where n is the limit (for example 1000), and x is the multiple you are using (so 1, or 3, or 5). So if n = 1000 and x = 5, it should find the sum of all multiples of 5 less than or equal to 1000).
Sometimes it adds up correctly and sometimes it doesn't.
For example, if I choose 1 and 2 as the multiples, and 20 as the limit, it prints out 320 (which is correct if you add 1+2+3...+20 and then add to that 2+4+6...+20).
But if I do the multiples of 3 and 5 and 1000 as the limit, it prints out 266,998 (which is wrong according to the internet).
I do not understand why it worked in the first instance but not the second (I have only taken 1 year of high school math, I'll be a sophomore).
Here is the code:
/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/
//Data Declarations
#include <iostream>
int main()
{
using namespace std;
int a; //Stores the number of multiples being used
cout << "Enter the amount of multiples you would like to use (up to 50
<< endl;
cout << "(for example, enter '2' if you would like to use two multiples,
maybe 3 and 5?)" << endl;
cin >> a;
cout << "Next, you will enter the mutliples you want to use." << endl;
cout << "(for example, if you want to find the sum of the multiples of 3
and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
2')" << endl;
int multiples[50]; //Stores the multiples being used
for (int i = 0; i < a; i++)
{
cout << "Enter 'multiple " << (i + 1) << "'" << endl;
cin >> multiples[i];
}
int limit; //Stores the limit
cout << "Enter the the limit for how high you want to add the multiples
<< endl;
cout << "(for example, you could set the limit to 1000 to find the sum
of the\nmultiples of 3 and 5 (if you entered those) less than and or
equal to 1000)" << endl;
cin >> limit;
int sum(0); //Stores the sum
for (int i = 0; i < a; i++)
{
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
}
cout << "The sum is "<< sum << endl;
system("pause");
return 0;
}
EDIT: I believe the problem might lie in the code not in the formula, because using it on multiples of 3 with 21 as the limit causes it to print out 72, not 84 like it should. I am still unsure of the coding error.
EDIT 2: I changed the for loop to this so it hopefully will function when the limit isn't a multiple of the multiple
for (int i = 0; i < a; i++)
{
int max = limit; /*This is done so I can change max in case it isn't
a multiple of the multiple*/
while (max % multiples[i] != 0) max--;
sum += ((max + multiples[i]) * (max / multiples[i] / 2));
}
Change
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
to
sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;
As it is, for your example of 3 and 21, you're computing (24 * (7 / 2)) = 24 * 3 = 72 (integer division of 7 by 2 gives 3, and the remainder is lost), but you want to be computing (24 * 7) / 2 = 84.

While loop logic clarification + harmonic series

This is my code for finding the sum of a harmonic series of 1/n. I want it to stop when the sum is greater than or equal to 15, but the code cannot run. Can anyone let me know what I'm doing wrong? It seems to follow the correct while loop structure. Thanks!
#include <iostream>
using namespace std;
int main ()
{
int divisor = 1;
int sum = 1;
while ((sum <= 15) && (divisor >=1))
{
sum = sum + (1/divisor);
divisor++;
}
cout << "You need " << divisor << " terms to get a sum <= 15" << endl;
return 0;
}
Your loop is actually running. However, your sum variable is of type int, and so is divisor.
1 (an int) / divisor (also an int) will return 1 or 0. This is because you are doing integer division. 1/1 == 1. However, 1/2 == 0, 1/3 == 0, etc... To solve this, cast divisor to double:
(1 / (double)divisor)
So that solves the issue of that segment returning only 1 or 0. However, you will still gain a sum of 1 as sum is of type int. Attempting to assign a double to an int variable will result in a truncation, or floor rounding. Sum will add the first 1, but it will remain 1 indefinitely after that. In order to solve this, change the type of sum to double.
Your assignment of sum = 1; is a logical error. Your result will be 1 higher than it should be. Your output statement is also mistaken... It should be...
cout << "You need " << divisor << " terms to get a sum > 15" << endl;
In addition, the condition of divisor >= 1 is needless... It is always greater than or equal to one because you assign it as 1 and are incrementing... If you do want a sum that is >= 15, change the while condition to...
while (sum < 15)
Your code should look like this...
#include <iostream>
using namespace std;
int main()
{
int divisor = 1;
double sum = 0; //Changed the type to double and assigned 0 rather than 1
while (sum <= 15) //While condition shortened...
{
sum = sum + (1 / (double)divisor); //Added type cast to divisor
divisor++;
}
//cout statement adjusted...
cout << "You need " << divisor << " terms to get a sum > 15" << endl;
return 0;
}