6

C++ Fundamentals and Basic Programming

LEARNING OBJECTIVES

At the end of this chapter, you should be able to understand and put to use

  • Development of C++ and OOPS as applied to C++ language.

  • C++ programming environment and programming structure.

  • Curtain raise programs in C++ using control loop, arrays, structure and classes. These programs are designed to give you a taste of things to come and also to make you productive from day one.

  • Console IO operations and unformatted functions used in input and output operations.

6.1 Introduction

In order to solve a problem, you need know the “method/procedure” or have the “know-how.” In computer parlance, this can be called an algorithm. An algorithm or program is a sequence of steps to be followed, which, when followed, leads to a desired output. The sequence of steps can be called a procedure. A group of procedures can be termed as a program.

For solving a complex problem, we need a programming environment that includes wellintegrated and cohesive programming elements, constructs and data structures. The structured programming paradigm with C as implementing language, in which the programmer breaks down the task to be accomplished into smaller tasks and specifies step-by-step procedures or algorithms to achieve the task at hand, has been very successful and popular.

Low productivity of programmers due to factors such as changing user needs, complexity of projects and non-availability of extensibility and reuse features is the main factor for projects not being completed on time. Object-oriented programming (OOP) promises extensive reusability features through inheritance, library functions in the form of standard template library (STL), etc. C++ is one of the most powerful OOP languages that supports both structured as well as OOP paradigms.

6.2 History and Development of Object-oriented Languages Like C++

With the advent of UNIX and communication hardware and software from 1969 onwards, the complexity of both hardware and software kept on increasing and software project development could not keep pace. As a result, the quality of programs suffered. The developers at Bell Laboratories and the Department of Defense, US, started to look at alternative paradigms wherein reusability and extensibility were strong features. Further, the specifications laid insisted on data primacy rather than process primacy.

C++ was developed by Bjarne Stroustrup in 1979 at Bell Laboratories. C++ is a sequel to the C language, with additional enhancement features, including virtual functions, function name and operator overloading, references, free space memory, and several features on reusability and extendibility through inheritance, templates, etc. Exception handling and a welldeveloped STL are two of the advanced features available in C++.

6.3 Object-oriented Language Features

OOP style can be of two types, i.e. object-based programming and object-oriented programming. In OOP paradigm, object is primacy. Object-oriented programming, such as C++, uses objects and interactions amongst them through invoking member functions. Figure 6.1 shows object holding data and member functions. The features include data hiding, data abstraction, encapsulation, inheritance and polymorphism.

 

Data and methods in OOP paradigm

 

Figure 6.1 Data and methods in OOP paradigm

Salient Features of the OOP Paradigm

  • Data encapsulation
  • Data hiding
  • Operator overloading
  • Initialization and automatic clearing of objects after use
  • Dynamic binding
  • Extensive and well-defined standard template library

6.4 Welcome to C++ Language

We want to make you reasonably comfortable with C++ language. The idea is that you should be productive from day 1. Get ready for an exciting tour of C++ in the introductory chapter itself. We will introduce C++ through simple programs after highlighting a few essential features you should know before you write your first C++ program.

6.4.1 Setting Path

After installation of Turbo C++ or Micro Soft Visual C++ or GNU C++ Compiler for Linux platforms, the relevant files will normally get loaded into C:Program FilesTC or C:Program Files Microsoft Visual StudioVC98 unless otherwise chosen by you. After downloading, the directory will look as in Figure 6.2.

 

Directory structure after installing TC or VC++

 

Figure 6.2 Directory structure after installing TC or VC++

 

Let us say that we want to use folder called “oopsc++” in D directory and within the folder we have created a separate folder called “c++chap1”. In this folder, we will create all our source code files and also store all object files and other related project files created by VC++.

Therefore, the path for storing all class files and source programs developed by us would be

  • D:oopsc++

We also need to link up bin and lib directories of TCVC++. Their paths would be

  • C:Program Files Microsoft Visual StudioVC98 in // contains all company
      //supplied programs
  • C:Program Files Microsoft Visual StudioVC98include; // win32 & header files
  • C:Program Files Microsoft Visual StudioVC98lib // libraries
                                 Or
  • C:Program Files TCin
  • C:Program Files TCinclude; C:Program Files TClib

 

Example 6.1:   How to Set Path for Windows Platforms

Permanent setting of path variable:

  • Go to settings->control panel->system -> advanced-> set environment variable.
  • Select path->edit : copy & paste path -> ok

 

Example 6.2:   How to Set Path for Linux Platforms

