Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

2/23/10

C example on how to use command line arguments

In this simple example we will see how to use the command line arguments in our C programs.
Well, we all noticed that main() get two parameters.
int main(int argc, char *argv[]);
argc is an integer representing the size of argv[]
argv is a table of pointer to chars ( Strings )
Below is a simple calculator which takes as arguments two numbers and prints the sum.
The code is:

#include <stdio.h>

int main(int argc, char *argv[]) {
if ( argc != 3) {
printf("Usage:\n %s Integer1 Integer2\n",argv[0]);
}
else {
printf("%s + %s = %d\n",argv[1],argv[2], atoi(argv[1])+atoi(argv[2]));
}
return 0;
}

Now lets explain the code:
line 4 : we check if the user passed two arguments to the program. We actually need two arguments but in C the first argument ( argv[0] ) is the name of our program, so we need two more.
line 5 : If the user didn't pass two arguments we print the usage of our program and exit
line 8 : Using atoi() function we convert pointers to char (string) to decimal numbers and display their sum

Example without arguments

C:\>ArgumentCalculator.exe
Usage:
ArgumentCalculator.exe Integer1 Integer2

C:\>

Example with two arguments

C:\>ArgumentCalculator.exe 123456789 987654322
123456789 + 987654322 = 1111111111

C:\>


In addition to the above the code to print all the arguments is:

#include <stdio.h>

int main(int argc, char *argv[]) {
for(int i = 0 ; i<argc ; i++)
printf("\nArgument %d: %s", i, argv[i]);
return 0;
}

5/25/09

My First Program in C Programming Language

Programing in C is not that difficult if you know the basic rules.

I'll show you how to create a simple program in C.

First of all open a text editor(kate,kwrite,vi,whatever you want). To compile the file I will show you, you will need to have gcc installed in your pc. If you are on Linux you open the software management,select gcc and install it. If you are on Windows I suggest you use a C developing program like Dev-Cpp witch is free.

If you installed Dev-Cpp on Windows or gcc on linux just do the following.

Open Dev-Cpp or a text editor and create a new empty file and save it as myfirstcprogram.c

Now first you have to include the stdio (standard library for input/output) so write in the first line

#include <stdio.h>

The next step is to write the header of the main function,open brackets {} and write your code.

This is your first program and I'm going to explain it.


#include <stdio.h>
int main(int argc, char *argv[]) {
int a,b;
printf("give number a : ");
scanf("%d",&a);
printf("give number b : ");
scanf("%d",&b);
printf("%d %d = %d\n",a,b,a b);
exit(0);
}

Now, What does the above code do?

Line 1: include the stdio library(explained above)

Line 2: main function from where your program will start execution

Line 3: we say that we have two integers named a and b

Line 4: print at the desktop the message give number a

Line 5: read the number entered. the function scanf waits until enter is pressed

Line 5 and 6 : do the same as 4 and 5 to read the number b

Line 7: prints the message number a + number b = a+b

Line 8: the program ended successfully

Now that you wrote the above code you have to compile it.

In Linux in the directory you saved the file type in the Konsole

gcc myfirstcprogram.c -o myfirstprogram

in Windows from the Dev-C++ menu select exectute - compile.

In windows open command prompt windows (start - run -cmd - ok)

use cd command to go to the directory you saved it.

In windows type myfirstprogram and press enter

and in Linux type ./myfirstprogram

Now you see the message " give number a : " type a number and press enter and you will see the same message for the number b so do the same again.

After that you will see the result : a + b = sum

Example of output:

give number a : 3

give number b : 4

3 + 4 = 7

That's it. You wrote and compiled your first program in C!!!

1/23/09

MIPS Reverse a String

MIPS example to reverse a string.

First it will be better to show how MIPS stores strings.

e.g.
the phrase "computerblog"
will be saved (address start form down to up):















??????00(zero byte)0x...b
g = 67o = 6fl = 6cb = 620x...8
r = 72e = 65t = 74u = 750x...4
p = 70m = 6do = 6fc = 630x...0


0x??????00 0x....b
0x676f6c62 0x....8
0x72657475 0x....4
0x706d6f63 0x....0

and reversed should be:
0x20736c00 0x....b
0x636f6d70 0x....8
0x75746572 0x....4
0x626c6f67 0x....0

when making syscall with 4 (li $v0,4) and $a = x00
will start printing bytes (characters) till the ending 0 (a zero byte)

Now I think it will be easier to understand the following MIPS code.
At this point it would be good to mention that it works only if the string length is even (2,4,6...2*k).
If you want it for odd length strings too you can solve it by changing the strreverse (after exiting loop if odd do another one loop) and please leave your comments.
Anw, this is the code (lines with comment *change means that it affects the table size or the strreverse function):

.data
.align 1
String: .space 14 #*change
msg1: .asciiz "Pls give a character: "
msg2: .asciiz "\n"
msg3: .asciiz "String is: "
msg4: .asciiz "\nString Reversed is: "
.text
.globl main
main:

addi $s0,$zero,13 #*change
addi $t0,$zero,0

in:
la $a0,msg2
li $v0,4
syscall

li $v0,4
la $a0,msg1
syscall
li $v0,12
syscall

add $t1,$v0,$zero
sb $t1,String($t0)
addi $t0,$t0,1
slt $t1,$s0,$t0
beq $t1,$zero,in

sb $zero,String($t0) #ending zero

la $a0,msg2
li $v0,4
syscall
la $a0,msg2
li $v0,4
syscall
la $a0,msg3
li $v0,4
syscall

