Weird Code.... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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