C++ Commands

Basics

Output:

cout << Variable;

Input:

cin >> Keyboard;

cin >> a >> b; =>
cin>>a;
cin>>b;
#include <string>
int main()
{
  string mystr;
  getline (cin, mystr);
}

Stringstream:

#include <sstream>
int main()
{
  string mystr;
  float price=0;
  getline(cin, mystr);
  stringstream(mystr) >> price;
}

Logic Operators:

&& And
|| Or
!  Not
? Conditional  condition ? result1 : result2


 , operator

Control structures:

Conditional

if (condition)
 {
   statement1;
   statement2;
 }
else
   statement3;

Iteration structures

while (expresion) statement
do statement while (condition);
for (initialization; condition; increase) statement;

for (int n=10; n>0; n--) {
        cout << n << ", ";
}

for (n=0, i= 100; n!=i; n++, i--){
 //wathever here...
}
break statement
continue statement
goto statement
cstdlib library
void exit(int exitcode);
do statement while (condition);
switch (expression)
{
        case constant1:
                group of statements1;
                break;
        case constant2:
                group of statements2;
                break;
        .
        .
        default:
                default group of statements
}

Functions(I)

type name(parameter1, parameter2, ...) (statements)

scope o variables

#include <iostream.h>

//Global variables
int integer;
char aCharacter;
char string[20]

main()
{
        //local variables
        unsigned short age;
        float ANumber, AnotherOne;

        //instructions

        ....
}

Functions with no type

void printmessage()
{
        cout<< "I'm a function!";
}



Call the function (Use parentheses)

printmessage();

Functions(II)

Arguments passed by value and by reference

By value:

int x=5, y=3, z;
z=addition(x,y);

By reference:

void duplicate(int& a, int& b, int& c)
// the values of a, b, c was passed by reference they could change their values into the function.

Overloaded functions:

// overload function
#include <iostream>
using namespace std;

int operate (int a, int b)
{
        return (a*b);
}

float operate (float a, float b)
{
        return (a/b);
}

int manin()
{
        int x=5, y=2;
        float n=5.0,m=2.0;
        cout<< operate (x,y);
        cout<< "\n";
        cout<< operate (n,m);
        cout << "\n";
        return 0;
}

Inline functions, the code of the function is inserted on the main code each time the function is called:

inline type name (arguments ...) (instructions ...)

Recussivity:

long factorial (long a)
{
        if (a>1)
        return (a * factorial(a-1));
        else
                return(1);
}

Declaring functions

//declaring function prototypes
# include<iostream>
using namespace std;

void odd (int a);
void even (int a);

int main()
{
        int i;
        do{
                cout<< "Type a number (0 to exit): ";
                cin>>i;
                odd(i);
        } while (i!=0);
        return 0;
}

void odd (int a){
        if (a%2)!=0) cout << "Number is odd. \n";
        else even(a);
}

void even (int a){
        if (a%2)==0) cout << "Number is even. \n";
        else odd(a);
}

Arrays

Declaration:

int billiy[5];

Initiallizing:

int billy[5]={16,2,77,40,12071};

Accesing:

a= billi[2];

Array as parameters:

void procedure(int arg[]);

Pass this function an array:

int myarray[40];
procedure(myarray);

Caracter sequences

char jenhy[20];
char myword[]={'H', 'e','l','l','o','\0'};
char myword[]="Hello";

Pointers

Reference operator (&)

ted= &andy;

Pos 1776

Name

Age

andy

25

Name

Year

ted

1776

Dereference operator (*)

bet= \*ted;
\*ted=andy;

*ted

25

bet

25

Declaring variables of pointer types

type* name;
int* number;
char* Character;
float* greatnumber;
//my first pointer
#include<iostream>
using namespace std;

int main()
{
        int firstvalue, secondvalue;
        int* mypointer;

        mypointer = &firstvalue;
        *mypointer=10;
        mypointer = &secondvalue;
        *mypointer=20;

        cout<<"firstvalue is "<< firstvalue << endl;  // prints 10
        cout<<"secondvalue is " << secondvalue << endl; // prints 20

        return 0;
}
//my first pointer
#include<iostream>
using namespace std;

int main()
{
        int firstvalue=5, secondvalue=15;
        int * p1, * p2;

        p1= &firstvalue;
        p2= &secondvalue;

        *p1=10;
        *p2=*p1;

        p1=p2;
        *p1=20;

        cout<< "firstvalue is " << firstvalue <<endl;
        cout<< "second value is " << secondvalue <<endl;

        return 0;
}

Pointers and arrays

The concept of array is very much bound to the one of pointer. In fact, the identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it poins to, so in fact they are the same concept, for example, supposing these two declarations:

int numbers[20];
int * p;

p=numbers;

After that p and numbers would be equivalent and would have the same properties. The only difference is that we could change the value of the pointer p by another one, whereas numbers will always point to the first of the 20 elements of type int with which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an array can be considered a constant pointer. Therefore, the following allocation would not be valid.

numbers=p;

Bacause numbers is an array, so it operates as a constant pointer, and we cannot assign values to constants.

//more pointers
#include<iostream>
using namespace std;

int main()
{
        int numbers[5];
        int * p;

        p= numbers; *p=10;
        p++; *p=20;
        P=&numbers[2]; *p=30;
        P=numbers+3; *p=40;
        p= numbers; *(p+4)=50;

        for (in n=0; n<5; n++)
                cout numbers[n]<< ", "; //prints 10, 20, 30, 40, 50,
        return 0;
}

