Search This Blog

Thursday 27 December 2012

Difference between cin.getline and cin in C++

You should know the difference between
char string[ 10 ];
  cin >> string;
And
cin.getline(string,10,'\n');

In cin>>string, user keeps on entering characters unless either Enter key or Spacebar is pressed or 10 characters are entered and stored. Where as in Case of cin.getline User may press Enter key, Spacebar or whatever except the Delimeter character (in this case '\n' which is Enter Key). Size of array should also be kept in mind that compiler won't allow you to store more than size of array (10 characters in this case).

Static in C++

What is Static in C++?
Ans: I believe that Examples are the best way to make someone understand so:


#include <iostream>

using namespace std;
f1();
void main()
{

f1();
f1();
}
f1()
{
static int s = 0;
cout << s++ << endl;
}




The value of 's' does not start from 0 when the function is called second time, rather it starts from last value of of s when function was called last time (i.e. 1 in this case when Function is called second Time).

Tuesday 11 December 2012

Precedence of operators in C++

Order of execution within a statement is called Precedence.
For Example: 2+2 % 2 gives 2 NOT 0. How did I come to know?
What will happen first is predefined according to the picture below:


 Link to view this image: http://i.imgur.com/lffHR.jpg
OR goto http://en.cppreference.com/w/cpp/language/operator_precedence

Sunday 9 December 2012

Program to Copy one String in another String in C++


#include <iostream>
using namespace std;

void copy1( char *, const char * );

int main()
{
char String1[10];
char String2[] = "Hello";

copy1(String1 , String2);
cout << String1 << endl;

return 0;
}

void copy1(char *String1, const char *String2)
{
for (int i = -1;  i<10;  String1[i] = String2[i])
i++;
}
//============================================================================
You can also use following copy function.

void copy1(char *String1, const char *String2)
{
for (int i = 0; (String1[i] = String2[i]) != '\0'; i++);
}
//============================================================================
Another way: or you can use following copy function.

void copy1(char *String1, const char *String2)
{
for ( ; (*String1 = * String2) != '\0' ; String1++, String2++);
}

Wednesday 5 December 2012

Convert lowercase letters to uppercase letters

Header file: cctype

// Converting lowercase letters to uppercase letters
#include <iostream>
#include <cctype> // For the use of toupper Function.
using namespace std;
int main()
{
 char a = 'a';
 char b = toupper(a);
 cout << b << endl;

 return 0;
}
//====================================

Better way:

#include <iostream>
#include <cctype>
using namespace std;
int main()
{
 char a = 'a';
 cout << static_cast<char>( toupper(a) ) << endl;
 return 0;
}
//---------------------------------------------------
//You will be thinking now, why we used static_cast<char> ?
//If we would have done as follows, what was wrong?

#include <iostream>
#include <cctype>
using namespace std;
int main()
{
 char a = 'a';
 cout << toupper(a) << endl;
 return 0;
}

Tuesday 4 December 2012

Interesting Tip: Increment, Decrement Operator:






Changing a variable by adding or subtracting 1 is so common that there is a special
shorthand for it,

x++  =>  x = x+1
x--   =>  x = x-1













You think you know about increment operator?
Lets see!
What will be its output?

Sunday 2 December 2012

What is Switch in C++?

#include<iostream>
using namespace std;

int main()

{
cout<< "Enter 1 or 2 -------> ";
int a; cin>>a;
switch (a)
{
case 1:
cout<<"1 pressed"<<endl;
break;

case 2:
cout<<"2 pressed"<<endl;
break;

}
return 0;
}
//===============================================================================
You may want to see: Calculator using switch statement. Takes Expression as we write on our copy.

Saturday 1 December 2012

What are Pointers in C++? Don't get affraid of Pointers, these are easy!

Points to Remember:
  • *  is used to acces value of a pointer. It's called indirection or dereferencing operator.
  • & is used to get the address of a variable or a pointer. It's called address operator.
  • While declaring a pointer * indicates that the variable being declared is a pointer. 


