Sunday, June 15, 2008

C++

Topics to Review
  • Virtual functions
  • extern keyword
  • Declaration vs definition and the use of extern
  • Standard Container class and vectors
  • Variable argument list (...): Better alternative in C++
  • Creating your own libraries
  • Recursion
  • Delete a character from a string. using pointers
  • Macros (P.P 191 volume 1)
  • shift operator
  • shifting operators



//Structures C++
#include <iostream>
#include<conio.h>
typedef unsigned short int usi;
using namespace std;

int main() {

//create struct1
struct struct1{

int i;
float k;
double o;
};

//instantiate struct1
struct1 s1, s2;

//create a pointer to point to s1
struct1* s1p=&s1;

//access the element of s1 via the pointer using the -> operator
s1p->i=44;

cout<<s1p->i<<endl;

//change the address to which s1p points. Now it points to the address of s2
s1p=&s2;
s1p->i=33;//this is equal to s1.i=33;

cout<<s2.i<<endl;





getche();
}

structures C++

//structures in C++
#include <iostream>
#include<conio.h>
typedef unsigned short int usi;
using namespace std;

int main() {

struct struct1{

int i;
float k;
double o;
};


struct1 s1, s2;
s1.i=5;

cout<<s1.i;



getche();
}

structures C++

typedef c++

typedef unsigned short int usi;

typedef

Non static variables c++
//non-static local variables c++
#include <iostream>
#include<conio.h>
using namespace std;

void function1(){

int i=0;//the variable will not preserve its value throught the program run
i++;
cout<<i<<endl;




}




int main() {

for (int k=0;k<10;k++){
function1();

}

getche();
}



static variable c++

in c++, every time you call a function, the function local variables are reinitialized. Once the function is called, the local variables are destroyed. To prevent that and to make the value of the local variable extant throughout the program life, use the static keyword.

//static local variables c++
#include <iostream>
#include<conio.h>
using namespace std;

void function1(){

static int i=0;//the variable will preserve its value throught the program run
i++;
cout<<i<<endl;




}




int main() {

for (int k=0;k<10;k++){
function1();

}

getche();
}


static variables c++

Void Pointer C++

-A void pointer can take the address of any data type
for exmple:

int i=5;
float k=9;
void* ip=&i;
void* kp=&k;

-You cannot dereference a void pointer unless you must cast back before dereferencing
*ip=3;//illegal

*(int*(ip))=3; //that's ok :)

-Void pointers are discouraged unless in very special cases.



void pointers c++

//pass by reference c++
#include <iostream>
#include<conio.h>
using namespace std;

void function1(int& z){//int& z means that function1() receives the address of the passed variable



cout<<"Indide the function before change i= "<<z<<endl;
z=6;//change the value that z reference holds. ie., i
cout<<"Inside Function after change i= "<<z<<endl;
cout<<"The address of i inside the function= "<<(long)&z<<endl;



}




int main() {
int i=5;
cout<<"Before Calling function i= "<<i<<endl;
function1(i); //it look like pass by value but it's not
//look at function1() definition
cout<<"After Calling function i= "<<i<<endl;
cout<<"The address of i in main function= "<<(long)&i<<endl;

getche();
}

pass by reference in c++, pointers

//c++ call by address

//pass by address c++
#include <iostream>
#include<conio.h>
using namespace std;

void function1(int* z){

*z=6;
cout<<"Inside Function i= "<<*z<<endl;



}




int main() {
int i=5;
int* ip=&i;
cout<<"Before Calling function i= "<<i<<endl;
function1(ip);
cout<<"After Calling function i= "<<i<<endl;

getche();
}


pass by address, pointers C++

//Call by Value C++
#include <iostream>
#include<conio.h>
using namespace std;

void function1(int z){

z=6;
cout<<"Inside Function i= "<<z<<endl;



}




int main() {
int i=5;
cout<<"Before Calling function i= "<<i<<endl;
function1(i);
cout<<"After Calling function i= "<<i<<endl;

getche();
}

