What is the difference between these two programs? - c++

What are the differences between these two programs? For the first program I got an output of 9 and for the second program I got an output of 10.
#include <iostream>
using namespace std; // So we can see cout and endl
int main()
{
int x = 0; // Don't forget to declare variables
while ( x < 10 ) { // While x is less than 10
cout << x << endl;
x++; // Update x so the condition can be met eventually
}
cin.get();
}
#include <iostream>
using namespace std; // So we can see cout and endl
int main()
{
int x = 0; // Don't forget to declare variables
while ( x < 10 ) { // While x is less than 10
x++; // Update x so the condition can be met eventually
cout << x << endl;
}
cin.get();
}

In the first code block you are outputting x then adding to it so it will output 0-9. In the second code block you are adding 1 to x before you output it so it will give you outputs 1-10. It's based on where you put the x++ in relation to the output statement

Output of first is 0 1 2 3 4 5 6 7 8 9. Output of second is 1 2 3 4 5 6 7 8 9 10.

In the first example, you write the number out and then increase the variable, whereas in the second one you increase the value at first.

This is due to the order (obviously). In the first while loop, when x is 9, it prints it, increases it and doesn't pass the condition and does not enter the loop again.
In the 2nd case, when x is 9, it increases it to 10 and then prints it, and then leaves the loop. It's just common sense. The second loop therefore skips the number 0, and prints till 10.
First loop : 0,1,2,3,4,5,6,7,8,9
Second loop : 1,2,3,4,5,6,7,8,9,10

The first snippet prints the value of the variable and then increments it. This means the value of the variable after the last incrementation will not be printed.
The second snippet increments the variable and then prints it. This means that it will not print 0. The value it was initialized as.

Related

Not getting correct output Function not working

I'm trying to write a code that will take a number that the user inputted and create an inverted triangle like:
8 6 4 2 0 on the first line,
6 4 2 0 on the second line,
4 2 0 on the third line,
2 0 on the fourth line,
0 on the last line.
My nested for loops worked in a previous code that was in the main not in a function, but I decided I wanted to create a function that when called would run through the loops. However, something in my code isn't right since now I don't get an inverted triangle. I just get 0 and I think that's because my return is 0. I'm not sure if I'm writing my function incorrectly or if it's something else.
Please help. Thank you
#include <iostream>
using namespace std;
int row(int num)
{
int number;
int decreasedNumber;
for(int i = number; i >= 0; i -= 2)
{
decreasedNumber = i;
for(int j = decreasedNumber; decreasedNumber >= 0; decreasedNumber -=2)
{
cout << decreasedNumber << " ";
}
cout << endl;
}
return 0;
}
int main()
{
int number;
//Prompting the user to enter a number and collect that input
cout << "Enter a number: " << endl;
cin >> number;
cout << row(number);
return 0;
}
You are accepting num as a parameter to row, but never using it. Also, you are using number, but never initializing it. Instead, it seems you want number to be the parameter to the function, instead of a local variable.
Here's a demo.
Also, the variable j is never used in the loop, so you should just remove it.
Also, please don't use using namespace std;, it's a bad habit that you should avoid.
You are using number as the initial value of i.
number is uninitialized and its value is indeterminate.
Instead of number, you should use the argument num as the initial value of i.

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

Confused about the output of this recursive function

I am just learning recursion and I am confused about the output of this recursive function.
int Run(int x)
{
if (x > 0)
cout << Run(x - 1) << " ";
return x;
}
If I call this function with Run(5), I get the output: 0 1 2 3 4
I expected to get the output: 0 1 2 3 4 5.
I'm confused as to why 5 is not returned at the end of the output. It's the value I plugged in to the function, so after all the recursive calls are made, shouldn't the function be returning that same value I plugged in?
Run does return 5, but the recursive calls to Run never do, and only the return of the recursive calls are printed.
Think about it like this: you aren't printing every x given to Run; you're only printing the return of the recursive calls. Your first call to Run that makes the recursive calls returns the 5 that you're expecting to be printed.
Basically, the 0 index means that your function will be executed n times, where n = the argument integer plus 1. the thing is the cout << Run(x - 1) << " "; will be executed n-1 times. This is because the first function call, once it executed all the other recursive calls, will return its value of x. but since it is not returning it to a previous recursive call which would then cout that value, it is not being displayed.
try this cout << Run(int x) on your main function.
We can see that Run(n) is a function that prints the non-negative whole numbers less than n and returns n. This means that for Run(n) you will get an output of 0 1 2 ... n-1 if n is positive.
What you have here:
cout << Run(x - 1) << " ";
is the same as
int r = Run(x - 1);
cout << r << " ";
That is, Run(x-1) will print the numbers less than x-1 and return x-1. So if x == 5 that means Run(x-1) printed the numbers from 0 to x-2 and r was set to 4. Then the function will print r and return. If you're still confused, it's also exactly the same as doing:
Run(x - 1);
cout << x-1 << " ";
Since we know that Run(x-1) will always return x-1 we can skip storing it in a variable and print it directly. A trick when analysing recursive functions is just to assume that they work - assume that Run(x-1) successfully prints the numbers from 0 to x-2 - the only thing left to do then is to print x-1.
So as you can see, the variable x never gets printed, only the numbers less than it. The function returns 5 but it just never prints it.
If you want it to print the non-negative whole numbers less than or equal to x, make this modification:
int Run(int x) {
if (x >= 0) {
cout << Run(x-1)+1 << " ";
}
return x;
}
The if statement has been changed to include 0 being printed now. Run(x-1) prints the numbers from 0 to x-1 and returns x-1, so adding 1 to the result allows us to print x.