How we use Pointers?
Ans:
#include<iostream>
using namespace std;
int main()
{
int *Ptr;   //Declaring a pointer named Ptr, you can change the name.
int a = 7;
Ptr = &a; //Pointers store addresses. Address of 'a' variable will be stored in the pointer.
cout<< *Ptr<<endl; //* means the value of Ptr where it's pointing
return 0;
}
//===============================================================================
//array_name gives the address of first location (index number 0) of array in hexadecimal system.
#include<iostream>
using namespace std;
int main()
{
int z[] = { 1, 2, 3, 4, 5 };
cout<<z;
return 0;
}
//===============================================================================
Both will have same output
But if we'll do something as below, then it's stupidity, because array_name gives the address of first location (index number 0) of array in hexadecimal system.

// *array_name gives the value stored at first location of array.
#include<iostream>
using namespace std;
int main()
{
int z[] = { 1, 2, 3, 4, 5 };
cout<<*z;
return 0;
}
//===============================================================================
// what if we want to access any other number stored in array?
#include<iostream>
using namespace std;
int main()
{
int z[] = { 1, 2, 3, 4, 5 };
cout<< *(z+4) << endl;// 5 is printed.
cout<< *z + 3 << endl;// = value of z at first location (1) + 3 => 4
return 0;
}
//===============================================================================
//You can access any index of array using pointers by using subscripts.
#include<iostream>
using namespace std;
int main()
{
int *Ptr;
int z[] = { 1, 2, 3, 4, 5 };
Ptr = z; // or You can write Ptr = &z[0];
cout<< Ptr[3]<<endl;
return 0;
}
//===============================================================================
//Pointer's pointing postion can be changed. Interesting!
#include<iostream>
using namespace std;
int main()
{
int *Ptr;
int z[] = { 1, 2, 3, 4, 5 };
Ptr = z; // or You can wrtie Ptr = &z[0];
Ptr++; // Now pointer starts pointing to the next integer stored in array i.e. 2
cout<< *Ptr <<endl;
return 0;
}
//===============================================================================
Subtracting pointers
Returns number of elements between two addresses
This means that p1_array is 3 ahead of p_array.
Lets move towards Void Pointers
We can't dereference a void pointer:
Example:
What if we want to dereference a void pointer???
We will have to change our style for this.
#include <iostream>using namespace std;
 int main()
{
 int x = 5;
 void *Voidptr; //declaring a void pointer, which will point to a variable of type void.
 Voidptr = &x;  //initializing void pointer with the address of x variable of int type.
//If we want to access x, then what will we do? Will we do cout << *Voidptr;          "NO"
//We cannot dereference a void pointer because it's pointing to a variable of type void.
//So, we cannot do cout << *Voidptr;
//Therefore we'll introduce another pointer (say ptr1) of type int which will point to x variable indirectly.
 int *ptr1 = static_cast<int*>(Voidptr); /*changing the type of pointer from void to int for one step and storing it permanently.*/
 cout<<*ptr1;
 return 0;
}


Feel free to ask if there is any problem?

Friday 30 November 2012

How to make the numbers fall in console?

#include<iostream>
#include<windows.h>
using namespace std;
//Function to move the cursor.
void gotoxy(int x, int y)
{
HANDLE console_handle;
COORD cursor_coord;
cursor_coord.X=x;
cursor_coord.Y=y;
console_handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(console_handle,cursor_coord);
}

int main()
{
for (int row = 0; row<25; row++)
{
gotoxy(25,row);
cout<<"5";
Sleep(200);
gotoxy(25,row);
cout<<" ";
}
}
//=========================================================================
Now, it's easy if you want to change your column. Just add a simple condition.
I recommend, before you goto the following program, try to think, what the condition can be?