la $a0,String
li $v0,4
syscall

addi $a1,$zero,14 #pass length-*change
jal stringreverse #reverse

la $a0,msg2
li $v0,4
syscall

la $a0,msg4
li $v0,4
syscall

la $a0,String
li $v0,4
syscall

li $v0,10
syscall


stringreverse:

add $t0,$a0,$zero #beginning address

add $t1,$zero,$zero #i=0
addi $t2,$a1,-1 #j=length-1

loop:

add $t3,$t0,$t1
lb $t4,0($t3) #lb String[i]

add $t5,$t0,$t2
lb $t6,0($t5) #lb String[j]

sb $t4,0($t5) #String[j]=String[i]
sb $t6,0($t3) #String[i]=String[j]

addi $t1,$t1,1 #i++
addi $t2,$t2,-1 #j--
#if i>=j break - $t1<$t2
slt $t6,$t2,$t1
beqz $t6,loop

jr $ra

#i-0;j=length-1;
# do {
# x = str[i]
# str[i]=str[j]
# str[j] = x
# i++;j--;
# } while(!(j<i))

Example of output:

Pls give a character: c
Pls give a character: o
Pls give a character: m
Pls give a character: p
Pls give a character: u
Pls give a character: t
Pls give a character: e
Pls give a character: r
Pls give a character: s
Pls give a character:
Pls give a character: b
Pls give a character: l
Pls give a character: o
Pls give a character: g

String is : computers blog

String Reversed is : golb sretupmoc

You may also want to see my post about how to reverse a file in C / C++.

I hope you find this post helpful and please leave your comments. Thank you.

1/22/09

MIPS Compare Strings

This is another MIPS example (program) which:
- ask user to enter two strings (max 20 characters) and saves them into memory.
- call (jal) a function (strcmp) which compares the two string and returns 0 (zero) if the two strings are the same or 1 (one) if not.
- prints a message depending on what strcmp returned.

.data
msg1:.asciiz "Please insert text (max 20 characters): "
msg2:.asciiz "\nNOT SAME"
msg3:.asciiz "\nSAME"
str1: .space 20
str2: .space 20
.text
.globl main
main:
addi $v0,4
la $a0,msg1
syscall
li $v0,8
la $a0,str1
addi $a1,$zero,20
syscall #got string 1
li $v0,4
la $a0,msg1
syscall
li $v0,8
la $a0,str2
addi $a1,$zero,20
syscall #got string 2

la $a0,str1 #pass address of str1
la $a1,str2 #pass address of str2
jal strcmp #call strcmp

beq $v0,$zero,ok #check result
li $v0,4
la $a0,msg2
syscall
j exit
ok:
li $v0,4
la $a0,msg3
syscall
exit:
li $v0,10
syscall

strcmp:
add $t0,$zero,$zero
add $t1,$zero,$a0
add $t2,$zero,$a1
loop:
lb $t3($t1) #load a byte from each string
lb $t4($t2)
beqz $t3,checkt2 #str1 end
beqz $t4,missmatch
slt $t5,$t3,$t4 #compare two bytes
bnez $t5,missmatch
addi $t1,$t1,1 #t1 points to the next byte of str1
addi $t2,$t2,1
j loop

missmatch:
addi $v0,$zero,1
j endfunction
checkt2:
bnez $t4,missmatch
add $v0,$zero,$zero

endfunction:
jr $ra

Example of the output:

Please insert text (max 20 characters): akoma ena blog
Please insert text (max 20 characters): computers blog
NOT SAME

Please insert text (max 20 characters): computers blog
Please insert text (max 20 characters): computers blog
SAME

Thank you very much for visiting and reading. I hope this example was helpful to you.
Any comments are appreciated.

JMenuItem not visible - JMenuItem behind Canvas

I was trying to make a GUI in java where I needed to have a JMenuBar (with some JMenuItems) and a Canvas. The problem I run into was that my JMenuItems were shown behind Canvas. I didn't know why so I searched the web to find the solution. I was not very lucky and for a few hours the only important "think" I found was that Canvas is heavyweight component (awt) and JMenuItem is lightweight (swing) component. And you only mix them if you know exactly what you are doing... So I "solved" that by only using awt components. How? It isn't difficult.
Just remove all J :-P
e.g.
JMenuItem = MenuItem
JMenuBar = MenuBar
setJMenuBar = setMenuBar
e.t.c
This can be done because swing has JMenuItem and awt has MenuItem e.t.c.

The line I had to change more was:

itemExit.setShortcut(
new MenuShortcut(
new KeyEvent
(this, 1 , 1 ,
KeyEvent.CTRL_MASK , KeyEvent.VK_X ,
KeyEvent.CHAR_UNDEFINED ).getKeyCode()
));

which became like this :

itemExit.setAccelerator(
KeyStroke.getKeyStroke (KeyEvent.VK_X, KeyEvent.CTRL_MASK)
);

or it could be:

itemExit.setShortcut(
new MenuShortcut(KeyStroke.getKeyStroke("X").getKeyCode())
);

That's all for now. That worked for me.
If you have any other similar problem please leave it as comment to help others too.
Thank you for visiting.

10/18/08

Strings and Pointers in C - Part 2

This post is the second part of the Strings and Pointers in C so you may consider reading the Strings and Pointers in C - Part 1 first.

#include <stdio.h>
#define N 10
#define M N+N-1

