BookmarkSubscribeRSS Feed
swayto
Fluorite | Level 6

Question Output is 10 , why not 7?

%Macro mysum(n);
%if &n > 1 %then %eval(&n + %mysum(%eval(&n-1)));
%else &n;
%mend;

%put %mysum(4);

4 REPLIES 4
ed_sas_member
Meteorite | Level 14

Hi @swayto 

 

You can use the mlogic option to display if the condition was evaluated as true or false:

 

options mlogic;

In the macro, you have nested conditions :

n = 4 so the first condition is true -> 4 + (as 3 is greater than 1, we apply the "if" condition so: 3 + (as 2 is greater than 1, we apply the "if" condition so: 2 + (as 1 is not greater than 1, we apply the 'else' condition so 1)

-> so 4 + 3 + 2+ 1

 

Hope it's clear.

 

Best,

newfee
Fluorite | Level 6

Do you want to have 7 as result? Or was it just that you wanted to have the code explained?

Satish_Parida
Lapis Lazuli | Level 10
/*Output 10 because of recursive code*/
%macro mysum(n);
	%if &n > 1 %then %eval(&n + %mysum(%eval(&n-1)));
	%else &n;
%mend;

options mprint mlogic;
%put %mysum(4);

/*Output 7 because of nonrecursive code*/
%macro mysum(n);
	%if &n > 1 %then %eval(&n + /*%mysum removed*/%eval(&n-1));
	%else &n;
%mend;

options mprint mlogic;
%put %mysum(4);

I hope this helped. 

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 583 views
  • 1 like
  • 5 in conversation