Awesome q2a theme
0 votes
23 views
Consider the following code:

int bar(int val)

{

int x=0;

while(val>0){

x=x+bar(val-1);

}

return val;

}                                                                                                 
Where does the difference in the functioning of the code occur when the statement x=x+bar(val-1);  in the above code gets replaced by x=x+bar(--val);

Please explain the difference between both of them and the way the logic works.
in Programming by (6 points) | 23 views

2 Answers

0 votes

When you use 

x = x + bar(val - 1);

here the value used for calling bar function is (val - 1), but the variable 'val' itself isn't decremented. Therefore val doesn't change at all, and the program is unable to break out of the while loop. So the program falls into an infinite loop (but the computer has finite memory and each function call consumes some stack space, therefore the program terminates when the computer runs out of memory).

 

When you use 

x = x + bar(--val);

In this case, 'val' is decremented. Therefore the while loop breaks out at some point and the program is able to terminate properly.

by (17 points)
0 votes
s = --val  <=> val = val-1; s=val

s= val -1 // s gets same value as earlier but val isn't decremented by 1.
by (66 points)
0

What does it mean..

 int bar(int val);

I have been seeing lot of these expression in E Balaguruswamy's book,but there is no mention earlier.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Welcome to GATE CSE Doubts, where you can ask questions and receive answers from other members of the community.
Top Users Jul 2020
  1. Shaik Masthan

    39 Points

  2. hiteshpujari

    9 Points

  3. Venkatesh Akhouri

    6 Points

  4. Meghana518

    6 Points

  5. bittujash

    6 Points

  6. Pawan_k

    6 Points

  7. rits78671

    6 Points

  8. srestha

    6 Points

  9. RavGopal

    4 Points

  10. Sumaiyas

    4 Points

7,543 questions
1,783 answers
10,867 comments
90,482 users