int main(int argc, char* argv[]) {
char s1[N],s2[N],s[M];
char *a=s1;
char *b=s2;
char *c=s;

/*input and output s1 & s2 */
printf("Give First String : ");
scanf("%s",a);
printf("String1 is %s \n",a);

printf("Give Second String: ");
scanf("%s",b);
printf("String2 is %s\n",b);
printf(" -----------------\n");

/* copy s1 and s2 to s */
for(; *a!='\0' ; c++,a++) {
*c=*a;
}
for(; *b!='\0' ; c++,b++) {
*c=*b;
}
*c='\0';
printf("Two strings together:\n");
for(c=s;((c<s+M) && (*c!='\0'));c++) {putchar(*c);}

/* s = s2reversed + s1 reversed */
for(b=s2; *b!='\0' ; b++) {} /* b = end of s2 */
for(a=s1; *a!='\0' ; a++) {} /* a = end of s1 */
for (c=s,b--; b!=s2-1 ; c++,b--) {
*c=*b;
}
for (a--; a!=s1-1 ; a--,c++) {
*c=*a;
}
*c='\0';
printf ("\nTwo strings reversed:\n");
for(c=s;((c<s+M) && (*c!='\0'));c++) {putchar(*c);}
printf("\n -----------------\n");

/*
replace same chars with * and replace
multiple * with one *
*/
a=s1;
b=s2;
c=s;
if (*a==*b){ *c='*';
}
else {
*c=*a;
}
a++;
b++;
c++;
for (; c<s+N-1; c++,a++,b++) {
if(*a=='\0') {*c='\0';}
else {
if (*a==*b) {
if (*(c-1)=='*') {c--;}
else {*c='*';}
}
else {
*c=*a;
}
}
}
*c='\0';
printf("\nSame char = *:\n");
for(c=s;((c<s+N) && (*c!='\0'));c++) {putchar(*c);}
printf("\n -----*END*-----\n");
}


And finally the third implementation.

#include <stdio.h>
#define N 10
#define M N+N-1

int main(int argc, char* argv[]) {
char *s1=(char*)malloc(sizeof(char)*N);
char *s2=(char*)malloc(sizeof(char)*N);
char *s=(char*)malloc(sizeof(char)*M);
char *temp,*temp1,*temp2;

/*input and output s1 & s2 */
printf("Give First String : ");
scanf("%s",s1);
printf("String1 is %s \n",s1);

printf("Give Second String: ");
scanf("%s",s2);
printf("String2 is %s\n",s2);
printf(" -----------------\n");

/* copy s1 and s2 to s */
for(temp=s,temp1=s1; *temp1!='\0' ; temp++,temp1++) {
*temp=*temp1;
}
for(temp=s,temp2=s2; *temp2!='\0' ; temp++,temp2++) {
*temp=*temp2;
}
*temp='\0';
printf("Two strings together:\n");
for(temp=s;((temp<s+M) && (*temp!='\0'));temp++) {
putchar(*temp);
}

/* s = s2reversed + s1 reversed */
for(temp1=s2; *temp1!='\0' ; temp1++) {} /* temp1 = end of s2 */
for(temp2=s1; *temp2!='\0' ; temp2++) {} /* temp2 = end of s1 */
for (temp=s,temp1--; temp1!=s2-1 ; temp++,temp1--) {
*temp=*temp1;
}
for (temp2--; temp2!=s1-1 ; temp2--,temp++) {
*temp=*temp2;
}
*temp='\0';
printf ("\nTwo strings reversed:\n");
for(temp=s;((temp<s+M) && (*temp!='\0'));temp++) {
putchar(*temp);
}
printf("\n -----------------\n");

/*
replace same chars with * and replace
multiple * with one *
*/
temp1=s1;
temp2=s2;
temp=s;
if (*temp1==*temp2){ *temp='*';
}
else {
*temp=*temp1;
}
temp1++;
temp2++;
temp++;
for (; temp<s+N-1; temp++,temp1++,temp2++) {
if(*temp1=='\0') {*temp='\0';}
else {
if (*temp1==*temp2) {
if (*(temp-1)=='*') {temp--;}
else {*temp='*';}
}
else {
*temp=*temp1;
}
}
}
*temp='\0'; //end of s
printf("\nSame char = *:\n");
for(temp=s;((temp<s+N) && (*temp!='\0'));temp++) {
putchar(*temp);
}
printf("\n -----*END*-----\n");
}

Now you can compare the source codes above and make your results.
The output of course is the same for the three programs above.
Here is an output example (playing_with_strings is the executable file after compilation):

>playing_with_strings
Give First String : computer-blog
String1 is computer-blog
Give Second String: -another_blog
String2 is -another_blog
-----------------
Two strings together:
-another_blog
Two strings reversed:
golb_rehtona-golb-r
-----------------
Same char = *:
comput*-*
-----*END*-----
>

I hope you enjoyed this long post and got something from it. Thank you for visiting. I am waiting for your comments/suggestions.

Strings and Pointers in C - Part 1

This is another simple program written in C programming language.
The purpose of this program is more educational than useful to anyone.
So, here is the explanation of what it does.
It reads two strings from the user into two tables of chars of size N where N is defined as 10 in this examples.
When the program read both strings it prints the two strings in one then reverse them.
Then prints another string a little more complicated. The last string contains the characters of the first one but when characters at position i of the two strings are the same it places a * as the i-th element. Then replaces continues * with one * and prints the string.
Well, I made three implementations of this "problem".
The first one uses char tables.
The second one uses tables too but instead of getting access directly to table's elements it uses pointers.
The third one uses only pointers.
That's why I said is for educational purposes. The interested reader can find the differences between them and understand better hoe to use pointers.

