Sunday 27 April 2014

Data Types in C++




While doing programming in any computer programming language, we need to use various variables in order to store various data. Variables are nothing butspecially reserved memory locations which stores differentvalues. It means that when we create a variable we actually reserve some space in memory.

We may even like to store information of various data types like character, Boolean, wide character, floating point, integer, double floating point etc. It is based on the data type of a specific variable, the operating system allocates specified memory and decides on what can be stored in that reserved memory.

Here is the list of data types used in C++ language programming along with their range and Bit Width

Type
Typical Range
Typical Bit Width
char
-127 to 127 or 0 to 255
1byte
unsigned char
0 to 255
1byte
signed char
-127 to 127
1byte
int
-2147483648 to 2147483647
4bytes
unsigned int
0 to 4294967295
4bytes
signed int
-2147483648 to 2147483647
4bytes
short int
-32768 to 32767
2bytes
unsigned short int
0 to 65,535
Range
signed short int
-32768 to 32767
Range
long int
-2,147,483,647 to 2,147,483,647
4bytes
signed long int
same as long int
4bytes
unsigned long int
0 to 4,294,967,295
4bytes
float
+/- 3.4e +/- 38 (~7 digits)
4bytes
double
+/- 1.7e +/- 308 (~15 digits)
8bytes
long double
+/- 1.7e +/- 308 (~15 digits)
8bytes
wchar_t
1 wide character
2 or 4 bytes


Saturday 26 April 2014

STRUCTURE OF C++ LANGUAGE PROGRAM



The best way to under the structure of a program is by using an small and simple example.

Input:

// first program in C++ 

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

 cout << "Hello World!"; 
 return 0; 
}

Output:

Hello World!  

Lets study each step in detail:

// my first program in C++ 

All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program

#include <iostream>

Hash sign (#) are directives for the preprocessor. The directive #include <iostream> tells the preprocessor to include the iostream standard file.
using namespace std;  It uses the standard library, and in fact it will be included in most of the source codes.

int main ()  This line corresponds to the beginning of the definition of the main function. The main function is the pointby where all C++ programs start their execution

cout << "Hello World!";
cout represents the standard output stream in C++

return 0;
The return statement causes the main function to finish.

Friday 25 April 2014

C++ LANGUAGE: INTRODUCTION



C++ is a general purpose language used for programming that is free-form as well as compiled. C++ is regarded as intermediate level language that is it comprises of both, high-level as well as low-level language features. It provides object oriented, imperative and generic programming features in its programs.

C++ is also standardized by quality check organization the International Organization for Standardization (ISO). C++ was initiated in 1979 by Bjarne Stroustrup working at Bell Labs. Originally it was named as "C with Classes" but in the year 1983, it was renamed to C++ due to its object oriented programming which was an enhancement to C language programming and hence the increment operator was added to C and it became C++ (pronounced as see plus plus).
Philosophies for developing C++:

• It should be driven by actual problems and the features should be useful immediately in real world programs.
• Every feature should be easily implementable.
• Programmers should be completely free to pick their own program style and that style should be supported by C++.
• Allowing useful feature is of utmost importance rather than preventing possible misuse of C++.
• Making user created types should have equal support and performance as that of built in types.
• Any features which you do not use, you never pay for.
• No language beneath C++


Thursday 24 April 2014

IMPORTATNT PROGRAMS OF C LANGUAGE





C language programming is considered to be the basic s of any programming language. so any developer or programmer is assumed to know some basic of C language programming. When we face any interview, the chances are quite high that the interviewer will ask some basic programs of C language because apart from programming skills, it also checks the problem solving skills of an individual.

So here are few important C language programs which are frequently asked in many interviews.

1. FIBONACCI SERIES

/* Fibonacci Series in C language */

#include<stdio.h>  /* header file */

int main()  /*initiate program*/
{
   int n, first = 0, second = 1, next, c;

   printf("Enter the number of terms\n");
   scanf("%d",&n); /*input number*/

   printf("First %d terms of Fibonacci series are :-\n",n);

   for ( c = 0 ; c < n ; c++ ) /*initiate loop*/
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d\n",next);
   }

   return 0;  /*display output*/
}




