C++ Prime Numbers

#include <stdio.h>
#include <time.h>

using namespace std;

bool isPrime(long n)
{
	long i, m;
	m = n / 2;
	if(n % 2==0)
		return false;
	else for(i=3; i<m; i+=2)
		if(n % i==0)
			return false;
	return true;
}

int main()
{
	long j;
	clock_t tStart = clock();
	for(j=1;j<1000000;j++)
		if(isPrime(j))
			printf("%ld\n", j);
	printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
	return 0;
}

 

Chloe

' Chloe Program
data "C", "h", "l", "o", "e", " ", "G", "r", "a", "c", "e"
data " ", "M", "o", "r", "e", "t", "z", ",", " ", "I", " "
data "l", "o", "v", "e", " ", "y", "o", "u", "!", chr$(13), "I"
data " ", "w", "a", "n", "t", " ", "t", "o", " ", "m", "a"
data "k", "e", " ", "l", "o", "v", "e", " ", "t", "o", " "
data "y", "o", "u", "!", chr$(13), chr$(26)

dim a as integer
dim c as string * 1

const newline=chr$(13)
const endline=chr$(26)

do while c<>endline
	read c
	select case c
	case newline
		print
	case endline
	case else
		print c;
	end select
loop
end

 

Fractal Tree C++ Logo Output

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <string>

usingnamespace std;

class ifstree
{
public:
    float minfactor;
    float maxfactor;
    float bend;
    float angle;
    float initlen;
    int fdim;
    ifstree();
    void turnleft(float ang)
    {
        printf("lt %4.2f\n", ang);
    };
    void turnright(float ang)
    {
        printf("rt %4.2f\n", ang);
    };
    void movefw(float value)
    {
        printf("fw %4.2f\n", value);
    };
    void movebw(float value)
    {
        printf("bw %4.2f\n", value);
    };
    float randfactor();
    void draw();
    void draw(float linelen,int depth);
};

ifstree::ifstree()
{
    minfactor =(float)1/3;
    maxfactor =(float)2/3;
    bend =8.0;
    angle =40.0;
    fdim =8;
    srand( time(NULL));
    initlen =100.0;
}

void ifstree::draw()
{
    draw(initlen, fdim);
}

float ifstree::randfactor()
{
    float rnd =(float) rand()/RAND_MAX;
    return(float) rnd;
}

void ifstree::draw(float linelen,int depth)
{
    if(depth>0)
    {
       float minlength = linelen * minfactor;
       float maxlength = linelen * maxfactor;
       float difflength = maxlength - minlength;
       movefw(linelen);
       turnleft(angle+bend);
       draw(minlength+(randfactor()*difflength), depth-1);
       turnright(angle);
       draw(minlength+(randfactor()*difflength), depth-1);
       turnright(angle);
       draw(minlength+(randfactor()*difflength), depth-1);
       turnleft(angle-bend);
       movebw(linelen);
    }
}

int main(int argc,char*argv[])
{
    ifstree T;
    if(argc>1)
    {
        string svalue(argv[1]);
        float fv =(float)atof(svalue.c_str());
        T.initlen = fv;
    }
    T.draw();
    return0;
}

 

Javascript

I am planning to do practice some javascript programming at the console rather than embedded in a web page. My main system runs windows so it does support jscript in the windows scripting host. However, I want something better than what windows provides. One of the possibilities was Google’s V8 interpreter, the fastest javascript interpreter today. However, it only available in source code and requires compiling. The problem is it not easy to compile using MinGW or Digital Mars, as the source code is generally targeted for production on a linux environment. I tried searching for compiled binaries but no luck finding any and I have no desire to run two platforms to achieve my ends. However when I am on linux, there no such problem. But when I am on windows I want to have the same benefits of when I am on linux. The second choice was what is available from Mozilla, two products, Rhino and Spidermonkey. Rhino was pretty easy to setup but it is a java application, it will run on any system with a java runtime. However, I wanted something to run natively. Spidermonkey like V8 runs natively, however I was beginning to face the same level of complexity with V8. However, there were a few resources online that detailed all the steps in developing a windows binary, including installing some Mozilla specific support files etc. So it was looking like I was going to have to go down that path to get a javascript interpreter. That is, until, I found a website, which did have a compiled version of spidermonkey. A sigh of relief and I clicked the download. Opened the archive, which included three files, a text file listing command line options, the binary and a support DLL. I copied them into my windows directory so they be available to me wherever directory my command line is in.

Mission accomplished.

Mistake: I didn’t bookmark the website I found it…. lol.

 

ROT13 C++

The following program (written in C++) creates a filter program for converting ascii into ROT13 encoding. A very simple cypher where each character in the alphabet is replaced with the 13th letter from its position. To download a compiled windows compatible binary, click here.

#include <cstring>
#include <cstdio>
#include <cctype>

using namespace std;

char translate(char c)
{
    int cflag = 0;
    char oc = c;
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    int alphalen = strlen(alphabet);
    if(isalpha(c)) {
        if(isupper(c)) {
            cflag = 1;
            c = tolower(c);
        }
        for(int i=0;i<alphalen; ++i) {
            if(c==alphabet[i]) {
                oc = alphabet[(i+13)%alphalen];
            }
        }
        if(cflag==1) {
            oc = toupper(oc);
        }
    }
    return oc;
}

