Saturday, March 13, 2010

My solution for Queue

Here is my solution for Queue which we are asked to be finished by Fardad in this week class.

//queue.h
class Queue;
class Node{
int data;
Node* next;
Node(int data , Node* next = (Node*)0);
friend class Queue;
};

class Queue{
Node* head;
Node* tail;
public:
Queue(); // empty list
void add(int data); // adds to tail of the list
int remove(); // removes from head
bool IsEmpty();// true if empty
~Queue();
};

//queue.cpp
#include "queue.h"
Node::Node(int data , Node* next){
this->data = data;
this->next = next;
}
Queue::Queue(){
head = (Node*)0;
tail = (Node*)0;
}
void Queue::add(int data){
if (head==tail && !head){
Node* temp = new Node(data, tail);
head = temp;
tail = temp;
}
else{
Node* temp = new Node(data, tail->next);
tail->next = temp;
tail = temp;
}
}
int Queue::remove(){
int data = head->data;
Node* ToDel = head;
head = head->next;
delete ToDel;
return data;
}
bool Queue::IsEmpty(){
return !head;
}
Queue::~Queue(){
while(!IsEmpty()){
remove();
}
}
//queuemain.cpp
#include
using namespace std;
#include "queue.h"

int main(){
Queue Q;
int i;
for(i=10;i<=50;i+=10){
cout<<"Add into a queue "< Q.add(i);
}
while(!Q.IsEmpty()){
cout< }
return 0;
}
output as:

Some concepts in C and C++

Those questions are found when I prepared for my job interview question.They might be simple questions but I've never think of them.Hope that I can understand better, and also for anyone are learning C and C++.

Why the constructor can't be virtual?
A: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. The reason is a constructor can not be virtual because at the time when the constructor is invoked the virtual table (vtable) would not be available in the memory.
Virtual allows us to call a function knowing only the interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the what you want to create exactly. Hence call to a constructor can't be virtual.

Difference between delete and destructor in c++?
Delete can deallocate the memory of those objects which are created by using the new operator whereas the destructor can delete any object once the life of the object ends.(this is normally when a program ends)

Differences between Structure and Class.
1.Structure cannot be inherited.
2.Structure is a value data type whereas Class is a reference type.
3.All declarations inside a structure are by default public whereas by default all the members inside the class are private.
4.Structure instances cannot be used as operand to arithmetic operators like +-*/ . But object (instances of classes) can be (using operator overloading).
5.A structure can't declare protected members,a class can.
6.We can't inherit a structue from another structure, which we can do in class.

Difference between "overloading" and "overriding"?
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

There are many valuable comments on it.

Thursday, February 18, 2010

Challenges solution : MyPrint()

Here is my solution for MyPrint().

#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
void print_int_hex(int val,int alg)
{
int i;
if (val==0)
{
_putch('0');
}
else
{
if (val/alg)
{
i = val % alg;
print_int_hex(val/alg,alg);
}
else
i = val % alg;
if (i>9)
{
i=i-10+'a';
_putch(i);
}
else
_putch(i?i+48:48);
}
}

void print_float(double val)
{
int temp = val *100;

if (val==0)
{
_putch('0');
}
else
{
print_int_hex(temp/100,10);
_putch('.');
print_int_hex(temp%100,10);
}
}

void MyPrint(char* pString,...)
{
int i=0;
int ch;
const char* str;
double f;

va_list args;
va_start(args, pString);
while (pString[i])
{
if (pString[i]=='%')
{
i++;
switch(pString[i])
{
case 'c':
ch = va_arg(args, int);
_putch(ch);
break;
case 's':
str = va_arg(args, const char*);
_cputs(str);
break;
case 'd':
ch = va_arg(args,int);
if (ch<0)
{
_putch('-');
ch=ch*(-1);
}
print_int_hex(ch,10);
break;
case 'x':
case 'X':
ch = va_arg(args, int);
print_int_hex(ch,16);
break;
case 'f':
f = va_arg(args, double);
print_float(f);
break;
}
i++;
}
_putch(pString[i]);
i++;
}
va_end(args);
}

