Sunday, 18 September 2016

PROGRAMS OF C++



  • PROGRAM TO FIND THE SIZE OF DATA TYPES.
  • PROGRAM BASED ON INCREMENT / DECREMENT OPERATORS.
  • PROGRAM BASED ON SWAPPING.
  • WRITE A PROGRAM TO FIND THE SUM OF TWO NUMBERS.
  • WRITE A PROGRAM TO REVERSE A NUMBER WITHOUT USING ANY CASE .
  • WRITE A PROGRAM TO MULTIPLY 2 FLOATING NUMBERS.
  • WRITE A PROGRAM TO PRINT "HELLO WORLD" IN DOUBLE QUOTES.
  • WRITE A PROGRAM TO FIND SMALLEST NUMBER WITHOUT USING ANY CASE.
  • WRITE A PROGRAM TO FIND THE FACTORIAL OF A NUMBER.
  • PROGRAM TO FIND THE PERIMETER AND AREA OF RECTANGLE.
  • WRITE A PROGRAM TO FIND THE MULTIPLICATION TABLE OF ANY NUMBER.
  • WRITE A PROGRAM TO DISPLAY THE FOLLOWING OUTPUT USING A SINGLE COUT STATEMENT.                                                                                                                       subject              marks                                                                                                                        mathematics=       86                                                                                                                          physics        =        96                                                                                                                         chemistry   =         98
  • WRITE A PROGRAM WHICH ACCEPT TEMPERATURE IN FAHRENHEIT AND PRINT IN CENTIGRADES. 
  • WRITE A PROGRAM TO FIND THE SIMPLE INTEREST.
  • WRITE A PROGRAM WHICH ACCEPTS A CHARACTER AND PRINTS ITS ASCII VALUE.
  • WRITE A PROGRAM TO CHECK WHEATHER THE GIVEN NUMBER IS POSITIVE OR NEGATIVE.



   
* WRITE A PROGRAM TO FIND THE SIZE OF DATA TYPES.


#include<iostream.h>
#include<conio.h>
    void main()
{
 int a;
 float b;
 char c; 
 double d;
 short e;

    cout<<"size of integer is %d= " <<sizeof(a);    //we use %d for integer
    cout<<"size of float is %f ="<<sizeof(b);         //we use %f for float 
    cout<<"size of character is %c = "<<sizeof(c); //we use %c for character
    cout<<"size of double is %f "<<sizeof(d);      //we use %f for double
    cout<<"size of short is %d="<<sizeof(e);        //we use %d for short

getch();

}
SAMPLE OUTPUT
SIZE OF INTEGER IS =2
SIZE OF FLOAT IS =4
SIZE OF CHARACTER IS=1
SIZE OF DOUBLE IS =8
SIZE OF SHORT IS =2

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


*WRITE  PROGRAMS TO SHOW INCREMENT OF A NUMBER .

CASE 1:

#include<iostream.h>
#include<conio.h>
void main();
{
   int i,j;
   i=5;
   j=++i;
   cout<<j;
   cout<<"\n"<<i;

getch();

}

