Sunday, April 13, 2014

Windows Scripting (the normal shell) for Ex VB Programmers - Lesson 2

In any programming language there are three things we need to learn at the earliest.

1. Types of variable

2. Selection Statements

3. Iteration or Loops

Since ours is a “get ready quick” course. We will only try what we think is essential.

1. Variable.

There are no types of variables. What ever you assign the variable takes that values. Unlike in other programming languages you have int, char, fload, date etc. There is nothing here. You can just put any value in any variable. The upside is variable usage is easy. Same variables can be recycled. The downside is explicit conversions are needed everytime a variable of a specific type is needed.

Assume you have a program with the following

i=5
wscript.echo i
i="Programs"
wscript.echo i

When you run it there is no error.

image

 

2. Selection statements.

Keeping it simple.

if <condn> then

<statements>

else

<statements>

randomize
i=int(rnd * 10)
wscript.echo i
if i mod 2 =0 then
    wscript.echo "Even Number"
else
    wscript.echo "Odd Number"
end if

randomize – resets the seed, so that you get a real random numbers all the time. rnd generates a random number between 0 and 0.999xxx. The int function converts the output to an integer (we don’t need the decimals). The mod is a operation to find the remainder.

The above program prints either even or odd depending on the random number. In the example the program is saved as third.vbs

C:\scripts>cscript third.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

7
Odd Number

C:\scripts>

C:\scripts>cscript third.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

1
Odd Number

C:\scripts>third
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

0
Even Number

C:\scripts>cscript third.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

6
Even Number

C:\scripts>

3. Iteration or Loops

The most convenient loop is the for – next.

An example

wscript.echo "Program 2"
for i=1 to 5
        wscript.echo i
next
wscript.echo "Random Numbers"
for i = 5 to 1 step -1
        randomize
        intnum=rnd
        wscript.echo int(intnum*10)
next

 

A simple program the prints, from 1 to 5. And then random numbers between 0 and 9.

Program 2
1
2
3
4
5
Random Numbers
1
0
8
2
0

Try this exercise.

Print the first 100 prime numbers.

use the concepts learnt.

No comments: