0
Basic math
Hey gang. My question is simple: How do you calculate: int x=1; for(int i=0; i<=1;i++){ int sum= x+i; cout<<sum; } The compiler shows 12 but to be honest as of late Iâve gotten confused on how to calculate the for loops properly. Thank you in advance, Dawid
8 Answers
+ 3
In for loops you intialized i with 0 and put a condition if i<=1.
If that condition satisfied, loops runs.
Now,
First condition check is 0<=1 is true so it will add value of sum to x+i which will be 1.
And then it will print 1.
Second condition is 1<=1 which is true.
It will again add 1+1 to sum. And prints 2 in output.
Third condition will be 2<=1 which is not true so loop will be break.
+ 3
p stored a which is the adress of first element of a, and that remains 0. So with *p you're printing a[0] 5 times.
+ 2
You cout with every iteration, so it's two results:
x+0 > 1
x+1 > 2
+ 2
If you don't put anything into your array but just declare it, there is random stuff at that place in memory, so your output could be anything.
+ 1
thanks for the answers. So by this logic, the output of the following code:
int a[5];
int *p=a;
for(int i=0; i<5;i++){
a[i]=i;
cout *p;
}
should be 0,1,2,3,4
but the compiler shows 00000.
what al i calculating wrong?
+ 1
Your code doesn't make sense: int[1]. Can you show the whole code?
0
Fair enough, makes sense. Now I added the following to the compiler and this came out:
int[1];
int x;
for(x=0;x<1;x++){
x=a[x];
cout<< x;
}
compiler shows 7208852.
How I try to explain it:
we have an array of 2 elements in int [1]. Int x is a variable. The for loop executes, given the condition x=0; and if itâs less than 1, increment it by one. So far so good. Now lets put that into practise:
x=a[x], meaning:
0=a[0], because in the first iteration of the loop x=0, the array srarts at 0 and therefore the output should be 0. How does the compiler calculate 7? And what did I understand wrong?
0
forgot to add a, its: int a[1];