CASE 2:

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

    void main( )
{
   int i,j;
   i=5;
   j=i++;
  cout<<"\n"<<j;
  cout<<"\n"<<i;

getch();

CASE 3:

#include<iostream.h.
#include<conio.h>
   void main ()
{
  int i;
  i=5;
  i= ++i + ++i + i++;
  cout<<"\n"<<i;

getch();

}

CASE 4:

#include<iostream.h>
#include<conio.h>
 void main()
{
 int i;
 i=5;
 j=++i + i++ + ++i + i++;
 cout<<"\n"<<j;

 getch();

}

CASE 5:

#include<iostream.h>
#include<conio.h>
void main ()
{
 int i,j;
 i=2;
 j=5;
 i=j++ + --i + j-- + --i + i-- + j--;
 cout<<"\n"<<i;
 getch( );
}
========================================================================

*WRITE A PROGRAM TO SHOW SWAPPING OF NUMBERS.
  CASE 1:

#include<iostream.h>
#include<conio.h.
   void main ()
{
 int a,r;
 a=52;
 r=a/10;                   // value of a is divided by 10 
 cout<<"\n"<<r;
getch( )
}

CASE 2:

#include<iostream.h>
#include<conio.h>
 void main ()
{
  int n,s,r;                  //initialization
  n=123;
  s=0;
r=n%10
  n=n/10;                  //value of n is divided by 10
  s=s+r;       
  r=n%10;                // % symbol is called modulus it gives the remainder 
  s=s+r;
  n=n/10;
  s=s+n;
  cout<<"\n"<<s;   //this line represent the output  

getch();                 //getch means get the character which holds the screen and show the output

}
========================================================================

* WRITE A PROGRAM TO FIND THE SUM OF TWO NUMBERS .
#include<iostream.h>
#include<conio.h>
  void main ()
{
 int a, b, sum=0;     //initialization of variables
 cout<<"enter the value of a ";    //print statement 
 cin>>a;                                       //output statement 
 cout<<"enter the value of b ";
 cin>>b;
 sum=a+b;                                   //sum statement
 cout<<"\n sum is "<<sum;         //this line shows the sum of two numbers
getch();
}
=======================================================================
* WRITE A PROGRAM TO REVERSE NUMBER WITHOUT USING ANY CASE.
 #include<iostream.h>
# include<conio.h>
 void main ()
{
int n=521,s=0,r;
r=n%10;
  n=n/10;                  
  s=s*10+r 
  r=n%10;                
  s=s*10+r
  n=n/10   
  s=s*10+n;
getch();
}

SAMPLE OUTPUT
125
========================================================================

* WRITE A PROGRAM TO MULTIPLY TWO FLOATING NUMBERS

#include<iostream.h>
#include<conio.h.
 void main ()
{
double a,b,mul;
cout<<"\nenter the first number %f";
cin>>a;
cout<<"\n enter the second number%f";
cin>>b;
mul=a*b;
cout<<mul;
getch();
}

======================================================================= *WRITE A PROGRAM TO PRINT "HELLO WORLD IN DOUBLE QUOTES.

#include<iostream.h>
#include<conio.h>
void main ()
{
cout<<"\"hello world\"";
getch();
}

SAMPLE OUTPUT

"HELLO WORLD"
=======================================================================
*WRITE A PROGRAM TO FIND SMALLEST NUMBER WITHOUT USING ANY CASE.

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

int compare(int a,int b)
{
return(a+4<b)? a:b;
}

  int main ()
{
  cout<<"\nsmallest number is :"<<compare(11,12);
  cout<<"\n"smallest number is :"<<compare(55,88);
  cout<<"\n"smallest number is :"<<compare(100,89);

getch();
return0;
}

SAMPLE OUTPUT

SMALLEST NUMBER IS 11
SMALLEST NUMBER IS 55
SMALLEST NUMBER IS 89
======================================================================= *WRITE A PROGRAM TO FIND THE FACTORIAL OF A NUMBER .

#include<iostream.h>
#include<conio.h>
int factorial(int var)
{
int fact=1;
for(int i=1;i<=var;i++)
fact=fact*i;
return fact;
}

  int main()
{
 cout<<"\nfactorial of a number is :"<<factorail(7);
 getch();
 return 0;
}

SAMPLE OUTPUT

FACTORIAL IS 5040.
 =======================================================================
* WRITE A PROGRAM TO FIND THE PERIMETER AND AREA OF A RECTANGLE.

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

void main ()
{

clrscr();
int length,width ,perimeter ,area;        //Declaration
cout<<"length=\n";                             //prompt user
cin>>length;
cout<<"width=\n" ;
cin>>width;

perimeter=2*(length+width);            //formula to find the perimeter
area=length*width;                            //formula to find the area

cout<<endl;
       <<"perimeter is "<<perimeter;
cout<<endl;
       <<"area is "<<area;
        <<endl;
getch();
}
========================================================================
*WRITE A PROGRAM TO FIND THE MULTIPLICATION TABLE OF  A NUMBER.

#include<iostream.h>
#include<conio.h>
void main()
{
int n;
cout<<"enter the number";
cin>>n;
for(int  i=1;i<=10;i++)
{
cout<<n<<" * "<<i<<"="<<n*i<<endl;
}
getch();
}
========================================================================
*  WRITE A PROGRAM TO DISPLAY THE FOLLOWING OUTPUT USING A SINGLE COUT STATEMENT.                                                                                                                                   subject              marks                                                                                                                               mathematics       86                                                                                                                                    physics                96                                                                                                                                   chemistry            98
#include<iostream.h>
#include<conio.h>
void main ()
{
clrscr();
cout<<"subject"<<"\marks"<<"mathematics\n"<<86<<"physics\n"<<96<<"chemistry\n"<<98;
getch();
}

SAMPLE OUTPUT
SUBJECT                MARKS
MATHEMATICS     86
PHYSICS                  96 
CHEMISTRY             98
========================================================================
*WRITE A PROGRAM WHICH ACCEPT TEMPERATURE IN FAHRENHEIT AND PRINT IN CENTIGRADES.

#include<iostream.h>
#include<conio.h>
void main()
{
int f,c;
cout<<"enter the temperature in fahrenheit";
cin>>f;

c=5*(f-39)/9;                    //formula which is converting the temperature 

cout<<"temperature in celcius is ";
cin>>c;

getch();
}
========================================================================
*WRITE A PROGRAM TO FIND THE SIMPLE INTEREST.

#include<iostream.h>
#include<conio.h>
void main ()
{
int p,r,t,s;
cout<<"enter the principal ";      // user input
cin>>p;                                        //the values

cout<<"enter the rate ";
cin>>r;

cout<<"enter the time";
cin>>t;

s=(p*r*t)/100;       //formula to find the simple interest

cout<<"simple interest is "<<s;

getch();
}
========================================================================
*WRITE A PROGRAM WHICH ACCEPTS A CHARACTER AND PRINTS ITS ASCII VALUE

#include<iostream.h>
#include<conio.h>
int main ()                 //int means it returns a value otherwise it shows an error.
{

char ch;

cout<<"enter any character ";
cin>>ch;

cout<<"its ASCII value is" <<(int)ch;        

return 0;
getch();
}
========================================================================
*WRITE A PROGRAM TO CHECK WHEATHER THE GIVEN NUMBER IS POSITIVE OR NEGATIVE.

#include<iostream.h>
#include<conio.h>
void main()
{
int n;

cout<<"enter the number ";
cin>>a;

(a>0)?cout<<"the number is positive ":cout<<"the number is negative";  //using ternary operator

getch();
}
========================================================================


Saturday, 3 September 2016

characteristics of an array


  • ARRAY TERMINOLOGY
  • CHARACTERISTICS OF AN ARRAY 
 

                                               ARRAY TERMINOLOGY

SIZE : Number of elements or capacity to store elements in an array is called its size . It is always                    mentioned in brackets([ ]).


TYPE: Types refer to data type.It decides which type of element is stored in the array .It also instructs              the compiler to reserve memory according to data type .

BASE: The address of the first element (0th) is a base address . The array name itself stores address                of the first  element.

INDEX: The array name is used to refer to the array element. For example , num[x] , num is array                       name and x is index.The value of x begins from 0 to onwards depending on the size of the                   array .The index value is always an integer .

RANGE: Index of an array i.e value of x varies from lower bound to upper bound while writing or                     reading elements from an array . For example  in  num[100]  the range of index is 0 to 99.

WORD: It includes the space required for an element. in each memory location,computer can store a                  data piece.The space occupation varies from machine to machine.If the size of element is                     more than word (one byte) then it occupies two successive locations.The variables of data                    type  int,float,long need more than one byte in memory.

                                  CHARACTERISTICS OF AN ARRAY

  1. The declaration int a[5]  is nothing but creation of five variables of integer type in memory instead of declaring five variables for five values, the programmer can define them in an array .
  2. All the elements of an array share the same name,and they are distinguished from one another with the help of the element number.
  3. The element number in an array play a major role for calling each element.
  4. Any particular element of an array can be modified separately without disturbing the other elements.
                    int a[5]={1,2,3,4,8};
            If a programmer needs to replace  8 with 10,then it need not require changing all other                         numbers except 8.To carry out this task the statement  a[4]=10 can be used. Here,other four               elements are not disturbed.

      5. Any element of an array  a[ ]  can be assigned/equated to another ordinary variable or array                 variable of its type.
   

  EXAMPLE:
   
       b=a[2];
      a[2]=a[3];
  •   In the statement   b=a[2]  or vice versa,the value of a[2]  is asigned to 'b',where 'b' is an integer.
  • In the statement  a[2]=a[3]or vice versa ,the value of a[2] is assigned to  a[3],where both the elements are of the same array .
  • The array elements are stored in continuous memory locations.
     6. Array elements are stored in contigious memory locations.
 
     7. Once the arrays is declared,its lowest boundary cannot be changed but upper boundary can be               expanded .The array name itself is  a constant pointer and we cannot modify it.Therefor, the                 lowest boundary of an array cannot be expanded.In other words ,even if the boundary exceeds             then specified,nothing happens.the compiler throws no errors. 
     8. We know that an array name itself is a pointer . Though it is a pointer , it does not need '*'                    operator.The brackets([ ]) automatically denote that the variable is a pointer.
     9. All the elements of an array share the same name, and they are distinguished from one another            with the help of the element number.
   10. The amount of memory required for an array depends upon the data type and the number of                elements.The total size in bytes for a single dimensional array is computed as shown below:
               total bytes=sizeof(data type)  x size of array 
   11. The  operation such as insertion,deletion of an element can be done with the list  but cannot be            done with an array .Once an array is created we cannot remove or insert memory location. An              element can be deleted,replaced but the memory location as it is.

Friday, 2 September 2016

Initialization of Array

                              INITIALIZATION OF ARRAY 

The array initialization can be done as under:

int a[5]={1,2,3,4,5};

Here 5 elements are stored in an array 'a'. List of elements initialized is shown within the braces.The elements are stored sequentially in separate locations.Then the question arises how to call individually to each element from this bunch of integer elements.

Reading of element begins from '0'.By indicating the position of elements, one can retrieve element of an array.Array elements are called with array names.

a[0] refers to 1st element i.e 1.
a[1] refers to 2nd element i.e 2.
a[2] refers to 3rd element i.e 3.
a[3] refers to 4th element i.e 4.
a[4] refers to 5th element i.e 5.

EXAMPLE:

To store more than one value the programming languages have an built data structure called an array .

  1.  int num[5] ;
          In the above declaration.an integer array of five elements is declared .Memories for five                       integers,i.e. successive 10 bytes ,are reserved for the num array.To initialize the num array                   following syntax can be used.



      2. int num[5] = {1,2,4,2,5};

          In the above statement ,all elements are initialized .It is also possible to initialize individual                 element by specifying the subscript number in the square bracket following the array name.
          Array elements are accessed as follows:

              num[0]=1;
              num[1]=2;
              num[2]=4;
              num[3]=2;
              num[4]=5;

The initialization can be done at the compile time or dynamic at the run time .The above is an example of compile time initialization./

In the above array, the element num[0]  i.e 1 is the lowest bound and num[4] i.e 5 is the last element .In c and c++ ,there is no  bound checking .Hence the programmer has to check it while accessing or storing elements.Once   the array is declared , its lowest bound cannot be changed but the upper bound can be expanded.The array name itself is a constant pointe,and therefore we cannot modify it. Storing elements in contigious memory locations can expand the upper bound.  


The array name itself is a pointer .The array num  is pointer to the first element i.e  num cotains address of memory locations where element 1 is stored .The address stored in the array name is called the base address .



To access individual elements,the following syntax is used:

num[0] refers to the 1

num[1] refers to the 2


num[2] refers to the 4


num[3] refers to the 2


num[4] refers to the 5


Thus, an array is a colection of elements of the same data type ,stored in unique and successive memory location.



Monday, 29 August 2016

Introduction of Array


                                                 INTRODUCTION OF ARRAYS 

An array is a very popular and useful data structure used to store data elements in successive memory locations. More than one element is stored ia an sequence ,so it is also called a composite data structure.
An array is a linear and homogeneous data structure . An array permits homogeneous data.It means that similar types of elements are stored contiguously in the memory and that too under one variable name.It can be combined with a non-homogeneous structure, and a complex data structure can be created. We know that an array of structure objects can also be useful.An array can be declared of any standard or custom data type .The array of character (strings) type works somewhat differently from an array of integers,floating numbers.
Consider the following example .A variable A having data type integer is initially assigned some value and later on its value is changed .Later assigned value to the variable can be displayed.

void main ()
{
   int a=2;
    a=4;
   cout<<a;
}

OUTPUT =4
 
In the above example , the value of A printed is 4. 2 is assigned to A before assigning 4 to it .When we assign 4 to A then the value stored in A is replaced with the new value .Hence,ordinary variables are capable of storing one value at a time.This fact is the same for all the data types.This can be obtained with the help of arrays.
An array variable allows the storing of more similar data type element /values at a time .
Declaration of a one-dimensional array can be done with data type first, followed by the variable name and at least the size is enclosed in square brackets.
int a[5] ;
It tells the compiler that A is an integer type of an array and can store five integers.The compiler reserves 2 bytes of memory for each integer array element, i.e 10 bytes are reserved for storing five integers in the memory .
In the same way,an array of different data types is declared as follows:

char ch[10];
float real[10];
long num [5];
 When we declare a variable , for example:
int x;
 the variable x is declared and the memory locations of two bytes is allocated to them and later a single value can be stored in it.
x=4;
Every variable has a name ,a value its memory locations.Hence from the above we can say that only one value can be assigned /stored to a variable

  • An array is a group of contiguous or related data items that share a common name.
  • used when programs have to handle large amount of data 
  • each value is stored at a specific position 
  • position is called a index or superscript.Base index=0
  • The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs .For example ,a loop  with index as the control variable can be used to read the entire array , perform calculations, and print out the results.

Sunday, 14 August 2016

Looping in c++

A loop is defined as a block of statement ,which are execute for a certain no. of times in a repititive manner.the loops are of two type where,

  1. Definite loop =In which the block of statement are executive according to the counter control repitition .
  2. Indefinite loop= In which the program is executive in such a way where the total number of iteration cannot be calculated 

A sequence of statement is executed until a specified condition is true.This sequence of statement to be executed is kept inside the curly braces {} known as loop body.After every execution of loop body,condition is checked ,and if it is found to be true the loop body is executed again,  when condition check comes out to be false,the loop body will not be executed .

                                      THERE ARE THREE TYPES OF LOOPS IN C++


  1. WHILE LOOP
  2. DO-WHILE LOOP
  3. FOR LOOP
  4. NESTED FOR LOOPS
WHILE LOOP

The while loop is frequently used in programs for the repeated execution of statement in a loop .Until a certain  condition is satisfied the loops statement are executed ,while loop is also known as entry control loop,because it only execute the statement if the test condition is true ,so if the condition is false the compiler will not enter in the body of while loop and does not execute its statement.

SYNTAX:

{
Initialization of variable
while(condition)
{
body of while loop
increment/decrement counter
}
}

 EXAMPLE:

void main()
{
int x=1;
while(x<10)
{
cout<<"value is ":<<x;
x++;
}
}

                                                     DO-WHILE LOOP

The do -while loop is also known as exit control loop.,which me ans that the body of the loop is executing atleast once even if the test condition is false because the test condition is given at the ending of the loop.The test condition is tested for the next time to execute the loop .The basic
difference between while and do while is that while loop is executed only if the test condition is true whereas do-while executes atleast once as we check the test condition at the end which desire the re-entry (only if it is true)inside the loop.


SYNTAX:

void main()
{
initialization variable;
do
{
body ;
increment/decrement;
}
while(test condition)
}


EXAMPLE:

void main()
{
int x=1;
do
{
cout<<"value is :"<<x;
x++;
while(x<10)
}
getch();
}


                                                             FOR LOOP

FOR loop allow to execute a set of instructions until a certain conditions is  satisfied . Condition may be predefined or open-ended.The general syntax of the FOR loop will be as given below.

explanation:
the FOR statement contains three expressions which are separated by semicolons.Following actions are to be performed in the three expressions.

SYNTAX:
for(initialize counter;test condition ; re-evaluation parameter)
{
     statement 1;
     statement 2;
}




  1. The initialize counter sets to an initial value. This statement  is executed only once.
  2. The test condition is a relational expression that determines the number of iterations desired or determine when to exit from the loop . The FOR loop continuous to execute as long as conditional test is satisfied .When the condition becomes false the control of the loop program exists from the body of the  FOR  loop and executes next statement after the body of the loop.
  3. The re-evaluation parameter decided how to make changes in the loop (increment or decrement operations are to be used quite often).
  4. The body of the loop may contain either a single statement or multiple statement s.In case, there is only one statement after the FOR loop, braces may not be necessary .In such a case ,only one statement is executed till the condition is satisfied .It is good practice to use braces even for single statement following the for loops.
EXAMPLE :

   void main ()
{
  int i;

  clrscr ( );
 
  for(int i=1;i<=5;i++)

  cout<<"number: ",i,i*i);
}

                                                       NESTED FOR LOOPS