here is the first implementation.(with tables only)

#include <stdio.h>
#define N 10

int main(int argc, char* argv[]) {
char a,s1[N],s2[N],s[N+N-1];
/* s=s1+s2, s=s2reversed+s1reversed, s=* */
int i,j,k; /* i for s1,j for s2, k for s */

/*input and output s1 & s2 */
printf("Give First String : ");
scanf("%s",s1);
printf("String1 is %s \n",s1);

printf("Give Second String: ");
scanf("%s",s2);
printf("String2 is %s\n",s2);
printf(" ---------------\n");

/* copy s1 and s2 to s */
for(i=0; s1[i]!='\0' ; i++) {
s[i]=s1[i];
}
for(j=0; s2[j]!='\0' ; i++,j++) {
s[i]=s2[j];
}
s[i]='\0';
printf("Two strings together:\n%s\n",s);

/* s = s2reversed + s1 reversed */
/* may use strlen() instead */
for(j=0; s2[j]!='\0' ; j++) {} /* j = end of s2 */
for(i=0; s1[i]!='\0' ; i++) {} /* i = end of s1 */
for (k=0,j--; j>=0 ; k++,j--) {
s[k]=s2[j];
}
for (i--; i>=0 ; i--,k++) {
s[k]=s1[i];
}
s[k]='\0';
printf ("Two strings reversed:\n%s \n");
printf("\n ---------------\n",s);

/*
replace same chars with * and replace
multiple * with one *
*/
i=0;
j=0;
if (s1[i]==s2[i]){ s[i]='*' ; }
else {
s[i]=s1[i];
}
i++;j++ ;
for (;i<N;i++,j++) {
if(s1[i]=='\0') { break;}
else {
if (s1[i]==s2[i]) {
if (s[j-1]=='*') {j--;}
else {s[j]='*';}
}
else {
s[j]=s1[i];
}
}
}
s[j]='\0'; //end of s
printf("Same char = *:\n%s",s);
printf("\n -----*END*-----\n");
}


As I decided to split this post so the reader can open in different windows and compare the implementations,
you can continue with the Strings and Pointers in C - Part 2 including second and third implementations is here.
Thank you for visiting, reading and commenting.

10/3/08

Java RMI and exceptions

Hello everyone. I know I had a lot of time to post in my blog but I was too busy. Sorry about that.

Now in this post I want to post some exceptions I had during trying to test an RMI application I was programming. I will post it as soon as I finish.

Firstly I wrote a policy file:

grant {
permission java.security.AllPermission;
};

and saved it in the same directory as policy.all
REMEMBER: I just wanted to test my application. This policy file should only be used for testing and not deployed.
I have all java files for this application in the folder C:\myRMIApp
I opened a console window and typed

cd C:\myRMIApp
javac *.java

After that I had all the classes files.
To run myapp I typed

java -Djava.security.policy=policy.all myRMIApp

where myRMIApp is the name of the class with main().
I got the following exception:

java.rmi.ConnectException: Connection refused to host: 127.0.0.1;
nested exception is:
java.net.ConnectException: Connection refused: connect