//Program to drop a number in different column.
#include<iostream>
#include<windows.h>
using namespace std;
//Function to move the cursor.
void gotoxy(int x, int y)
{
 HANDLE console_handle;
 COORD cursor_coord;
 cursor_coord.X=x;
 cursor_coord.Y=y;
 console_handle=GetStdHandle(STD_OUTPUT_HANDLE);
 SetConsoleCursorPosition(console_handle,cursor_coord);
}
int main()
{
 int column = rand() % 80; //80 because Total columns are 0-79. i.e. less than 80.
 for (int row = 0; row<25; row++)
 {
  gotoxy(column,row);
  cout<<"5";
  Sleep(200);
  gotoxy(column,row);
  cout<<" ";
  //Now we add another condition so that our number again comes at first row and a different
  if (row == 24) // last line of console screen.
  {
   row = 0;
   column = rand() % 80;
  }
 }
}
//========================================================================

Similarly you can increase the number of Numbers falling downward.
//Program for falling two numbers in changing columns.
#include<iostream>
#include<windows.h>
using namespace std;
//Function to move the cursor.
void gotoxy(int x, int y)
{
 HANDLE console_handle;
 COORD cursor_coord;
 cursor_coord.X=x;
 cursor_coord.Y=y;
 console_handle=GetStdHandle(STD_OUTPUT_HANDLE);
 SetConsoleCursorPosition(console_handle,cursor_coord);
}
int main()
{
 int column = rand() % 80; //80 because Total columns are 0-79. i.e. less than 80.
 int column1 = rand() % 80;
 for (int row = 0; row<25; row++) 
 {
  gotoxy(column,row);
  cout<<"2";//first number.
  gotoxy(column1,row);
  cout<<"9";
  Sleep(200);
  gotoxy(column,row);
  cout<<" ";
  gotoxy(column1,row);
  cout<<" ";
  //Now we add another condition so that our number again comes at first row and a different
  if (row == 24)
  {
   row = 0;
   column = rand() % 80;
   column1 = rand() % 80;
  }
 }
}

Thursday 29 November 2012

Variable Data Type: Bool in C++

Bool is a variable data type which can store either 1 or 0.


#include<iostream>
using namespace std;
int main()

{
bool j,k,m;
bool i = j = k = m = 0;
cout<<j<<endl<<i<<endl<<k<<endl<<m<<endl;
return 0;
}
//===============================================================================


#include<iostream>
using namespace std;
int main()

{
bool j,k,m;
bool i = j = k = m = 1;
cout<<j<<endl<<i<<endl<<k<<endl<<m<<endl;
return 0;
}
//===============================================================================

Monday 26 November 2012

Program to make a word appear for 1 second and then it disappears.


#include <iostream>
#include <windows.h>
using namespace std;
 int main()


 {
cout<<"  a";
Sleep(1000);
cout<<"\b ";
cout<<endl;

return 0;
 }
//You can extend this to get your required result.

2-D arrays

Program to assign a value (say 5) to 1st column of 4 by 3 array. 4 = rows & 3 = columns.


#include <iostream>
using namespace std;
int main()
{
int Rehan[4][3]; // This is the way to declare 2-d array named Rehan.

for (int i = 0; i <=3; i++) //This loop performs the following assigning of values.
Rehan[i][0] = 5;
//Rehan[0][0] = 5;
//Rehan[1][0] = 5;
//Rehan[2][0] = 5;
//Rehan[3][0] = 5;

for ( i = 0; i<=3; i++)
cout<<Rehan[i][0]<<endl;
//if we don't use loop then we had to do following.
//cout<<Rehan[0][0]<<endl;
//cout<<Rehan[1][0]<<endl;
//cout<<Rehan[2][0]<<endl;
//cout<<Rehan[3][0]<<endl;

return 0;
}

Now lets make a program for the same number of rows and columns. Storing 5 in the second column of array and then printing  the whole array. Sounds Interesting, it's.