call by value c++, pointers

//Pointers Basics C++
#include <iostream>
#include<conio.h>
using namespace std;

int main() {
int i=9;
int* ip=&i;

cout<<(long)ip<<endl;
ip++;
cout<<(long)ip<<endl;
ip--;
cout<<*ip<<endl;
*ip=10;
cout<<*ip<<endl;
cout<<(long)ip<<endl;

getche();
} ///:~
pointers C++

//undsigned short int size
#include<conio.h>
#include<iostream>
#include<string>

using namespace std;


int main(void){

int counter=0;

for (unsigned short int i=1;;i++){

counter++;

if (i==0) {

cout<<"Maximum possible number using unsigned shortnint is ";
cout<<counter-1; break;}



}





getche();
return 0;

}


//cast double to int C++
#include<conio.h>
#include<iostream>
#include<string>

using namespace std;


int main(void){

cout<<int(5e4);


getche();
return 0;

}


continue in C++

#include<conio.h>
#include<iostream>
#include<string>

using namespace std;


int main(void){


for (int i=0; i<=10;i++){

if (i==5)continue;
//don't cout 5
cout<<i;

}


getche();
return 0;

}


//Find number of prime integers in N range
//Adel Shehadeh
#include <iostream>
#include<conio.h>

using namespace std;

int main(){
int n=0;
bool prime=true;
int count =0;

while (n<=1){
cout<<"Enter N range [1-N]. N should be an integer > 1:"<<endl;
cin>>n;
}

for (int k=n;k>=2;k--){

prime=true;
for (int i=k;i>=2;i--){


if (k==i)
continue;

if (k%i==0)
{prime=false;}
}

if (prime==true)
count++;



}

cout<<count<<" prime Numbers in range.";

getche();
return 0;

}







//convert dec to ASCII C++

#include<conio.h>
#include<iostream>



using namespace std;

char getChar(int);

int main(){
int num=0;
cout<<"Enter number from 0 to 255"<<endl;
cin>>num;
cout<<"The ASCII char is: " <<getChar(num);

getche();
return 0;

}


char getChar(int i){

return char(i);
}



Copy file to a vector

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>

using namespace std;

int main(){

vector<string> vector1;
ifstream input("input.txt");
string string1;

while (getline (input,string1)){

vector1.push_back(string1);

}

for (int i=0; i<vector1.size();i++){
cout<<i<<":"<<vector1[i]<<endl;


}


getche();

}


Create a vector<float>

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>


using namespace std;

int main(){


vector<float> vector1;
float k=0;



for (int i=0;i<=25;i++){

k+=.1;
vector1.push_back(k);
cout<<vector1[i]<<endl;
}

getche();

return 0;

}





Square a vector in C++


#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>


using namespace std;

int main(){


vector<float> vector1;

float k=0;



for (int i=0;i<=25;i++){

k+=1;

vector1.push_back(k);
vector1[i]=vector1[i]*vector1[i];
}





for (int i=0;i<=25;i++){


cout<<vector1[i]<<endl;

}


getche();

return 0;

}





Count words in a file

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>

//count whitespace seperted words in a file.
using namespace std;

int main(){


ifstream input("input.txt");
string str1;
int count=0;


while(input >> str1)
count++;

cout<<count;

getche();

}


Count the occurrences of a word in a file

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>

//count whitespace seperted words in a file.
using namespace std;

int main(){


ifstream input("input.txt");
string str1;
int count=0;


while(input >> str1)
if (str1=="and")
count++;

cout<<count<<"times the word "and" occured";

getche();

}


Print the lines of a file but backward in C++

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>


using namespace std;

int main(){
//print the lines of a file backward using vectors

vector<string> vector1;
ifstream in("input.txt");
string line;
while(getline(in, line))

vector1.push_back(line);
for(int i = (vector1.size()-1); i > 0 ; i--)
cout << i << ": " << vector1[i] << endl;

getche();

}


//Concatenate all the vector elements into a single string in C++

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>


using namespace std;

