Professional Documents
Culture Documents
Object Oriented Programming Structure: Class Assignment No. 1
Object Oriented Programming Structure: Class Assignment No. 1
Page 1
1. endl:
Inserts a new-line character. Additionally, for buffered streams, endl flushes the buffer (i.e. writes all unwritten characters in the buffer to the output sequence).
Example: cout << "Exforsys" << endl; cout << "Training"; Output: Exforsys Training
2. setw:
This Setw () stands for the set width. The Setw () manipulator is used to set the width of the word to be displayed on screen. The header file that must be included while using setw manipulator is <iomanip.h> Example: #include <iostream.h> #include <iomanip.h> int main () { cout << setw (10); cout << 77 << endl; return 0; } Output: 77
3. setfill:
Page 2
Example: #include <iostream.h> #include <iomanip.h> int main () { cout << setfill ('x') << setw (10); cout << 77 << endl; return 0; } Output: xxxxxxxx77
4. setprecision:
The setprecision Manipulator is used with floating point numbers. It is used to set the number of digits printed to the right of the decimal point. This may be used in two forms: fixed scientific
These two forms are used when the keywords fixed or scientific are appropriately used before the setprecision manipulator. The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation. The keyword scientific, before the setprecision manipulator, prints the floating point number in scientific notation. Example: // setprecision example #include <iostream> #include <iomanip> int main () { double f =3.14159; cout << setprecision (5) cout << setprecision (9) cout << fixed; cout << setprecision (5) cout << setprecision (9) return 0; }
<< f << endl; << f << endl; << f << endl; << f << endl;
Page 3
Program:
#include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { char str[50]; int i,c=0,w=0,s=0,l=0,sp=0; clrscr(); cout<<"Enter the string\n"; gets(str); cout<<str; if(strlen(str)!=0) w++; for(i=0;str[i]!='\0';i++) { if(str[i]==32) { s++;
Page 4
OUTPUT:
Page 5
As Pointer operator
It is pointer to a variable.
As Aritmetic operator
Example:
Page 6
Example : &a; will give actual address of the variable a. & as Bitwise AND Operator
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Example: Assume variable A holds 60 and variable B holds 13 then (A & B) will give 12 which is 0000 1100
3.
:: Scope Resolution Operator : The :: operator is known as Scope Resolution operator in C++.
To access the Global variables when same variable name exist in Local scope.In this case the the local variable can be accessed normally but when we want to access global variable we have to use :: (Scope Resolution) operator.
Its use is to define the member functions outside the class. In this case when we want to define the member function whose prototype is declared inside the class.
Page 7
You can tell the compiler to use the global identifier rather than the local identifier by prefixing the identifier with ::, the scope resolution operator. :: identifier class-name :: identifier namespace :: identifier The identifier can be a variable or a function.
If you have nested local scopes, the scope resolution operator does not provide access to identifiers in the next outermost scope. It provides access to only the global identifiers.
4.
The . (dot) operator is used to access class, structure, or union members. The member is specified by a postfix expression, followed by a . (dot) operator, followed by a possibly qualified identifier or a pseudo-destructor name. The postfix expression must be an object of type class, struct or union. The name must be a member of that object. The value of the expression is the value of the selected member. If the postfix expression and the name are lvalues, the expression value is also an lvalue. If the postfix expression is type-qualified, the same type qualifiers will apply to the designated member in the resulting expression.
In this case, to refer to the structure, which is a member of a namespace, use ::. To access the variable in an object of a particular type, you use .. ns::type obj; obj.var = 1;
5.
++ Increment operator:
Page 8
1. Fundamental Data Types: As the name suggests these are the atomic or the
fundamental data types in C++.
2. Derived Data Types: These are the data types which are derived from the
fundamental data types. It is further divide into two categories
Page 9
i)Built-In
and
ii)User-defined
Integer types: Name bool char short Size (in bits, on x86) 8 (top 7 bits are ignored) 8 16 Range 0 or 1 -128 to 127(signed) or 0255(unsigned) -32768 to 32767(signed) or 065536(unsigned) -2147483648 to 2147483647(signed) or 0-4294967296(unsigned) same as int Notes C++ only standard issue "byte" just like a char, only twice as large standard-issue integer number type ditto
int
long
Floating Point types: Name Float Double Size (in bits, on x86) 32 64 Range +/- 1.4023x10-45 to 3.4028x10+38 +/- 4.9406x10-324 to 1.7977x10308 Notes general purpose realnumber higher-precision real number
1. Arrays: Arrays refer to a list of finite number of same data types. The data in the
array can be accessed by an index number ranging from 0 to n(where n is the number of data element it can store). Ex- if arr[3] is an array of int(egers) then the different values in the array can be accessed as shown below. arr[0], arr[1],arr[2] when we declare an array such as the one sown above then by arr[3] we mean that we want three elements in the array and hence while accessing arr[2] is the last element. 2. Pointer: A pointer is a variable that holds the memory address of other variable. It is also of different data types, ex- char pointer can store address of only char variables, int pointer can store address of int variables and so on. 3. Reference: A reference in the simplest sense is an alias or alternate name for a previously defined variable.
Page 10
1. Class: A class is a collection of variables and function under one reference name.
it is the way of separating and storing similar data together. Member functions are often the means of accessing, modifying and operating the data members (i.e. variables). It is one of the most important features of C++ since OOP is usually implemented through the use of classes. 2. Structure: In C++ structure and class same except for some very minor differences. 3. Union: A union is a memory location shared by two or more different variables, generally of different data types. Giving more details here would only confuse you; Ill leave it for future articles. 4. Enumerations: It can be used to assign names to integer constants. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. Conditional structure: if and else The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: For example: 1 if (x == 100) 2 cout << "x is 100"; 3 else 4 cout << "x is not 100"; prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. Iteration structures (loops) Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. The while loop
Page 11
Page 12
Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): // break loop example #include <iostream.h>
Page 13
int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; } 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: // continue loop example #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
Page 14
The exit function exit is a function defined in the stdlib library. The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:
Page 15
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure. If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure. Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).
Q.5) Explain the features of OOP? Ans. The programming in which data is logically represented in the form of a class and physically represented in the form an object is called as object oriented programming (OOP). OOP has the following important features. Class : In OOP languages it is must to create a class for representing data. Class contains variables for storing data and functions to specify various operations that can be performed on data. Class will not occupy any memory space and hence it is only logical representation of data. Data Encapsulation : Within a class variables are used for storing data and functions to specify various operations that can be performed on data. This process of wrapping up of data and functions that operate on data as a single unit is called as data encapsulation. Data Abstraction : Within a class if a member is declared as private, then that member cannot be accessed from outside the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction. Advantage of data abstraction is security. Polymorphism :
Page 16
Q.6) Explain call by reference and call by value? Ans. Call by value method: The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows. EXAMPLE: #include <iostream.h> void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put x into y */
Page 17
return; } int main () { // local variable declaration: int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; // calling a function to swap the values. swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; } return 0;
Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200 Which shows that there is no change in the values though they had been changed inside the function. Call by reference method: The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. EXAMPLE: #include <iostream.h> void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put x into y */ return;
Page 18
Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100
Q.7) Explain structure and union? Ans. Structure: A structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name. Declaring a Structure: The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces "{"and "}". Finally, the closed braces end with a semicolon denoted as ";" following the statement. The above structure declaration is also called a Structure Specifier.
Page 19
In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer. Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure. To declare Structure Variable This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name. In the above example, structure variable cust1 is defined as:
What happens when this is defined? When a structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type int and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum, 2 bytes for salary and 4 bytes for commission.
Page 20
Union: Union is a user-defined type that uses same block of memory for every its list member. Union may be useful when it is necessary to work with different representation of same binary data. Declaring a Union Begin the declaration of a union with the union keyword, and enclose the member list in curly braces: // declaring_a_union.cpp union DATATYPE // Declare union type { char ch; int i; long l; float f; double d; } var1; // Optional declaration of union variable int main() { }
Example :
Page 21
// iValue = 10
Q.8) W.A.P to delete the spaces from the text entered by the user? Ans.
PROGRAM:
#include<iostream.h> #include<conio.h> #include<stdio.h> void main() { int i,j; char str[30]; clrscr(); cout<<"Enter the string\n"; gets(str); for(i=0;str[i]!='\0';i++) { if(str[i]==32) { for(j=i;str[j]!='\0';j++)
Page 22
OUTPUT:
Page 23
Page 24
The most obvious difference is that the C++ approach takes care of the low-level details necessary to determine how many bytes to allocate. With the C++ new operator, you simply describe the type of the desired storage, in this example "int[100]". Q.10) What is data encapsulation? Explain its importance? How data encapsulation ensures security? Explain it with the suitable example. Ans. Encapsulation is the process of binding together of Data and Code. It can also be defined as the concept that an object totally separates its interface from its implementation. The concept of Encapsulation hides the implementation details behind its interface
1. Program statements (code): This is the part of a program that performs actions
and they are called functions. program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example: class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.
2. Program data: The data is the information of the program which affected by the
Page 25
When the above code is compiled and executed, it produces following result: Total 60
Page 26
PROGRAM:
#include<iostream.h> #include<conio.h> #include<stdio.h> enum flag{false,true}; void main() { int i,c=0; char ch; flag word=false; clrscr(); cout<<"Enter the string\n"; do { ch=getche(); if((ch==32)||(ch=='\r')) { if(word) { c++; word=false; }
Page 27
OUTPUT:
Page 28