GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rating: Thread Rating: 5 votes, 5.00 average.
  #11  
Old 20-Jun-2004, 19:30
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

VII.The if else Statements


These are extremely simple.
CPP / C++ / C Code:
Syntax:
if (condition)
	{
	CODE1
	}
else
	{
	CODE2
	}
If the condition is true, CODE1 is executed, else CODE2 is executed. And these can be nested.
CPP / C++ / C Code:
Example:
if (a>50) cout<<"\n>50";
else if (a<30) cout<<"\n<30";
else cout<<"Between 30 & 50";
Please note that if you use a variable in the condition bracket, the if statement considers any non-zero value as TRUE and zero as FALSE.
CPP / C++ / C Code:
Example:
int bool=2;
if(bool) cout<<bool;
Of course, a slightly more complex version of the if else concepts are nested if else statements.
CPP / C++ / C Code:
Eg.
if(--code--)
	{
	--code--
		if(--code--)
			{
			--code--
				if(--code--)
				{
				--code--
				}
			}
		else
			{
			--code--
			}
	}
else if
		{
		--code--
		}
else
	{
	--code--
	}
I'll leave the applications to your imagination.
__________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times.
  #12  
Old 20-Jun-2004, 19:31
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programe #1


EP1:
->Make a programme to find all the prime numbers from 2 to a given number
CPP / C++ / C Code:
//Example Programme 1: Prime Number Generator
#include <iostream.h>
void main()
{
int n;
cout<<"\nEnter a number: ";
cin>>n;

for(int i=2,prime=1;i<n;++i)	//i starts from 2 as 1 is both prime and composite
{
        for(int j=2;j<=i/2;++j) //j ends at i/2 as the rest of the values cannot be factors
                {	
                if(i%j == 0)
                        {
                        prime=0;
                        break;
                        }
                else prime=1;
                }
if(prime) cout<<"\n"<<i;
}

}
  #13  
Old 20-Jun-2004, 19:32
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

IX.Arrays


Suppose you had 50 people and you wanted to store all their ages, according to their roll numbers. So the 'obvious' thing to do is declare 50 int variables and assign them, perhaps like this:

int _0=17,_1=45,_2=12, .... etc.

Note: The _ is required as a variable cannot start with a number.

Now, to avoid this cumbersome and unwieldy code, we have the concept of arrays.

An array is basically a collection of variables of the SAME type. They are declared and accessed in the following way.
CPP / C++ / C Code:
Declaration: (data type) (name)[ (number of variables) ];
Example:
int age[50];

Assignment: (name) [ (variable number you want to assign the value to) ] = (value);
Example:
age[3]=12;

Please note that numbering starts from 0. So if you want to assign the age 17 to the first variable,

age[0]=17;

And obviously the last variable is accessed by the number one less than the total number of variables.

age[49]=18;

Arrays can be initialized when declared in the following manner:
CPP / C++ / C Code:
Syntax: (data type) (name)[no. of vars]={ (val0), (val1), ... };
Example: int class[3]={1,2,3};

And by the way, and array of characters is a string. It can be declared in the previous fashion:

char name[8]={'P','h','a','n','t','o','m'};

Or:

char name[8]="Phantom";


Remember the " " for strings and ' ' for characters?

You might be wondering why I've used 8 as the number of variables instead of 7 as Phantom has 7 characters. In the case of strings, a NULL character is always added to the end of the string to show that the string ends here. The reason why we require a null character is the characters are actually stored in consecutive memory blocks one-byte-wide. The only information given is the address of the block which contains the first character. cout stops only when it encounters the null character. So, when we declare the array, we have to make an allowance for that. And the null character is added by the compiler, as you can see, I just used "Phantom".

{More on how arrays work in Pointers}
__________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times.
  #14  
Old 20-Jun-2004, 19:34
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #2


EP2:
->Make a programme to input an array of intergers and sort it in the ascending order
CPP / C++ / C Code:
//Example Programme 2: Array Sorter
#include <iostream.h>
void main()
{
int array[10];				//The array
int temp;				//A variable which will temporarily store a value

        for(int i=0;i<10;++i)		// i<10 will ensure that it will end at array[9] as
        {				// 10 is not less than 10
        cout<<"\nEnter value "<<i+1<<" : ";
        cin>>array[i];
        }

cout<<"\nSorting in ascending order.....";

for(i=0;i<10;++i)			//I haven't declared i again (int i=0) as it has 
        for(int j=i+1;j<10;++j)		//already been declared
                if(array[i]>array[j])
                {
                temp=array[i];		//Here we swap the values of array[i] and array[j]
                array[i]=array[j];
                array[j]=temp;
		}

cout<<"\n";

for(i=0;i<10;++i) cout<<array[i]<<"\t";
}
Note:
In EP2 I've used a sorting algorithm known as a SELECTION sort. Here, we start with the first value, array[0] and check it with array[1]. If array[0] is greater that array[1] then we swap the values as we want it in ascending order. Once that swap is done, we will be comparing the old array[1] with the rest of the variables and will keep repeating it until all the variables are compared with each other.
  #15  