So I remembered that I had to run rmiregistry (I don't comment this :-P)
And this is what I did. I opened another console and executed rmiregistry. (I could use rmiregistry & in the same console)
Anw rmiregistry was running and I tried again to run my application so I typed the same command as above but I got another exception:

java.rmi.ServerException: RemoteException
java.rmi.UnmarshalException: error unmarshalling argument
nested exception is: java.lang.ClassNotFoundException:
myRMIAppServerInterface

I was looking my code for mistakes but I couldn't find anything wrong.
After a while I thought to try again with a little difference.
I executed rmiregistry form the C:\myRMIApp

For my big surprise this solved the above exception and I was able to test my application.
I looked the web but nobody else said that he solved this exception by running rmiregistry in the same directory so I decided to post it and probably help some people ou there having the same problem.
Thank you for visiting and reading. I'm waiting for your comments.

6/17/08

C Program to execute shell script

As I promised in my previous post Suse Linux View CPU speed and Hard disk/CPU temperature I am back to publish my little C program which executes the script. Actually I extended it a little so it can execute any script witch is given as argument and it is located in the same directory with the executable (after compiling the code below).

Well,
The first think needed was how to execute a script.
I first though was fork() and execv().
But after a while I remember that I could use the command system() with argument the script path.

The second think I needed to know was the directory path of execution.
This isn't that difficult, you can have the directory path with the command getenv("PWD");

Here is the first version of my little program witch executes only the script in Suse Linux View CPU speed and Hard disk/CPU temperature post.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXPATH 127
int main(int argc,char* argv[]){
char *path = malloc(MAXPATH);
path = getenv("PWD");
if(path!=NULL) {
strcpy(path+(strlen(path)),"/temperature");
}
else {
printf("Couldn't find script\n");
exit(1);
}
printf("Executing script : %s\n",path);
if(system(path)){
perror("error\n");
}
}

After compiling the above and executing you get the output:

Executing script : /blabla/blabla/temperature
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 53

Cool isn't it?
But it wasn't really useful to exec the program every time to see the results...
So I modified it again to take as argument two integers.
The one was how many times to exec script and the other how many seconds to sleep between executions.
After that I told my self, why don't you make it to keep a log file for you?
So I did. I added ability to print time (to see how see the code below), and to run in a infinite loop if repeat times = -1.
I didn't make a file cos I am a little lazy, I just used the operator > to redirect output to a file!!!
And after that I though it would be useful to others if it was able to exec any script, so I modified it again to take the script name as argument.

Finally here is the final version (for me at least):

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

#define MAXPATH 127
#define DEFAULTVALUE 5
int main(int argc,char* argv[]){
if (argc!=4 && argc!=2) {
printf("Usage : \n %s \"script file\" \"sleeptime in sec\"
\"repeat times\"\n",argv[0]);
exit(0);
}
char *path = malloc(MAXPATH);//MAXPATH chars
path = getenv("PWD");
if(path!=NULL) {
strcpy(path+(strlen(path)),"/"); //add / to the end
strcpy(path+(strlen(path)),argv[1]); //add the script file to the end
}
else {
printf("Couldn't find path\n");
exit(1);
}
int repeat,sleep_sec,i;
if(argc==4) {
sleep_sec = atoi(argv[2]);
if(sleep_sec<0) sleep_sec = DEFAULTVALUE;
repeat = atoi(argv[3]);
if(repeat<0 && repeat!=-1) repeat = DEFAULTVALUE;
}
else {
repeat = DEFAULTVALUE;
sleep_sec = DEFAULTVALUE;
}
i=0;
time_t t;
if(repeat!= -1) {
printf("Executing script : %s %d times every %d seconds\n",
path,repeat,sleep_sec);
}
else {
printf("Executing script : %s every %d seconds\n",path,sleep_sec);
}
while( repeat == -1 || i<repeat) {
sleep(sleep_sec);
time(&t);
printf("\t%s", asctime(localtime(&t))); //print current time
fflush(stdout); //force write date and time
if(system(path)){ //execute script
perror("error\n");
}
i++;
}
printf("\n");
return 0;
}

And the output looks like that:

:/blabla/blabla # ./temperature2
Usage :
./t2 "script file" "sleeptime in sec" "repeat times"
:/blabla/blabla # ./temperature2 temperature 2 3
Executing script : /blabla/blabla/temperature 3 times every 2 seconds
Tue Jun 17 15:38:39 2008
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 50
Hard disk Temperature = 52
Tue Jun 17 15:38:41 2008
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52
Tue Jun 17 15:38:43 2008
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52

:/blabla/blabla #

Now you can use it like that to keep a log file:

:/blabla/blabla # ./temperature2 temperature 30 -1 > temp_log_file.txt &
16716 <--- this is the pid of the new proccess.
:/blabla/blabla #

Now it is running in the background and you will notice the file temp_log_file.txt in the directory.

To stop the process use:

kill 16716

replace 16716 with the correct pid. If you don't remember it use ps to find it.
You may don't want to kill it as it only uses about 1kb of memory...
After all OS will send the kill signal at shutdown!

I forgot to show you my log file. Here it is.

Executing script : /blabla/blabla/temperature every 30 seconds
Tue Jun 17 15:55:04 2008
current CPU frequency is 2.00 GHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52
Tue Jun 17 15:55:34 2008
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52
Tue Jun 17 15:56:04 2008
current CPU frequency is 798 MHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52
Tue Jun 17 15:56:35 2008
current CPU frequency is 2.00 GHz (asserted by call to hardware).
CPU Temperature = 51
Hard disk Temperature = 52

I hope you like. Thank you for visiting and reading my posts.
Comments appreciated.

5/30/08

C Example to Reverse a file

This an example how to reverse a file. It is based on recursion.
The idea is to read all the file and when you reach the end(EOF) print them.


#include <stdio.h>
#include <stdlib.h>

void reverse(FILE * file) {
int fscanf_return_value;
char x;
/* read a char */
fscanf_return_value = fscanf(file,"%c",&x) ;
if(fscanf_return_value == EOF) { //fscanf returns EOF as the END OF FILE
return;
}
reverse(file); //Get the next char
//do something with the char e.g. print
putchar(x);
return;
}

int main(int argc, char *argv[]) {
int i;
FILE *fd;
if (argc!=2) {
printf("Usage : \n %s FILENAME\n",argv[0]);
exit(0);
}
if(!(fd=fopen(argv[1],"r"))) {
printf("Opening file error\n");
exit(1);
}
reverse(fd);
printf("\n\n\t---\tenoD - Done\t---\n");
close(fd);
exit(0);
}

To run it just give it argument the name of the file you want.
For example if the code above is in a file named reverse.c
and compiled with the command

gcc reverse.c -o reverse

just type in the konsole

./reverse reverse.c

and you will get the output bellow.
If you want to save it to another file the easiest way to do it
is to execute

./reverse reverse.c >> output.txt

Example of output is:

}
;)0(tixe
;)df(esolc
;)"n\---t\enoD - Donet\---t\n\n\"(ftnirp
;)df(esrever
}
;)1(tixe
;)"n\rorre elif gninepO"(ftnirp
{ )))"r",]1[vgra(nepof=df(!(fi
}
;)0(tixe
;)]0[vgra,"n\EMANELIF s% n\ : egasU"(ftnirp
{ )2=!cgra( fi
;df* ELIF
;i tni
{ )][vgra* rahc ,cgra tni(niam tni

}
;nruter
;)x(rahctup
tnirp .g.e rahc eht htiw gnihtemos od//
rahc txen eht teG// ;)elif(esrever
}
;nruter
ELIF FO DNE eht sa FOE snruter fnacsf// { )FOE == eulav_nruter_fnacsf(fi
; )x&,"c%",elif(fnacsf = eulav_nruter_fnacsf
/* rahc a daer */
;x rahc
;eulav_nruter_fnacsf tni
{ )elif * ELIF(esrever diov

>h.bildts< edulcni#
>h.oidts< edulcni#

--- enoD - Done ---

I think it is a simple to understand example.
Another way to do it is to use fseek(FILE,SEEK_END) to move the pointer in the file at the end and then start reading a char,do something with it,use fseek(FILE,-1,SEEK_CUR) to move the pos one char back and do this untill you reach the SEEK_SET.
i hope this was helpful. Please post any comments you have.

5/7/08

Simple Java Menu

This is another simple Java example on how to implement a console menu interface with the user.
The steps are really simple.
In a loop:
a) A String which contains the menu options is printed.
b) A number from keyboard is read.
c) Using switch - case statement the correct method is called.
The following Java code is showing the above steps.

import java.util.Scanner;

public class SimpleMenu {
public void start(){
Scanner keyboard = new Scanner(System.in);
int choice;
String menu = "Options\n";
menu+="1. Choice1\n";
menu+="2. Choice2\n";
menu+="3. Choice3\n";
menu+="4. Exit\n";
menu+="Select an option : ";
while(true) {
System.out.print(menu);
choice = keyboard.nextInt();
switch (choice) {
case 1: choice1(); break;
case 2: choice2(); break;
case 3: choice3(); break;
case 4: System.exit(0); break;
default:
System.out.println("Invalid choice.");
break;
}
}
}

private void choice1(){
System.out.println("Menu example choice 1");
}
private void choice2(){
System.out.println("Menu example choice 2");
}
private void choice3(){
System.out.println("Menu example choice 3");
}

public static void main(String[] args) {
new SimpleMenu().start();
}
}

4/8/08

Excecution time in Java

I am going to write my answer to the question " HOW DO I CALCULATE ELAPSED TIME IN JAVA ?"
As far as I now there are two simple ways to calculate the elapsed time - excecution time in JAVA programming language.
Java gives two methods ,nanoTime() and currentTimeMillis() both declared in class java.lang.System .
currentTimeMillis() returns the current time in milliseconds (long) and (as expected) nanoTime() returns the current value of the most precise available system timer in nanoseconds (long).
Below you can see an example of how to calculate the excecution time of a method. The example bellow calculate excecution time of a simple method which it's just a for loop which print numbers from 0 to 1000 but it can be any method you want.

First I used System.currentTimeMillis() to calculate the elapsed time and then System.nanoTime().

import java.lang.String;

public class time_example {

public static void print_num(){
for(int i = 0 ; i<=1000 ; i++) {
System.out.print(i+" ");
}
System.out.println();
}

public static void main(String args[]) {

long start,end;
start = 0; end = 0;

start = System.currentTimeMillis();
print_num();
end = System.currentTimeMillis();
System.out.println("Elapsed time (approximately)
in milliseconds = " +(end-start));

start = System.nanoTime();
print_num();
end = System.nanoTime();
System.out.println("Elapsed time (approximately)
in nanoseconds = " +(end-start));
}
}

And the output is :

0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in milliseconds = 47
0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in nanoseconds = 193986945

You may also want to see Elapsed Time in C.
I hope that this post was helpful and don't forget to post your comments. Thank you.

4/4/08

Fibonacci in C

This code calculates the Fibonacci of a number inputted by user. Calculation is done with recursion and not.
Fibonacci is declared as followed:

fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) n>=2
fibonacci(0) = 0
fibonacci(1) = 1

Here is the source code of Fibonacci in C:

#include <stdio.h>

int fibonacci(int y){
if (y==0) return 0;
if (y==1) return 1;
return( fibonacci(y-1)+fibonacci(y-2) );
}

int fibonacci2(int a) {
if (a==0) return 0;
if (a==1) return 1;

int x,y,z,i;
for (i=1,x=0,y=0,z=1;i<a;i++) {
x=y+z;
y=z;
z=x;
}
return(x);
}
int main() {
int x;
printf("Give an integer ");
scanf("%d",&x);
printf("Fibonacci of %d is %d ",x,fibonacci(x));
printf("\nFibonacci2 of %d is %d ",x,fibonacci2(x));
exit (0);
}

Example of output:

Give an integer: 30
Fibonacci of 30 is 832040
Fibonacci2 of 30 is 832040

MIPS power X^Y example

Calculate the X raised to the power of Y. X and Y are read from user input and also X must be from 1 to 20 and Y must be from 0 to 5. To understand better the following MIPS code you may read Calculate power X^Y in C example.
This is the MIPS code:

.data
str1: .asciiz "Give integer X from 1 to 20 "
str2: .asciiz "Give integer Y from 0 to 5 "
errormsg: .asciiz "Out of range.\n"
nline: .asciiz "\n"
result1: .asciiz " raised to "
result2: .asciiz " gives: "
.text

error:
li $v0,4 #print string1
la $a0,errormsg
syscall
beq $s2,$zero,getX
j getY

.globl main
main:
addi $s0,$zero,21 #s0=21
addi $s1,$zero,6 #s1=6

getX:
addi $s2,$zero,0 #s2=0 to input x and 1 to input y
li $v0,4
la $a0,str1
syscall #print string1
li $v0,5
syscall #read int
slt $s3,$v0,$s0 #$s3=($v0<$s0) if(x<21) $s1=1
beq $s3,$zero,error #if $s3=0 goto error
blez $v0,error #if ($v0<=0) goto error
move $t0,$v0

getY:
addi $s2,$zero,1
li $v0,4
la $a0,str2
syscall #print string2
li $v0,5
syscall #read int
slt $s3,$v0,$s1 #$s3=($v0<$s1) if(x<6) $s3=1
beq $s3,$zero,error #if $s3=0 goto error
bltz $v0,error #if ($v0<0) goto error
move $t1,$v0

beq $t1,$zero,else #if (t1=0) t2=1, t1=y,t2=result
addi $t2,$zero,1
addi $s4,$zero,0

loop: #if s4<t1
slt $s5,$s4,$t1 #$s5=($s4<$t1) if(x<21) $s5=1
beq $s5,$zero,printresult
#if $s1=0 goto printresult(s4=t1)
mul $t2,$t2,$t0 #t2=t2*t0
addi $s4,$s4,1
j loop

else:
addi $t2,$zero,1
j printresult

printresult:
li $v0,1
move $a0,$t0
syscall #print X
li $v0,4
la $a0,result1
syscall #print " raised to "
li $v0,1
move $a0,$t1
syscall #print Y
li $v0,4
la $a0,result2
syscall #print " gives "
li $v0,1
move $a0,$t2
syscall #print result(t2)
li $v0,10
syscall #exit

You may would like to see MIPS Bubble sort or simple MIPS counter.

Calculate power X^Y in C

A simple program in C programming language which asks from user to input two numbers (X,Y) and then calculates the result of X raised to the power of Y. Calculation is done with recursion and not and prints both results which of course must be the same! Maybe you want to see the code of MIPS power X^Y example.
Here is the code for the C power example:

#include <stdio.h>

/*
power recursive
return x^y
*/
int power(int x,int y){
if (y==0) return 1;
if (y==1) return x;
return( x*power(x,y-1) );
}
/*
power not recursive
return x^y
*/
int power2(int x,int y) {
if (y==0) return 1;
if (y==1) return x;

int result,i;
for (i=0,result=1;i<y;i++) {
result = result * x;
}
return(result);
}
int main() {
int x,y;
do{
printf("Give integer X from 1 to 20 : ");
scanf("%d",&x);
}
while( x>20 || x<1 );
do{
printf("Give integer Y from 0 to 5 : ");
scanf("%d",&y);
}
while( x>20 || x<1 );

printf("%d raised to %d gives %d \n",x,y,power(x,y));
printf("%d raised to %d gives %d ",x,y,power2(x,y));
exit (0);
}

The output is like that:

Please give integer X from 1 to 20: 2
Please give integer Y from 0 to 5: 5
X raised to Y gives: 32

You may want to see Simple MIPS counter or MIPS bubble sort.

Simple Counter in C

This is a very simple program in C. User is asked for a number. If user gives a number from 1 to 20 then the program prints all the numbers from 1 to the number the user inputed.
If user give a number out of range program asks again for a valid number.
This program is here so reader can understand better how this little program is written in MIPS code. The same in MIPS code is here.

#include <stdio.h>

int main() {
int x,i;
do{
printf("Please give an integer from 1 to 20 : ");
scanf("%d",&x);
}
while( x>20 || x<1 );
for (i=1;i<=x;i++) {
printf("%d\n",i);
}
exit(0);
}

Simple MIPS counter

This a simple MIPS program. User is asked for a number. If user gives a number from 1 to 20 then the program prints all the numbers from 1 to the number the user inputed.
If user gave a number out of range program asks again for a valid number.
The same program in C is here.

.data
str1: .asciiz " Please give an integer from 1 to 20 : "
errormsg: .asciiz " Out of range (1-20). \n"
nline: .asciiz "\n" #new line
.text
error:
li $v0,4
la $a0,errormsg
syscall #print error msg
j get
.globl main # label "main" must be global
main:
addi $s0,$zero,21 #s0=21
get:
li $v0,4
la $a0,str1
syscall #print string1
li $v0,5
syscall #read int
slt $s1,$v0,$s0 #$s1=($v0<$s0) if(x<21) $s1=1
beq $s1,$zero,error #if $s1=0 goto error
blez $v0,error #if ($v0<=0) goto error
move $t0,$v0
add $t1,$0,$0
loop:
addi $t1,$t1,1 #$t1++
li $v0,1
move $a0,$t1
syscall #print int
li $v0,4
la $a0,nline
syscall #print nline
slt $t2,$t1,$t0 #$t2=($t1<$t0)
bnez $t2,loop #if $t2!=0 goto loop
li $v0,10 #exit program
syscall

Example of output is:

Please give an integer from 1 to 20: 35 Out of range (1-20).
Please give an integer from 1 to 20: -5 Out of range (1-20).
Please give an integer from 1 to 20: 5
1
2
3
4
5

I hope that this post was helpful for you. Maybe you would like to see MIPS Bubble sort.

3/22/08

Elapsed time in C

Here you will see some ways to calculate elapsed time or execution time or real time of a program, procedure,function,whatever.... This is an example of calculating elapsed time with three different ways in C programming language.
First way is to use the gettimeofday() function. This function works in Linux but not in Windows by default. That's the reason I commented the code which calculate elapsed time with gettimeofday().
Second way is to use the GetTickCount() function from win32 API (windows.h).
Third way is to use the clock() function from time.h.
In the following example the three method are almost the same. Get the time before, get the time after and calculate. I used a function called printmsg which prints a message for PRINT_TIMES times.
This is the code.

#include <stdio.h> //printf()
#include <time.h> //clock()
#include <windows.h> //GetTickCount();

#define PRINT_TIMES 1000

void printmsg(){
int i=0;
for(;i<PRINT_TIMES;i++)
printf("Elapsed time example ");
}

int main(int argc, char *argv[]) {
//struct timeval td_start,td_end;
//float elapsed = 0;
unsigned long tick_start,tick_end;
clock_t clock_start,clock_end;
/*
gettimeofday() doesn't work in windows
but it works very well in Linux
/*
printf("Elapsed time example - gettimeofday()\n");
if(gettimeofday(&td_start,NULL)) {
printf("time failed\n");
exit(1);
}
printmsg();
if(gettimeofday(&td_end,NULL)) {
printf("time failed\n");
exit(1);
}
elapsed = 1000000.0 * (td_end.tv_sec -td_start.tv_sec);
elapsed += (td_end.tv_usec - td_start.tv_usec);
printf("Time elapsed - gettimeofday() is %g
microseconds\n",elapsed);
printf("---------------------------------
------------------\n");
sleep(2);/**/
printf("\n--------------------------------
-------------------\n");
printf("Elapsed time example - GetTickCount()\n\n");
tick_start = GetTickCount();
printmsg();
tick_end = GetTickCount();
printf("\n\n------------------------------
---------------------");
printf("\nTime elapsed with GetTickCount() is
%ld milliseconds\n", tick_end - tick_start);
printf("----------------------------------
-----------------\n\n");
sleep(2);
printf("Elapsed time example - clock()\n\n");
clock_start = clock();
printmsg();
clock_end = clock();
printf("\n\n------------------------------
---------------------\n");
printf("\nTime elapsed with GetTickCount() is
%ld cycles\n",clock_end-clock_start);
exit(0);
}

At this point I would like to remind you that you can use > for output to a file.
For example if you compiled
      gcc elapsedexample.c -o elapsedexample
you can run it like this
      elaspsedexample > result.txt
Now you have the result.txt file and you can open it with any editor you like.
I hope that this example was helpful. If you think there is something wrong please post it. Thank you for posting.

3/20/08

Semaphore Example in C

This is a Semaphore example in C. I extended the C Thread example to use semaphores. Every thread created will first try to acquire the semaphore lock and then start printing numbers. After printing is done lock is left so other threads can continue their job. Semaphores is a powerful tool for programmers.
Here is the semaphore example source code in C.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_THREAD 100

typedef struct {
int start,end;
} param;
sem_t mysem;
void *count(void *arg){
sem_wait(&mysem);
int i =0;
param *p=(param *)arg;
printf("\nprintfrom %d to %d\n",p->start,p->end);
for(i =p->start ; i< p->end ; i++){
printf(" i = %d",i);sleep(1);
}

sem_post(&mysem);
return (void*)(1);
}

int main(int argc, char* argv[]) {

if ( sem_init(&mysem,0,1) ) {
perror("init");
}
int n,i;
pthread_t *threads;
param *p;

if (argc != 2) {
printf ("Usage: %s n\n",argv[0]);
printf ("\twhere n is no. of threads\n");
exit(1);
}

n=atoi(argv[1]);

if ((n < 1) || (n > MAX_THREAD)) {
printf ("arg[1] should be 1 - %d.\n",MAX_THREAD);
exit(1);
}

threads=(pthread_t *)malloc(n*sizeof(*threads));

p=(param *)malloc(sizeof(param)*n);
/* Assign args to a struct and start thread */
for (i=0; i<n; i++) {
p[i].start=i*100;
p[i].end=(i+1)*100;
pthread_create(&threads[i],NULL,count,(void *)(p+i));
}
printf("\nWait threads\n");
sleep(1);
/* Wait for all threads. */
int *x = malloc(sizeof(int));
for (i=0; i<n; i++) {
pthread_join(threads[i],(void*)x);
}
free(p);
exit(0);
}

C Thread Example

This is a simple C Thread example. Don't forget, to compile use:

gcc -lpthread filename.c -o exename

This THREAD EXAMPLE in C is reads arg[1] as an integer (n) and starts n threads which print 100 numbers each. More specific if n is 5 then 5 threads will start and thread 1 will print from 0 - 99. thread 2 from 100 - 199.... thread i will print from i*100 - (i+1)*100.
As you see code is very simple. If you want to start threads in JAVA then read JAVA Thread example post.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_THREAD 100

typedef struct {
int start,end;
} param;

void *count(void *arg) {
int i =0;
param *p=(param *)arg;
for(i =p->start ; i< p->end ; i++){
printf(" i = %d",i);
}
return (void*)(1);
}

int main(int argc, char* argv[]) {
int n,i;
pthread_t *threads;
param *p;

if (argc != 2) {
printf ("Usage: %s n\n",argv[0]);
printf ("\twhere n is no. of threads\n");
exit(1);
}

n=atoi(argv[1]);

if ((n < 1) || (n > MAX_THREAD)) {
printf ("arg[1] should be 1 - %d.\n",MAX_THREAD);
exit(1);
}

threads=(pthread_t *)malloc(n*sizeof(*threads));

p=(param *)malloc(sizeof(param)*n);
/* Assign args to a struct and start thread */
for (i=0; i<n; i++) {
p[i].start=i*100;
p[i].end=(i+1)*100;
pthread_create(&threads[i],NULL,count,(void *)(p+i));
}
printf("\nWait threads\n");
sleep(1);
/* Wait for all threads. */
int *x = malloc(sizeof(int));
for (i=0; i<n; i++) {
pthread_join(threads[i],(void*)x);
}
free(p);
exit(0);
}