#include <iostream>
using namespace std; 
int main()
{
int Rehan[4][3]={0};
for (int i = 0; i <=3; i++)
Rehan[i][1] = 5; 
//What happens within the loop:
//Rehan[0][1] = 5;
//Rehan[1][1] = 5;
//Rehan[2][1] = 5;
//Rehan[3][1] = 5;

//Now we want to print whole of the array.
for (int rows = 0; rows<=3; rows++)
{
for (int columns = 0; columns <= 2; columns++)
cout<<Rehan[rows][columns]<<" ";
cout<<endl;
}
return 0;
}


Sunday 25 November 2012

What is '&', lets clearify our concepts.



You can see a program at your right side.
It's simple.

Point to be noted: We say b = a;
When we increase b, the value of b will be increased but a will not change. Why? because b = a means that value of a will be stored in b. When we print 'a', the original value of a is printed.

In the second program, &b = a means that value of a is stored in b and "by changing b value of a will be changed".
In other words b and a correspond to same number (which is 1 initially).


Saturday 24 November 2012

getch()


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

int main()
{
cout<<"Hi"<<endl;
getch();         //Screen is paused till the user presses a button.
cout<<"By"<<endl;
}

=========================================================================================

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

int main()
{
cout<<"Hi"<<endl;
int a = getch();         //Screen is paused till the user presses a button and that pressed button's ASCII will be stored in a.
cout<<a;
}

Did you see how useful is it?
Once you have stored the ASCII value, you can compare it. Let me clarify what I mean.


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

int main()
{
cout<<"Hi"<<endl;
int a = getch();         //Screen is paused till the user presses a button and that pressed button's ASCII will be stored in a.
if (a == 97)
cout<<"How dare you to press \"a\""<<endl;
else
if (a == 98)
cout<<"How dare you to press \"b\""<<endl;
else
cout<<"You pressed a key other than A and B."<<endl;
}



Friday 23 November 2012

How to Change the Size of output screen?

Interesting code:


#include <windows.h>

main()
{
      while(true)
      {
          Sleep(100);
          SMALL_RECT WinRect = {0, 0, rand() % 100 + 1, rand() % 70 + 1};
          SMALL_RECT* WinSize = &WinRect;
          SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), true, WinSize);
      }
}

This code was for fun, isn't it cool?
Now execute the following code:


#include <windows.h>
main()
{
          SMALL_RECT WinRect = {0, 0, 30, 57 };// 30 is for changing screen horizontally and 57 for changing vertically.
          SMALL_RECT* WinSize = &WinRect;
          SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), true, WinSize);
}


You can get your desired output screen by changing 30 and 57.

Thursday 22 November 2012

Wednesday 21 November 2012

Sizes of int, float, double, unsigned, short, unsigned short, long long

In addition to the int and double types, C++ has several other numeric types.
     C++ has two floating-point types. The float type uses half the storage of the double type, but it can only store 6–7 digits. Many years ago, when computers had far less memory than they have today, float was the standard type for floating-point computations, and programmers would indulge in the luxury of “double precision” only when they needed the additional digits. Today, the float type is rarely used.
     By the way, these numbers are called “floating-point” because of their internal representation in the computer. Consider numbers 29600, 2.96, and 0.0296. They can be represented in a very similar way: namely, as a sequence of the significant digits—296—and an indication of the position of the decimal point. When the values are multiplied or divided by 10, only the position of the decimal point changes; it “floats”. Computers use base 2, not base 10, but the principle is the same.


Friday 9 November 2012

How to generate Numbers automatically within a specific Range?

Lets say we want to print Numbers between 4 and 6, including 4 and 6.

#include<iostream>
using namespace std;
int main()

{
int x;
for ( x = 1 ; x <= 70 ; x++ ) // you can replace 70 with Any Number.
cout<< 4+   rand() % 3 <<endl; // to Produce Numbers between 4 & 6 including 4 and 6.

cout<<endl<<endl;
return 0;
}