Let us suppose that TC or VC++ has been installed in directory /usr/local/

Linux :

For C shell (csh), edit the startup file (~/.cshrc):

set path=(/usr/local/TC/bin )

For bash, edit the startup file (~/.bashrc):

PATH=/usr/local/TC/bin:

export PATH

For ksh, the startup file is named by the environment variable, ENV.

To set the path:

PATH=/usr/local/TC/bin:

export PATH

For sh, edit the profile file (~/.profile):

PATH=/usr/local/TC/bin:

export PATH

6.4.2 C++ Program Structure

Any C++ program contains sections shown in Figure 6.3. Global section, also called external section, contains subsections which are available and visible to all parts and functions and sections of the program. Preprocessor directives are instructions to compilers to perform certain tasks before actual compilation of source code takes place.

 

Structure of a C++ program

 

Figure 6.3 Structure of a C++ program

Global/External Section: For example, #include<stdio.h> statement gets the file from include section of the library created by compiler and attaches it with your code, and then the source code is compiled. Declarations of user-defined data types such as class and structures are included. Member functions and macrofunctions are declared and defined in this section. They are available to the entire program.

Function main() is mainly used to create required objects and variables and as interface with the user. It is used to obtain input data and displaying the final results. Objects created interact with other objects by invoking functions and passing arguments and achieve the desired result.

6.4.3 C++ Development Environment

Before we execute our program there is a need to understand the C++ development environment. Refer to Figure 6.4.

 

C++ development environment

 

Figure 6.4 C++ development environment

Step 1: Edit

Edit the source program using any of the editors notepad. For example, our program will have a main class “HelloWorld”. Hence, our Java program also to be named as HelloWorld.cpp Move to directory d:oopsc++c++chap1 and create the required source file. Use any text editor like notepad, vi editor, etc., and enter your code and save it as HelloWorld.cpp.

d:oopsc++c++chap1> edit HelloWorld.cpp

  1. /* HelloWorld.cpp. This is our first program to introduce you
  2. to some basic io statements like cin and cout & multi line comment*/
  3. #include<iostream> //iostream, a library file contains cin , cout programs
  4. using namespace std;
  5. void main( ) // start of maim programme
  6. {
  7. char name[20]; // name is a data type of char of c++ length 20
  8. cout<<”
 Please enter your name : “; //cout is an object of iostream
  9. cin>>name; // cin is an object of iostream cout<<”
 Hello “<<name<<endl; //
 means goto new line
  10. cout<<”
 Welcome to Objective Oriented Programming in C++”<<endl; // endl means goto new line
  11. cout<<”
 Best Wishes from authors. Have a good day!”<<endl;
  12. }// end of main

Lines No. 1 and 2: C++ provides two types of comment statements. Comments are included to enhance the readability of the program. C++ allows both single-line comment statements and also multiline comment statements.

  • Single-line comments: These comment lines start with double slash : //

    Ex ://Circle.cpp, a C++ cprogram to print a line of text

  • Multiline comments: These comment lines are used when comments extend beyond a single line. They start with /* and end with */

    Ex: /* Inheritance.cpp :The programme introduces concepts of

Inheritance and other related reusability features of C++ */

Global Declarations and Definitions. All statements included before main() function. All include sections, define statements, function prototype declarations, and structure definitions are global declarations. Hence they are available to all functions also.

Line No. 3: include<……> statements are preprocessor directives. iostream is included, so that all functionality provided by iostream, i.e. input and output stream like cin and cout are available to us. If you are using Turbo C++ compiler you will use #include<iostream.h>.
Line No. 4: Using name space std; is a statement used to resolve conflicts arising due to the same names being used in different programs. Here we are instructing the compiler to use standard library supplied by compiler. For Turbo C++ users, using name space std; statement is not required.
Line No. 5: void main() is start of main function and program. Void is a data type that a function returns after executing the function. Observe that start of main is indicated by an opening brace bracket and closing brace at line no 12.
Line No. 7: Name has been declared as data type char of length 20. We can hold name in this field.
Lines No. 8–11: Cin and cout are objects of iostream used to input and output data using iostream.. means printing starts in new line. What has been written with in “ “ is printed as it is on to output console. >> & << are extraction operators in iostream. They are used to stream data in and out with cin and cout, respectively .<<endl is a command directing compiler to go to new line.

Step 2: Compile

We need to store all our compiled code in d:oopsc++c++chap1. Therefore, from the directory d:oopsc++c++chap1. Compile the source file