2. PALINDROME

#include <stdio.h>
#include <string.h>

int main()
{
   char a[100], b[100];

   printf("Enter the string to check if it is a palindrome\n");
   gets(a);

   strcpy(b,a);
   strrev(b);

   if( strcmp(a,b) == 0 )
      printf("Entered string is a palindrome.\n");
   else
      printf("Entered string is not a palindrome.\n");

   return 0;
}


3. ARMSTRONG NUMBER

#include <stdio.h>

int main()
{
   int number, sum = 0, temp, remainder;

   printf("Enter an integer\n");
   scanf("%d",&number);

   temp = number;

   while( temp != 0 )
   {
      remainder = temp%10;
      sum = sum + remainder*remainder*remainder;
      temp = temp/10;
   }

   if ( number == sum )
      printf("Entered number is an armstrong number.\n");
   else
      printf("Entered number is not an armstrong number.\n");

   return 0;
}


4. FACTORIAL OF A NUMBER

#include <stdio.h>

int main()
{
  int c, n, fact = 1;

  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &n);

  for (c = 1; c <= n; c++)
    fact = fact * c;

  printf("Factorial of %d = %d\n", n, fact);

  return 0;
}


5. PRIME NUMBER OF A NUMBER

#include<stdio.h>

int main()
{
   int n, i = 3, count, c;

   printf("Enter the number of prime numbers required\n");
   scanf("%d",&n);

   if ( n >= 1 )
   {
      printf("First %d prime numbers are :\n",n);
      printf("2\n");
   }

   for ( count = 2 ; count <= n ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }
      if ( c == i )
      {
         printf("%d\n",i);
         count++;
      }
      i++;
   }

   return 0;
}

Wednesday 23 April 2014

HEADERS IN C LANGUAGE




A header file is a file with extension .h which contains C function declarations and macro definitions and to be shared between many several source files. There are two kinds of header files: the files that the programmer writes and the files that come with your compiler.
You request the use of a header file in your program by including it, with the C preprocessing directive #include like you must have seen inclusion of stdio.h header file as wll which comes along with the compiler.

Including a header file is equivalent to copying of the content of the header file but we do not do it because it will be very much error-prone and it is not a good idea to copy the content of header file into the source files, especially if there are multiple source file comprising our program.
In a simple practice program in C language, the place where we keep all the macros, constants, system wide global variables and function prototypes in the header files and include that header file wherever it is required.

SYNTAX:

Both user and system header files are included using the preprocessing directive #include. It has following two forms:

#include <abc>
This form of header is used in system header files. In this, it searches for a file named "abc" in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code.

#include "abc"
This form of header file is used in your own programs .In this header, it searches for a file named abc in the directory containing the current file. You can also prepend directories to this list with the -I option while compiling your source code.

Monday 21 April 2014

SCOPE OF VARIABLE IN C LANGUAGE




SCOPE: A scope in any programming language is the region of that program where this defined variables can have their own existence and beyond this scope of a particular variable, that variable can't be accessed.
What is  Local Variable?
Variable whose existence is known only to the main program or functions are called local variables. Local variables are declared within the main program or a function.
Syntax
auto data_type identifier

What is The Scope of Local Variables?
Local variables have a scope inside the function it is declared and not outside it.

What is Lifetime?
The time period for which a variable exists in the memory is known as lifetime of variable.

What is Lifetime of Local Variable?
Lifetime of a local variables starts the moment when programmer enters the function inside  which the variable is declared and gets destroyed when programmer exists from the function.

What is Global Variable?
Variables whose existence is known to the both main() as well as other functions are called global variables. Global variables are declared outside the main() and other functions.
What is The Scope of Global Variable?
Global variables as the name says can be accessed from any part of a program and can be used in multiple functions. for this, the variables are defined before the "main" function

