Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)

Slides:



Advertisements
Similar presentations
 2000 Prentice Hall, Inc. All rights reserved. Chapter 17 - C++ Classes: Part II Outline 17.1Introduction 17.2 const (Constant) Objects and const Member.
Advertisements

Classes: A Deeper Look Systems Programming.
Classes and Objects. const (Constant) Objects and const Member Functions Principle of least privilege –Only give objects permissions they need, no more.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
JavaScript, Third Edition
Data Types.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 4 - Classes Jan 27,
Review of C++ Programming Part II Sheng-Fang Huang.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
C Tokens Identifiers Keywords Constants Operators Special symbols.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Computer Engineering 1 st Semester Dr. Rabie A. Ramadan 3.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 17 - C++ Classes: Part II Outline 17.1Introduction.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Chapter 17 - C++ Classes: Part II Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
1 const and this Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
 2000 Prentice Hall, Inc. All rights reserved const (Constant) Objects and const Member Functions Principle of least privilege –Only give objects.
 2000 Prentice Hall, Inc. All rights reserved. 1 Outline 7.1Introduction 7.2 const (Constant) Objects and const Member Functions 7.3Composition: Objects.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
 2000 Prentice Hall, Inc. All rights reserved. 1 Outline 7.1Introduction 7.2 const (Constant) Objects and const Member Functions 7.3Composition: Objects.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 7.1Introduction 7.2const (Constant) Objects and const Member Functions 7.3Composition: Objects.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Lecture 5: Classes (continued) Feb 1, 2005
Chapter 1.2 Introduction to C++ Programming
BASIC ELEMENTS OF A COMPUTER PROGRAM
Chap. 2. Types, Operators, and Expressions
Java Primer 1: Types, Classes and Operators
Basic Elements of C++.
Multiple variables can be created in one declaration
Constructor & Destructor
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 17 - C++ Classes: Part II
Chapter 17 - C++ Classes: Part II
Chapter 7: Classes Part II
Chapter 7: Classes Part II
Basic Elements of C++ Chapter 2.
Starting JavaProgramming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to C++ Programming
Chapter 2: Basic Elements of Java
10.2 const (Constant) Objects and const Member Functions
C Operators, Operands, Expressions & Statements
Chapter 7: Classes Part II
Capitolo 7: Classes Part II
7.4 friend Functions and friend Classes
elementary programming
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 2: Introduction to C++.
Chapter 7: Classes Part II
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Primitive Types and Expressions
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 7: Classes (Part II)
Chapter 7: Classes Part II
Presentation transcript:

Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)

Concept of Class and Object “Class” refers to a blueprint. It defines the variables and methods the objects support “Object” is an instance of a class. Each object has a class which defines its data and behavior

Class Members A class can have three kinds of members: fields: data variables which determine the status of the class or an object methods: executable code of the class built from statements. It allows us to manipulate/change the status of an object or access the value of the data member nested classes and nested interfaces

