Page 252 - Computer_Science_F5
P. 252

Program Example 4.9:

               Global variable declaration


                                  int x=5, y=2;                                                    Chapter Four: Object oriented programming with C++
          FOR ONLINE READING ONLY
                                  main()
                                  {
                                  fun();
                                  }
                                  fun()
                                  {
                                  int sum;
                                  sum = x + y;
                                  }


               Variables x and y in this program are global variables because they have been
               declared before the main function, main(), and are also used within the function.

              (c) Static variables
              Static variables are types of variables declared only once within a function, but they
              are used in a whole program. The keyword “static” is used to declare static variables.
              For Example:
                 static int i, j;
                 static float a, b;
                 static char name;

              The following is a Program Example 4.10 of a C++ program that finds the area of
              the rectangle. The output is shown in Figure 4.24.

                      Program Example 4.10:

               Finding the area of the rectangle

                     #include<iostream>
                     using namespace std;
                     int main()
                     {
                           int l, w;     //Declaration of length (l) and width (w)as integers data type
                           double area;                    //Declaration of area as double data type
                           cout<<”Enter a length in metres: “;
                           cin>>l; //Read value of length entered by the user
                           cout<<”Enter a width in metres: “;
                           cin>>w; //Read value of width entered by the user
                           area=l*w;
                           cout<<”The area of the rectangle is “<<area<<”square metres”<<endl;
                           return 0;
                     }


                                                    243
               Student’s Book  Form Five



     Computer Science Form 5.indd   243                                                     23/07/2024   12:33
   247   248   249   250   251   252   253   254   255   256   257