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. 

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 1162 views
  • 1 like
  • 5 in conversation