Pointer initialization

int number;
int *tommy=&number;

char *terry="Hello";

Pointer arithmetics

char *mychar;
short *myshort;
long *mylong;

mycharr++;
myshort++;
mylong++;

Equivalent to:

mychar=mychar + 1;
myshort=myshort +1;
mylong=mylong+1;

and equivalent to the ambiguous writing:

*mychar++;
*myshort++;
*mylong++;

Because ++ has greater precedence than *.

Different to:

(*mychar)++

Avoid unexpected results by using parentheses.

pointers to pointers

char a;
char *b;
char **c;
a= 'z';
b= &a;
c= &b;

void pointers

Pointers that point to a value that has no type (and thus also an undetermined lenght and undetermined deference properties).

//increaser
#include <iostream>
using namespace std;

void increase(void* data, int psize)
{
        if (psize == sizeof(char))
        {char* pchar; pchar=(char*)data; ++(*pchar);}
        else if (psize == sizeof(int) )
        {int* pint; pint=(int*)data; ++(*pint);}
}

int main()
{
        char a= 'x';
        int b=1602;
        increase (&a, sizeof(a));
        increase (&b, sizeof(b));
        cout << a << ", "<< b << endl;
        return 0;
}

Null pointer

int *p;
p=0;

Pointers to functions

To pass a function as an argument to anoter functuion. you have to declare it as a protoype of the function except that the name of the function is enclosed betwen parentheses () and an asterix (*) is inserted before the name.

//pointers to functions
#include<iostream>
using namespace std;

int addition (int a, int b)
{return (a+b);}

int substraction(int a, int b)
{ return (a-b);}

int operation(int x, int y, int(*functioncall)(int,int)
{
        int g;
        g=(*functioncall)(x,y);
        return (g);
}

int main()
{
        int m,n;
        int (*minus)(int,int)=substraction;

        m=operation(7,5, addition);
        n=operation(20, m, minus);
        cout<< n;
        return 0;
}

Dynamic memory

Operators new and new[]

pointer = new type pointer = new type [number of elements]

int *bobby;
bobby = new int[5];

Operators delete and delete[]

delete pointer;
delete [] pointer;

The first deletes memory used for a single element. The second deletes memory used for arrays of elements.

The argument passed to delete must be either a pointer toa memory block previously allocated with new, or a null pointer.

//rememb-o-matic
#include<iostream>
#include<new>
using namespace std;

int main()
{
        int i,n;
        int *p;
        cout <<how many numbers would you like to type? ";
        cin >>i;
        p=new (nonthrow) int[i];
        if (p==0)
                cout << "Error: memory could not be allocated";
        else
        {
                for (n=0; n<i; n++)
                {
                        cout<< "Enter the number: "
                        cin>>p[n];

                }
                cout << "You have entered: "
                for (n=0; n<i; n++)
                        cout <<p[n]<<", ";
                delete[] p;
        }
        return 0;
}

Data structures

Data structures

struct structure_name{ member_type1 member_name1; member_type2 member_name2; . . } object_names;

struct product{
        int weight;
        float price;
} apple, banana,melon;

apple.weight;
banana.price;

Pointers to structures

//pointers to structures
#include<iostream>
#include<string>
#include<sstream>

struct movies_t {

        string title;
        int year;
};

int main()
{
        string mystr;

        movies_t amovie;
        movies_t * pmovie;
        pmovie = &amovie;

        cout << "Enter title: ";
        getline(cin,pmovie->title);
        cout << "Enter year: ";
        getline(cin, mystr);
        (stringstream) mystr>>pmovie->year

        cout<<"\nYou have entered:\n";
        cout<< pmovie->title;
        cout<< "("<<pmovie-year << ")\n";
        return 0;
}
pmovie->title

Is equivalent to

(*pmovie).title

Expresion

What is evaluated

a.b

Member b of object a

a->b

Member b of object pointed by a

(*a).b

*a.b

Value pointed by member b of object a

*(a.b)

Nesting structures

struct movies_t{
        string title;
        int year;
};

struct friends_t{
        string name;
        string email;
        movie_t favorite_movie;
} charlie, maria;

friends_t *pfriends=&charlie;

After the previous declaration we could use any of the following expressions:

charlie.name;
maria.favorite_movie.title;
charlie.favorite_movie.year;
pfriends-> favorite_movie.year;

Other data types

Defined data types (typedef)

typedef existing_type new_type_name;

typedef char C;
typedef unsigned int WORD;
typedef char * pchar;
typedef char field[50];

We can use it in declaratios like:

C mychar, anotherchar, *ptcl;
WORD myword;
pChar ptc2;
field name;

Unions

Anonymous unions

Enumeration

Classes (I)

class class_name {
        access_specifier_1;
        member1;
        access_specifier_2;
        member2;
        .......
} object names;

Acces specifiers:

private members of a class are accesible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. public members are accessible from anywhere where the object is visible.

By default al members of a class declared with the class keyword have private acces for all its members. Therefore, any member that is declared before any other class specifier automatically has private access. i.e

//classes example
#include <iostream>
using namespace std;

class CRectangle {
        int x,y;
        public:
                void set_values (int, int);
                int area () {return (x*y);}
};

void CRectangle::set_values (int a, int b) {

        x=a;
        y=b;
}

int main () {

        Crectangle rect;
        rect.set_values (3,4);
        cout << "area: " << rect.area();
        return 0;

}

Operator scope of (::) Specifies the class to wich the member being declared belongs.