int main()
{
MyPrint("int %d, char %c, string %s, hex %x, float %f", -102, 'A', "hello", 31, 12.34567);
return 0;
}

Result as:
int -102, char A, string hello, hex 1f, float 12.34
For float, I thought might be have better solution.

Wednesday, February 3, 2010

Optimizing bio_display()

Here is the source code:
void bio_display(const char *str, int row, int col, int len){
bio_move(row, col);
if(len <= 0){
bio_putstr(str);
}
else{
int i;
for(i=0; i< len && str[i];i++){
bio_putch(str[i]);
}
for(;i< len;i++){
bio_putch(' ');
}
}
}
To optimize it, I got this solution :
void bio_display(const char *str, int row, int col, int len) {
bio_move(row, col);
if( len <= 0)
bio_putstr(str);
else {
for(;len>0; len--) bio_putch(*str ? *str++ : ' ' );
}
}
From the same logic, it also can be shortened as:
void bio_display(const char *str, int row, int col, int len) {
for((bio_move(row, col), (len <= 0)?bio_putstr(str):0); len>0; len--)
bio_putch(*str ? *str++ : ' ' );
}
I tried to use bio_putstr() instead of bio_putch() which Farad mentioned in the class, but considered the length of the string I insisted to use bio_putch().

Thursday, January 28, 2010

week 3 challenge - bio_putint(int val)

My result as below, has been test.
void sep(int val)
{
    int i;
    if (val/10)
    {
        i = val % 10;
        sep(val/10);
    }
    else
        i = val % 10;
    _putch(i?i+48:48);
}
void bio_putint(int val)
{
    sep(val);
}

Wednesday, January 27, 2010

First IRC meeting

In our first IRC meeting, Fardad introduced some guidelines to us to get familiar with IRC environment and its culture. Through the meeting, we impressed the knowledge we learned from the classes. Meanwhile, we learnt lots new knowledge. There are two interested website as:
http://www.pastebin.ca is a website to copy the text and post it, then copy the url and pass the url share with your friend.
http://tinyurl.com is a website to help you make a long url short to tiny one. When you clicked the short one, it will redirect to the long one.

Starting from IRC is very good for us to get start to familiar with developing environments. For open source programming, by WIKI or IRC is very common for people communicating with their teammates.

But be honest, IRC meetings and chats are very slow. Especially when talking with an 8 people’s group, some people did not pay attention that will cause the meeting last much longer. And Fardad need to talk to all the groups that will take him longer time.
Is there better way to solve this problem?

Monday, January 25, 2010

The declaration and algorithm about Pointers

I.Declare a pointer

int* p;     p is an integer pointer variable
int* p[n];   p is a pointer array by the amount of n-pointer pointing to an integer elements
int* p();   p points to a function which return an integer pointer
int (*p)();   p is a function pointer, points to a function which return an integer value
int** p;    p is an pointer variable points to another pointer, this pointer point to an integer

II. Algorithm
(1)get address:

use "&" get the address of the variable

(2)get value:

use "*" get the target of the pointer

(3)assign operate:

·assign variable address to an pointer
int i;
int* p = &i;
·between the same type pointer variable assignment
int* p = &i;
int * q = p;
·address of the first element in the array assign to pointer
int a[3]={10,20,30};
int* p = a;
·assigned to the function entry address of a pointer variable
typedef int (*funcptr)();
funcptr p;
extern int foo();
p = &foo;

(4)Addition and Subtract

·array pointer
int a[5]={10,20,30,40,50};
int* p = a;
p+=3; p-=3; p++; P--;
·subtract a pointer from a pointer of the same type,
get the difference in the subscripts of the two elements. So, the resulting type isn't a pointer but is a signed integer type.

(5)Comparison

·The two pointers point to the same array of variables can be greater than, less than, equal to the comparison operator.
·Compared with Zero,p==0 means point to NULL。