We can also use loop within loops ,In nested  FOR loops one or more FOR statements are included in the body of the loop . In other words c++ allows multiple FOR loops in nested forms.The numbers of iterations in this type of structure will be equal to the number of iteration in the outer loop multiplied by the number of iteration in the inner loop . Given below examples are based on the nested FOR loops.

EXAMPLE:

Write a program to perform subtraction of two loop variables.use nested for loop.

void main()
{
      ina a,b,sub;
     clrscr();
 
       for(a=3;a>=1;a--)
  {
        for(b=1;b<=2;b++)
     {
        sub=a-b;
       cout<<"a=%d a-b= %d"<<a,b,sub;
     }
  }

}


what is c++

                                                       WHAT IS C++

C++ is an object-oriented programming language . It was developed by Bjarne stroustrup at AT&T Bell Laboratories in murray hill , New jersey,USA in the early 1980's stroustrup ,an admirer of simula67 and a strong supporter of C, wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of c , The result was C++ . therefore,c++ is an extension of c with a major addition of the class construct feature of simula67,Since the class was a major addition to the original C language,'C with classes'However later in 1983,the name was changed to c++.The idea of c++ comes from the C increment operator ++, thereby suggesting that c++ is an augmented (incremented)version of c.

During the early 1990's the language underwent a number of improvements and changes.In November 1997, the ANSI/ISO standards committee standardised these changes and added several new features to the language specifications.

