+ 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

11th Dec 2019, 8:14 PM
Tanmoy
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
11th Dec 2019, 8:34 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 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
11th Dec 2019, 8:28 PM
Talha Altınel (The Last Sith Lord)
Talha Altınel (The Last Sith Lord) - avatar
+ 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
11th Dec 2019, 8:30 PM
Talha Altınel (The Last Sith Lord)
Talha Altınel (The Last Sith Lord) - avatar
+ 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 :-)
11th Dec 2019, 9:26 PM
Tanmoy
+ 1
What kind of code can you make with only beginner python concepts
12th Dec 2019, 8:15 PM
K-Trap
0
Bjr frere
13th Dec 2019, 8:46 AM
Siborurema martin