Compile it using #gcc HelloWorld.cpp Output using # a.out for Linux based system

          Run ----- Compile ----- Execute for Turbo C

If you are using vc++ platform, the job of compilation and link load and run are fairly simple. On the task bar choose: compile, build and run buttons.

If you are using Linux environment:

  1. Switch on the computer.
  2. Select the Red hat Linux environment.
  3. Right click on the desktop. Select ‘New Terminal’.
  4. After getting the $ symbol, type vi filename.cpp and press Enter.
  5. Press Esc+I to enter into Insert mode and then type your program there.

    The other modes are Append and Command modes.

  6. After completion of entering program, press (Esc + Shift + :). This is to save your program in the editor.
  7. Then the cursor moves to the end of the page.

    Type ‘wq’ and press Enter.

    (wq=write and quit)

  8. On $ prompt type, c++ filename.cpp and press Enter.
  9. If there are any errors, go back to your program and correct them.

    Save and compile the program again after corrections.

  10. If there are no errors, run the program by typing

    ./a.out and press Enter.

  11. To come out of the terminal, at the dollar prompt, type exit and press Enter.

    /* Out put

    Please enter your name: Ramesh

    Hello Ramesh

    Welcome to Objective Oriented Programming in C++

    Best Wishes from authors. Have a good day! */

6.5 Further Sample Programs of C++

6.5.1 Execution of a Program in a Loop

The second problem is finding surface area of a. We would like to compute the surface area of a football that is spherical in shape, given its radius, given by the formula 4 * PI * r * r. In this section, we will use a while loop to run the program. The code for the above problem is given below:

 

Example 6.3:   SurfaceArea.cpp. to Compute Surface Area of a Football

//Example 6.3 SurfaceArea.cpp Program to calculate surface area of a ball

  1. #include<iostream>
  2. using namespace std;
  3. /* Declare function prototype that will compute the surface area given the radius of float (real number) data type and returns area again of float data type
  4. float FindArea(float radius , const double PI);
  5. void main( )
  6. { // You will need float (real numbers) data types for holding radius and area
  7. float radius, area;
  8. const double PI=3.1415926; // PI value is constant and does not change
  9. // Obtain radius from the user. User can enter 0 to stop the programme*/
  10. cout<<”
 Enter radius of the ball. To stop enter 0 for the radius 
”;
  11. cout<<”
 Radius = ? “;
  12. cin>>radius; // user enters value for radius
  13. /* We would like to compute surface areas of different balls. So user enters various radii. User can stop by entering 0 for the radius. We will use while statement.*/
  14. while (radius != 0) // i.e. till user does not enter 0
  15. {
  16. if (radius < 0) area = 0; // if radius is negative area =0
  17. else area = FindArea(radius,PI); // calling out function. Radius & PI are arguments  // We store the result returned by FindArea() at area.
  18. // print out put
  19. cout<<”
 Surface area of football :”<<area<<endl; //
  20. /* what is in quotes appears as it is in the output. 
 means leave a line after print
  21. We are inside while statement. We have just completed printing of area.
  22. What should we do next? Ask the user for next problem i.e. next radius. Ask it.*/
  23. cout<<”
 Enter radius of the ball. To stop enter 0 for the radius 
”;
  24. cout<<”
 Radius = ? “;
  25. cin>>radius;
  26. }//  end of while
  27. }// end of main
  28. // function definition. Here we will tell what FindArea function does
  29. float FindArea (float radius,const double PI)
  30. { float answer; // we will store the area
  31. answer = 4* PI * radius * radius;
  32. return answer;
  33. } // end of function definition
      /* OUTPUT : Enter radius of the ball. To stop enter 0 for the radius
      Radius = ? 2.0
      Surface area of football :50.2655
      Enter radius of the ball. To stop enter 0 for the radius
      Radius = ? 3.0
      Surface area of football :113.097
      Enter radius of the ball. To stop enter 0 for the radius
      Radius = ? 0
      Press any key to continue*/
Line No. 4: Function Prototype like float FindArea (float radius,const double PI); tells the compiler that function definition is after main( ) but its usage will be in the main( ). It is like advance information to the compiler to accept usage prior to definition. We could also define the above function as: float FindArea(float radius , const double PI) {return 4*PI*radius*radius;}

We will be using this second and short form for convenience throughout the book.

Function definition has been provided at Line No 28.

Line No. 8: We have declared PI as constant and of data type double. Double means it is double precision data type.

6.5.2 Arrays Implementation

In this example, we will show the use of arrays. Array is a data structure comprising of contiguous memory location. It will store the same data type in all locations. In Example 6.5.1, we have taken in the radius and immediately declared the result and continued the process till user entered 0 to exit. In this example, we will take all the radii and heights of several sizes of cones (ice cream?) together and store them in memory location, compute corresponding volumes of these cones and store them as well and declare the results in the end. Array comes to our rescue here. Array is used to hold the same data type in contiguous memory locations. We will define three arrays named radius, height, and volume, each with a dimension of 10 elements as shown is Figure 6.5.

 

Arrays for radius heights and volume

 

Figure 6.5 Arrays for radius heights and volume

 

In C++ language, it is customary to number the cells of the array starting with 0. Accordingly, radius[0] holds a value 2.0 and radius[9] holds a value of 11.0. height[0] holds a value of 5.0 and height[9] holds a value of 14.0. The formula for volume of cone is 4*PI*radius*radius. We will store the values of cones in an array called volume. With this knowledge, let us attempt array implementation of cones.

 

Example 6.4:   volume.cpp. to Compute Volumes of Ice Cream Cones

/*Example 6.5.2 volume.cpp. a program to compute volumes of cone using arrays. We will store all the radii and heights and compute the volume and store them in an array called volume. When user terminates the program by entering 0 for radius, we will declare all the results.*/

  1.  #include<iostream> // for using cin and cout from library.
  2.  using namespace std; // to resolve naming conflicts. Use from standard library.
  3.  // Declare Function Prototype
  4.  float FindVolume(float radius, float height, const double PI);
  5.  void main( )
  6.  { int n, i =0; // i we will use as array index, n for keeping count
  7.  const double PI=3.1415296;
  8.  float radius[50]; // Array of radius, numbering max of 50
  9.  float height[50]; // Array of heights, numbering max of 50
  10. float volume[50]; // Array of volume, numbering max of 50
  11. cout<<”
 Enter radius & height of a cone <To stop enter 0 for the radius> “<<endl;
  12. cout<<” Radius & Height : ? “;
  13. cin>>radius[i]>>height[i]; //Store at address of radius[i]& height[i]
  14. while (radius[i] != 0)
  15. { if (radius[i] < 0)
            volume[i] = 0;
      else
            volume[i]= FindVolume(radius[i],height[i],PI);// result in array volume
  16. // get the next set of data. we have to increment i prior to getting
  17. // new set of data else old data will be overwritten and hence lost.
  18. i++;
  19. cout<<”
 Enter radius & height of cone <To stop enter 0 for the radius>”<<endl;
  20. cout<<” Radius & Height : ? “;
  21. cin>>radius[i]>>height[i];
  22. }// end of while
  23. n = -- i; // This is because you have increased the count for i for
               // radius = 0 case also. We will use n in for loop.
  24. // display array elements
  25. cout<<”
 Volume of Ice cream Cones
”;
  26. // You have n cones (i.e. 0 to n-1 as per C++ convention).
  27. //Therefore print i <=n using a for loop
  28. for (i=0; i<= n; i++)
  29. cout<<” radius[“<<i<<”]=”<<radius[i]<<” height[“<<i<<”] =”<<height[i]<<” : volume[“<<i<<”]=”<<volume[i]<<endl;
  30. }// end of main
  31. // function definition
  32. float FindVolume(float radius,float height, const double PI )
  33. {return (4*PI * radius * radius*height);}
      /*Output :Enter radius & height of a cone <To stop enter 0 for the radius>
      Radius & Height : ? 2.0 3.0
      Enter radius & height of cone <To stop enter 0 for the radius>
      Radius & Height : ? 4.0 5.0
      Enter radius & height of cone <To stop enter 0 for the radius>
      Radius & Height : ? 0 0
      Volume of Ice cream Cones
      radius[0]=2 height[0]=3 : volume[0]=150.793
      radius[1]=4 height[1]=5 : volume[1]=1005.29*/
Line No. 4: A function prototype takes radius, height and PI as input and returnsvolume.
Line No. 8–10: Declare arrays of maximum length <=50.
Line No. 13: cin>>radius[i]>>height[i] ; inputs values for radius and height. Data values need to be separated by space while entering the data.
Line No. 28: for (i=0; i<= n; i++) It is a header statement of for loop. Initial condition is i=0; Final condition for loop to terminate is i<= n; The loop will be executed in Steps of 1. Hence i++)
Line No. 29: Displays Radius, height and volume. It is body of loop. Body of the loop is a single line.
Line No. 32: Function definition to return volume.

6.5.3 Use of Structure to Implement Problem

While arrays store the same type of data in contiguous locations, structure can be used to store different types of data, bundled together as an instance of structure. C++, in addition to object-oriented features, supports all features of C such as structures and unions. These find extensive use in data structures and other C-based software implemented in C++ environment. We can define structure in C++ language for records shown in Figure 6.6.

 

Student record for three students

 

Figure 6.6 Student record for three students

 


struct Student
{
char name[20];
int rollNo;
float totalmarks;
char grade;
};
students
// Stud typecasted to Student structure typedef struct Student

   Stud; We can refer to items inside the structure using

std[i].name, std[i].rollNo, std[i].totalMarks std[i].grade

We have used typedef statement so that we can use Stud in lieu of lengthy struct Student every time we refer to Student structure. User enters name and total marks. If total marks are more than 80% declare as A grade, 60–79 % declare as B grade and below 60% declare as C grade.

 

Example 6.5:   StudStru.cpp. to Compute Grades of Students Using Structures

  1.  #include <iostream>
  2.  using namespace std;
  3.  // declare function prototypes
  4.  char FindGrade(float totalMarks);
  5.  // declare a structure
  6.  struct Student
  7.  {
  8.  char name[20];
  9.  int rollNo;
  10. float totalMarks;
  11. char grade;
  12. };
  13. // Stud typecasted to Student structure
  14. typedef struct Student Stud;
  15. void main( )
  16. { Stud std[3]; //maximum of 3 Students
  17. int n, i=0; // i we will use as structure index, n for keeping count
  18. cout<<”
 Enter Roll Number <0 to STOP> :”;
  19. cin>>std[i].rollNo;
  20. while ( std[i].rollNo!=0) // variable declared in std are referred with dot(.)
  21. { cout<<”
 Enter name & roll number & total Marks< 200 to 600”<<endl;
  22. cin>>std[i].name>>std[i].totalMarks;
  23. std[i].grade= FindGrade(std[i].totalMarks);
  24. ++ i;
  25. cout<<”
 Enter Roll Number <0 to STOP> :”;
  26. cin>>std[i].rollNo;
  27. }// end of while
  28. n = -- i; // because you have increased the count for i for name =STOP case also.
  29. // display structure elements
  30. cout<<”
 Students Grades
”;
  31. for(i=0;i<= n; i++)
  32. { cout<<”
 name :”<<std[i].name<<” “<<”Roll No :”<<std[i].rollNo;
  33. cout<<” Total Marks”<<std[i].totalMarks<<” “
  34. <<”Grade : “<<std[i].grade<<endl;
  35. }// end of for loop
  36. }// end of main
  37. // function definition
  38. char FindGrade(float totalMarks)
  39. {char grade;
  40. if ( totalMarks>=480)
  41. grade=’A’;
  42. else
  43. if ( totalMarks>=360)
  44. grade=’B’;
  45. else
  46. grade=’C’;
  47. return grade;
  48. } // end of function definition
      /*Output : Enter Roll Number <0 to STOP> :50595
      Enter name & roll number & total Marks<between 200 to 600
      Ramesh 358
      Enter Roll Number <0 to STOP> :60695
      Enter name & roll number & total Marks<between 200 to 600
      Gautam 540
      Enter Roll Number <0 to STOP> :75775
      Enter name & roll number & total Marks<between 200 to 600
      Anand 540
      Enter Roll Number <0 to STOP> :0
      Students Grades
      name :Ramesh Roll No :50595 Total Marks358 Grade : C
      name :Gautam Roll No :60695 Total Marks540 Grade : A
      name :Anand Roll No :75775 Total Marks540 Grade : A */
Lines No. 6–13: Structure declaration. Observe structure declaration ends with };
Line No. 14: Type casting of Stud to structure. Hence we can use Stud instead of struct Stud as in statement 16, which declares three instances of structure stud.
Line No. 19: Variables of structure are always referred with dot(.) operator.

6.5.4 Class Implementation

In this section, we will introduce the concepts of class and objects. What is an object? An object is an entity that you can feel. For example, pen, student and football are all objects. Consider a class in which, let us say, there are 60 students who are interested in studying for C++ course. Then we can group all 60 students into a class, just like your college administration groups all its B.Tech computer science students into a class. In C++, we would declare a class. A class will have member data and member functions. We call this as attributes and behaviour. Once a class is created, we will create an instance of class called object. Objects invoke functions and interact amongst themselves to achieve the desired result.

In Example 6.5, we will compute the total and grade of a student. A class called Student will have name and roll number, subject marks, total and average as private member data. As a policy of C++, all data is declared as private. When you declare a data as private, access is permitted only for members of the class. We will access these private data through public functions.

 

