Introduction of C++ OOP forces us to think in terms of object and the interaction between objects.

Similar documents
UNIT- 3 Introduction to C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

6.096 Introduction to C++ January (IAP) 2009

CHAPTER-6 GETTING STARTED WITH C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Introduction to C++

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

LECTURE 02 INTRODUCTION TO C++

A First Program - Greeting.cpp

Fundamental of Programming (C)

Basics of Java Programming

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

BITG 1233: Introduction to C++

Introduction to C++ Introduction and History. Characteristics of C++

2 nd Week Lecture Notes

C++ Programming: From Problem Analysis to Program Design, Third Edition

Creating a C++ Program

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Chapter 2: Overview of C++

The C++ Language. Arizona State University 1

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Full file at

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Chapter 2: Using Data

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

Computer Programming : C++

Unit 3. Operators. School of Science and Technology INTRODUCTION

CHAPTER 3 BASIC INSTRUCTION OF C++

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Fundamentals of Programming

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Basics of Programming

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Visual C# Instructor s Manual Table of Contents

JAVA Programming Fundamentals

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

DEPARTMENT OF MATHS, MJ COLLEGE

UNIT-2 Introduction to C++

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Objectives. In this chapter, you will:

Java Notes. 10th ICSE. Saravanan Ganesh

BASIC ELEMENTS OF A COMPUTER PROGRAM

3. Java - Language Constructs I

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Information Science 1

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Maciej Sobieraj. Lecture 1

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Lecture 2 Tao Wang 1

Chapter 1 Introduction to Computers and C++ Programming

CSCE 110 PROGRAMMING FUNDAMENTALS

Java Programming Fundamentals. Visit for more.

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Chapter 2. Outline. Simple C++ Programs

Programming. C++ Basics

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 3: Operators, Expressions and Type Conversion

Typescript on LLVM Language Reference Manual

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Course Outline Introduction to C-Programming

Chapter 2. Lexical Elements & Operators

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Differentiate Between Keywords and Identifiers

Operators in C. Staff Incharge: S.Sasirekha

Computer Skills (2) for Science and Engineering Students

Chapter 1. Principles of Object Oriented Programming

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Operators. Lecture 3 COP 3014 Spring January 16, 2018

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Data Structure Lab. Prepared By Dr. Hanan Ahmed Salman

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Programming for Engineers Introduction to C

Topic 2: C++ Programming fundamentals

C++ INDEX. Introduction: Instructions for use. Basics of C++: Structure of a program Variables. Data Types. Constants Operators Basic Input/Output

QUIZ: What value is stored in a after this

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Computer System and programming in C

Operators and Expressions:

Fundamental of C programming. - Ompal Singh

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Fundamentals of Programming CS-110. Lecture 2

CS102: Variables and Expressions

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Transcription:

Introduction of C++ Object Oriented Programming :- An Object Oriented Programming (OOP) is a modular approach which allows the data to be applied within the stipulated area. It also provides reusability features to develop productive logic which means to give more emphasis on data. OOP forces us to think in terms of object and the interaction between objects. Basic elements of OOP (Principle of OOP) Following are the elements of OOP : 1. Object :- It is a unique entity which contains data and functions together in an object oriented programming language. (i.e.) an object is an identifiable entity with some characteristics and behavior. 2. Classes :- A class is a group of objects that have common property and relationship. 3. Data abstraction :- Wrapping of data and functions into a single unit is known as data encapsulation. 4. Data Encapsulation :- It refers to act of representing a essential feature without including the background detail or explanation. 5. Modularity :- It is the property of system that has been decomposed into set of cohesive and loosely coupled modules. 6. Inheritance :- It is the process by which object of one class can link and use some common properties of object from another class. 7. Poly morphism :- It is the ability for a message or data to be processed in more than one form. History :- C++ programming language was developed at AT & T Bell laboratories in the early 1980 s by Bjarne Stroustrup. He found C lacking for stimulation and decided to extend the language by adding features from his favourite language Stimula 67. Stimula 67 was one of the earliest Object Oriented Language. Bjarne Stroustrup called it C with Classes originally. The name C++ was coined by Rick Mascitti where ++ is the increment operator. 1