Why is this loop running invisible code? and not working in order

int ASCI1 = 1;
for (int i = 1; i < 8; i++)
{
cout << ASCI1 << endl << ASCI1++;
}
I get output :
2
13
24
35
46
57
68
7 (and no end line here for some reason).
The idea was to get
1
2
3
4
etc.
Completely stumped, please help!
The << operator is not defined as a sequence point in C++, so it's possible for ASCI1 and ASCI1++ to be evaluated in any order.
If you try to perform reads and writes on an object with unsequenced evaluation, then you have undefined behavior, hence the garbage output you are seeing.
Finally, you don't see a newline at the end 1) because you got lucky, and 2) because even if your loop executed as you had planned, you're still performing a write without following it up with another endl
The code is not invisible. You are outputting two numbers per each loop execution, one on first line, then a newline, then another on the next line.
Just do
int ASCI1 = 1;
for (int i = 1; i <= 4; i++){
cout << ASCI1++ << endl;
}
Not clear why you created that mess, just use:
int ASCI1 = 1;
for (int i = 0; i < 4; i++) {
cout << ASCI1++ << endl;
}
Note you should either start with 0 (as shown) or change condition to <= otherwise you will loop 3 times instead of 4.
Let's consider the very first iteration of for loop (when ASCI1 is 1):
cout << ASCI1 << endl << ASCI1++;
This statement is transformed as (hypothetically):
cout.print(ASCI1).printNewLine().print(ASCI1++);
As others commented, order of evaluation is not defined. In your case, ++ operation is being performed first, but the last print statement is to be passed old value of variable (i.e. 1), and not incremented value. The just incremented value is passed to first print. Hence it becomes:
cout.print(2).printNewLine().print(1);
The value of ASCI1 would be 1 after this statement. It will give output as:
2\n
1
And the next iteration would print 3 and 2 the same way I explained above
2
13
2\n
You've been lucky that you used just one ++ statement in one statement.
What if first print is passed 1 and second is passed 2, or 1 and 1. It is up to compiler, and the compilation phase. This is Undefined Behaviour (UB)

long integer multiplication in c++

I am a beginner in C++. I am trying this long integer multiplication. I am not understanding that how the value ofsum[3][0] is changing in the subsequent loop cycle.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num1, num2;
int i,j,l1, l2,temp,k;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
l1= num1.size();
l2= num2.size();
cout << l1 << " " << l2 << endl;
int sum[l2-1][l2]; // 5 6 7 8 ---> num1
// 1 2 3 4 ---> num2
for(i=0; i<l1; i++) // ---------
num1[i]-='0'; // 2 2 7 1 2 sum[3][4]---->sum[3][0]
// 1 7 0 3 4 i.e sum[3][0] should be 2
for(i=0; i<l2; i++) // 1 1 3 5 6
num2[i]-='0'; // 5 6 7 8
// -------------
for(i=l2-1; i>=0; i--) // 7 0 0 6 6 5 2
{
k=0;
temp=0;
for(j=l1-1; j>=0; j--)
{
temp+=(num2[i]*num1[j]);
sum[i][k]= temp%10;
temp=temp/10;
k++;
}
sum[i][k]=temp;
cout << sum[3][0] << endl;
}
for(i=l2-1; i>=0; i--) // output is 2 2 7 1 1 Here value of sum[3][0] is 1 but the desired output is 2.
{ // 1 7 0 3 1
for(k=l2; k>=0; k--) // 1 1 3 5 0
cout << sum[i][k]; // 0 5 6 7 8
cout << endl;
}
return 0;
}
I tried this code for the case num1=5678 and num2=1234. So sum[3][0] should be 2 in that case.
You did not make sum large enough. You use sum[0..l2-1][0..l1] so the size would need to be sum[l2][l1+1].
When you exceed the second dim of sum that typically makes part of one row of sum share storage with part of another, so the place where you stored sum[2][0] is the same place you later stored sum[1][4]
When you exceed the first dim of sum (or the second dim in the last row) that makes sum share storage with other things, such as(but not necessarily) the other variables local to that function.
Also, your loop for displaying sum is incorrect. You use rows of sum from l2-1 down to 0 and columns from 0 up to L1. But you display columns l2 down to 0. The columns are computed based on l1, so should be displayed based on l1. That error would have symptoms if you tried an example with l1 not equal l2.
The sum array should be create like this:
int sum[l2][max(l1,l2)+1];
It is too small to store results of you calculations now.
Why program doesn't crash while you write out of bounds of the array? Because C++ has not any array bounds checking.
To be honest, you should declare the array by new and remove it by delete when it is not needed anymore. C++ standard doesn't provide to create non-constant size array without new. Only some compilers supports it as an extension and many of them prints warnings when you do that. More informations here: How do I declare a 2d array in C++ using new?