What is The Lifetime of Global Variable?
Global variables are bound to exist in the memory for as long as the program is in running state. These variables get are destroyed as soon as the program terminates. These variables occupy memory for a longer duration in comparison with than local variables.

INPUT/OUTPUT FILES IN C LANUGAGE




In C programming, when the program is closed, all the data and results are lost. In order to keep that enormous amount of data safe from getting deleted and used for future purpose, we need to form files to save those data into secondary memory. For these, different commands were needed to solve our purpose of creating, editing and closing of a file.
There are a lot of functions in C language for handling of input and output of a file. Here we’ll show you some of important commands for you to increase your understanding with C language programming.
High level file I/O functions can be divided into 2 categories as:
1. Text file
2. Binary file
File Operations

1. Create a new file
2. Open an existing file
3. Read from and write information to a file
4. Close a file
Working with file
To working with a file, we need to declare pointer of that type of file. This declaration is required to communicate between a file and a program.
FILE *ptr;
Opening a file
In C language, a file is opened using a library function fopen().
The syntax used for opening a file in standard I/O is:
ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprog\file.txt","w");

Here, E:\\cprog\file.txt is the location where file is to be created while "w" represents the mode for writing.
Here, the program.txt file is opened for writing mode.


File Mode
Meaning of Mode
During Inexistence of that file
r
Open for reading
fopen() returns NULL
w
Open for writing
File will be created
a
Open for edit/append
File will be created
r+
Open for both reading and writing
fopen() returns NULL
w+
Open for both reading and writing
File will be created
a+
Open for both reading and appending
File will be created


Close a File
A file is to be closed after reading or writing of a file. To close a file, a library function fclose() is used.
fclose(ptr);
Here, ptr is a file pointer which is used to associate the program with the file to be closed.

