Saturday, 8 June 2013

Tokens, Expressions and Control Structures


Tokens

We know that the smallest individual unit in a program is known as token. C++ has the following tokens :-

  • Keywords
  • Identifiers
  • Constants
  • Strings
  • Operators

Keywords

The keywords implement specific C++ language features. They are explicitly reserved identifiers which cannot be used as names for the program varibales or other user-defined program elements.

Given below is the list of the keywords used in C++ , many of which are common to the keywords of C.

  • asm                                                      
  • auto
  • break
  • case
  • catch
  • char
  • class
  • const
  • continue
  • default
  • delete
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • friend
  • goto
  • if
  • inline
  • int
  • long
  • new
  • operator
  • private
  • protected
  • public
  • register
  • return
  • short
  • signed
  • sizeof
  • static
  • struct
  • switch
  • template
  • this
  • threw
  • try
  • typedef
  • union
  • unsigned
  • virtual
  • void
  • volatile
  • while
  • bool
  • const_cast
  • dynamic_cast
  • explicit
  • export
  • false
  • mutable
  • namespace
  • reinterpret_Cast
  • static_Cast
  • true
  • typeid
  • typename
  • using
A major difference between C and C++ is the limit on the length of a variable length. While ANSI C recognises only the first 32 characters of a name, ANSI C++ places no limit on the length of the name.

Constants refer to fixed values that do not change during the course of execution of the program.

Data Types

Data types in C++ can be broadly categorised into three types :-
  •  User Defined
  • Built In
  • Derived Data type
 Thats all the concept for today and now we put the answers to yesterday's problems.

Answers to problems in post 7.

The Questions we had were :-
Q1. Write a program to display the following output using a single cout statement.

•Maths = 90
...•Physics = 77
•Chemistry = 80.
Q2. Write a program to read two numbers from keyboard and display the larger value on the screen.

Q3. Write a program to read the values of a,b and c and display the value of x, where

x = a/b-c
Test your program for the following set of values :-

i) a=250, b=85, c=25;
ii) a=300, b=70, c=70.

Q4. Write a C++ Program that will ask for a temperature in Fahrenheit and diplay its corresponding temperature in Celsius.

And we have the solutions

Question 1 ( Input Cascading concept)

#include<iostream>

using namespace std;

int main()
{
cout<<"Maths= 90"<<"\n"<<"Physics= 77"<<"\n"<<"Chemistry= 80"<<"\n";

return 0;
}.


Question 2 (If else statement)

#include<iostream>

using namespace std;

int main()
{
int number1, number2;

cout<<"\nEnter the first number : ";
cin>>number1;

cout<<"\nEnter the second number : ";
cin>>number2;

if(number1>number2)
cout<<"\nThe greater number = "<<number1<<"\n";

else if (number2>number1)
cout<<"\nThe greater number = "<<number2<<"\n";

else
cout<<"\nBoth the numbers are equal."<<"\n";

return 0;
}


Question 3 (Simple Input/Output with variable)

#include<iostream>
using namespace std;

int main()
{

int a,b,c,x;

cout<<"\nEnter the values of a, b, c : ";
cin>>a>>b>>c;

x=a/b-c;

cout<<"\nThe value of x is = "<<x<<"\n";

return 0;

}


Question 4 ( Implementing the formula)

#include<iostream>

using namespace std;


int main()
{
float tempf, tempc=0 ;

cout<<"Enter the temperate in Fahrenheit: ";
cin>>tempf;

tempc = (tempf-32)*5/9;

cout<<"The Celsius equivalent temperature is : "<<tempc;

return 0;

}.


Assignment for today :-
Try to find out the number of keywords which you find are common between C and C++.

Thursday, 6 June 2013

Some more C++ Sample programs



Sample program which takes in variables and input statements

We will read two numbers from the keyboard and display the average on the screen. A sample C++ program for this purpose is given below


C++ Program to calculate the average of two numbers

#include<iostream>

using namespace std;

int main()
{

          float number1, number2, sum , average;        //Declaring the variables as float datatype
          cout<<"Enter the two numbers : ";                // String displayed on screen asking for two inputs
          cin>>number1;                                              //Reading Input 1 from the keyboard
          cin>>number2;                                              //Reading Input 2 from the keyboard

         sum=number1 + number2;                            //Calculating the sum of two numbers
         average = sum/2;                                           //Calculating the average of two numbers

         cout<<"Sum = " <<sum<<"\n";                    //Displaying the sum
         cout<<"Average of two numbers = "<<average<<"\n";      //Displaying the result of the average

         return 0;
}
        

The output of this program would be something like this :-

Output of the above program

 

Variables

This program uses four variables number1, number2, sum and average. They are declared as float type by the statement
 
  float number1, number2, sum, average;
 
All variables must be declared before they are used in a program.
 

Input Operator

The statement - cin>>number1;