Sample class class Pencil { public String color = “red”; public int length; public float diameter; public static long nextID = 0; public void setColor (String newColor) { color = newColor; }

Classes and Objects

const (Constant) Objects and const Member Functions Principle of least privilege Only give objects permissions they need, no more Keyword const Specify that an object is not modifiable Any attempt to modify the object is a syntax error Example const Time noon( 12, 0, 0 ); Declares a const object noon of class Time and initializes it to 12

const (Constant) Objects and const Member Functions const objects require const functions Member functions declared const cannot modify their object const must be specified in function prototype and definition Prototype: ReturnType FunctionName(param1,param2…) const; Definition: ReturnType FunctionName(param1,param2…) const { …} Example: int A::getValue() const { return privateDataMember }; Returns the value of a data member but doesn’t modify anything so is declared const Constructors / Destructors cannot be const They need to initialize variables, therefore modifying them

1 // Fig. 7.1: time5.h 2 // Declaration of the class Time. 3 // Member functions defined in time5.cpp 4 #ifndef TIME5_H 5 #define TIME5_H 6 7 class Time { 8 public: 9 Time( int = 0, int = 0, int = 0 ); // default constructor 10 11 // set functions 12 void setTime( int, int, int ); // set time 13 void setHour( int ); // set hour 14 void setMinute( int ); // set minute 15 void setSecond( int ); // set second 16 17 // get functions (normally declared const) 18 int getHour() const; // return hour 19 int getMinute() const; // return minute 20 int getSecond() const; // return second 21 22 // print functions (normally declared const) 23 void printMilitary() const; // print military time 24 void printStandard(); // print standard time 25 private: 26 int hour; // 0 - 23 27 int minute; // 0 - 59 28 int second; // 0 - 59 29 }; 30 31 #endif

The constructor is non-const but it can be called for const objects. 32 // Fig. 7.1: time5.cpp 33 // Member function definitions for Time class. 34 #include <iostream> 35 36 using std::cout; 37 38 #include "time5.h" 39 40 // Constructor function to initialize private data. 41 // Default values are 0 (see class definition). 42 Time::Time( int hr, int min, int sec ) 43 { setTime( hr, min, sec ); } 44 45 // Set the values of hour, minute, and second. 46 void Time::setTime( int h, int m, int s ) 47 { 48 setHour( h ); 49 setMinute( m ); 50 setSecond( s ); 51 } 52 53 // Set the hour value 54 void Time::setHour( int h ) 55 { hour = ( h >= 0 && h < 24 ) ? h : 0; } 56 57 // Set the minute value 58 void Time::setMinute( int m ) 59 { minute = ( m >= 0 && m < 60 ) ? m : 0; } 60 61 // Set the second value 62 void Time::setSecond( int s ) 63 { second = ( s >= 0 && s < 60 ) ? s : 0; } The constructor is non-const but it can be called for const objects.

64 65 // Get the hour value 66 int Time::getHour() const { return hour; } 67 68 // Get the minute value 69 int Time::getMinute() const { return minute; } 70 71 // Get the second value 72 int Time::getSecond() const { return second; } 73 74 // Display military format time: HH:MM 75 void Time::printMilitary() const 76 { 77 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 78 << ( minute < 10 ? "0" : "" ) << minute; 79 } 80 81 // Display standard format time: HH:MM:SS AM (or PM) 82 void Time::printStandard() // should be const 83 { 84 cout << ( ( hour == 12 ) ? 12 : hour % 12 ) << ":" 85 << ( minute < 10 ? "0" : "" ) << minute << ":" 86 << ( second < 10 ? "0" : "" ) << second 87 << ( hour < 12 ? " AM" : " PM" ); 88 } Non-const functions cannot use const objects, even if they don’t modify them (such as printStandard).

89 // Fig. 7.1: fig07_01.cpp 90 // Attempting to access a const object with 91 // non-const member functions. 92 #include "time5.h" 93 94 int main() 95 { 96 Time wakeUp( 6, 45, 0 ); // non-constant object 97 const Time noon( 12, 0, 0 ); // constant object 98 99 // MEMBER FUNCTION OBJECT 100 wakeUp.setHour( 18 ); // non-const non-const 101 102 noon.setHour( 12 ); // non-const const 103 104 wakeUp.getHour(); // const non-const 105 106 noon.getMinute(); // const const 107 noon.printMilitary(); // const const 108 noon.printStandard(); // non-const const 109 return 0; 110 } Compiling... Fig07_01.cpp d:fig07_01.cpp(14) : error C2662: 'setHour' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers d:\fig07_01.cpp(20) : error C2662: 'printStandard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Time5.cpp Error executing cl.exe.   test.exe - 2 error(s), 0 warning(s)

const (Constant) Objects and const Member Functions Member initializer syntax Data member increment in class Increment constructor for Increment is modified as follows: Increment::Increment( int c, int i ) : increment( i ) { count = c; } : increment( i ) initializes increment to i All data members can be initialized using member initializer syntax consts and references must be initialized using member initializer syntax Multiple member initializers Use comma-separated list after the colon

1 // Fig. 7.2: fig07_02.cpp 2 // Using a member initializer to initialize a 3 // constant of a built-in data type. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 class Increment { 10 public: 11 Increment( int c = 0, int i = 1 ); 12 void addIncrement() { count += increment; } 13 void print() const; 14 15 private: 16 int count; 17 const int increment; // const data member 18 }; 19 20 // Constructor for class Increment 21 Increment::Increment( int c, int i ) 22 : increment( i ) // initializer for const member 23 { count = c; } 24 25 // Print the data 26 void Increment::print() const 27 { 28 cout << "count = " << count 29 << ", increment = " << increment << endl; 30 } 31 32 int main() 33 { If we try to initialize increment with an assignment statement (such as increment = i ) instead of a member initializer we get an error.

34 Increment value( 10, 5 ); 35 36 cout << "Before incrementing: "; 37 value.print(); 38 39 for ( int j = 0; j < 3; j++ ) { 40 value.addIncrement(); 41 cout << "After increment " << j + 1 << ": "; 42 value.print(); 43 } 44 45 return 0; 46 } Before incrementing: count = 10, increment = 5 After increment 1: count = 15, increment = 5 After increment 2: count = 20, increment = 5 After increment 3: count = 25, increment = 5