Example 6.6:   stud1.cpp to Compute Total and Average and Display Result

  1. #include<iostream>
  2. using namespace std;
  3. //declare a class called Student
  4. class Student
  5. {
  6. private:
  7.   int rollNo;
  8.   char name[30];
  9.   double marks[5];// set of five subject marks
  10.  double tot;
  11.  double avg;
  12.public:
  13.  void GetData(int n);
  14.  void ComputeAvg(int n);
  15.  void DispData(int n);
  16.}; 
  17.// Define member functions
  18.void Student::GetData(int n)
  19.{ cout<<“
 Enter Students Details ”<<endl;
  20.  cout<<“ Enter Roll No <space> name : ”;
  21.  cin >>rollNo>>name;
  22.cout<<“ Enter marks in ”<<n<<“ subjects separated by spaces :”;
  23.for ( int i=0;i<n;i++)
  24.cin>>marks[i];
  25.}
  26.void Student::DispData(int n)
  27.{ cout<<rollNo<<“ ”<<name<<“ ”;
  28.for ( int i=0;i<n;i++) cout<<marks[i]<<“ ”;
  29.cout<<“ ”<<tot<<“ ”<<avg<<endl;
  30.}
  31.void Student::ComputeAvg(int n)
  32.{ tot=0;
  33.for ( int i=0;i<n;i++)
  34.tot +=marks[i];
  35.avg=tot/n;
  36.}
  37.void main()
  38.{
  39.Student std[60];//std object of class Student with maximum of 60 students
  40.int n; //no of student
  41.// Get the number of students in the class
  42.cout<<“ Enter number of Students in the class : ”;
  43.cin>>n;
  44.// get the data for n number of students
  45.for ( int i=0;i<n;i++)
  46.std[i].GetData(n);
  47.// Compute Average
  48.for (i=0;i<n;i++)
  49.std[i].ComputeAvg(n);
  50.// Print the details of the student
  51.cout<<“Roll No”<<“ Name”<<“ Marks”<<“ Total”<<“ Avg”<<endl;
  52.for ( i=0;i<n;i++)
  53.std[i].DispData(n);
  54.}
     /* Output :Enter number of Students in the class : 2
     Enter Students Details
     Enter Roll No <space> name : 50595 Ramesh
     Enter marks in 2 subjects separated by spaces :87 89
     Enter Students Details
     Enter Roll No <space> name : 60695 Gautam
     Enter marks in 2 subjects separated by spaces :99 98
     oll No Name Marks Total Avg
     0595 Ramesh 87 89 176 88
     0695 Gautam 99 98 197 98.5
     */
Lines No. 4–16: class declaration. Terminated by ;
Lines No. 6–11: Member data is declared as private. Name is an array of 20 characters and other variables are double data type.
Line No. 18: In void Student::GetData(int n) the symbol :: is called scope resolution operator. It tells the compiler to look beyond the controlling braces for the definition in class at line no 13.
Lines No. 17–25: The member function is defined with scope resolution operator
Line No. 39: Student std[60];// declares 60 objects identified by std[i] of class
Line No. 46: std[i].GetData(n); Member functions are always invoked by object using a dot operator

6.6 Console IO Operations

Console IO means get input from standard input device, i.e. keyboard and output to standard IO device, i.e. screen or monitor.

6.6.1 Console IO Functions – Commands getchar() and putchar()

Can be used to input single character at a time from keyboard. Consider the following program, wherein we will read characters into an array and output the array in uppercase.

 

Example 6.7:   getchar.cpp to Demonstrate Usage of getchar() and putchar()

#include<iostream>
using namespace std;
void main()
{     char city[80]; // declare an array of 80 characters length
      char c; // we will use it to store the character input
      int i=0,j=0; // i & j we will use them as counters
      while ( (c=getchar())!=’
’) /* read in line .’
’ is an end of line recognized when ‘enter’ is pressed*/ city[i++]=c;
      //use i as counter once again.
      j=i; // store the value in j. This is because we will
      i=0; //store it in city[i] and then post increment i.
      while ( i<j) // output the character in uppercase
      putchar(toupper(city[i++])); // post increment i
} // end of main.
/* OUTPUT: : Hi Anand! Welcome to India
HI ANAND! WELCOME TO INDIA */

Observe that in using while loops we have used brace brackets only for clarity. These while loops have only one line in the body; hence could have been written without brace brackets as

  while ( c!=’
’)
  city[i++]=c;

6.6.2 Console IO Functions – Commands gets and puts

These commands are used to input and output strings.

 

Example 6.8:   getsputs.cpp to Demonstrate Usage of gets() and puts()

  1.  #include<iostream>
  2.  #include<stdio.h> // for gets() and puts
  3.  #include<string> // for finding string length using strlen() function
  4.  using namespace std;
  5.  void main()
  6.  { int len;
  7.  char line[80]; // declare an array of 80 characters length
  8.  cout<<”
Enter any line: “;
  9.  gets(line); // read a line till ‘enter’(new line character is pressed )
  10. len = strlen(line);
  11. puts(line); // output a line
  12. cout<<”
Length of given string = “<<len<<endl;
  13. }
      /*OutputEnter any line: Hello World
      Hello World
      Length of given string = 11*/
Line No. 2: includes stdio.h for using gets() and puts() from stdio header file. These are imported from C language library. Note that C++ supports all features of C language.
Line No. 3: #include<string> gets all the functions for handling strings from a library called string. len = strlen(line); at ine No 10 computes length of the string using string library.

6.6.3 Unformatted Stream IO Functions – get(), put(), getline() and write()

Get() and put() are single character input and output functions. They can be used with iostream objects of cin and cout. For example:

char ch ;
cin.get(ch); // fetches a single character from keyboard and stores it in ch.
cout.put(toupper(ch)); // converts ch to upper case and displays on screen
cout.put(‘z’); // displays z on the screen

In the next example, we will use get() and put commands. The program will accept lowercase sentence from the user one character at a time till it encounters a full stop. It will convert each input character into uppercase and displays on the screen.

 

Example 6.9:   getput.cpp to Demonstrate Usage of get() and put()

  1.  /* Example 6.10 getput.cpp to demonstrate the working of get & put.*/
  2.  #include<iostream>
  3.  using namespace std;
  4.  void main()
  5.  { int count=1;
  6.  char ch;
  7.  cout<<”
Enter a character<. to stop>”;
  8.  cin.get(ch);
  9.  while( ch!=’.’)
  10. { cout.put(toupper(ch));
  11. cin.get(ch);
  12. count++;
  13. }
  14. --count; // This is because we have added for (.) case also
  15. cout<<”
 No of characters entered = “<<count<<endl;
  16. cout<<”
End of Programme”<<endl;
  17. }
      /*Output :Enter a character<. to stop>abcd. ABCD
      No of characters entered = 4
      End of Programme*/
Line No. 9: toupper() function converts to uppercase, tolower() converts string to lowercase

Getline() and write() are line oriented functions. Usage is shown below:

char text[80];
cin.getline(text,80);// will read white spaces and 
 character.
cout.write(text,80); // out puts the line of text

It may be noted that cout>>text will not print white spaces. Similarly cin>> text will not read white spaces like tab, space, etc.

 

Example 6.10:   getlinewrite.cpp to Demonstrate the Working of getline & write & write.*/

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. void main()
  5. { int len1,len2;
  6. char text[20], stg[20];
  7. //char line[20];
  8. cout<<”
Enter a line of Text”;
  9. cin.getline(text,20);
  10. len1=strlen(text);
  11. cout.write(text, len1);
  12. // cout<<”
Now input put usiing cin>>”;
  13. // cout<<”
Observe that cin>> can not read white spaces like space”<<endl;
  14. // cin>>line;
  15. // cout<<line;
  16. cout<<”
output second string using cin.getline()”<<endl;
  17. cin.getline(stg,20);
  18. len2=strlen(stg);
  19. cout.write(stg,len2).write(text,len1);
  20. cout<<“
End of Programme“<<endl;
  21. }
      /*Output: Enter a line of TextI Love India!
      I Love India!
      output second string using cin.getline()
      I Love Delhi
      I Love DelhiI Love India!
      End of Programme*/
Lines No. 9–11: show how to use getline() and write() commands with cin & cout.
Lines No. 7 and Lines No. 12–15: are commented out. You can include the when you want to check the property of >> operator that it cannot read white space.
Line No. 19: concatenates stg and text.

6.7 Summary

  1. C++ was developed by Bjarne Stroustrup in 1979 at Bell Laboratories.
  2. These additional features include virtual functions, function name and operator overloading, references, free space memory and several features on reusability and extendibility features through inheritance, templates, etc.
  3. Exception handling and a well-developed standard template library are two of the advanced features available in C++.
  4. C++ allows both single-line comment statements as well as multiline comment statements.
  5. Using name space std; is a statement used to resolve conflicts arising due to the same names used in different programs.
  6. >> & << are extraction operators in iostream. They are used to stream data in and out with cin and cout, respectively.
  7. <<endl is a command directing compiler to go to a new line.
  8. Array is derived data type storing the same data type in different contiguous locations in memory.
  9. Structure can be used to store different types of data, bundled together as an instance of structure.
  10. A class will have member data and member functions. We call this as attributes and behaviour. Once class is created, we will create an instance of class called object.
  11. Objects invoke functions and interact amongst themselves to achieve the desired result.
  12. Console IO means get input from standard input device, i.e. keyboard and output to standard IO device, i.e. screen or monitor.

Exercise Questions

Objective Questions

  1. Which of the following are true with respect to C++:
    1. Data primacy
    2. Process primacy
    3. Objective based
    4. Object oriented
    1. i and iv
    2. i, ii and iv
    3. i, ii and iii
    4. ii and iv
  2. void main() returns
    1. integer
    2. 0
    3. null
    4. void
  3. To go to new line the escape sequence required is
    1. ‘a’
    2. ‘ ew’
    3. ‘ ’
    4. ‘ ’
  4. Function prototype statement will have a semicolon     True/False
  5. Function definition statement will have a semicolon     True/False
  6. Global declarations and definitions are available to all functions     True/False
  7. Type defining a structure would allow shorter names in lieu of key word struct and structure name     True/False.
  8. Which of the following are true in respect of C++ declarations?
    1. Arrays hold different data types.
    2. Array data is stored in continuous memory locations.
    3. Structure hold different data types.
    4. Class hold data as well as functions.
    1. i and ii
    2. ii, iii and iv
    3. i, ii, iii and iv
    4. i and iv
  9. Namespace std; in C++ is used for
    1. For cin and cout functions
    2. For console standard functions
    3. For resolving naming conflicts
    4. To import standard functions
  10. In C++ to declare a variable that does not change its value during program runs, use
    1. const declaration before variable declaration
    2. global
    3. static
    4. structure
  11. Scope resolution operator is
    1. ;
    2. :
    3. ::
    4. (.)
  12. Class declaration is terminated always by
    1. ;
    2. :
    3. ::
    4. (.)
  13. Member functions are invoked by objects using the following operator:
    1. ;
    2. :
    3. ::
    4. .
  14. The operator >> can read white spaces like blan     TRUE/ FALSE
  15. The cin.getline(string,length) can read white space     TRUE/FALSE
  16. The cin.get() cannot read white spaces     TRUE/FALSE

    Short-answer Questions

  17. What are global declarations?
  18. What does <iostream> or iostream.h>contain?
  19. Why are function prototypes declared before main( ) function?
  20. Declare an array of integers X to hold 25 values. Draw pictorially and put a value of 25 in X[10].
  21. Distinguish structure and arrays in C++.
  22. Distinguish get() and gets() commands.
  23. Distinguish getchar() and get().
  24. Declare a structure called BankCustomer. Show the fields name, acctno, balance. Type define structure as customer and creates an array of customers called cust to hold 25 customers of type BankCustomer.
  25. Use class declaration for problem at 5. Add functions line FindBalance() and Transact() to the class declaration.
  26. What are console IO operations?

    Long-answer Questions

  27. Explain C++ program structure and development environment.
  28. What are the salient features of the OOP paradigm?
  29. What are the special OOP-related features of C++?
  30. Explain console IO operations and commands with examples.

    Assignment Questions

  31. Write the various steps involved in executing a c program and illustrate this with the help of a flowchart.
  32. Write a function program to convert Fahrenheit to centigrade using the formula: Celsius = 5*(fahrenheit – 32)/9.
  33. Write a c module to compute simple and compound interest using the formula: SI = P*N*R/100 and CI = P*(1+R/100)^N
  34. Write a program to prepare name, address and telephone number of five of your friends. Use the structure called friend.
  35. Write a program to store number, age and weight in three separate arrays for 10 students. At the end of data entry, print what has been entered.
  36. Using the formula A = Squareroot(s*(s-a)*(s-b)*(s-c)), compute the area of the triangle. S = (a+b+c)/2, and a, b and c are sides of the triangle.
  37. Write a cpp to check if two strings have the same number of characters. Use getline().

Solutions to Objective Questions

  1. a
  2. d
  3. d
  4. True
  5. False
  6. True
  7. True
  8. b
  9. c
  10. a
  11. c
  12. a
  13. d
  14. False
  15. True
  16. False
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.178