is an input statement and causes the program to wait for the user to type in a number. The number keyed in is placed in the variable number1. The identifier cin is a predefined object in C++ that correspons to the standard input stream.

The operator >> is known as extraction or get from operator. It extracts or takes the value from the keyboard and assigns it to the variable on its right.

Cascading of Input/Output Operators

We have used the insertion operator <<repeatedly in the last two statements for printing results.

The statement
cout<<"Sum ="<<sum<<<<"\n";

first sends the string "Sum=" to cout and then sends the value of sum. Finally it sends the newline character so that the next output wil be in the new line. The multiple use of << in one statement is called cascading. When cascading an output operator , we should ensure necessary blank spaces between different items. Using the cascading technique the last two statements can be combined as follows :-

cout<<"Sum="<<sum<<"\n"<<"Average= "<<average<<"\n";

We can cascade the input operator as well

cin>>number1>>number2;

Note :-  The values are assigned from left to right. That is if we key in two values, say 10 and 20, then 10 will be assigned to number1 and 20 will be assigned to number2.


An example with class

One of the major functions of C++ is classes. They bind the functions which operate on them. Like structure in C , classes are user defined data types.

The following program shows the use of a class in a C++ program.

#include<iostream>

using namespace std;

class person
{
               char name[30];
               int age;
              public :
                         void getdata(void);
                         void display(void);
};

void person::getdata(void)
{
            cout<<"Enter the name of the person: ";
            cin>>name;
            cout<<"\nEnter age of the person: ";
            cin>>age;
}

void person::display(void)
{
            cout<<"\nName = "<<name<<"\n";
            cout<<"\nAge= "<<age<<"\n";
}

int main()
{
             person p;
             p.getdata();
             p.display();
             return 0;
}


Analysis of the program

This program defines person as a new data of type class. The class person includes two basic data type items and two functions to operate on that data. These functions are called member functions. The main program uses person to declare variables of its type. As said earlier class variables are known as objects. Here , p is an object of type person. Class objects are used to invoke the functions defined in that class.

Note :- cin can read only one word and therefore we cannot uses blank spaces to write a full name.

Assignments on the concepts learnt today :-

Q1. Write a program to display the following output using a single cout statement.

  • Maths = 90
  • Physics = 77
  • Chemistry = 80.
Q2. Write a program to read two numbers from keyboard and display the larger value on the screen.

Q3. Write a program to read the values of a,b and c and display the value of x, where

            x = a/b-c
Test your program for the following set of values :-

i) a=250, b=85, c=25;
ii) a=300, b=70, c=70.

Q4. Write a C++ Program that will ask for a temperature in Fahrenheit and diplay its corresponding temperature in Celsius.

Please try doing all the programs yourself if u face any problem do use the comment section.

Answers for all these problems will be posted tommorow.

 

Wednesday, 5 June 2013

Beginning with C++

 

A Bit about 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 years of 1980's.

Since the language is an extension of the language C with the major addition being the class construct feature Stroustrup called the new language "C with classes" however in 1983 the name was changed to C++, the idea of C++ coming from the increment operator ++, thus bringing the logic that C++ is an incremented version of language C.

A Simple C Program

Let us begin with a simple example of a C++ prorgam that prints a string on screen.

#include<iostream>                 //Including the header file

using namespace std;

int main ()                                   //Main function
{

      cout<< "Hello World.\n";    //C++ statement to print the string "Hello World"
     
      return 0;                               // we have taken int main() hence we have to return an integer value
}                                                // End of Program.

Analysing the program

Like C, the C++ program is also a collection of functions. In the above example we have only one function i.e the main() . As usual execution of any program begins at main(). Every C++ program will have a main() . Like C , the statements in C++ end with a semicolon (;) .

Comments

Comment symbol is  // (double slash) for single line comments and for multi line comments we use
/*

*/

Similar to C programming.

Output operator

The only statement in the above program is an output statement.

The statement

cout<<"Hello World\n";
causes the string contained within the quotation marks to be displayed on the screen.

We find two new C++ features here 'cout' and '<<' . The identifier "cout" is a predefined object that represents the standard output stream in C++.

The operator "<<" is called the insertion or put to operator. It inserts or sends the contents of the variables on its right to the objects on the left.

Note :-   C++ also supports printf() for displaying an output but we will use the standard C++ notation i.e cout.

Header File

We have used the #include directive in the program :

#include<iostream>

This directive causes the preprocessor to add the contents of the iostream file to the program. It contains the declarations for the identifier cout, cin and the operators << .

The header files iostream should be included in the beginning of all programs that use input/output statements and as practically all programs use I/O statements so using iostream.h is compulsory.

Common Header Files

1. ctype.h - Contains function prototypes for functions to test characters for certain properties and prototypes for function that can be used to convert lowercase letters to uppercase letters and vice versa.

2. float - Contains the floating point size limits of the system.