int main(){


vector<string> vector1;
ifstream in("input.txt");
string line;
string finalString;
while(getline(in, line))

vector1.push_back(line);
for(int i = 0; i<vector1.size() ; i++)
finalString+=vector1[i];

cout <<finalString;

getche();

}


Copy Files using vectors

#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>

using namespace std;

int main(){

vector<string> vector1;
ifstream input("input.txt");
ofstream output("output.txt");
string string1;

while (getline (input,string1)){

vector1.push_back(string1);

}

for (int i=0; i<vector1.size();i++){
output<<vector1[i]<<endl;

}



getche();

}



copy all the words of a file to another file. Word by word


#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>


//copy each word in a file seperately to a vector element.
//Then copy the whole elements to another file
using namespace std;

int main(){

vector<string> wordsVector;
ifstream input("input.txt");
ofstream output("output.txt");
string str1;


while(input >> str1) //read input from file to str1. Line by line
wordsVector.push_back(str1);


for(int i = 0; i < wordsVector.size(); i++)
output << wordsVector[i] << endl;

getche();

}


C++ Copy entire file to string. Copy file to string

#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>

using namespace std;
int main() {


ifstream in("in.txt");
string string1, string2;


while (getline (in,string1)){
string2+=string1+"n";
}
cout<<string2;
getche();

}


The problem with reading lines
from a file into individual string objects is that you don’t know up
front how many strings you’re going to need – you only know after
you’ve read the entire file.






c++ copy file 1 to file 2

#include <fstream>
#include <string>

using namespace std;
int main() {


ifstream in("in.txt");
ofstream out("out.txt");
string s;
int lineNumbers=0;

while (getline (in,s)){
out<<s<<"n";

lineNumbers++;
}
cout<<lineNumbers<<" Lines copied babe";
getche();

} ///:~

IS-A relationship in inheritance

A test for inheritance is to
determine whether you can state the is-a relationship about the
classes and have it make sense.

Like when you say: a circle is a shape.









access specifiers

C++ uses three explicit keywords to set the boundaries in a class:
public, private, and protected. Their use and meaning are quite
straightforward. These access specifiers determine who can use the
definitions that follow. public means the following definitions are
available to everyone. The private keyword, on the other hand,
means that no one can access those definitions except you, the
creator of the type, inside member functions of that type. private is
a brick wall between you and the client programmer. If someone
tries to access a private member, they’ll get a compile-time error.
protected acts just like private, with the exception that an
inheriting class has access to protected members, but not private
members. Inheritance will be introduced shortly.


Composition in C++
Becauseyou are composing a new class from existing classes, this concept is called composition (or more generally, aggregation). Composition is often referred to as a “has-a” relationship, as in “a car has an engine.”

Basic Input/Output
string mystr; cout << "What's your name? "; getline (cin, mystr);










Basic Input/Output
using the function getline() to get input


// cin with strings #include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!n"; return 0; }




Operators
LevelOperatorDescriptionGrouping
1::scopeLeft-to-right
2() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeidpostfixLeft-to-right
3++ -- ~ ! sizeof new deleteunary (prefix)Right-to-left
* &indirection and reference (pointers)
+ -unary sign operator
4(type)type castingRight-to-left
5.* ->*pointer-to-memberLeft-to-right
6* / %multiplicativeLeft-to-right
7+ -additiveLeft-to-right
8<< >>shiftLeft-to-right
9< > <= >=relationalLeft-to-right
10== !=equalityLeft-to-right
11&bitwise ANDLeft-to-right
12^bitwise XORLeft-to-right
13|bitwise ORLeft-to-right
14&&logical ANDLeft-to-right
15||logical ORLeft-to-right
16?:conditionalRight-to-left
17= *= /= %= += -= >>= <<= &= ^= |=assignmentRight-to-left
18,commaLeft-to-right


Operators
Example 1Example 2
B=3;
A=++B;
// A contains 4, B contains 4
B=3;
A=B++;
// A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.



Operators

Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

For example, the following code:

a = (b=3, b+2);

Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.