Objects as Members of Classes Construction of objects Member objects constructed in order declared Not in order of constructor’s member initializer list Constructed before their enclosing class objects (host objects)

friend Functions and friend Classes friend function and friend classes Can access private and protected members of another class friend functions are not member functions of class Defined outside of class scope Properties of friendship Friendship is granted, not taken Not symmetric (if B a friend of A, A not necessarily a friend of B) Not transitive (if A a friend of B, B a friend of C, A not necessarily a friend of C)

friend Functions and friend Classes friend declarations To declare a friend function Type friend before the function prototype in the class that is giving friendship friend int myFunction( int x ); should appear in the class giving friendship To declare a friend class Type friend class Classname in the class that is giving friendship if ClassOne is granting friendship to ClassTwo, friend class ClassTwo; should appear in ClassOne's definition

Changing private variables allowed. 1 // Fig. 7.5: fig07_05.cpp 2 // Friends can access private members of a class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // Modified Count class 9 class Count { 10 friend void setX( Count &, int ); // friend declaration 11 public: 12 Count() { x = 0; } // constructor 13 void print() const { cout << x << endl; } // output 14 private: 15 int x; // data member 16 }; 17 18 // Can modify private data of Count because 19 // setX is declared as a friend function of Count 20 void setX( Count &c, int val ) 21 { 22 c.x = val; // legal: setX is a friend of Count 23 } 24 25 int main() 26 { 27 Count counter; 28 29 cout << "counter.x after instantiation: "; 30 counter.print(); Changing private variables allowed.

31 cout << "counter.x after call to setX friend function: "; 32 setX( counter, 8 ); // set x with a friend 33 counter.print(); 34 return 0; 35 } counter.x after instantiation: 0 counter.x after call to setX friend function: 8

1 // Fig. 7.6: fig07_06.cpp 2 // Non-friend/non-member functions cannot access 3 // private data of a class. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 // Modified Count class 10 class Count { 11 public: 12 Count() { x = 0; } // constructor 13 void print() const { cout << x << endl; } // output 14 private: 15 int x; // data member 16 }; 17 18 // Function tries to modify private data of Count, 19 // but cannot because it is not a friend of Count. 20 void cannotSetX( Count &c, int val ) 21 { 22 c.x = val; // ERROR: 'Count::x' is not accessible 23 } 24 25 int main() 26 { 27 Count counter; 28 29 cannotSetX( counter, 3 ); // cannotSetX is not a friend 30 return 0; 31 }

