In Lab 3 we see the first loop which is called the While Loop:
Clear[n,counter];
n=0;counter=0;
While[n<10,{If[EvenQ[n]==True,counter++],Print["The number is ",n,"."] };n++];
Print["The number of even numbers is ",counter,". We looked at the first ",n," numbers."]
Output:
The number is 0.
The number is 1.
The number is 2.
The number is 3.
The number is 4.
The number is 5.
The number is 6.
The number is 7.
The number is 8.
The number is 9.
The number of even numbers is 5. We looked at the first 10 numbers.
Counter and n are just variable named and counter++ and n++ means to add one to their value. You could have written also counter=counter+1 and n=n+1 which may be clearer. "While" is just the English meaning "While I live I breath..."
I modified the program slightly as follows: instead of EvenQ[n]==True I wrote Mod[n,2]==0 (this means; The remainder when I divide n by 2 is 0 which really means that n is even)
Clear[n, counter];
n = 0; counter = 0;
While[n < 10, {If[Mod[n, 2] == 0, counter=counter+1],
Print["The number is ", n, "."] }; n = n + 1];
Print["The number of even numbers is ", counter, ". We looked at the \
first ", n, " numbers."]
Play with it a little more and try different things.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment