Example:(problem) int a,b cin >> a cin >> b // b = 0

Similar documents
CSCE 110 PROGRAMMING FUNDAMENTALS

Linked List using a Sentinel

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 9


Tokens, Expressions and Control Structures

Variables. Data Types.

Introduction to Programming

Programming. C++ Basics

Exceptions, Case Study-Exception handling in C++.

Programming in C++: Assignment Week 8

PES Institute of Technology

Example Final Questions Instructions

CS2141 Software Development using C/C++ C++ Basics

Input And Output of C++

Programming in C++: Assignment Week 8

Module Operator Overloading and Type Conversion. Table of Contents

Pointers, Dynamic Data, and Reference Types

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Example Final Questions Instructions

Fast Introduction to Object Oriented Programming and C++

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Data Structures. data object. set or collection of instances. integer = {0, +1, -1, +2, -2, +3, -3, } daysofweek = {S,M,T,W,Th,F,Sa}

1 #include <iostream> 2 using namespace std; 3 4 // implementing the dynamic List ADT using Linked List 5 6 class Node{ 7 8 private: 9 int data; 10

CS 247: Software Engineering Principles. ADT Design

CSCE 110 PROGRAMMING FUNDAMENTALS

C++_ MARKS 40 MIN

COMSW Introduction to Computer Programming in C

TEMPLATE IN C++ Function Templates

Introduction to C++ Systems Programming

AN OVERVIEW OF C++ 1

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Review Questions for Final Exam

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Structured Data. CIS 15 : Spring 2007

CS24 Week 3 Lecture 1

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

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++

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

CS 240 Computer Programming 1 Arrays

CSC 330. An Exception is. Handling Exceptions. Error Handling. Assertions. C++ Exception. Example

Module 9. Templates & STL

Short Notes of CS201

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CS349/SE382 A1 C Programming Tutorial

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

CS201 - Introduction to Programming Glossary By

Programming in C++: Assignment Week 1

CMSC 202 Midterm Exam 1 Fall 2015

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

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

COMP 2355 Introduction to Systems Programming

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

CS3157: Advanced Programming. Outline

2. First Program Stuff

TEMPLATES AND EXCEPTION HANDLING

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Name Section: M/W or T/TH. True or False (14 Points)

Hashing. mapping data to tables hashing integers and strings. aclasshash_table inserting and locating strings. inserting and locating strings

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

Chapter 15 - C++ As A "Better C"

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

Lab Instructor : Jean Lai

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ For Science and Engineering Lecture 27

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

CS 103 Lab - Party Like A Char Star

Name SECTION: 12:45 2:20. True or False (12 Points)

6.096 Introduction to C++ January (IAP) 2009

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

05-01 Discussion Notes

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

W3101: Programming Languages C++ Ramana Isukapalli

Objectives. In this chapter, you will:

True or False (15 Points)

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Faculty of Information and Communication Technologies

Transcription:

Exceptions Exceptions are unexpected events that occur during the execution of a program. An exception can be the result of an error condition or simply an unanticipated input. Exceptions can be thought of as being object themselves. Error Exception Handling try throw (exception) catch (error type).. //handle the error Example:(problem) int a,b cin >> a cin >> b // b = 0 cout << a/b // divided by Zero int *ptr = new int[10000] // null ptr *ptr = 4 // memory error solution : int a, b ; cin >> a ; cin >> b ; try if ( b!= 0) cout << a / b else throw (b) Asst. Lec. Zainab Mahmood Fadhil Page 1

int *ptr = new int [10000] if ( ptr == Null ) throw ( out of memory ) *ptr = 4 catch (int i ) cout << i ; return 0 ; catch ( char * s) cout << s ;return 0 general catch catch( exception-type identifier) cout << an error occurred return 0 // exceptions with arguments #include <iostream> #include <string> using namespace std; /////////////////////////////////////////////////// class Distance //English Distance class private: int feet; float inches; public: //------------------------------------------------- class InchesEx //exception class public: Asst. Lec. Zainab Mahmood Fadhil Page 2

string origin; //for name of routine float ivalue; //for faulty inches value InchesEx(string or, float in) //2-arg constructor origin = or; //store string ivalue = in; //store inches ; //end of exception class //------------------------------------------------- Distance() //constructor (no args) feet = 0; inches = 0.0; //------------------------------------------------- Distance(int ft, float in) //constructor (two args) if(in >= 12.0) throw InchesEx( 2-arg constructor, in); feet = ft; inches = in; //------------------------------------------------- void getdist() //get length from user cout << \nenter feet: ; cin >> feet; cout << Enter inches: ; cin >> inches; if(inches >= 12.0) throw InchesEx( getdist() function, inches); //------------------------------------------------- void showdist() //display distance Asst. Lec. Zainab Mahmood Fadhil Page 3

cout << feet << \ - << inches << \ ; ; /////////////////////////////////////////////////// int main() try //Templates and Exceptions Distance dist1(17, 3.5); //2-arg constructor Distance dist2; //no-arg constructor dist2.getdist(); //get value //display distances cout << \ndist1 = ; dist1.showdist(); cout << \ndist2 = ; dist2.showdist(); catch(distance::inchesex ix) //exception handler cout << \ninitialization error in << ix.origin <<.\n Inches value of << ix.ivalue << is too large. ; cout << endl; return 0; Asst. Lec. Zainab Mahmood Fadhil Page 4