Program Output Compiling... Fig07_06.cpp   Compiling... Fig07_06.cpp D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\Fig07_06.cpp(22) : error C2248: 'x' : cannot access private member declared in class 'Count' D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\ Fig07_06.cpp(15) : see declaration of 'x' Error executing cl.exe. test.exe - 1 error(s), 0 warning(s) Program Output

Dynamic Memory Allocation with Operators new and delete Used for dynamic memory allocation Superior to C’s malloc and free new Creates an object of the proper size, calls its constructor and returns a pointer of the correct type delete Destroys object and frees space Examples of new TypeName *typeNamePtr; Creates pointer to a TypeName object typeNamePtr = new TypeName; new creates TypeName object, returns pointer (which typeNamePtr is set equal to)

Dynamic Memory Allocation with Operators new and delete Examples of delete delete typeNamePtr; Calls destructor for TypeName object and frees memory Delete [] arrayPtr; Used to dynamically delete an array Initializing objects double *thingPtr = new double( 3.14159 ); Initializes object of type double to 3.14159 int *arrayPtr = new int[ 10 ]; Creates a ten element int array and assigns it to arrayPtr

static Class Members static class members Shared by all objects of a class Normally, each object gets its own copy of each variable Efficient when a single copy of data is enough Only the static variable has to be updated May seem like global variables, but have class scope only accessible to objects of same class Initialized at file scope Exist even if no instances (objects) of the class exist Both variables and functions can be static Can be public, private or protected

static Class Members static variables Static variables are accessible through any object of the class public static variables Can also be accessed using scope resolution operator(::) Employee::count private static variables When no class member objects exist, can only be accessed via a public static member function To call a public static member function combine the class name, the :: operator and the function name Employee::getCount()

static Class Members Static functions static member functions cannot access non-static data or functions There is no this pointer for static functions, they exist independent of objects

Data Types

Objectives of this session Keywords Identifiers Basic Data Types Built-in Data Types User-defined Data Types Derived Data Types

Variables and Data Types Tokens The smallest individual units in a program are known as tokens. Keywords Identifiers Constants Strings Operators

Keywords

Identifiers A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ).

Identifiers The name of a variable: continue… The name of a variable: Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice. Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _ScoreSide1. Cannot include special characters such as !, %, ], or $. Cannot include an empty space. Cannot be any of the reserved words. Should not be longer than 32 characters (although allowed).

Basic Data Types C++ Data Types User-defined Type Built-in Type Derived Type structure union class enumeration array function pointer reference Integral Type Void Floating Type int char float double

Built-in Data Types int, char, float, double are known as basic or fundamental data types. Signed, unsigned, long, short modifier for integer and character basic data types. Long modifier for double.

Built-in Data Types Type void was introduced in ANSI C. continue… Type void was introduced in ANSI C. Two normal use of void: To specify the return type of a function when it is not returning any value. To indicate an empty argument list to a function. eg:- void function-name ( void )

Built-in Data Types continue… Type void can also used for declaring generic pointer. A generic pointer can be assigned a pointer value of any basic data type, but it may not be de-referenced. void *gp; // gp becomes generic pointer int *ip; // int pointer gp = ip; // assign int pointer to void pointer Assigning any pointer type to a void pointer is allowed in C & C++.

Built-in Data Types continue… void *gp; // gp becomes generic pointer int *ip; // int pointer ip = gp; // assign void pointer to int pointer This is allowed in C. But in C++ we need to use a cast operator to assign a void pointer to other type pointers. ip = ( int * ) gp; // assign void pointer to int pointer // using cast operator *ip = *gp;  is illegal

User-Defined Data Types continue… Enumerated Data Type: Enumerated data type provides a way for attaching names to numbers. enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on. enum shape {circle, square, triangle}; enum colour {red, blue, green, yellow}; enum position {off, on};

