Simple C++ Program


A few simple programs are explained in this section to help you get a feel of C++. First, let’s write a program to calculate the area of a circle. The variables needed in this program are the radius of the circle (which can be obtained as input from the user) and the constant ‘pi’ (whose value can be provided in the code itself).

      // To Calculate the Area of a Circle

      # include <iostream.h>
      int main( )
      {
          float PI = 3.14;                // variables can be initialized during declaration
          int rad;
          cout<< "Enter the radius" ;
          cin>>rad;
          cout<< "Area of the circle is "<< PI * rad * rad;
          return 0;
      }      

The preprocessor has only one directive and it will include the iostream.h header file into the source code. The compiler will start reading the code from the main ( ) function onwards.

Remember: Whatever is typed within the main ( ) function will be executed. The main ( ) function is used as the entry point for a C++ program.

PI is a variable name and is declared as a float quantity (because the value of PI has a decimal point). At the point of declaration, PI is initialized to a value of 3.14. This means that whenever PI is used in the program, the compiler will use 3.14 instead of PI.

The line:

cout<<"Enter the radius";

will cause

Enter the radius

to be displayed on the screen. This is because "Enter the radius" is typed within double quotes following ‘cout’ and the insertion operator. Anything between double quotes, along with cout<< will be displayed on the screen just as it appears within the double quote.

The value entered by the user will be stored in the variable ‘rad’.

Then the statement "Area of the circle is " will be displayed on the screen. The compiler will calculate the value of ‘PI * rad * rad’ and display it at the end (* is the multiplication operator in C++).

The output for the above program is:

Bold indicates that the user entered the value. In this case 9 was entered as the radius.

Suppose we type

cout<< "rad";

the output will be just the word

rad

The value of the variable ‘rad’ will not be displayed.

Remember: When you want to display some variable’s value on the screen, DO NOT ENCLOSE IT IN DOUBLE QUOTES; just mention the name of the variable after the insertion operator.


Initializing variables:

It is a good idea to initialize variables at the time of declaration. Even if you are unsure of the value you can still initialize it to 0. If you are wondering why, just consider the example below:

#include <iostream.h>
int main( )
{
            int correct, choice;
            cout<<"\nEnter your guess of the lucky number: ";
            cin>>choice;
            if (choice= =correct)
            {
                        cout<<"\nCongrags. You are correct!";
            }
            else
            {
                        cout<<"\nSorry. Wrong guess";
            }
            cout<<correct;                                                 //uninitialized variable
            return 0;
}

Let’s not get into the details of this program for the time being (we’ll discuss about the ‘if’ statement, escape sequences \n later). You should have got a rough idea as to what the program is about. We ask the user to enter a number and if that number matches the number we’ve decided upon then we display a message saying ‘Congrags’.

The user’s value is stored in the variable ‘choice’ and the actual correct value should have been stored in the variable ‘correct’. Run the program and you’ll get something like the following:

            Enter your guess of the lucky number: 5         

            Sorry. Wrong guess 469772 

The problem is that in the program we haven’t assigned a value to the variable ‘correct’ and neither have we initialized it. Thus this variable has an unknown value (also called garbage value).  

There are 2 ways to initialize variables:

            int correct = 25;

or

            int correct(25); 

The second form is called functional notation and we generally don’t use this to initialize in-built data types (like integers, characters, double etc.). This form is used to initialize user defined data types (which we’ll discuss in the chapter on Classes).


Another example program:

//Can you guess what this program is for and how it works?

      #include<iostream.h>
      int main( )
      {
          char check;
          int i;
          cout<<"Enter the character that you want to convert to ASCII : ";
          cin>>check;
          i = check;
          cout<<"The ASCII value for "<<check<< " is "<<i;
          return 0;
      }

The above program is for finding out the ASCII value for any character that you type. How does it work?

Always go line by line and put yourself in the position of the compiler. ‘check’ is declared as a character and ‘i’ is declared as an integer. The first value entered is stored in the variable ‘check’. ‘check’ is a character but ‘i’ is an integer variable. How can we equate ‘check’ to ‘i’? Won’t there be some problem?

It is not advisable to equate one data type to another. Many a times this could lead to errors (usually logical errors) but in the above program this is done purposely. ‘check’ is a character (one byte) but it is stored as a number in memory (for example: an ‘a’ is not stored as an ‘a’ in memory. It is converted into a decimal number using the ASCII code and then into binary form and stored in memory). A character occupies one byte while an integer occupies 2 bytes. A character has a range from –127 to 127 while an integer has a much greater range. Thus, whatever value is held by ‘check’ can be held by the integer ‘i’ as well. And this value is actually the ASCII value for the character that the user types. You might wonder, why not use the statement below since ‘check’ also has the same value:

cout<<check;

This will display the same character that you entered and not the ASCII value. Why? Because when something is stored as a character (though it is stored in integer format), it will go through the same process of ASCII coding and find out what is the equivalent character (and display the character). But when something is stored as an integer, the number will be displayed as it is (without going through the ASCII coding process).

Try it: Write a program that will do the reverse process (i.e. type a number and the program has to display the corresponding character).


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.