Loading....
Coupon Accepted Successfully!

 

More Programs

8.43 Write a program to accept string and display the string. Use null character for determining the end of string.

Explanation: In the above program, the class text is defined with one data member of character type. The get() function is used to read text through the keyboard. The show() function is defined with integer argument. The show() function displays the string character by character. The integer variable x shows the element number in the character array str[50]. The if statement checks whether the current character is null or other. If the character is null then it returns 0, otherwise it displays the character and returns 1. In function main(), s is an object of class text. The object s calls gets() and reads text.

The show() function is called within the bracket of while loop. The integer variable k is incremented before passing it to the function show(). In the statement, ++k increment first takes place and then incremented value is sent. The array element counting starts from zero. In order to display the string from first character, the initial value of k should be 0. Thus, initializing k to –1 and applying increment operator as prefix can do this.

We know that the while loop is executed till the given test condition evaluates to 1. Thus, till the function show() returns 1 the loop is executed and when it returns 0 the loop is terminated. The function show() returns 0 only when it reaches the end of text. Meanwhile, the entire text is displayed on the screen.

8.44 Write a program to enter two strings and concatenate them. Display the resulting string.

Explanation: In the above program, the class text has three character array data members, namely str1[15], str2[15], and str3[30], and has also four member functions, namely get(), len(), show(), and combine(). The get() function is used to read strings through the keyboard; the len() function returns the length of the first string; the show() function displays the strings; and the combine() function combines the first and second strings and assigns to the third string. The integer variable k is initialized to –1. The integer variable y contains the length of the first string. The function combine() is called within the bracket of while loop and two integers variable k and y are passed.

In combine() function, x indicates character element position in character arrays str3[] and str1[]. The statement str3[x]=str1[x] assigns characters of str1[] array-to-array str3[]. This assignment continuous till x >= y (y is length of the first string). When x is greater than y, the statement str3[x]=str2[x-y] is executed; that is, assignment of second string is now carried out. 

The x-y displays the element number of second string. The second if statement in the combine() function checks whether the null character has met or not. If yes it returns 0, otherwise 1. The values 0 or 1 returned by combine() are collected by the while loop. The while loop is executed till it gets 1 from function combine(). When the combine() function returns 0, the while loop is terminated. The show() function after while loop displays all the strings.
 

Tip: The reader may be in confusion as to why so much effort is required to write simple programs in C++. We can easily solve these problems with very short codes in C. The objective is to master how to solve these problems using OO concepts and to make the reader think more on objects. In the previous examples, the reader might have noticed that even for a small task, it might be calculation or comparison, and for every task, we defined member functions. The class should provide every operation in the form of method or member function needed by objects and the object should not be dependent on main() or other non-member function for any requirement. This is the pure object-oriented programming.

 

8.45 Write a program to declare data member of a class as public. Initialize and display them without using function.

Explanation: In the above program, the class boy contains two public members, namely weight and height. The members are public and can be accessed directly without using member function. In function raj and sonu are two objects of the class boy. The data elements of weight and height of both objects are initialized and displayed.

8.46 Write a program to declare constant member function arguments.

Explanation: In the above program, the arguments of function sub() are declared as constant. Hence, an attempt to modify these arguments will generate an error. Thus, by declaring the member variable arguments const, we can prevent them from modification.

8.47 Write a program to show the difference between private and public data members of a class.

Explanation: In the above program, a class player is defined with four member variables char name[20], int age, float height, and float weight. The first two members are private and last two members are public. In the function main(), a is an object of type class player. The public member variables of class player are height and weight initialized with 5.5 and 38, respectively, through object a. It is not possible to access the private member of the class directly. Hence, the variables name and age cannot be accessed. Any attempt to access them through the object will display an error message “‘player::name’ is not accessible” or “ ‘player::age’ is not accessible”.

8.48 Write a program to initialize private and public member variables of the class. Display the contents of member variables.

Explanation: In the above example, the class num contains private as well as public member variables. The two private member variables x and y are assigned values using member functions. The public member variable z is assigned directly in function main(). The variable j is an object, readdata() is a member function. The variables j and k are parameters to be passed. Consider the following statements.

 

a) j.y=10.5 // invalid statement

b) j.z=’C’ // valid statement


The statement (a) is invalid because member variable y is private whereas statement (b) is a valid because member variable z is public and accessible by the object of the same class.

Member Function Inside the class

8.49 Write a program to declare class with member variables and functions. Read and display the data using the member functions.

 

Explanation: In the above program, the class player contains four private member variables and two public member functions setdata() and show().The definition of both the functions is inside the class. In the previous example, we noticed that the object of any class could not access the private member variables of the class. To access the private member variables of the class, member function of that class are used. In this program, setdata() and show() are the member functions of class player. The setdata() function reads data through the keyboard and show() functions display the data on the screen. These member functions cannot be called directly as ordinary functions. Consider the statement a.setdata(). Here, a is an object of class player followed dot(.) operator and function name. An attempt to call these member functions directly without using object of that class will generate an error in the program such as “Function ‘ ‘ should ‘ ‘ have a prototype”.

In this program, function definition of the member function is inside the class. It is also possible to put prototype of the function inside the class and definition outside the class. While defining the function, it is necessary to specify class name followed by scope access operator. This declaration tells the compiler the relation between the class and the member function. For understanding this concept, the following program is illustrated as follows.

Member Function Outside the class

8.50 Write a program to declare class with member variables and functions. Read and display the data using the member functions. Declare function definition outside the class.

Explanation: The above program is same as previous one. The only difference is that the function definition of the member functions is outside the class. The prototypes of these functions are inside the class, which are enough for these functions to join membership with class player.

 

Consider the following statements.
 

void player:: setdata()

Void player:: show()


Both these statements tell the compiler that the functions setdata() and show() are member functions of class player.


So far we declared the entire member functions as public. It is also possible to declare member functions as private. A private function can be called only from public member functions. Even an object of same class cannot access the private function. An example is illustrated below based on this idea.

Private Member Functions

8.51 Write a program to declare private member function and call this member function using another public member function.

 

Explanation: In the above program, the function sqr() is declared as private and the function input() as public. The input() function reads an integer through the keyboard and calls the private function sqr(). The function sqr() calculates the square of the number and returns result to the input() function. The input() function again returns this value to the variable sq declared in main(). The last cout statement displays the entered number and its square. The statement given in remark is invalid statement, because an object cannot access private member. The input() public function acts as an inter-mediator in between private function and an object of the class. Without public functions, it is not possible for the object to access private functions.

8.52 Write a program to enter hours. Convert it into seconds and minutes. Display results.


Explanation: In the above program, the class hour is declared with three integer members and three member functions. The input() function reads number of hours through the keyboard. The function convert() calculates minutes and seconds and assigns results to minutes and seconds variables. The function show() displays the contents of all the member variables. In the function main(), X is an object of class hour. The object X calls all the member functions one by one. The values of member variables after execution are displayed at the output.


8.53 Write a program to count the number of vowels present in the entered string.

Explanation: In the above program, instead of class keyword struct keyword is used. The struct vowels has only one member variable, which is a character array str. The function input() reads text through the keyboard and assigns it to the member variable str[20]. The function length() determines the length of the string. The function vowel() when called receives an integer from calling function. The if statement checks whether the (x) the character of the string is vowel or consonant. If it is one of the vowels, the function returns 1 otherwise 0.

In main(), b is an object of struct vowels. Using for loop, the object b calls the function vowel() repetitively. The return value (0 or 1) is added to a variable c during repetitive calls. The value of c finally displays the number of vowels present in the string.

8.54 Write a program to enter text. Find a given character in the string and replace it with another given character.

Explanation: In the above program, the class fandr have three character data type member variables. The function accept() reads the text through the keyboard. Here, the function cin.getline(str, 40) is used to connect with the keyboard. The first argument is the name of array and second is size of array. Followed by this, the character to be traced and replaced is entered in variable f and r. The function len() is obviously used for calculating length of the string. The function find() receives an integer from calling function. The if statement checks whether the specified character by the integer is equal to a given character or not. If the character is found, the replace() function is called which replaces the traced character with value of ‘r’ variable. The for loop in main() function repetitively calls the functions find() and display(). Remember, the function replace() is called by find() function whenever the if condition is true. The cout.put() is used to display the character on the screen. Thus, find and replace operations execute.

8.55 Write a program to find largest out of ten numbers.

Explanation: In the above program, the class num has one integer array as its member variable with element size 10 (number[10]). The input() function reads an integer through the keyboard and returns it to main() function. The first for loop repetitively calls function input(). The return value of input() function is added to variable sum. The second and third for loops together are used to find the largest number in the array. The second and third for loop variables are used as arguments for the function large(). As per iteration, the successive element numbers and decremented value of sum assigned to variable k. The values of variables k and loop variable i are sent to function large(). In each third for loop iteration, the second for loop executes once and value of sum is decremented. The if condition in large() function checks both the arguments. If the arguments are the same, the largest number is displayed, and the exit(1) function terminates the program, otherwise the program execution continues.

8.56 Write a program to count the numbers between 1 and 100, which are not divisible by 2,3, and 5.

Explanation: In the above program, the class div is declared with one static data member variable, that is num. The class div also contains member functions check(), show(), and loop(). The function check() checks the received value with if statement whether it is divisible by 2, 3, and 5 or not. If it is not divisible, the number is displayed and the value of static data member num is incremented. The loop() function contains for loop and calls the function check() with one argument. The prototype of function is given inside the class and definition outside the function, because the member function with any loop defined inside the class cannot be expanded inline and will result in a warning message. The more applicable practice is to write the definition of this kind of function outside the class. The function show() displays the total number of numbers that satisfies the condition. The object d declared in function main() invokes the member functions loop() and show().

8.57 Write a program to generate the nth Fibonacci number by using recursion.

Fibonacci series:1 1 2 3 5 8 13

 





Test Your Skills Now!
Take a Quiz now
Reviewer Name