typedef defines a synonym for the specified type-declaration typedef type-declaration synonym for class,struct,union and enum declarations, typedef declaration do not introduce new types, they introduce new names for existing types. example 1) typedef unsigned long ulong ulong x // same as unsigned long x 2) typedef struct mytag mystruct ; mystruct ms ; // same as struct mytag ms 3) struct node typedef node *link struct node int elem link next // link is ptr to struct node 4) typedef struct. point ; point pt // instead of strut point-tag pt assert evaluates an expression and when the result is false,abort the program void assert (int expression) Asst. Lec. Zainab Mahmood Fadhil Page 5

examples assert (str!= NULL) // can not be NULL assert(*str!= \0 ) // ptr can not be empty assert (strlen(str)) > 2 // length must exceed 2 enum an enumeration consists of a set of named integer constants, by default the first enumerator has a value of 0. examples enum bool false, true // means false = 0, true = 1 enum colors R,G,B // means R= 0, G = 1, B = 2 Data types to class Conversion classname object (datatype) or object = classname ( datatype) or object = datatype example String :: String (char *a) len = strlen ( a) p = new char [len+1] strcpy (p, a ) string s1,s2 char * ptr = test Asst. Lec. Zainab Mahmood Fadhil Page 6

s1= string (ptr) s2=ptr // char * class string s3 (ptr ) class time int h, m public : time (int t) h= t / 60 m = t % 60 int i = 85 time t1( i ) time t2 t2 = i Asst. Lec. Zainab Mahmood Fadhil Page 7

Data structure: is a data object together with the relationships (functions) that exist among the instances and among the individual elements that compose an instance. Abstraction is ``the idea of a quality thought of apart from any particular object or real thing having that quality''. For example, we can think about the size of an object without knowing what that object is. Similarly, we can think about the way a car is driven without knowing its model or make. Abstraction is used to suppress irrelevant details while at the same time emphasizing relevant ones. The benefit of abstraction is that it makes it easier for the programmer to think about the problem to be solved. Abstract data type (ADT ): set of all possible values (the domain) of an encapsulated data object plus the specifications of the operations that are provided to create and manipulate the data. ADT provide a specification of the instances and operation. Data representation 1.vector list (formula-based) 2. linked list (chain) Linear lists Linear list is a data object of the form (e1,e2,,en) where n islength of elements. when n=0, the list is empty, Linear list have several operations (method) like create( ),destroy( ), length( ), IsEmpty ( ), find( ), Asst. Lec. Zainab Mahmood Fadhil Page 8

elements : [0] [1] [2] [3] maxsize-1 1 2 3 4. Length= 4 Element position(i) = i - 1 we have discussed, an array is an ordered set, which consist of a fixed number of elements. No deletion or insertion operations are performed on arrays. Another main disadvantage is its fixed length; we cannot add elements to the array. Lists overcome all the above limitations. A list is an ordered set consisting of a varying number of elements to which insertion and deletion can be made. A list represented by displaying the relationship between the adjacent elements is said to be a linear list. // class specification Template < class T > class linearlist int length int maxsize T * element Public : linearlist(int maxlistsize = 10 ) ~ LinearList( ) delete [ ] element bool Isempty( ) return ( length == 0 ) bool find ( int, T&) Asst. Lec. Zainab Mahmood Fadhil Page 9

int search ( T&) LinearList<T> Delete ( int,t &) ~ LinearList<T> Inseart ( int,t &) void output (LinearList<T>) ; // class implementation #include<iostream> using namespace std; template <class T> class LinearList int length; int maxsize; T *element; public: LinearList(int maxlistsize=10); ~LinearList() delete [ ]element; int Length() return length; bool Isempty() return (length==0); bool Find(int, T&); int Search(T); LinearList<T>& Delete(int, T&); void Insert(int, T); void output( ); ; Asst. Lec. Zainab Mahmood Fadhil Page 10

template<class T> LinearList<T> :: LinearList(int max) maxsize = max; element = new T[maxsize]; length = 0; template<class T> bool LinearList<T> ::Find(int k, T& x) if(k<1 k>length()) return false; x = element[k-1]; return true; template<class T> int LinearList<T> ::Search(T x) for (int i=0; i<length(); i++) if(element[i]==x) return ++i; return 0; template<class T> LinearList<T>& LinearList<T> ::Delete(int k, T& x) if(find(k,x)) for(int i=k; i<length(); i++) element[i-1] = element[i]; length--; Asst. Lec. Zainab Mahmood Fadhil Page 11

else return *this; throw("out of bounds"); template<class T> void LinearList<T> ::Insert(int k, T x) if(k<0 k>length()) throw("out of bounds"); if(length() == maxsize) throw("list is full"); for(int i=length()-1; i>=k; i--) element[i+1] = element[i]; element[k]= x; length++; template<class T> void LinearList<T> ::output() for(int i=0; i<length(); i++) cout<<element[i]<<" "; void main( ) try LinearList<int> L(5); cout<<"length = " << L.Length() <<endl; cout<<"isempty = " << L.Isempty() << endl; Asst. Lec. Zainab Mahmood Fadhil Page 12

L.Insert(0,2); L.Insert(1,6); L.Insert(2,7); L.Insert(3,9); L.Insert(4,2); L.output( ); L.Insert(5,100); cout<<"list is "; L.output(); cout<<endl; cout<<"is Empty= "<<L.Isempty( ) <<endl; int z; L.Find(1,z); cout<<"first element is " << z << endl; cout<<"length = " << L.Length() <<endl; cout<<"search location of element 7: "<<L.Search(7)<<endl; L.Delete(4,z); cout<<"deleted element is " << z << endl; cout<< "List is "; L.output( ); cout<<endl<<"length = " << L.Length() <<endl; cout<<endl; catch(char *s) cout<<s; Asst. Lec. Zainab Mahmood Fadhil Page 13