C++ is a superset of C, Most of what we already know about c applies to c++ also therefore, almost all C programs are also  c++ programs .However there are a few minor differences that will prevent a c program to run under c++ compiler, we shall see these differences later as and when they are encountered .

The most important facilities that c++  adds on to c are classes,inheritance,function overloading ,and operator overloading.These features enable creating of abstract data types,inherit properties from existing data types and support  polymorphism,thereby making c++ a truly object-oriented language.

The object-oriented features in c++ allow programmers to build large programs with clarity,extensibility and ease of maintenance,incorporating the spirit and efficiency of C. the addition of new features has transformed C from a language that currently facilitates top-down , structured design, to one that provides bottom-up,object oriented design.


                                               APPLICATION OF C+ +

C++ is a versatile language for handling very large programs.It is suitable for virtually any programming task including development of editors,compilers, databases,communication system and any complex real-life application system.

  • Since c++ allows us to create hierarchy -related objects ,We can build special object-oriented libraries which ca n be used later by many programmers.
  • While c++ is able tp map the real world problem property,the C part of C++ gives the language the ability to get close to the machine -level details.
  • C++ programs are easily maintainable and expandable .When a new feature needs to be implemented ,it is very easy to add to the existing structure of an object.
  • It is expected that C++ will replace C as a general-purpose language in the near future.


                                        A SIMPLE C++ PROGRAM