Another example

#include <iostream>
#include <conio.h>


using namespace std;

int main (){

int i=0;
int j=0;

j=(i=5,i+1); //the comma operator
cout<<i<<endl;
cout<<j;

getche();

return 0;

}


Operators

Bitwise Operators ( &, |, ^, ~, <<, >> )

Bitwise operators modify variables considering the bit patterns that represent the values they store.

operatorasm equivalentdescription
&ANDBitwise AND
|ORBitwise Inclusive OR
^XORBitwise Exclusive OR
~NOTUnary complement (bit inversion)
<<SHLShift Left
>>SHRShift Right


Constants
Defined constants (#define)
#include <iostream>
#include <conio.h>

using namespace std;

int main (){


#define PI 3.14;

cout<<PI;

getche();

return 0;

}



Constants

Declared constants (const) value cannot be chagned



const int pathwidth = 100;
const char tabulator = 't';

Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.



Constants
a = 5;

the 5 in this piece of code was a literal constant.



Variables. Data Types.


Variables. Data Types.


Variables. Data Types.
unsigned short int NumberOfSisters;
signed int MyAccountBalance;

By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written:

int MyAccountBalance;


Variables. Data Types.

Constructor Initialization


The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):

type identifier (initial_value) ;

For example:

int a (0); 








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

int main (){

int a=0; //intialization
int b(5);//constructor initialization


cout<<a<<endl;
cout<<b;

getche();

return 0;

}



Variables. Data Types.
Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case they can begin with a digit.

Seperate Lines

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

int main (){
cout<<"t"
"est"<<endl;

cout<<
"test";

getche();

return 0;

}
output:
test
test



Structure of a program
A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution.

for consle programs i use the library conio.h to keep the window opened and wait for a character input

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

int main (){
cout<<"test"<<endl;

getche();

return 0;

}


Variables. Data Types.

Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:

NameDescriptionSize*Range*
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
short int (short) Short Integer. 2bytes signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
bool Boolean value. It can take one of two values: true or false. 1byte true or false
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
double Double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
long double Long double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
wchar_t Wide character. 2 or 4 bytes 1 wide character


Saturday, March 1, 2008

Simple UI to Verify database in Java

Disclaimer: This post is related to IBM Rational Functional Tester With Java. It needs some slight modifications to work with other tools.

Sometimes, your automated test script needs to do some strange stuff. Like accessing the database, extracting some value and using this value in subsequent U.I steps in your script.

Suppose that you have hundreds of scripts that needs the following block to access the DB and read a certain value:

try{
Connection db_connection = DriverManager.getConnection("jdbc:odbc:DBNAME",
"username","password");


Statement stm2 = db_connection.createStatement();
stm2.executeQuery("select * from TableName");

}
catch( SQLException x ){

JOptionPane.showMessageDialog(null,
x.getLocalizedMessage().toString(),"Error",
JOptionPane.ERROR_MESSAGE);

}

What if the username and password is changed after a period of time for a certain reason. This means that you need to modify all your scripts and change the credentials. And this could be a pain and very time consuming.

A good practice is creating a class that will prompt the user to enter the credentials and validates them before running the script. This will save time and headache in subsequent releases.

The following is the code for the class with the proprietary information removed:


import javax.swing.JOptionPane;
import resources.SendValidUNandPWHelper;