Mod of 3 with any random number will give value less than 3 and greater than 0, and by adding any number from 0 to 2 with 4, we get either 4,5 or 6.

Simple!
C++: How to detect that user Pressed P button from keyboard? - Yahoo! Answers #include<iostream>
using namespace std;
int main()

{
int x;
for ( x = 1 ; x <= 70 ; x++ ) // you can replace 70 with Any Number.
cout<< 4+   rand() % 3 <<endl; // to Produce Numbers between 4 & 6 including 4 and 6.

cout<<endl<<endl;
return 0;
}


Mod of 3 with any random number will give value less than 3 and greater than 0, and by adding any number from 0 to 2 with 4, we get either 4,5 or 6.

Simple!

Monday 5 November 2012

How to produce Completely Random Number


ctime is included to use Time.
And cstdlib (C Standard Library) is used for rand & srand.


Note: Without changing any thing, I executed my program twice, and it gave me different Output, So we get completely Random Numbers in this way.

Time is changing.




srand(time(0)), seed is changing so outcome is changing (variety of random Numbers are being generated

Difference between Rand & Srand


You can use rand without srand (but the problem will be that you'll get same output whenever you run your program). Srand is a "seed value". As you sow so shall you reap. A group of random numbers are generated with each particular value of srand. Whenever we use a specific value in srand, a specific group of numbers will be generated, and that specific group of values (so called random) can be obtained whenever we use that number in srand which we used previously.


Note: C Standard Library (cstdlib) has been included for using srand and rand statements.





















Q. What does it really mean if we use srand (5); in a program?

Ans: It means that a set of predefined operations will be carried out at 5, and then a number will be generated (using rand).
User can use this number. If called second time (using rand) again set of predefined operations will be performed to produce second number. These Operations are set in such a way that they produce random number.

Time in C++


Syntax: After #include<ctime> as header, write time(0) OR time(NULL) in the body of program.

The manpage states that, « time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). »

Sunday 4 November 2012

Loops


Loop:

It's basically Repetition of one or more set of instructions (commands).

For Loop:



Both of the above programs give same output.

Friday 2 November 2012

Basics

Comments:  Comments are for Programmer, he writes it in order to make his code understandable (since the code becomes complex often). C++ Compiler Ignores comments.
//Write the comment after two consective forward slashes (if your coomment is in single line)
/*Comments are written
in this way when they
occupy more than 1 line in C++ Compiler.*/


Output:

cout<<"Write here (within the inverted commas)whatever you want to see on the Screen when your Program Runs.";


cout<<"Write here whatever you want to see on the Screen when your Program Runs. "<< a; /*Prints the sentence within inverted commas as it is and then Prints the value stored in variable 'a'.*/
Usefull things for output:





Example:cout<<"\n\t I love \n\n";



Input: Prompts user to Enter Data.

cin>>Variable_Name;
Data can be entered in more than one variable:
cin>>first>>SeCond>>fifth;
(When your Program Runs) User enters something and Presses ENTER or SPACEBAR, whatever he writes before pressing Enter will be stored in variable named 'first'. User will again be prompted, he enters something and presses ENTER or SPACEBAR, that will be stored in variable named 'SeCond'. Similarly in variable fifth, the third value entered by the user will be stored.
NOTE: C++ is very strict in its CaSE  ==> 'You' & 'you' are two different variables.


Setw: Specify Number of Spaces.

In order to use this feature of C++, you'll have to include a header file in the beginning of your program source code.
#include<iomanip>
Then with in the program you can use Setw anywhere.

cout<<"I want"<<setw(20)<<"$";Note: $ sign is mixed with "Press any..."




How to seperate dollar sign from mixing to rest of line?
Simple, cout<<"I want"<<setw(20)<<"$\n\n";




This command needs small extra practice.


Setprecision: How many digits should appear after point (.) .

Also see the output by replacing fixed with scientific to know the difference.