2012年6月22日 星期五

Batch Tutorial 01 - Multiplication Table


Hey guys! 
In this tutorial we are going to help children!
Actually it's just a simple multiplication table... but let's not be demotivated!
Alright! What is always the first step?

@echo off

That's right!
Now we need three values: a, b and c
The values will represent a certain number that you set it to.
Now, you simply set numbers by using "set" command.

set a=1
set b=1

We will leave c for now.
The idea is to have the number substituted into the equation "a*b=c"
Now we need to have our system planned.
Let's just move on and I will explain every part.

:a

When you have a letter or a word after ":" it is like a check point.
With "goto" command you can move to check points.
If you read the first tutorial, the batch file runs from top to bottom.
"goto" command forces it to keep going from the check point.
Now, let's do our calculation!

set /a c=%a%*%b%

Note that when you set an unknown, you do not need "%", but when you use the unknown as a value you need it in front and behind the letter.
The "/a" behind the "set" command is to calculate, any value that needs to be calculated from other values, needs the "/a" after "set". In this case, it sets "c" to "a*b" which is 1*1=1
All these will NOT be shown to the client, to show a message to the clients, use "echo"
"echo" will show everything on that line except for the space behind it.

echo %a% x %b% = %c%

We will use "x" for now, because it looks like the multiplication symbol in the cmd.
Now we should have "1x1=1" done.
let's set b to 2

set /a b+=1

"+=" increase the value before it by the value after it, "-=" does the exact opposite.
Ok, now we can use "goto" to make it loop, but we don't want b to be anything more than 9.
We need a new check point, and we need to make sure that when b gets to 10, it goes to the check point.

if %b%==10 goto b

Ok, now let's discuss what ":b" does.
It sets the a value to one higher, and sets b to 1.
Then return it to ":a"

:b
set /a a+=1
set b=1

Just stop there before you type in the "goto" command.
Think about it, if we have "goto a", then there is a loop which multiplies a to 9 and increase it by 1
But we do not want a to be any higher than 9

if %a%==10 goto c

Let's deal with c later on, now we can have "goto a"

goto a

":a" and ":b" are both done, now let's make ":c" pause the whole thing

:c
pause => nul

The "=> nul" stops "pause" command from showing "Press any key to continue..."
Now we connect the whole thing together:

@echo off
set a=2
set b=1
:a
set /a c=%a%*%b%
echo %a% * %b% = %c%
set /a b+=1
if %b%==10 goto b
goto a
:b
set /a a+=1
set b=1
if %a%==10 goto c
goto a
:c
pause => nul















Save it as whatever name you want followed by ".bat"
This is the end of this tutorial, hope you like it!

沒有留言:

張貼留言