3. limits - Contains the integral size limits of the system.

4. math - Contains function prototypes for math library functions.

5. string - Contains function prototypes for C style string processing functions.

6. stdlib - Contains function prototypes for conversion of numbers to texts, text to numbers, memory allocation, random numbers and various other utility functions.

7. time - Contains function prototype and types for manipulating the current system time and date.

8. iomanip - Contains function prototypes for stream manipulators that enable formatting of streams of data.

9. fstream - Contains function prototype for functions that perform input from files on disk and output to files on disk.

10. iostream - Contains standard prototype functions for standard input and output functions.

Return type of main ()

In C++, main() returns an integer type value to the operating system. Therefore every main() should ed with a return 0 statement; otherwise a warning or error might occur. Since main() returns an integer type value, return type is specified as int. The default type for all functions in C++ is int.

Try making some more programs to practise things learnt today and print some more strings. We will be back tommorow with some more programs to understand the input operator, variables and some more concepts of C++.

Thats all for today friends do post your comments below for sending us your feedback.

 

Tuesday, 4 June 2013

Basic Concepts of Object Oriented Programming in Details

 

         1. OBJECTS

Objects are the basic run time entities of an object oriented programming system.  They may represent a person, a place, a bank account, a table of data of any item that the program has to handle. A programming problem is analysed in terms of objects and the nature of communication between them. Objects take up space in the memory and have an associated address similar to what structures are in C.
When a program is executed the objects interact by sending messages to one another .
For example :- If  "Customer" and "Bank Account" are two Objects in a program, then the customer object sends a message to the account object requesting for the bank balance.
Each object contains data, and code to manipulate the data. Objects can interact without having to know the details of each other's data or code. It is sufficient to know the type of message accepted and the type of response recieved by the object.

    2.  CLASSES

We know that objects contain data, and the required code to manipulate the data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact, objects are variables of the type class. Once a class has been defined, we can create a number of objects belonging to that class. Each object is associated with the data of type class with which they are created. 
A class is thus a collection of objects of similar type.
For example :- mango, apple and orange are members of the class fruit. Classes are user defined data types and behave like the built in type of a programming language. 
If fruit has been defined as a class then the syntax for creating an object is
fruit mango;
//This will create an object mango belonging to the class fruit

    3. DATA ABSTRACTION AND ENCAPSULATION 

Wrapping up of data and functions into a single unit (known as class) is known as       encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside classes, only those functions which are wrapped in the class can access the data. This insulation of the data from direct access by the program is called data hiding or information hiding.
Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight, and functions to operate these attributes. They encapsulate all the essential properties of the object that are to be created. The attributes are sometimes called data members because they hold information. The function that operate on these data are called methods or member functions.
Since classes use the concept of data abstraction they are known as Abstract Data Types (ADT).
 

       4. INHERITANCE

Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird "robin" is a part of the class 'flying bird' which is again part of the class 'bird'. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived.
In OOP, the concept of Inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. The real appeal and power of inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly what he wants, and to tailor the class in usch a way that it does not introduce any undesirable side effects into the rest of the classes.

      5. POLYMORPHISM

Polymorphism is another important concept of OOP. Polymorphism is a Greek term which means the ability to take more than one form. An operation may exhibit different behaviours in different instances. The behaviour depends upon the type of data used in the the operation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading.
Polymorphism plays an important role in allowing objects having different internal structures to share same external interface. This means that a general class of operation may be accessed in the same manner even though specific action associated with each operation may differ. Polymorphism is extensively used to implement inheritance.

      6. DYNAMIC BINDING

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding also known as late binding means that the code associated with a given procedure call is not known until the time of the call at run time. It is associated with polymorphism and inheritance. A function call assocaited with a polymorphic reference depends on the dynamic type of that reference.
For example the procedure "Answering" . By inheritance every object "Student" will have this procedure however individual algorithms for each class will have different answers for the same procedure.

     7. MESSAGE PASSING

An object oriented program consists of a set of objects that communicate with each other. The process of programming in an OOP Language therefore involves the following basic steps :-
  1. Creating classes that define objects and their behaviour
  2. Creating objects from class definitions and
  3. Establishing communication between objects.
Objects communicate with one naother by sending and recieving information much the same way people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real world counterparts.
The message for an object is a request for execution of a procedure, and therefore will invoke a function in the recieving object that generates the desired result. Message passing involves specifying the name of the object, the name of the funtion and the information to be sent.
 

APPLICATION OF OOP

  • Real time systems
  • Simulation and modelling
  • Object Oriented databases
  • Hypertext, hypermedia and expertext
  • AI and expert systems
  • Neural networks and parallel programming
  • Decision support and office automation systems
  • CIM/CAM/CAD systems.
 
Tommorow we will learn about the various Header files of C++ and the basic input/output commands and also write our first C++ Program so do visit again tommorow.
Thank for visiting the page.