Variables, Data Types, Constants and Operators

Source Code from Notes


Example 1


//  program to add two integer values 
//  and display result                 

#include <iostream.h>

main()
{
        // declare variables 
        int     value1, value2, sum;

        // assign values and compute the result 
        value1 = 32;
        value2 = 27;
        sum = value1 + value2;

        // display the result 
        cout << "The sum of " << value1 << " and  << value2  << " is " <<
		sum << "\n" ;
}


Example 2

This is the example program to calculate the area of a rectangle

#include <iostream.h>

main()
{
        // type definitions 
        // 3 variables - length, breadth and area 

        float   length, breadth, area;

        // input phase - read length and breadth from user 

        cout << "Enter the length and breadth\n";
         cin >> length >> breadth;

        // computation - calculate area 

        area = length * breadth;

        // output phase 

        cout << "The area of the rectangle with length  " << length << " and breadth "
	     << breadth  << " is " << area << "\n"; 

}


Example 3

This example calculates the average value of three numbers entered by the user.


// Program to calculate the average of three numbers
#include <iostream.h>

main()
{
        float   number1,number2,number3;
        float   average;

        // Enter values
        cout << "Enter three numbers: ";
        cin >> number1 >> number2 >> number3;

        // calculate average
        average = (number1 + number2 + number3)/3.0;

        // Output result
        cout << "The average value of " << number1 << " , " << number2 <<
             " and " << number3 << " is "  << average << "\n";
}


Example 4

This example prompts the user to input a number and then calculates the reciprocal of this number.


// Program to calculate the reciprocal of a number
#include <iostream.h>

main()
{
        float   number;
        float   reciprocal;

        // Enter Value
        cout <<"Enter a number: ";
        cin >> number;

        // Calculate reciprocal
        reciprocal = 1.0 / number;

        // output result
        cout << "The reciprocal of " << number << " is " << reciprocal << "\n";
}


Example 5

This example illustrates the use of constants. It calculates the area and circumference of a circle, when given the radius.


// program to calculate circumference and area of circle 

#include <iostream.h>

main()
{
	const float PI = 3.14156;
        // define variables
        float   radius,circumference,area;

        // Input radius
	cout << "Enter the radius: ";
        cin >> radius;

        // calculate radius and circumference
        circumference = PI * 2 * radius;
        area = PI * radius * radius;

        // display results
        cout << "The circumference is " << circumference << " and the rea is " << area 
	     << "\n"; 
                                           
}


Back to Main Page for Lecture 2