import com.rational.test.ft.*;
import com.rational.test.ft.object.interfaces.*;
import com.rational.test.ft.object.interfaces.siebel.*;
import com.rational.test.ft.script.*;
import com.rational.test.ft.value.*;
import com.rational.test.ft.vp.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
* Description : Functional Test Script
* @author Ashehadeh
*/
class SendValidUNandPW extends SendValidUNandPWHelper
{
/**
* Script Name : CheckDBDialog
* Generated : Feb 19, 2008 8:31:06 AM
* Description : Functional Test Script
* Original Host : WinNT Version 5.1 Build 2600 (S)
*
* @since 2008/02/19
* @author Ashehadeh
*/
/**
* @param args
*/





public String[] sendValidCredentials(){

String[] result=null;
String[] k =validateInput();

while (k==null){
k= validateInput();
}

return k;


}


//check if the provided credential can access the DB
public static String[] validateInput(){

String[] result=null;
String[] k =isDBonline();

if (k==null){
result =null;
System.exit(0);

}

else {


try{
Connection db_connection = DriverManager.getConnection("jdbc:odbc:DBNAME",k[0],k[1]);

Statement stm2 = db_connection.createStatement();
stm2.executeQuery("select * from TABLEName");
result =k;

}
catch( SQLException x ){

JOptionPane.showMessageDialog(null,
"Please Enter correct Uasername/Password!","Error",
JOptionPane.ERROR_MESSAGE);
/* JOptionPane.showMessageDialog(null,
x.getLocalizedMessage().toString(),"Error",
JOptionPane.ERROR_MESSAGE);*/

result=null;

}

}
return result;
}


//check if the db is online from the first place

public static String[] isDBonline(){


String[] result=null;
String[] k =isOneEmpty();


if (k==null){
result =null;
System.exit(0);


}


//now check for DB connectivity
else {

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

result =k;

}



catch(ClassNotFoundException c){
JOptionPane.showMessageDialog(null,
"DB Unavailable!","Error",
JOptionPane.ERROR_MESSAGE);
result=null;
System.exit(0);

}

}
return result;
}


//is one of the fields empty? if so, exit
public static String[] isOneEmpty(){

String[] k=showDialog();
String[] result;

// if one of the username or passwords are empty, exit.
if (k[0]==null || k[1].equals("") ||
k[1].equals("") || k[1]==null){

JOptionPane.showMessageDialog(null,
"Error. Fill the two fields. Click ok to exit!","Error",
JOptionPane.ERROR_MESSAGE);

result=null;
System.exit(0);

}


//if both of them are not empty continue
else{
result=k;

}

return result;

}

//prompt the user for username and password
public static String[] showDialog() {

String DBUsername=JOptionPane.showInputDialog(null,
"Enter DB username:", "Input", JOptionPane.QUESTION_MESSAGE);
String DBpassword=JOptionPane.showInputDialog(null,
"Enter DB password:", "Input", JOptionPane.QUESTION_MESSAGE);
String[] UPArray={DBUsername,DBpassword};
return UPArray;

}



}


Original post: Click here

Saturday, February 2, 2008

pass by reference java

Truth #1: Everything in Java is passed by value. Objects, however, are never passed at all.

That needs some explanation - after all, if we can't pass objects, how can we do any work? The answer is that we pass references to objects. That sounds like it's getting dangerously close to the myth, until you look at truth #2:

Truth #2: The values of variables are always primitives or references, never objects.

This is probably the single most important point in learning Java properly. It's amazing how far you can actually get without knowing it, in fact - but vast numbers of things suddenly make sense when you grasp it.

[source]





public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Radio radio_1=new Radio();

//The value of status before calling
//the method
System.out.println("Old Value of status="+radio_1.status);

//call the method that changes
//status
Switcher switcher1 =new Switcher();
switcher1.on(radio_1);

//note that the value of status is changed
System.out.println("Old Value of status="+radio_1.status);

}

}


class Radio {

int status=0;


}

class Switcher{

public void on(Radio i){
//this will change the value of
//status even after the method is called
//
i.status=1;

}

}

output:
Old Value of status=0
Old Value of status=1

Fields shadowing in Java

public class FieldShadow {

public FieldShadow() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

TestClass TestClass1 =new TestClass();
TestClass1.printParameters(1,3);

TestClass1.printFields();



}

}

class TestClass {

//fields within class
private int x=0;
private int y=1;

//Here x and y parameters shadows x and y fields
public void printParameters(int x, int y){

System.out.println(x+" and "+y);

}


//this will show the fields
public void printFields(){
System.out.println(x+" and "+y);
}



}


output:
1 and 3
0 and 1

Category Cloud

Label Cloud