#include<iostream>          // include header file
using namespaces std ;
int main ()
{

cout<<"c++ is better than c"; // c++ statement
return 0;

}           // end of example 

Expressions and their types

                                          EXPRESSION AND THEIR TYPES

An expression is a combination of operators, constants and variables arranged as per the rules of the language.It may also include functions calls which return values.An expression may consist of one or more operands , and zero or more operators to produce a value. expressions may be of the following seven types.


  • Constant expressions 
  • Integral expressions 
  • Float expressions
  • pointer expressions
  • Relational expressions
  • Logical expressions
  • Bitwise expressions
An expression may also use combination of the above expression . Such expression are known as compound expressions.


CONSTANT EXPRESSIONS

CONSTANT expressions consist of only constant values. EXAMPLE:

15

20+5/2.0

'X'


INTEGRAL EXPRESSIONS 

integral expressions are those which produce integer results after implementing all the automatic and explicit type conversions . EXAMPLE :

m

m*n-5

m*'X'

5+ int(2.0)
where m and n are integer variables.

FLOAT EXPRESSIONS

Float expressions are those which,after all conversions, produce floating-point results.
EXAMPLE:

x+y

x*y /10

5 + float(10)

10.75

where x and y are floating-point variables.

POINTER EXPRESSIONS 

Pointer expressions produce address values.example:

&m

ptr

ptr +1

"xyz"
where x is a variable and ptr is a pointer.

RELATIONAL EXPRESSIONS 

Relational expressions yield results of type bool which takes a value true or false. Examples:

x<=y

a+b == c+d

m+n>100

When arithmetic expressions are used on either side of a relational operator,they will be evaluated first and then the results compared . Relational expressions are also known as BOOLEAN EXPRESSIONS .

LOGICAL EXPRESSIONS

Logical expressions combine two or more relational expressions and produces bool type results. Examples:

a>b &&x==10

x==10|| y==5

BITWISE EXPRESSIONS

Bitwise expressions are used to manipulate data at bit level.They are basically used for testing or shifting bits .Examples:

x<<3 // shift three bit position to left
y>>1 // shift one bit position to right

Shift operators are often used for multiplication and division by power of two.

ANSI c++ has introduced what are termed as operator keyword that can be used as alternative representation for operator symbols . 

Saturday, 13 August 2016

Decision making statements in c++

                                     DECISION MAKING STATEMENTS IN C++

The decision making statement in a programming language help the programmer to transfer the control from one part to another part of the program and thus controls the flow of program execution in c++. we are having different types of decision making statement such as .


  1. if statement 
  2. if-else statement
  3. else-if statement  
  4. switch statement 
  5. Go-to statement
  • nesting of if -else statement
  • Break statement 
  • continuous statement 
                                                           IF STATEMENT

C++ use the keyword if to execute a set of a command of lines or one command line when the logical condition is true it means that the if block statement only execute when the condition is true and if condition is false than the control passes to the next statement after the if block .


SYNTAX:

               if(condition)
              statement 1;
                  OR
    if (condition)
{
 statement 1;
 statement 2;
}

EXAMPLE:

int a=2;
int b=3;
int c=4;

if(a<<b&&b<<c)
{
cout<<"helloo";
cout<<"exit";
}

                                                  IF-ELSE STATEMENT 

If the condition in if statement evaluates to true,then the specified set of statement block is executed ,otherwise the statement -block in the else block is executed. In other words,the if-else statements contains a set of statement-block for both the cases , either the condition evaluates to true or false , The syntax of the if  statement is as follows :-

SYNTAX:

if(condition)    
{                                     
   statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}     

EXAMPLE:

#include<iostream>
using namespace std ;
  void main()
{
int a=15,b=20;

if(b>a)
{
cout<<"b is greater "<<endl;
}
else
{
cout<<"a is greater "<<endl;
}
}

                                                   ELSE-IF STATEMENTS

What is the need of else-if statement when is-else has both the options i.e, Either the specified conditions evaluate to true or false,a corresponding set of statement block will be executed depending upon the condition status.But what if ,When we want to use multiple conditions with the if statement .For this , C++ provides an else-if block.

SYNTAX:

if(condition)
{
statement 1;
statement 2;
}
else if
statement 1;
statement 2;
}
else if 
{
statement 1;
statement 2;
}
else
{
statement 1;
}

EXAMPLE:

#include<iostream>
using namespace std ;
void main()
{
int a,b,c;
cout<<"enter the values ";
cin>>a>>b>>c;

if(a>b&&a>c)
{
cout<<"a is greater ";
}
else if (b>a&&b>c)
{
cout<<"b is greater ";
}
else
{
cout<<"c is greater ";
}
getch();
}

                                                    SWITCH STATEMENT

A switch statement allows a variable to be tested for quality against a list of values .Each value is called a case , and the variable being switched on is checked for each case .

SYNTAX:

Switch(variable)
{

case 1:  // execute your code 

break;

case n:  // execute your code 

break;

default:  //  execute your code 

break;


EXAMPLE:

#include<iostream>
using namespace std;
void main()
{
int a ;
cout<<"please enter a number between 1 and 5 :"<<endl;
cin>>a;
switch(a)
{
case 1:
cout<<"you chose one "<<endl;
cin>>a;

break;
case 2:
cout<<"you chose two"<<endl;

break;
case 3:

cout<<"you chose three "<<endl;

break;
case 4:

cout<<"yopu chose four "<<endl;
break;

case 5:

cout<<"you chose five "<<endl;
break;

default:

cout<<"invalid choice enter a number between  1 and 5"<<endl;
break;
}
     

                                                       GO-TO STATEMENT

t The go-to statement does not require only condition. This is an unconditional control jump which means that this statement passes control any where in the program . i.e control is transferred to another part of the program without any text condition.go-to is always associated with  a lab of which describes the position where the control is to be transferred.

SYNTAX:

 void main()
{
 statement 1;
 statement 2;
{
 statement 1;
 statement 2;
 go to 2;
}
 label 1;
 statement 1;
 statement 2;
 label 2:
 statement 1;
 statement 2;
 go to 1;
 statement 1;
 statement 2;
}

EXAMPLE:

void main()
{
int x;
cout<<"enter a number ";
cin>>x;
if(x%2==0)
go to even;
else
go to odd;
cout<<"even number:"<<x;
cout<<"odd number:"<<x;
}

                                                 
                                              NESTED IF-ELSE STATEMENT 

Nested if-else is used as a block or statement within the if else block. By using this we can have multiple if else statements.When we are having inner is else block than we first solve that ans then move on to outer if else block.

SYNTAX:

   if(expression)
{
     if(expression)
{
    statement-block 1;
}
else
{
    statement-block 2;
}

}
else
{
    statement-block 3;
}

if 'expression 'is false the' statement block-3' will be executed ,otherwise it continuous to perform the test for' expression 1' , if the 'expression 1' is true the 'statement block 1' is executed otherwise 'statement -block 2 'is executed


EXAMPLE:

void main()
{
int a,b,c;
clrscr();
cout<<"enter the 3 numbers of your choice ";
cin>>a>>b>>c;
    if(a>b)
{
      if(a>c)
{
  cout<<"a is greatest ";
}
else
{
    cout<<"c is greatest ";
 }
}
else
{
    if(b>c)
{
   cout<<"b is greatest";
}
else
{
  cout<<"c is greatest";
 }
}
   getch();
}


                                                         BREAK STATEMENT

The break statement is used to terminated the loop as it means that whenever we encounter a break statement in a loop than the control skips the remaining statements of the loop,and passes the control to the first statement after the loop 

  • no header file is indeed 
  • it is a keyword
  • it stops the execution of the loop
if(condition)
{
statement 1;
statement 2;
  
break;
}
statement 3;
   
                                                       CONTINUOUS STATEMENT 

Continuous statement is used to reenter in the loop which means that if we encounter continuous statement than the control skip the rest of the statement in the loop and takes the control to the text condition at the beginning of the loop and re enter in it.

if(condition)
{
   statement 1;
   statement 2;

continuous 
   statement 3;
}


Wednesday, 10 August 2016

Operators in c++

                                                            Operators In C++

Operators are special type of functions,that takes one or more argument and produces a new value. For example: addition(+) , subtraction (-), multiplication (*), etc,are all operators . Operators are used to perform various operations on variables and constants .




                                                         TYPES OF OPERATORS 


  1. Assignment operators
  2. Mathematical operators 
  3. Relational operators 
  4. Logical operators
  5. Bitwise operators 
  6. Shift operators
  7. Unary operators 
  8. Ternary operators 
  9. Comma operators




                                                      ASSIGNMENT OPERATORS

Operator "=" is used for assignment , it takes the right hand side (called rvalue) and copy it into the left -hand side (called lvalue). assignment operator is the only operator which can be overloaded but cannot be inherited .

 RESULT OF ASSIGNMENT OPERATORS:

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value these operators have right- to- left associativity . the left operand must be a modified l-value.

In ANSI C , the result of  an assignment expression is not an l-value . therefore ,the legal c++ expression (a+=b)+=c is illegal .

                                                    MATHEMATICAL OPERATORS

There are operators used to perform basic mathematical operations . Addition (+),subtraction(-),
division(/),multiplication(*) and modulus(%) are the basic mathematical operators.Modulus operator cannot be used with floating -point numbers.
C++ and C also use a shorthand notation to perform an operation and assignment at same type .Example,

int x=10 ;
x+=4          //will add 4 to 10 , and hence assign 14 to x.
x-=5           // will subtract 5 from 10 and assign 5 to x.

                                                   RELATIONAL OPERATORS 

A relational operators compares two operands to determine whether one is greater than ,greater than or equal to , less than, less than or equal to the other:
> greater than
< less than
>= greater than equal to
<= less than equal to
When used in an expression they all return a boolean value which states the result of the comparison (i.e, 4>3 can be read as is 4 greater than 3 ?which returns true )

EXAMPLE:

int x=12;     //assignment operator
x=5;           // again assignment operator
if(x==5)    // here we have used equivalent relational operator , for comparison
{
cout<< " successfully compared";
}

                                                 LOGICAL OPERATORS

The logical operators apply logic functions (NOT,AND, and inclusive OR) to boolean arguments (or types  contextually -convertible to bool),with a boolean result Unlike the bitwise logic operators ,these operators do not evaluate the second operand if the result is known after evaluating the first .
                                                                     OR
The logical operators are AND(&&) and OR(||). They are used to combine two different expression together .
If two statement are connected using AND operator, the validity of both statement will be considered,but if they are connected using OR operator, then either one of them must be valid.These operators are mostly used in loops and in decision making .

                                                 BITWISE OPERATORS

The bitwise operators performs bitwise -AND(&),bitwise-exclusive-OR(^),and bitwise -inclusive-OR(|) operations.
The operands of bitwise operators must have integral types, but their types can be different . These operators perform the usual arithmatic conversions:the type  of the result is the type of the operands after conversion .

                                                    SHIFT OPERATORS 

Shift operators are used to shift bits of any variable .ITis of three types

  1. Left  shift operator <<
  2. Right shift operator >>
  3. Unsigned right shift operator >>>
                                                    UNARY OPERATORS

A unary operator in c# is an operator that takes a single operand in an expression or a statement . The unary operators in c#  are +,-,!,~,++ and the  cast operator .
other unary operators : address of &,dereference *,new and delete,bitwise not ~,logical not !, unary minus -, and unary plus +.
                                                     TERNARY OPERATORS 

The ternary if-else ?: is an operator which has three operands .
int a=11;
a>6? cout<<"true":cout<<"false";

                                                      COMMA OPERATORS

This is used to separate variable names and to separate expression .In case of expression, the value of last expression is produced and used .

EXAMPLE:

int a,b,c;             //  variable declaration using comma operator
a=b++,c++          // a=c++  be done .

                                                         SIZE OF OPERATOR IN C ++

Sizeof is also an operator not a function , it is used to get information about the amount of memory allocated for data types & objects . It can be used to get size of user defined data types too.

sizeof operator can be used with and without parentheses. i you apply it to a variable you can use it without parentheses.

cout<<sizeof(double); // will print size of double
int x=2;
int i=sizeof x;

Saturday, 6 August 2016

What are variables

In this c++ programming tutorial we take a look at variables and data types.

Variables

If you declare a variable in c ++ ( later on we will talk about how to do this),you ask the operating system for a piece of memory . you (can) give this pieces of memory a name and you can store something in that piece of memory (for later use ).

The name of a variable is called an identifier .you can give a variable any  name you want ,as long as it is a valid identifier .

Valid identifier

a valid identifier is a sequence of one or more letters,digits or underscore and the identifier must begin with a letter.(it is not possible to start an identifier with a number.) It is also not possible to use punctuation marks, symbols and spaces in an identifier .compiler specific keywords or externals identifiers usually begin with an underscore.(it possible to use an underscore at the beginning of your identifier, but it is not recommended.) 

The c++ language is a "case sensitive " language .This means that an identifier with capital letters is not the same as with normal letters.

for example: mtrb,Mtrb,mtrB, mTRB are four different variable identifiers.

Basic types of variables

Each variable while declaration must be given a datatype,on which the memory assigned to the variable depends. following are the basic types of variables ,

  1. bool  for variable to store boolean values(true or false)
  2. char  for variables to store character types.
  3. int     for variable with integral values 
  4. float and double  are also types for variables with large and floating point  values .
Declaration of variables 

Variable must be declared before they are used .usually it is preferred to declare them at the starting of the program,but in c++ the can be declared in the middle of program too ,but must be done before using them .
                                                               OR
Declare a variable is very easy .first you have to declare the data type .after the data type you place the name of the variable .but remember choose the name wisely .It is easier if a variable name reflects the use of that variable.

EXAMPLE:
int i;    //declared but not initialized
char c;
int i,j,k ; // multiple declaration

initialization means assigning value to an already declared variable,it is possible to declare more than one variable at the same time .

int i; // declaration
i=13; // initialization

Signed and Unsigned variables

The difference between signed and unsigned variable is that signed variables can be either negative or positive but unsigned variables can only be positive .By using an unsigned variable you can increase the maximum positive range .When you declare a variable in the normal way it is automatically a signed variable .
To declare an unsigned variable you just put the word unsigned before your variable declaration or signed for a signed variable although there is no reason to declare a variable as signed since they already are .

why should i use an unsigned integer?

  • They are more efficient.
  • The signed integer can be negative .
  • You get a larger dynamic range.
  • You can safely perform shift operations.
  • modulus arithmetic is completely defined .
  • overflowing an unsigned data type is defined,whereas overflowing a signed integer type could result in world war 4 starting .       
              Initialization of  variables 

When declaring a regular local variable , its value is by default undetermined .It is possible to store a concrete value in a variable at the same moment that the variable is declared .If you do this you are initializing a variable.
This can be done in two ways:
  1. The first method is the c-like method :int a=0;
  2. The second method is known as the constructor initialization:int a(0);
Both ways of initialization are valid and equivalent in the c++ language.

EXAMPLE:
                           #include<iostream>
                        using namespace   std;
                             int main ()
                        {
                            int a=10;
                            int b(86);
                            int result;
                            a=a+4;
                            result=a-b;
                            cout<<result;
                            return 0;
                        } 
                                 
Scope of variables 

All the variables have their area of functioning , and out of that boundary they don't hold their value, this boundary is called scope of the  variable . For most of the cases its between the curly braces, in which variable is declared that a variable exists,not outside it. We will study the storage classes later, but as of now ,we can broadly divide variables into main types ,
  • GLOBAL VARIABLES
  • LOCAL VARIABLES
                                                   GLOBAL VARIABLES
Global variables are those , which are once declared and can be used throughout the lifetime of the program by any class or  any function . They must be declared outside the main() function . If only declared , they can be assigned different values at different time in program lifetime . But even if they are declared and initialized at the same time outside the main() function , then also they can be assigned any value at any point in the program.

EXAMPLE: only declared , not initialized
                      
      #include <iostream>
      using namespace std ;
      int x;       // GLOBAL VARIABLE DECLARED
      int main()
{
     x=11;     // INITIALIZED ONCE
     cout<<"first value of x="<<x; 
     x=21;     // INITIALIZED AGAIN
     cout<<"initialized again with value ="<<x;
}


                                                LOCAL VARIABLES

Local variables are the variables which exist only between the curly braces , in which its declared, outside that they are unavailable and leads to compile time error .

EXAMPLE:  
   #include<iostream>
  using namespace std ;
  int main()
{
      int i=12;
     if(i<22)  //IF CONDITION SCOPE STARTS 
{
     int n=233;   // LOCAL VARIABLE DECLARED AND INITIALIZED 
}      // IF CONDITION SCOPE ENDS 
    cout<<n;     //COMPILE TIME ERROR, N NOT AVAILABLE HERE 
}
                                             SOME SPECIAL TYPES OF VARIABLES 

There are also some special keywords , to impart unique characteristics to the variables in the program . following two are mostly used , we will discuss them in detail later.

  1. FINAL- once initialized, its value cant be changed.
  2. STATIC- These variables holds their value between function calls.
EXAMPLE: 

 #include<iostream.h>
using namespace std 
int main ()
{
final i=256;
satic y=351;
}
  
                                                                                                

Sunday, 31 July 2016

HOW TO START A PROGRAM ?

               DECLARATION AND INITIALIZATION


Variable must be declared before they are used .usually it is preferred to declare them at the starting of the program,but in C++ they can be declared in the middle of program too,must be done before using them .

EXAMPLE:
  
int i;               //declared but not initialized
char c;
int i, j, k; n                   //multiple declaration

initialization means assigning value to an already declared variable,

int i;                        //declaration
i=20;                // initialization

initialization and declaration can be done in one single step also,

int i=20;                    // initialization and declaration in same step
int=20, j=56;

if a variable is declared and not initialized by default it will hold a garbage value also,if a variable is once declared and if try to declare it again ,we will get a compile time error.

int i,j;
i=20;
j=56;
int j=i+j;     // compile time error,cannot redeclare a variable in same scope


PROGRAM TO FIND THE SIZE OF VARIOUS DATA TYPES

# include<iostream.h>
using namespace std;
int main()
{
    cout<<"size of char:"<<sizeof(char)<<endl;
    cout<<"size of int:"<<sizeof(int)<<endl;
    cout<<"size of short int:"<<sizeof(short int)<<endl;
    cout<<"size of  long int:"<<sizeof(long int)<<endl;
    cout<<"size of float:"<<sizeof(float)<<endl;
    cout<<"size of double:"<<sizeof(double)<<endl;
    cout<<"size of wchar_t:"<<sizeof(wchar_t)<<endl;
    return 0;
}

In this example :
1)       endl       = endl is use to insert a new line character after every line .
2) << operator= this is being used to pass multiple values out to the screen .
3)     sizeof       = this is used to get size of various data types.