User-Defined Data Types continue… Enumerated Data Type: enum colour {red, blue, green, yellow}; In C++ the tag names can be used to declare new variables. colour background; In C++ each enumerated data type retains its own separate type. C++ does not permit an int value to be automatically converted to an enum value.

User-Defined Data Types continue… Enumerated Data Type: colour background = blue; // allowed colour background = 3; // error in C++ colour background = (colour) 3; // OK int c = red; // valid

User-Defined Data Types continue… Enumerated Data Type: By default, the enumerators are assigned integer values starting with 0. We can override the default value by explicitly assigning integer values to the enumerators. enum colour { red, blue=4, green =8}; enum colour {red=5, blue, green};

User-Defined Data Types continue… Enumerated Data Type: C++ also permits the creation of anonymous enum (i.e., enum with out tag name). enum {off, on}; here off  0 and on  1 int switch_1 = off; int switch_2 = on;

Derived Data Types Arrays Functions The application of arrays in C++ is similar to that in C. Functions top-down - structured programming ; to reduce length of the program ; reusability ; function over-loading.

Derived Data Types Pointers continue… Pointers Pointers can be declared and initialized as in C. int * ip; // int pointer ip = &x; // address of x assigned to ip *ip = 10; // 10 assigned to x through indirection

Derived Data Types Pointers continue… Pointers C++ adds the concept of constant pointer and pointer to a constant. char * const ptr1 = “GOODS”; // constant pointer int const * ptr2 = &m; // pointer to a constant

Computer Fundamentals and Programming in C OPERATORS Computer Fundamentals and Programming in C

Operators and Expressions An operator is a symbol or letter used to indicate a specific operation on variables in a program. Example, the symbol `+' is an add operator that adds two data items called operands. Expression. An expression is a combination of operands (i.e., constants, variables, numbers) connected by operators and parentheses. Example, in the expression given below, A and B are operands and `+' is an operator. A + B An expression that involves arithmetic operators is known as an arithmetic expression. The computed result of an arithmetic expression is always a numerical value. An expression which involves relational and/or logical operators is called a Boolean expression or logical expression. The computed result of such an expression is a logical value, i.e., either 1 (True) or 0 (False). Computer Fundamentals and Programming in C

Rules for Formation of an Expression A signed or unsigned constant or variable is an expression. An expression connected by an operator to a variable or a constant is an expression. Two expressions connected by an operator also form an expression. Two operators should not occur in continuation. Computer Fundamentals and Programming in C

Computer Fundamentals and Programming in C Arithmetic Operators Arithmetic operators can further be classified as unary operators and binary operators. Arithmetic operators Computer Fundamentals and Programming in C

Binary Arithmetic Operators The binary arithmetic operators supported by C are addition, subtraction, multiplication, division, and modulus or remainder. They are called binary operators because they require two operands to work with. The evaluations of binary operators is left associative. Operators of the same level are evaluated from left to right.   Computer Fundamentals and Programming in C

Unary Arithmetic Operators A unary operator requires only one operand or data item. The unary arithmetic operators supported by C are, unary minus (‘–’), increment (‘++’), and decrement (‘––’). Compared to binary operators, the unary operators are right associative in the sense that they evaluate from right to left. The operators ‘++’ and ‘––’ are unique to C. These are called increment and decrement operators respectively. The increment operator ++ adds 1 to its operand. Therefore we can say that the following expressions are equivalent.  i = i +1 ; ≡ ++i Computer Fundamentals and Programming in C