The Functions fprintf() and fscanf()
The functions of fprintf() and fscanf() is same as that of printf() and scanf(). The difference lies between them is that fprintf() and fscanf() are used to refer to a particular file.
Writing to a file
Here is an example of writing a file:
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\prog.txt","w");
if(fptr==NULL)
{
printf("Error!");  
exit(1);            
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
In this program it takes a number from user and stores it into a file. After the program is compile and run, we will see can a text file prog.txt created in C drive of our computer. When we will open that file, we’ll see the integer we entered.
Similarly, fscanf() function is used to read data from a file.
Reading from file
Example of file reading

#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   if ((fptr=fopen("C:\\program.txt","r"))==NULL)
   {
       printf("Error! opening file");
       exit(1);    
   }
   fscanf(fptr,"%d",&n);
   printf("Value of n=%d",n);
   fclose(fptr);  
   return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.

Friday 18 April 2014

POINTERS IN C LANGUAGE




Pointers, as the name says points towards a memory location. This not only gives great flexibility and power to programmers in creating a program, but it also one of the great hurdles that the beginner must overcome in using the language.
All variables in a program will reside in memory; the statements
    float x;
    x = 6.5;
request that the compiler reserve 4 bytes of memory (on a 32-bit computer) for the floating-point variable x, then put the ``value'' 6.5 in it.
There are times when we wish to know that where a variable resides in the memory. The address (location in memory) of any variable is obtained by placing the operator ``&'' before its name. Hence address of x is &x. C programming allow us to go a step further and defines a variable better known as a pointer, which contains the address of other variables. This can be seen in following example:
    float x;
    float* px;

    x = 6.5;
    px = &x;
defines px to be a pointer objects of type float and it sets equal to the address of x:




Pointer use for a variable

The content of the memory location referenced by a pointer is obtained using the ``*'' operator (this is called dereferencing the pointer). Thus, *px refers to the value of x.
C allows us to perform arithmetic operations using pointers, but beware that the ``unit'' in pointer arithmetic is the size (in bytes) of the object to which the pointer points. Let’s take an example, if px is a pointer to a variable x of typefloat, then the expression px + 1 refers not to the next bit or byte in memory but to the location of the next float after x (4 bytes away on most workstations); if x were of type double, then px + 1 would refer to a location 8 bytes away, and so on. Only if x is of type char will px + 1 actually refer to the next byte in memory.
Thus, in
    char* pc;
    float* px;
    float x;

    x = 6.5;
    px = &x;
    pc = (char*) px;
(the (char*) in the last line is a ``cast'', which converts one data type to another), px and pc both point to the same location in memory--the address of x--but px + 1 and pc + 1 point to different memory locations.
Consider the following simple code.


void main()
{
    float x, y;    /* x and y are of float type      */
    float *fp, *fp2;   /* fp and fp2 are pointers to float  */

    x = 6.5;    /* x will now contain value 6.5      */

     /* print contents and address of x   */
    printf("Value of x is %f, address of x %ld\n", x, &x);

    fp = &x;    /* fp now points to location of x    */
  
     /* the content of fp is printed      */
    printf("Value in memory location fp is %f\n", *fp);

     /* change content of memory location */
    *fp = 9.2;
    printf("New value of x is %f = %f \n", *fp, x);

     /* perform arithmetic               */
    *fp = *fp + 1.5;
    printf("Final value of x is %f = %f \n", *fp, x);

     /* transfer values                   */
    y = *fp;
    fp2 = fp;
    printf("Transfered value into y = %f and fp2 = %f \n", y, *fp2);
}


Thursday 17 April 2014

OPERATORS IN C PROGRAMMING





First of all let us know what an operator actually means? Well in layman term, an operator is a special symbol used on C programming which instructs compiler to specified mathematical or logical operation. Various operators are pre-defined in C language which proves to be useful for programmers in programming different software.
There are mainly 5 kinds of operators, namely:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators

Arithmetic Operator
This operator is used to most of the mathematical calculations in a c programming.
See the table given bellow to understand what arithmetic operators are:
(let A=30 and B=15)

Operator
Description
Example
+
Adds two operands
A+B will give 45
-
Subtracts operand
A-B will give15
*
Multiplies both operands
A*B will give 450
/
Divide operands
A/B will give 2
%
Modulus Operator
A%B will give 0
++
Increment
A++ will give 31
--
Decrement
B-- will give 14


Relational Operator
Relational operators are those symbols which are used to compare two or more operands. Examples of relational operator are equal to, less than, more than, more than or equal to, less than or equal to, not equal to etc.
We’ve already discussed about Relational Operator in our previous blog.
Click Here to See

Logical Operator
Logic operators work like logic gates that are OR gate, AND gate, NOT gate etc. They only work in case of binary code i.e. 1 or 0.
Here are logical operators used in C language programming.
(Let A=1 and B=0)

Operator
Description
Example
&&
AND operator
(A && B) gives False
||
OR Operator
(A || B) gives True
!
NOT Operator
A! gives False;
B! gives True

Bitwise Operator
Bit-wise operator first covert a number into its binary code and then operate upon it to give the result.
Following are the results of bitwise operation:

u
v
u&v
u|v
u^v
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1

These are bitwise operator:
(Let A=60 and B=13)
A= 00111100
B= 00001101

Operator
Description
Example
&
Binary AND gate
(A & B) will give 12, which is 00001100
|
Binary OR gate
(A | B) will give 61, which is 00111101
^
Binary XOR gate
(A ^ B) will give 49, which is 00110001
~
Binary Compliment
(~A ) will give -60, which is 11000011
<< 
Binary Left Shift Operator
A << 2 will give 240, which is 11110000
>> 
Binary Right Shift Operator
A >> 2 will give 15, which is 00001111

Assignment Operator

These operator perform following tasks in C language programming:

Operator
Description
Example
=

A+B=C, C will be  A+B
+=

C+=A, C will be  C+A
-=

C-=A, C will be  C-A
*=

C*=A, C will be  C*A
/=

C/=A, C will be  C/A
%=

C%=A, C will be  C%A
<<=

C<<=2, C will be C<<2
>>=

C>>=2, C will be  C>>2
&=

C&=2, C will be  C&2
^=

C^=2, C will be  C^2
|=

C|=2, C will be  C|2