*when you execute the above program you will get the following  result.
 size of char : 1
 size of  int : 4
 size of  short int : 2
 size of  long int : 4
 size of float : 4
 size of double : 8
 size of wchar_t : 4 

Data types in c++

DATA TYPES

A data type determines the type and the operations that can be performed on the data.They are used to define types of variables and contents used . Data type define the way you use storage in the programs you write.C++ provides various data types and each data type is represented differently within the computer's memory. the various data types provided by C++ are BUILT-IN data types,DERIVED data types and USER-DEFINED data types as shown in figure .




BUILT-IN DATA TYPES


The basic (fundamental) data types provided by c++ are integral,floating point and void data type.Among these data types, the integral and floating-point data types can be preceded by several type modifiers.These modifiers(also known as type qualifiers ) are the keywords that alter either size or range or both of the data types .The various modifiers are short ,long,signed and unsigned .By default the modifier is signed.
In addition to these basic data types ,ANSI C++ has introduced two more data types namely,bool and wchar_t.
                                                                    OR
THESE ARE THE DATA TYPES WHICH ARE PREDEFINED AND ARE WIRED DIRECTLY INTO THE COMPILER.eg: int,char etc.



Integral Data Type :The integral data type is used to store integers and includes char (character) and int (integer) data types.

CHAR:Character refer to the alphabet ,numbers and other, characters (such as {,@,#,etc) defined in the ASCII character set .In C++, the char data type is also treated as an integer data type as the characters are internally stored as integers that range in value from -128 to 127. The char data type occupies 1 byte of memory (that is, it holds only one character at a time ).

The modifiers that can precede char are signed and unsigned .The various character data type with their size and range are listed in above table.

INT:Numbers without the fractional part represent integer  data . In C++ , the int data  type is used to store integers such as 4,42,5233,-55,-759. Thus,it cannot store numbers such as 4.29,-586,-65.2579.The various integer data types with their size and range are listed below



FLOATING-POINT DATA TYPE:A floating -point data type is used to store real numbers such as 3.98,12.345,0.25,-45.85.This data type includes float and double' data types. The various floating-point data types with their size and range are listed below.



VOID:The void data type is used for specifying an empty parameter list to a function and return type for a function . When void is used to specify an empty parameter list,it indicates tha a function does not take any argument and when it is used as a return type for a function , it indicates that a function does not return any value .For void, no memory is allocated and hence, it cannot be used to declare simple variables, however, it can be  used to declare generic pointers.

BOOL AND WCHA_T: The bool data type can be held only boolean values,that is;either true or false, where true represents 1 and false represents 0. It requires only one bit of storage ,however,it is also considered as an integral data type .The bool data type is mostly commonly used for expressing the result of logical operations performed on the data.It ia also used as a return type of a function indicating the success or the failure of the function.

In addition to char data type ,C++ provides another data   type wchar_pt which is used to store 16- bit wide characters.Wide characters are used to hold large character sets associated with some non-english languages.

DERIVED DATA TYPES: Data types that are derived from the built-in data types are known as derived data types .the various derived data types provided by c++ are arrays,junction,references and pointers . 
                                                                      
ARRAY: An array is a set of elements of the same data type that are referred to by the same name.All the elements in an array are stored at contiguous(one after another) memory locations and each  element is accessed by a unique index or subscript value. the subscript value indicates the position of in an array.

FUNCTION:A function is a self-contained program segment that carries out a specific well-defined task. In  C++, every program contains one or more funcyions which can be invoked from other parts of a program ,if required.

REFERENCE:A reference is an alternative name for a variable .that is ,a reference is an alias for a variable in a program .A variable and its reference can be used interchangeably in a program as both refer to the same memory locations . Hence, changes made to any of them (say,a variable) are reflected int the  other (on reference).

POINTER:A pointer is a variable that can store the memory address of another variable. pointers allow to use the memory dynamically. That is, with the help allocated of pointers , memory can be allocated or de-allocated to the variables at run-time , thus,making a program more efficient.