Arithmetic with Characters A peculiar aspect of C is that arithmetic operations can also be performed with characters as shown in the following program segment. : char ch; ch = `A'; ch = ch + 1; printf ("ch = % c", ch); The output of this program segment would be: ch = B Computer Fundamentals and Programming in C

Computer Fundamentals and Programming in C Key Points The division of an integer by another integer always results in an integer value. Example: the result of 5/2 is 2 (the decimal portion of the result is dropped). If both or one of the operands in a division operation is a floating point, the result is always a floating point. Example: the result of 15/2.0 is 7.5. The remainder operator % produces the remainder of an integer division. For example, the result of 5 % 2 is 1. This operator cannot be used with floating point numbers. Computer Fundamentals and Programming in C

Relational and Logical Operators A relational operator is used to compare two values and the result of such an operation is always logical, i.e., either true or false. The valid relational operators supported by C are given below: Symbol Stands for Example >  >= <  <= == != Greater than Greater than equal to Less than Less than equal to Equal to Not equal to X > Y X >= Y X < Y X <= Y X == Y X != Y Computer Fundamentals and Programming in C

Computer Fundamentals and Programming in C Logical Operators A logical operator is used to connect two relational expressions or logical expressions. The result of such an operation is always logical, i.e., either True (1) or False (0). The valid logical operators supported by C are given below: Symbol Stands for Example && || ! Logical AND Logical OR Logical NOT x && y x || y ! x Computer Fundamentals and Programming in C

Rules of Logical Operators The output of a logical AND operation is true if both its operands are true. For all other combinations, the result is false. The output of a logical OR operation is false if both of its operands are false. For all other combinations the result is true. The logical NOT is a unary operator. It negates the value of the operand. Computer Fundamentals and Programming in C

Computer Fundamentals and Programming in C Assignment Statement An assignment statement assigns the value of the expression on the right hand side to a variable on the left hand side of the assignment operator (=). Its general form is given below: < variable name > = < expression > The variable on the left side of the assignment operator is also called lvalue and is an accessible address in the memory. Expressions and constants on the right side of the assignment operator are called rvalues. Multiple assignments in a single statement can be used, especially when the same value is to be assigned to a number of variables. a = b = c = 30; A point worth noting is that C converts the type of the value on the right hand side to the data type on the left. Computer Fundamentals and Programming in C

FILES

Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word 4.0 - binary file lab1.c - text file lab1.data - text file term-paper - text file

Text Files All files are coded as long sequences of bits (0s and 1s) Some files are coded as sequences of ASCII character values (referred to as text files) files are organized as bytes, with each byte being an ASCII character Other files are generally referred to as binary files

File Terms Buffer - a temporary storage area used to transfer data back and forth between memory and auxiliary storage devices Stream - files are manipulated in C with streams, a stream is a mechanism that is connected to a file that allows you to access one element at a time

File Pointers Each stream in C is manipulated with the file pointer type FILE *stream FILE is a type containing multiple parts file for stream, current element in file, etc. FILE * is the address where the FILE type is located in memory FILEs always manipulated as FILE *

Standard File Pointers <stdio.h> contains three standard file pointers that are created for you (each of type FILE *) stdin - file pointer connected to the keyboard stdout - file pointer connected to the output window/terminal stderr - file pointer connected to the error window (generally the output window)/terminal

Showing a File FILE *ins; int c; if ((ins = fopen(“file1”,”r”)) == NULL) { printf(“Unable to open file1\n”); exit(0); } while ((c = fgetc(ins)) != EOF) putchar(c); fclose(ins);

Writing Characters C also provides functions for writing one character: int putchar(int c) - prints char c to output window int putc(int c, FILE *fp) - print char c to stream fp int fputc(int c, FILE *fp) - print c to stream fp Routines accept int args (chars are coerced) Routines return EOF if there is a problem

Creating a File FILE *outs; int c; if ((outs = fopen(“file2”,”w”)) == NULL) { printf(“Unable to open file2\n”); exit(0); } while ((c = getchar()) != EOF) fputc(c,outs); fclose(outs);

Copying a File FILE *ins; FILE *outs; int c; if ((ins = fopen(“file1”,”r”)) == NULL) { printf(“Unable to open file1\n”); exit(0); } if ((outs = fopen(“file2”,”w”)) == NULL) { printf(“Unable to open file2\n”); while ((c = fgetc(ins)) != EOF) fputc(c,outs); fclose(ins); fclose(outs);

THANK YOU