C++ Character Sets : Character set is a set of valid characters that a language can recognize. A characters represents any letter, digit and any other sign. C++ has following character set : 1. Letter A to Z, a-z 2. Digits 0-9 3. White Space Blank space, Horizontal Tab ( ), carriage return, New Line, Form feed. 4. Special symbols - + - * / ^ \ () *+,- =!= <> $ ; : % &? - # <= >= @ Keywords :- The word whose meaning is already explained to the C++ compiler. It cannot be used as an identifier. E.g. int, if, for. Identifier :- Identifiers are the names given to different program element such as variable, array, objects, classes, functions etc. e.g. int a; Here a is an identifier. An identifier will always start with letters. Spaces are not allowed between the name of an identifier. Special symbols such as cannot be used as the name of an identifier. Underscore (_) can be used. Literals (constant) :- They are data items that never change their value during a program run. Following are the C++ literals. 1. Integer Constant :- An integer constant must have atleast one digit and must not contain any decimal point. It may contain + or - sign. A number with no sign is assumed to be +ve. Commas cannot appear in an integer constant. 2. Character Constant : A character constant in C++ must contain one character and must be enclosed in a single quotation mark. In C++, / followed by single character may convey special meaning to the compiler. \n New Line \r - Carriage return \a Audible Beep \t Tab Space \b Backspace \ Single quote \ double quote \\- Back slash 2

3. Floating Constant :- They are also called real constant. These are the number having decimal points. 4. Escape Sequence :- In C++ non-printing characters are called escape sequence. It will be not printed on the screen but it will change the output. 5. Comment :- Comments are piece of c ode that the compiler ignores or simply does not execute. The purpose of comments is only to allow the programmer to insert some notes or descriptions to enhance readability of understandability of the program. Preprocessor Directives :- Statements that begins with (#) hash are directives for preprocessors. That means, these statements are processed before compilation take place. The #include <iostream.h> tells the compiler s preprocessor to include the header file iostream.h. Header Files (<iostream.h>) :- The file iostream.h consists of declaration of standard stream input and output facilities. It also consists of procedures that predefine a set of operations for handling reading and writing of built-in data types. Need for getch() :- getch() is used to hold the screen in simple language, if u don t write this, the screen will just flash and go away. Getch() requires the header file conio.h i.e. #include <conio.h> BASIC DATA TYPES C++ supports a large number of data types. The built in or basic data types supported by C++ are integer, floating point and character. These are summarized in table along with description and memory requirement Type Byte Range Description int 2-32768 to +32767 Small whole number long int 4-2147483648 to +2147483647 Large whole number float 4 3.4x10-38 to 3.4x10+38 Small real number double 8 1.7x10-308 to 1.7x10+308 Large real number long double 10 3.4x10-4932 to 3.4x10+4932 Very Large real number char 1 0 to 255 A Single Character VARIABLES It is a location in the computer memory which can store data and is given a symbolic name for easy reference. The variables can be used to hold different values at different times during the execution of a program. To understand more clearly we should study the following statements: Total = 20.00; In this statement a value 20.00 has been stored in a memory location Total. 3

Declaration of a variable Before a variable is used in a program, we must declare it. This activity enables the compiler to make available the appropriate type of location in the memory. float Total; You can declare more than one variable of same type in a single statement int x,y; Initialization of variable When we declare a variable it's default value is undetermined. We can declare a variable with some initial value. int a = 20; TYPE CONVERSION The process in which one pre-defined type of expression is converted into another type is called conversion. There are two types of conversion in C++. 1. Implicit conversion 2. Explicit conversion Implicit conversion Data type can be mixed in the expression. For example double a; int b = 5; float c = 8.5; a = b * c; When two operands of different type are encountered in the same expression, the lower type variable is converted to the higher type variable. The following table shows the order of data types. Order of data types Data type order long double double (highest) float long To int char (lowest) 4

The int value of b is converted to type float and stored in a temporary variable before being multiplied by the float variable c. The result is then converted to double so that it can be assigned to the double variable a. Explicit conversion It is also called type casting. It temporarily changes a variable data type from its declared data type to a new one. It may be noted here that type casting can only be done on the right hand side the assignment statement. T_Pay = double (salary) + bonus; Initially variable salary is defined as float but for the above calculation it is first converted to double data type and then added to the variable bonus. CONSTANTS A number which does not change its value during execution of a program is known as a constant. Any attempt to change the value of a constant will result in an error message. A constant in C++ can be of any of the basic data types, const qualifier can be used to declare constant as shown below: const float pi = 3.1415; The above declaration means that Pi is a constant of float types having a value 3.1415. Examples of valid constant declarations are: const int rate = 50; const float pi = 3.1415; const char ch = 'A'; STRUCTURE OF C++ PROGRAM #include<header file> main ()......... A C++ program starts with function called main ( ). The body of the function is enclosed between curly braces. The program statements are written within the braces. Each statement must end by a semicolon;(statement terminator). A C++ program may contain as many functions as required. However, when the program is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be executed. 5

// This is my first program is C++ /* this program will illustrate different components of a simple program in C++ */ # include <iostream.h> int main ( ) cout <<"Hello World!"; return 0; When the above program is compiled, linked and executed, the following output is displayed on the VDU screen. Hello World! Various components of this program are discussed below: Comments First three lines of the above program are comments and are ignored by the compiler. Comments are included in a program to make it more readable. If a comment is short and can be accommodated in a single line, then it is started with double slash sequence in the first line of the program. However, if there are multiple lines in a comment, it is enclosed between the two symbols /* and */ #include <iostream.h> The line in the above program that start with # symbol are called directives and are instructions to the compiler. The word include with '#' tells the compiler to include the file iostream.h into the file of the above program. File iostream.h is a header file needed for input/ output requirements of the program. Therefore, this file has been included at the top of the program. int main ( ) The word main is a function name. The brackets ( ) with main tells that main ( ) is a function. The word int before main ( ) indicates that integer value is being returned by the function main (). When program is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be executed. Curly bracket and body of the function main ( ) A C++ program starts with function called main(). The body of the function is enclosed between curly braces. The program statements are written within the brackets. Each statement must end by a semicolon, without which an error message in generated. 6

cout<<"hello World!"; This statement prints our "Hello World!" message on the screen. cout understands that anything sent to it via the << operator should be printed on the screen. return 0; This is a new type of statement, called a return statement. When a program finishes running, it sends a value to the operating system. This particular return statement returns the value of 0 to the operating system, which means everything went okay!. /* This program illustrates how to declare variable, read data and display data. */ #include <iostream.h> int rollno; //declare the variable rollno of type int float marks; //declare the variable marks of type float cout << "Enter roll number and marks :"; cin >> rollno >> marks; //store data into variable rollno & marks cout << "Rollno: " << rollno<<"\n"; cout << "Marks: " << marks; return 0; Sample Run: In this sample run, the user input is shaded. Enter roll number and marks :102 87.5 Rollno: 102 Marks: 87.5 Program - 1 cout<<"banana\t Apple\nMango"; OUTPUT Banana Apple Mango 7

Program 2 : Write a program to get the following output : I study in DPS-MIS cout<<"i am study in \"DPS-MIS\""; Program 3 : Write a program to get the following output : cout<<"half a circle, full a circle\nhalf a circle, a"; cout<<"\n\nhalf a circle, full a circle\nright Angle\, a"; Program 4 : Write a program to get the following output : 8

cout<<"i am a C++ Program\n"; cout<<"i am a "<<"C++ program\n"; cout<<"i am a C++"; cout<<" program"; Program 5 : Write a program to print the addition of 2 numbers. int a,b,sum; cout<<"\nenter the first number\t\t"; cin>>a; cout<<"\nenter the second number\t\t"; cin>>b; sum=a+b; cout<<"\nthe addition of 2 numbers is\t"<<sum; 9

Program 6 : Write a program to print the subtraction of 2 numbers. int a,b,sub; cout<<"\nenter the first number\t\t"; cin>>a; cout<<"\nenter the second number\t\t"; cin>>b; sub=a-b; cout<<"\nthe subtraction of 2 numbers is\t"<<sub; Program 7 : Write a program to print the multiplication of 2 numbers. int a,b,multi; cout<<"\nenter the first number\t\t\t"; cin>>a; cout<<"\nenter the second number\t\t\t"; cin>>b; multi=a*b; cout<<"\nthe multiplication of 2 numbers is\t"<<multi; 10

Program 8 : Write a program to print the division of 2 numbers. int a,b,div; cout<<"\nenter the first number\t\t"; cin>>a; cout<<"\nenter the second number\t\t"; cin>>b; div=a/b; cout<<"\nthe division of 2 numbers is\t"<<div; Program 9 : Write a program to create an integer variable called age with the value 25. Print the value of age. int age=25; cout<<"\nage\t"<<age; 11

Program 10 : Write a program to create an integer variable called age. The user will input value of age at runtime and should be printed on the screen. int age; cout<<"\nenter the age\t"; cin>>age; cout<<"\nthe age is\t"<<age; Program 11 : Write a program to print the area and perimeter of a rectangle whose length is 5 metres and breadth is 10 metres. int l,b; cout<<"\nenter the length\t"; cin>>l; cout<<"\nenter the breadth\t"; cin>>b; cout<<"\nthe area of the rectangle is\t\t"<<l*b; cout<<"\nthe perimeter of the rectangle is\t"<<2*(l+b); 12

Program 12 : Write a program to input the age of three friends and find their average age. int age1,age2,age3; float avg; cout<<"\nenter the age of three friends\t"; cin>>age1>>age2>>age3; avg=(age1+age2+age3)/3.0; cout<<"average Age=\t"<<avg; Program 13 : Write a program to find the area and perimeter of a circle whose radius is input at runtime. int r; float area, peri; const float pi=22/7.0; cout<<"\nenter the radius of the circle\t"; cin>>r; area=pi*r*r; peri=2*pi*r; cout<<"\narea=\t\t"<<area<<"\nperimeter\t"<<peri; 13

Program 14 : Write a program to input temperature in degree Fahrenheit and print it in degree Celsius using formula c=5/9f-32. int f,c; cout<<"\nenter the temperature in Fahrenheit\t"; cin>>f; c=(5/9.0)*(f-32); cout<<"\ntemperature in Celsius\t\t\t"<<c; OPERATORS Operators are special symbols used for specific purposes. C++ provides six types of operators. Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment operators, Conditional operators, Comma operator Arithmetical operators Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation. You can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or remainder % operator is used only with the integral data type. Operators that have two operands are called binary operators. 14

Relational operators The relational operators are used to test the relation between two values. All relational operators are binary operators and therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true. The following table shows the relational operators. Relational Operators Meaning < Less than <= Less than or equal to == Equal to > Greater than >= Greater than or equal to! = Not equal to Logical operators The logical operators are used to combine one or more relational expression. The logical operators are Operators Meaning OR && AND! NOT Unary operators C++ provides two unary operators for which only one variable is required. For Example a = - 50; a = + 50; Here plus sign (+) and minus sign (-) are unary because they are not used between two variables. Assignment operator The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m = 5; The operator takes the expression on the right, 5, and stores it in the variable on the left, m. x = y = z = 32; This code stores the value 32 in each of the three variables x, y, and z. in addition to standard assignment operator shown above, C++ also support compound assignment operators. Compound Assignment Operators Operator Example Equivalent to + = A + = 2 A = A + 2 - = A - = 2 A = A - 2 % = A % = 2 A = A % 2 /= A/ = 2 A = A / 2 *= A * = 2 A = A * 2 15

Increment and Decrement Operators C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post. The syntax of the increment operator is: Pre-increment: ++variable Post-increment: variable++ The syntax of the decrement operator is: Pre-decrement: variable Post-decrement: variable In Prefix form first variable is first incremented/decremented, then evaluated In Postfix form first variable is first evaluated, then incremented/decremented int x,y; int i=10,j=10; x = ++i; //add one to i, store the result back in x y= j++; //store the value of j to y then add one to j cout<<x; //11 cout<<y; //10 Conditional operator The conditional operator?: is called ternary operator as it requires three operands. The format of the conditional operator is: Conditional_ expression? expression1 : expression2; If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2 is evaluated. int a = 5, b = 6; big = (a > b)? a : b; The condition evaluates to false, therefore biggets the value from b and it becomes 6. The comma operator The comma operator gives left to right evaluation of expressions. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. int a=1, b=2, c=3, i; // comma acts as separator, not as an operator i = (a, b); // stores b into i Would first assign the value of a to i, and then assign value of b to variable i. So, at the end, variable i would contain the value 2. 16

The sizeof operator As we know that different types of Variables, constant, etc. require different amounts of memory to store them The sizeof operator can be used to find how many bytes are required for an object to store in memory. For example sizeof (char) returns 1 sizeof (int) returns 2 sizeof (float) returns 4 If k is integer variable, the sizeof (k) returns 2. the sizeof operator determines the amount of memory required for an object at compile time rather than at run time. The order of Precedence The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is called the order of precedence. The following table shows the order of precedence. Order Operators First () Second *, /, % Third +, - The following table shows the precedence of operators. ++, --(post increment/decrement) ++ (Pre increment) -- (Pre decrement), sizeof ( ),!(not), -(unary), Highest +(unary) *,/, % +, - To <, <=, >, >= ==,!= &&? : Lowest = Comma operator 17