Old 20-Jun-2004, 19:35
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #3


EP3:
->Make a programme to merge 2 arrays into one array and make sure that none of the values exceed 50 and is greater than 0.
CPP / C++ / C Code:
//Example Programme 3: Array Merger
#include <iostream.h>
void main()
{
int a[10], b[10], c[20];

cout<<"\nArray 1..";

for(int i=0;i<10;++i)
        do
        {
        cout<<"\nEnter value "<<i+1<<": ";
        cin>>a[i];
        }while( ! (a[i]<=50 && a[i]>=0) );

/*This might seem a bit complex, but it's really simple. I've encased the input in a loop so that it will keep asking for the value if the given value doesn't satisfy the given conditions. a[i]<=50 && a[i]>=0 is the required condition. So, adding a ! makes the loop work in the following manner: THE LOOP WILL CONTINUE AS LONG AS THE GIVEN VALUE IS *NOT* LESSER OR EQUAL TO 50 AND GREATER OR EQUAL TO 0*/

cout<<"\n Array 2...";

for(i=0;i<10;++i)
        do
        {
        cout<<"\nEnter value "<<i+1<<": ";
        cin>>b[i];
        }while( ! (b[i]<=50 && b[i]>=0) );
 


for(i=0;i<10;++i) c[i]=a[i];
for(;i<20;++i) c[i]=b[i-10];

for(i=0;i<20;++i) cout<<c[i]<<"\t";
}
  #16  
Old 20-Jun-2004, 19:36
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

X.Multi-dimensional Array


We can extend the concept of arrays in the following manner. In, the previous example the array was 1-dimensional, or just extended in a straight line. We can also declare a 2-dimensional array so that we have a matrix of variables of the same data type.

Example:
int chessboard[8][8];


I've used the chessboard as an example as it's easy to point out how this 2-D array works

---------------------------------
¦0,0|0,1|0,2|0,3|0,4|0,5|0,6|0,7¦
¦1,0|1,1|1,2|1,3|1,4|1,5|1,6|1,7¦
¦2,0|2,1|2,2|2,3|2,4|2,5|2,6|2,7¦
¦3,0|3,1|3,2|3,3|3,4|3,5|3,6|3,7¦
¦4,0|4,1|4,2|4,3|4,4|4,5|4,6|4,7¦
¦5,0|5,1|5,2|5,3|5,4|5,5|5,6|5,7¦
¦6,0|6,1|6,2|6,3|6,4|6,5|6,6|6,7¦
¦7,0|7,1|7,2|7,3|7,4|7,5|7,6|7,7¦
---------------------------------


As you can see from this crude chessboard, it has 8 rows and 8 columns, just like the 2-D array. It's called 2 dimensions as we require 2 variables to point out a variables' location on it. For example, suppose we're on a straight road, then we only need 1 variable, to show where we are taken some point as the origin

CPP / C++ / C Code:
	Origin				Destination
	  ._________________________________X_______________________________
	  		25 km

Therefore by saying 25km from the origin to the right is sufficient. So only one dimension exists: length.

But, suppose we wanted to fix a point on the paper ( 2-dimensions) , then we'll need 2 variables


|
|
|
|
|
|----------X
| |
| |
| |
|_ _ _ _ _ _|_ _ _ _


Therefore 2 dimensions are there: length and breadth



|
|
|
|
|
|_ _ _ _ _ _ _ _
/
/
/
/
/


And the world we live in is 3-dimensional: length, breadth & height.

Mathematically, these 3 dimensions are called, x,y & z co-ordinates.

Alright, back to the chessboard. Suppose I wanted to place a value on the square (4,3):

chessboard[4][3]=val;

And suppose you wanted to declare the 2-D array and initialize it at the same time:
CPP / C++ / C Code:
int chessboard[8][8]={ 1,2,3,4,5,6,7,8,
		           11,12,13,14,15,16,
			     17,18,19,20,21,22,23,24,
			     ...etc. };

Note how a 2D array is initialized.

The number of programmes you can make out of this concept are endless. You can simulate matrix operations too.

