+ 4
Weird Code....
Okay,so i've few questions regarding the code below: Q1) How does this loop work ? Please explain the output (5 2) Q2) Why is the output reversed in this case while Q3 gives the expected output ? (Expected 7 6 5 4 3) (Actual : 3 4 5 6 7) Code here: https://code.sololearn.com/colI0LlGowyd
6 Answers
+ 10
before main starts the executionĀ numĀ initialized withĀ 7 ( note that it is stored under static memory due to it is static number. )
on first iteration :-Ā r()Ā ā¹Ā returnĀ 7Ā butĀ numĀ changed toĀ 6.
r()Ā ā¹Ā returnĀ 6Ā butĀ numĀ changed toĀ 5.Ā ā¹ condition evaluate to trueĀ ā¹Ā for loop body executes !
printf("%d",r());Ā ā¹Ā returnĀ 5Ā butĀ numĀ changed toĀ 4 ā¹Ā printĀ 5Ā on the screen.
r()Ā ā¹Ā returnĀ 4Ā butĀ numĀ changed toĀ 3.
r()Ā ā¹ returnĀ 3Ā butĀ numĀ changed toĀ 2.Ā ā¹Ā condition evaluate to trueĀ ā¹Ā for loop body executes !
printf("%d",r());Ā ā¹Ā returnĀ 2Ā butĀ numĀ changed toĀ 1.Ā ā¹Ā printĀ 2Ā on the screen.
r()ā¹Ā returnĀ 1Ā butĀ numĀ changed toĀ 0.
r()Ā ā¹Ā returnĀ 0Ā butĀ numĀ changed toĀ ā1.Ā ā¹Ā condition evaluate to falseĀ ā¹Ā for loop over !
Hence output :Ā ā52
printf() print the statement generally from right to left that's why second output is printed from right.
third is obvious as you are printing one by one
+ 3
1) Q1 is a great question because you see for loops take 3 paramaters one is initial number second is condition to continue(this one is also done at the end of a for loop i forgot to mention) and third one is step function which is done at the end of every function. As loop starts your first parameters which is replaced by letter function makes it 5 and prints it when function ends step parameter decrements to 3 then you apply the same process and print 2. Why does it print less number? Because it is static int means that once it is declared in block it will be same all the time and compiler will ignore reallocation to 7
+ 3
2) is also something i have never seen but clearly second parameter sends its value to the last %d in print formatter so it creates an illusion that you reversed inputs. 3 is pretty much basic self explainatory because it is an expected behaviour of static data types and a great exam question
+ 1
Oh..Well,Thanks for the answers.Was quite confused until now. C never fails to amaze me.I still have a lot to learn..Wish me luck :-)
+ 1
What kind of code can you make with only beginner python concepts
0
Bjr frere