int main() {
    char c;
    while((c=(char)getchar())!=EOF) {
        putchar(translate(c));
    }
    return 0;
}

Hello World C++ with Objects

Ok… this is a “Hello World” program in C++ using objects. It illustrates a number of aspects of object oriented programming in C++ allowing you to get a quickstart into C++ programming. First there is the #include directives which tells C++ that the program uses two libraries, iostream and string (actually they specify the header files that define the libraries to be used). “iostream” provides input/output to streams, in this case we are sending a stream to the console. “string” is a string type library that provide a string datatype that is not native to the base C++, this allows us to manipulate strings in an easy manner.

#include <iostream.h>
#include <string.h>
using namespace std;

class oHello
{
    string hstr;
public:
    oHello();
    ~oHello();
    void print();
};

oHello::oHello()
{
    hstr = "Hello World\n";
}

oHello::~oHello()
{
}

void oHello::print()
{
    cout << hstr;
}

>int main()
{
    oHello myObject;
    myObject.print();
    return 0;
}

Class oHello is defined as having three methods, oHello method is the constructor that is executed when the object is created, ~oHello is the destructor that is executed when the program destroys the object (in this case, when the program terminates), lastly there is print which sends hstr to the output stream. These are declared as public so that they can be accessed from other modules in the program that are not members of the oHello object class. “hstr” is private to the class and only the class methods can access this data. It is of type string, the object string that was defined in the string class library.

The oHello method does one thing, assign hstr the value of “Hello World\n”. “\n” means add a carriage return to the end of the string. Now, when any member methods access hstr it would contain the value “Hello World\n”.

The print method contains the instruction cout << hstr, this calls the hstr object using the << method which directs it to send the value it contains to the cout stream class, which as stated earlier sends the data to the output stream.

Now that all the objects are defined… we can use them in the main() function which is automatically executed when the program is run. First we create an instance of the oHello object, called myObject. Next we call the print method of the myObject object, which prints “Hello World\n” to the output stream (in this case the console). Lastly since main() is a function it must return something before terminating, so we return the value zero.

Hello World ooREXX

Ok, as my previous post showed how to write a routine oriented hello world program in gforth, I now explain a hello world program using objects in object oriented rexx (ooRexx).

#!/usr/bin/rexx
/*
    Object Oriented Hello World in REXX
*/

myobject = .hello~new
myobject~print
exit

::class hello
 ::method init
 expose hellostring
    hellostring = "Hello World"
 return
 ::method print
 expose hellostring
    say hellostring
 return;

Like all rexx programs, the main() like section is the beginning lines of the program. The object definitions begin after the main instruction sequence. In this case we have one object called “hello”

::class hello

It contains two methods, a constructor and general purpose method named “print”. Both objects share a variable common to the object called “hellostring”, which contains the string we want the object to print. It is initially set by the constructor to the value “Hello World”. The print method does only one thing, to print the value of the variable “hellostring” to the console.

So, here we have an illustration of using objects, methods, constructors and internal data passing between objects in a rexx program. (Note, I am not going into the details of what is object oriented programming, as if you reading this you should have already studied what is object oriented programming).

The beginning part of the program does two things, create an object named “myobject” of the type “hello” and initialize it. The second instruction calls the “print” method.

Pretty simple.

Hello World Gforth (better example)

One of the issues of most of the information out there with respect to the forth language (and this includes books) is the lack of a clear illustration of how to write a routine and call it in the program in a easy to understand manner. They show how to write a routine and call it from another routine but no one tells you where your main program should be to call all the functions… do you create an main() like routine, do you put the instructions at the beginning and the routines after, or do you define the routines and call them after…. most of the forth manuals seem to skip this part in clear english. I am not a anything like an experienced forth programmer, but like all experimental programmers, I am interested in all programming languages, including forth… while most of what I might do is in other languages, I would like to say that I know something of forth, but most of the information out there leaves a lot to be desired when you do not “know” forth.

Anyway this is my illustration of routine calls in a forth program. Ye old “Hello World” program. I believe all first “Hello World” program in any programming language should illustrate how routines (subroutines or functions) call called.

: hello
." Hello World" cr ;

hello
bye

So what does this program do? First it defines a routine called “hello” that does only one thing, print the text string “Hello World” with a carriage return.

With respect to forth, the routine must be defined before being used, so it comes before any instruction that calls the routine. This is why the rest of the program follows the routine. BTW the routine definition is terminated by the semi-colon. (Note all colons and semi-colons are spaced away from any other element, as forth needs a space when parsing to determine it sytnax).

There is no main() like construct in forth, so the instructions are listed right after all routines are defined. We therefore have two instructions: “hello” and “bye”. “hello” calls the hello routine and executes it before passing it off to the next instruction “bye” which in gforth tells the forth environment to terminate, exiting the program.

There you have it, a gforth “hello world” program that illustrates the use of routines in the source program.