Now, let's try a 3-D array. Here we can consider the array to be as pages of a book:

Example: int book[ page no ][x co-ordinate ][y-coordinate];

Similarly, you can make an n-dimensional array if you want to, but arrays chew up a lot of memory so most people stop at 3.
  #17  
Old 20-Jun-2004, 19:37
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XI.Structures


XI.a)What is an object?
Consider a blue print for a digital diary was made. Using this we can make hundreds of objects based on the same model, with the same memory capacity, games, power options, scheduler, phone book etc. But is each model the same? Of course not, each model depends on what the user puts into it. For example, the 2 phone books must contain different phone nos. not the same ones! So would the scheduler.. And some users use more memory than the others..

Basically, an object is the basic model created from a blue-print.

XI.b)Defining a object
An array holds variables of the same type, but a structure can hold variables of any type.

Consider a table, it contains many drawers. Suppose each drawer contained 3 objects, how would you access the object? First you would access the drawer, and then any one of the objects.
CPP / C++ / C Code:
Syntax: struct (name)
	{
	(declarations)
	}(names of structures);

Example: A structure of a students info

	struct student
	{
	int roll_no, age;
	float marks[5];
	char name[50];
	};

You can declare an object by either:

student Phantom;

Or when declaring:

	...
	...
	char name[50];
	}Phantom;

XII.b.i)Accessing the elements
So, how would I use this structure? Simple, we use the DOT operator. According to Appendix B the DOT operator is a C++ component selector. Basically, it is used to select the components within objects of a structre or class such as the variables INSIDE it. {More on classes later}.

So, I wish to gain all the information of a student, this is how I'd do it.
CPP / C++ / C Code:
student Phantom;

cout<<"\nEnter roll no: ";
cin>>Phantom.roll_no;		//Note the .

cout<<"\nEnter name: ";
cin>>Phantom.name;

cout<<"\nEnter age: ";
cin>>Phantom.age;		//Very bad way to read a string

for(int i=0;i<5;++i)
	{
	cout<<"\nEnter marks for Subject "<<i+1<<": ";
	cin>>Phantom.marks[i];
	}

Now, suppose I wish to store the entire class' information, what would I do?

Declare an array, of course!!

CPP / C++ / C Code:
student class12[50];

for(int i=0;i<50;++i) cin>>class12[i].roll_no;

Alright, now suppose you wished to use the structure for only one variable. Then,
struct
{
(..)
} (name) ;
  #18  
Old 20-Jun-2004, 19:38
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XII.Functions :: Intro, Calling & Definition


Functions are the second-most important concept in a language. A function is basically a block of code which does some work. Got that? A function basically allots a group of program statements under a name which can be called any time within the programme.
Consider the following:
CPP / C++ / C Code:

		
				       DATA
					|
					|
				-------------------
				|		|
				|Function does 	|
				|some work on 	|
				|DATA and gives	|
				|OUTPUT	 	|
				|	 	|
				-------------------	
					|
					|
				      OUTPUT

Alright, consider a rock-crushing machine; the machine is the function, the rocks are the data or the ARGUMENT, and the powdered rock is the output or RETURN.

Well, hope that concept is clear...
CPP / C++ / C Code:
Syntax: (return type) (name of function) ( (argument1), (argument2), .... )
		{
		--code--
		--code--
		-...-
		return (variable of same type as return type);
		}

Example: int add( int a, int b)
		{
		int c=a+b;
		return c;
		}

Hope you understood that...it's really very simple.

XII.a)Definition
To define a function we employ the above syntax. Thus whenever we call the function (next topic) the compiler automatically inserts the code in the function definition.

XII.b)Calling a function
Calling a function is simple.
CPP / C++ / C Code:
Syntax: (name of function)( arg1, arg2, .. );

Example:
#include <iostream.h>

int add( int a, int b)
	{
	int c=a+b;
	return c;
	}
void main()
	{
	int a,b;
	cout<<"\nEnter nos.to be added: ";
	cin>>a>>b;
	cout<<"\n Sum is: "<<add(a,b);
	}

Note, add(a,b). As you can see we are working on the 2 variables, a & b, hence they are the arguments. We can always consider the entity add(a,b) as the return value, i.e. c or a+b. So WHEREVER we use a value, we can use the function.
CPP / C++ / C Code:
Example:
cout<<add(a,b);
int sum=add(a,b);

The return data type, can be anything. A special one has been provided by the compiler, it's called VOID. As you can guess, it's void, or returns nothing. I hope the signifiance of main is visible now. main() is a function run by the compiler, and as we don't return any value to anything, we have void main().

