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);
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,
Do you want to have 7 as result? Or was it just that you wanted to have the code explained?
/*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.
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.