Functions are of infinite use when it comes to simplifying a programme. My first function:
CPP / C++ / C Code:
void cleanup(int cont)					//cont=continue
	{
	cout<<"\nPress any key to ";
	if(cont) cout<<"continue...";
	else cout<<"exit...";
	getch();
	clrscr();
	if(!cont) exit(0);
	}
The functions exit(),getch(),and clrscr() will be explained in XIII.b.
  #19  
Old 20-Jun-2004, 19:40
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XII.Functions :: Some Things You Ought to Know About Functions


XII.c)Some Things You Ought to Know About Functions
XII.c.i)Inline Functions
Inline functions basically store the function code directly "in line" with the main programme. The benefits of this is that even though it hogs memory, it's faster than the usual function as the usual function is stored at a separate memory block, and is accessed by a "jump" from the main programme involving many steps (which doesn't have to be explained) which generally slows down the programme.
CPP / C++ / C Code:
Syntax:
-------
inline (return type) (name of function) ( (arguments...) )
	{
	--code--
	}

Example:
--------
inline float area(int r)
	{
	return 3.142*r*r;
	}

Obviously the only difference is that we add an inline before the return type.

Btw, inline is nothing but a request to the compiler, i.e. it may choose to ignore it if the function is too large, etc..

XII.c.ii)Function Prototypes
A function prototype states the return type, argument no and type, and name of the function without actually defining it. This is used to clean up the code and also speeds up the compiler.
CPP / C++ / C Code:
#include <iostream.h>

int add(int a, int b);	//Note the semicolon->shows it's a function prototype

void main()
{
int a,b;
cout<<"\nEnter 2 nos.";
cin>>a>>b;
cout<<a+b;
}
int add(int a, int b)
	{
	return a+b;
	}

XII.c.iii)Global & Local Variables
Definition
A global variable is accessible to ALL functions whereas a local variable is only accessible to the function it's declared in.

For example, in the silly math problems, we can eliminate the need for an argument by making the variables gloabal.
CPP / C++ / C Code:
Example:
int a,b,c;
void add()
	{
	c=a+b;
	}
void main()
{
cout<<"\nEnter nos.";
cin>>a>>b;
add();
cout<<c;
}

As you can see, the variables a,b, & c were accessible to main() and add() as they were globally declared.

Scope Resolution Operator (:
This operator has allowed many a sadistic teacher to set ridiculously hard programmes for exams.
If you remember (III.c.i), you can't have 2 variables with the same name. Well, not exactly...you can't have 2 GLOBAL or 2 LOCAL variables with the same name.
CPP / C++ / C Code:
int a=8;
void main()
{
int a=5;
cout<<a;
}
Output? 5, of course....the variable with greater precedence is the local one. But suppose I wanted to use the global variable yet stubbornly insist on using the same name for both....that's were we use the scope resolution operator.
CPP / C++ / C Code:
int a=8;
void main()
{
int a=5;
cout<<::a;
}
Output: 8
  #20  
Old 20-Jun-2004, 19:41
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #4


EP4:
->Make a calculator with addition, multiplication, subtraction, and division abilities.
CPP / C++ / C Code:
//Example Programme 4: Calculator
#include <iostream.h>

struct data
	{
	char ch;
	float a,b;	//Even though float is for decimals, it has a higher memory than int
	};		//Consult Appendix C for the maximum values each data type can hold

float add(float a, float b)	
	{
	return a+b;
	}

float sub(float a, float b)
	{
	return a-b;
	}
float mul(float a, float b)
	{	return a*b;
	}
float  div(float a, float b)
	{
	return a/b;
	}

data menu()
	{
	data inp;
	cout<<"\n1.Add\n2.Subtract\n3.Divide\n4.Multiply\n5.Exit\n\nEnter your choice: ";
	cin>>inp.ch;
	cout<<"\nEnter 2 operands: ";
	cin>>inp.a>>inp.b;
	return inp;
	}
void main()
	{
	data temp;
	do
	{
	temp=menu();
	if(temp.ch=='1') cout<<"\nSum: "<<add(temp.a,temp.b);
	else if(temp.ch=='2') cout<<"\Diff: "<<sub(temp.a,temp.b);
	else if(temp.ch=='3') cout<<"\nProd: "<<mul(temp.a,temp.b);
	else if(temp.ch=='4') cout<<"\nQuot: "<<div(temp.a,temp.b);
	}while(temp.ch<'5');
	}
 
 

Recent GIDBlogProblems with the Navy (Chiefs) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 14:02.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.