UNIT 1. Introduction

Size: px
Start display at page:

Download "UNIT 1. Introduction"

Transcription

1 UNIT 1 Introduction 1

2 PROCEDURE-ORIENTED PROGRAMMING Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow and organizing these instructions into groups known as functions. Uses flowchart to organize these actions and represent the flow of control from one action to another. More importance to functions very little attention to data that are being used by the functions. 2

3 PROCEDURE-ORIENTED PROGRAMMING In multi-function program many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. In large program it is very difficult to identify what data is used by which function. To revise an external data structure needs to revise all function that access it. 3

4 OBJECT-ORIENTED PROGRAMMING OOP is an approach to program organization and development It attempts to eliminate some of the pitfalls of conventional programming methods Incorporates the best of structured programming features with several powerful new concepts. 4

5 OBJECT ORIENTED PROGRAMMING Developments in software technology continue to be dynamic. This made the software industry and software engineers to continuously look for new approaches to software design and development. Rapid advances appear to have created a situation of crisis within the industry. 5

6 OBJECT ORIENTED PROGRAMMING Major issues need to resolved: How to represents real-life entities How to ensure reusability and extensibility of modules How to develop modules that are tolerant to any changes in future How to improve software productivity and decrease software cost How to improve the quality of software How to manage time schedules 6

7 PROCEDURE ORIENTED AND OBJECT ORIENTED PROGRAMMING APPROACH procedure and object oriented are both strategies of information processing and knowledge ordering, used in a variety of fields and management. Actually, they can be seen as a style of thinking and teaching. These are the ways to implement the core logic of a system. 7

8 PROCEDURAL PROGRAMMING In procedural programming our code is organized into small "procedures" that use and change the data. These functions typically take some input, do something, then produce some output. The key idea here is that our functions have no intrinsic relationship with the data they operate on. Sometimes functions need to access data that is not provided as a parameter, i.e. data that is outside the function. Data accessed in this way is considered "global" or "shared" data. 8

9 OBJECT ORIENTED PROGRAMMING In object oriented programming, the data and related functions are bundled together into an classes". The data inside a class can only be manipulated by calling that class s functions. The procedural systems make use of shared and global data, while object oriented systems lock their data privately. All variables are inside class body Only with an object of that class the variables can be accessed or changed. 9

10 COMPARISON Procedure oriented approach Emphasis is on doing things (algorithms) Large Programs are divided into smaller programs known as functions. Object oriented approach Emphasis is on data rather than on procedure Programs are divided into objects Data structures are characterized with independent variables Data structures are designed in such a way that it characterizes the object Most of the functions share global data. Functions that operate on data are ties together in a data structure called class 10

11 Procedure oriented approach Data move openly around the system and can be accessed by any function Functions transform data from one form to another. Difficult to add new functions after specific phases. Employs top down approach in program design. Object oriented approach Data is hidden and cannot be accessed by external functions. Objects may communicate to each other with the help of functions. New data and functions can be easily added whenever necessary Follows bottom-up approach. 11

12 Procedure oriented approach Object oriented approach Manual work is more. Implementation cost is more. Reusability is less. Not that much difficult. Modular dependency is less. More consistent. Replaces many manual processes. Implementation cost is less. Reusability is maximum. Difficult to modify primitive requirements at the end. Modular dependency is more. Less consistent. 12

13 SUMMARY It is meant to address the difficulties with procedural programming. The main modules in a program are classes, rather than procedures. This approach create classes and objects that model real world objects. 13

14 Features of C++ Emphasis on data rather than procedure Programs are divided into what are known as objects Data is hidden and cannot be accessed by external functions Object may communicate with each other through functions Follows bottom up approach in program design New data and functions can be easily added 14

15 C++ PROGRAMS A C++ program is a collection of one or more subprograms, called functions A subprogram or a function is a collection of statements that, when activated (executed), accomplishes something Every C++ program has a function calledmain The smallest individual unit of a program written in any language is called a token 15

16 Sample C++ Programs Program1 #include<iostream.h> int main() { int i; // input a number // cout<< enter a number: ; cin >> i; // square of the number is // cout<< i<< square is << i*i<< \n ; } return 0; 16

17 program 2 #include<iostream.h> void main() { int s1,s2,s3,s4,s5,sum; float avg; cout<< enter marks of student: ; cin>>s1; cin>>s2; cin>>s3; cin>>s4; cin>>s5; sum=s1+s2+s3+s4+s5; avg=sum/5; cout<< sum of marks <<sum; cout<< avg << avg; } 17

18 ASSIGNMENT PROGRAMS Write a C++ program to display personal information i.e. name, age,cellno. Write a C++ program to calculate simple interest using formula si=p*n*r/

19 C++ CONCEPTS C++ has following tokens: Keywords Symbols Identifier Constants Strings Operators 19

20 KEYWORDS Class Friend Inline Public Private Protected New Virtual Delete Template etc. 20

21 SYMBOLS Special symbols + - * /. ;?, <=!= == >= 21

22 SYMBOLS (CONTINUED) Word symbols Reserved words, or keywords Include: int float double char void return 22

23 IDENTIFIERS Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive Some predefined identifiers are cout and cin Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea 23

24 DATA TYPES Data Type: set of values together with a set of operations is called a data type C++ data can be classified into three categories: Simple data type Structured data type Pointers 24

25 SIMPLE DATA TYPES Three categories of simple data Integral: integers (numbers without a decimal) Floating-point: decimal numbers Enumeration type: user-defined data type also structures, unions classes and enumerated data types with keyword enum. 25

26 26

27 INT DATA TYPE Examples: Positive integers do not have to have a + sign in front of them No commas are used within an integer Commas are used for separating items in a list 27

28 BOOL DATA TYPE bool type Has two values, true and false Manipulate logical (Boolean) expressions true and false are called logical values bool, true, and false are reserved words 28

29 CHAR DATA TYPE The smallest integral data type Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes 29

30 FLOATING-POINT DATA TYPES C++ uses scientific notation to represent real numbers (floating-point notation) 30

31 FLOATING-POINT DATA TYPES (CONTINUED) float: represents any real number Range: 3.4E-38 to 3.4E+38 Memory allocated for the float type is 4 bytes double: represents any real number Range: -1.7E+308 to 1.7E+308 Memory allocated for double type is 8 bytes On most newer compilers, data types double and long double are same 31

32 FLOATING-POINT DATA TYPES (CONTINUED) Maximum number of significant digits (decimal places) for float values is 6 or 7 Float values are called single precision Maximum number of significant digits for double is 15 Double values are called double precision Precision: maximum number of significant digits 32

33 ARITHMETIC OPERATORS C++ Operators + addition - subtraction * multiplication / division % remainder (mod operator) +, -, *, and / can be used with integral and floating-point data types Unary operator - has only one operand Binary Operator - has two operands 33

34 ORDER OF PRECEDENCE All operations inside of () are evaluated first *, /, and % are at the same level of precedence and are evaluated next +and have the same level of precedence and are evaluated last When operators are on the same level Performed from left to right 34

35 EXPRESSIONS If all operands are integers Expression is called an integral expression If all operands are floating-point Expression is called a floating-point expression An integral expression yields integral result A floating-point expression yields a floating-point result 35

36 MIXED EXPRESSIONS Mixed expression: Has operands of different data types Contains integers and floating-point Examples of mixed expressions: / * / 2 36

37 EVALUATING MIXED EXPRESSIONS If operator has same types of operands Evaluated according to the type of the operands If operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point 37

38 EVALUATING MIXED EXPRESSIONS (CONTINUED) Entire expression is evaluated according to precedence rules Multiplication, division, and modulus are evaluated before addition and subtraction Operators having same level of precedence are evaluated from left to right Grouping is allowed for clarity 38

39 TYPE CASTING (CONVERSION) Value must be compatible with the variable. If not, we have to make a type conversion. Converting an expression of a given type into another type is known as type-casting. Types of Type Casting There are two ways of achieving the Type Casting. Implicit Conversion : Numeric Numeric Explicit Conversion : Numeric Character Character Numeric

40 A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. The most general cast supported by most of the C++ compilers is as follows: <data type name> (expression) 40

41 PROPERTIES OF IMPLICIT TYPE CASTING Occurs between compatible types. Transfers data from a smaller type to a bigger type. No data loss. No extra operation. Automatic type conversion.

42 COMPATIBLE TYPES

43 EXAMPLE Implicit Conversion No data loss

44 44

45 #include <iostream.h> main() { double a = ; float b = 10.20; int c ; c = (int) a; cout << "Line 1 - Value of (int)a is :" << c << endl ; c = (int) b; cout << "Line 2 - Value of (int)b is :" << c << endl ; return 0; } Line 1 - Value of (int)a is :21 Line 2 - Value of (int)b is :10 45

46 PROPERTIES OF EXPLICIT TYPE CASTING Occurs between incompatible types. May lose data. Extra coding needed. Use with caution.

47 EXAMPLE

48 TYPES OF EXPLICIT TYPE CASTING const_cast<type> (expr): The const_cast operator is used to explicitly override constant values. dynamic_cast<type>(expr): The dynamic_cast performs a runtime cast that verifies the validity of the cast reinterpret_cast<type>(expr):the reinterpret_cast operator changes a pointer to any other type of pointer. static_cast<type>(expr): The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer. 48

49 STRING DATA TYPE Programmer-defined type supplied in standard library Sequence of zero or more characters Enclosed in double quotation marks Null: a string with no characters Each character has relative position in string Position of first character is 0, the position of the second is 1, and so on Length: number of characters in string 49

50 ALLOCATING MEMORY Named Constant: memory location whose content can t change during execution The syntax to declare a named constant is: In C++,const is a reserved word 50

51 51

52 DECLARING & INITIALIZING VARIABLES Variables can be initialized when declared: int first=13, second=10; char ch=' '; double x=12.6, y= ; first and second are int variables with the values 13 and 10, respectively ch is a char variable whose value is empty xand y are double variables with 12.6 and , respectively 52

53 INPUT Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: 1. Instruct the computer to allocate memory 2. Include statements to put data into allocated memory 53

54 INPUT (READ) STATEMENT cin is used with >> to gather input cin >> variable >> variable...; The extraction operator is >> For example, if miles is a double variable cin >> miles; Causes computer to get a value of type double Places it in the memory cell miles 54

55 INPUT STATEMENT (CONTINUED) Using more than one variable in cin allows more than one value to be read at a time For example, if feet and inches are variables of type int a statement such as: cin >> feet >> inches; Inputs two integers from the keyboard Places them in locations feet and inches respectively 55

56 OUTPUT The syntax ofcout and<< is: cout<< expression or manipulator << expression or manipulator <<...; Called an output (cout) statement The << operator is called the insertion operator or the stream insertion operator Expression evaluated and its value is printed at the current cursor position on the screen 56

57 OUTPUT (CONTINUED) Manipulator: alters output endl: the simplest manipulator Causes cursor to move to beginning of the next line 57

58 ENUMERATION i) An enumerated data type is another user defined type which provides a way of attaching names to numbers to increase simplicity of the code. ii) It uses enum keyword which automatically enumerates a list of words by assigning them values 0, 1, 2,..etc. Syntax:- enum shape { circle, square, triangle } Now shape become a new type name & we can declare new variables of this type. EX. shape oval; 58

59 CONTD iv) In C++, enumerated data type has its own separate type. Therefore c++ does not permit an int value to be automatically converted to an enum value. Ex. shape shapes1 = triangle, // is allowed shape shape1 = 2; // Error in c++ shape shape1 = (shape)2; //ok v) By default, enumerators are assigned integer values starting with 0, but we can over-ride the default value by assigning some other value. EX:- enum color {red, blue, pink = 3}; it will assign red to o, blue to 1, & pink to 3 or enum color {red = 5, blue, green}; it will assign red to 5, blue to 6 & green to 7. 59

60 PROGRAM TO IMPLEMENT ENUMERATED DATA TYPES #include <iostream.h> #include <stdlib.h> enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000}; void main() { cout << "Welcome to the world of Roman numerals!" << endl; int num = (int)(m + C + L + X + V + I); cout << "MCLXVI=" << num << endl; num = (int)((l-x) + (V-I)); cout << "XLIV=" << num << endl; getch(); } 60

61 OPERATORS IN C++ INCREMENT & DECREMENT OPERATORS Increment operator: increment variable by 1 Decrement operator: decrement variable by 1 Pre-increment:++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-- 61

62 CONTD Input / Output operator 1. Input Operator cin :- The identifier cin is a predefined object in c++ that corresponds to the standard input stream. This stream represents keyboard. Syntax:- cin>>variable; The operator >> is known as extraction or get from operator & assigns it to the variable on its right. 2. Output operator cout :-The identifier cout is predefined object that represents the standard output stream in c++. Here standard output stream represents the screen. Syntax:- cout<<string; The operator << is called the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left. 62

63 CONTD C++ had rich set of operators. Some of the new operators in C++ are- 1 :: - Scope resolution operators. 2 ::* - pointer to member declaration. 3 *-pointer to member operator. 4.* - pointer to member operator. 5 delete - memory release operator. 6 new - Memory allocation operator. 7 endl - Line feed operator 8 setw - Field width operator. 63

64 SCOPE RESOLUTION OPERATOR In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope resolution operator (::), because this operator allows access to the global version of a variable. C++ is a block - structured language. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A major application of the scope resolution operator is in the classes to identify the class to which a member functions belongs. 64

65 MEMBER DEREFERENCING OPERATORS C++ permits us to define a class containing various types of data & functions as members. C++ also permits us to access the class members through pointers. C++ provides a set of three pointer to member operators. 1) ::* - To access a member of a class. 2).* - To access a member using object name & a pointer to that member. 3) * - To access a member using a pointer in the object & a pointer to the member. 65

66 MEMORY MANAGEMENT OPERATORS. 1) C++ supports two unary operators new and delete that perform the task of allocating & freeing the memory. 2) An object can be created by using new and destroyed by using delete. A data object created inside a block with new, will remain existence until it is explicitly destroyed by using delete. 3) It takes following form. variable = new data type The new operator allocated sufficient memory to hold a data object of type data-type & returns the address of the object. EX - p = new int. Where p is a pointer of type int. 66

67 CONTD 4) New can be used to create a memory space for any data type including user defined type such as array, classes etc. Ex- int * p = new int [10] Creates a memory space for an array of 10 integers. 5) When a data object is no longer needed, it is destroyed to release the memory space for reuse. The general form is delete variable. If we want to free a dynamically allocated array, we must use following form. delete [size] variable. The size specifies the no of elements in the array to be freed 67

68 CONTD 6) The new operator has following advantages over the function malloc() in c -. i) It automatically computes the size of the data object. ii) iii) No need to use sizeof(). If automatically returns the correct pointer type, so that there is no need to use a type cast. iii) new and delete operators can be overloaded. iv) It is possible to initialize the object while creating the memory space. 68

69 MANIPULATORS Manipulators are operators that are used to format the data display. There are two important manipulators. 1) endl 2) setw 1) endl : - This manipulator is used to insert a linefeed into an output. It has same effect as using \n for newline. Ex- cout<< a << a << endl << n = <<n; << endl<< p =<<p<<endl; The output is a = 2568 n = 34 p =

70 2) Setw : With the setw, we can specify a common field width for all the numbers and force them to print with right alignment. EX. cout<<setw (5) <<sum<<endl; The manipulator setw(5) specifies a field width of 5 for printing the value of variable sum the value is right justified

71 // setw example #include <iostream.h> #include <iomanip.h> void main () { cout << setw(10); cout << 77 << endl; getch( ) ; } Output:

72 // setfill example #include <iostream.h> #include <iomanip.h> void main () { cout << setfill ('x') << setw (10); cout << 77 << endl; getch(); } Output: xxxxxxxx77 72

73 ASSIGNMENT STATEMENT The assignment statement takes the form: variable = expression; Expression is evaluated and its value is assigned to the variable on the left side In C++ = is called the assignment operator 73

74 CONTROL STRUCTURES Three control structures Sequence structure Programs executed sequentially by default Selection structures if, if else, switch Repetition structures while, do while, for 74

75 1.IF STATEMENT The if statement is implemented in two forms 1. Simple if statement 2. if else statement Both are used for decision making tasks 75

76 CONTD Form1 if (expression is true) { action1; } action2; 76

77 CONTD Form2 if (expressions is true) { action1; } else { action2; } action3; 77

78 2. SWITCH STATEMENT Multiple-branching statement. Based on condition, control is transferred to one of many possible points. 78

79 Format:- switch(expression) { case1: { } case2: { case3: { action1; action2; } action3; } default: { } action5; action4; } 79

80 3.DO-WHILE STATEMENT It is an exit controlled loop. Based on a condition, control is transferred back to a particular point in the program do { } action1; while(condition is true) action2; 80

81 4.WHILE STATEMENT Entry-controlled loop structure. While(condition is true) { action1; } action2; 81

82 5.FOR STATEMENT Entry-controlled loop. Used when action is to be repeated for a predetermined number of times. for( initial value; test; increment) { action1; } action2; 82

83 ARRAYS Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name Position number Format: Array name[ position number ] First element at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n 1 ] Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of 83 the element within array c

84 DECLARING ARRAYS When declaring arrays, specify Name Type of array Number of elements array Type array Name[number of elements]; Examples: int c[ 10 ]; float myarray[ 3284 ]; Declaring multiple arrays of same type Format similar to regular variables Example: int b[ 100 ], x[ 27 ]; 84

85 ARRAY INITIALIZATION Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array 85

86 CONTD Character arrays String first is really a static array of characters Character arrays can be initialized using string literals char string1[ ] = "first"; Null character '\0' terminates strings string1 actually has 6 elements It is equivalent to char string1[ ] = { 'f', 'i', 'r', 's', 't', '\0' }; Can access individual characters string1[ 3 ] is character s 86

87 PASSING ARRAYS TO FUNCTIONS Passing arrays To pass an array argument to a function, specify the name of the array without any brackets int myarray[ 24 ]; myfunction( myarray, 24 ); Array size usually passed to function Arrays passed call-by-reference Name of array is address of first element Passing array elements Passed by call-by-value Pass subscripted name (i.e., myarray[ 3 ]) to function 87

88 CONTD Function prototype void modifyarray( int b[], int arraysize ); Parameter names optional in prototype int b[] could be written int [] int arraysize could be simply int 88

89 SORTING ARRAYS Sorting data Important computing application Virtually every organization must sort some data Bubble sort Several passes through the array Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged Repeat 89

90 Example: original: pass 1: pass 2: Small elements "bubble" to the top Like bubble sort we can use quick and 90

91 SEARCHING ARRAYS Search an array for a key value Linear search Simple Compare each element of array with key value Useful for small and unsorted arrays Binary search For sorted arrays Compares middle element with key If equal, match found If key < middle, looks in first half of array If key > middle, looks in last half Repeat 91

92 TWO DIMENSIONAL ARRAYS Two Dimensional Arrays contains Tables with rows and columns (m by n array) Like matrices: specify row, then column Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Array name Row subscript Column subscript 92

93 CONTD Initialization int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] );

94 STRINGS A string is a sequence of characters A null terminated <char> arrays to store and manipulate strings. ANSI C++ provides a class called string. Include <string.h> in our program. 94

95 STRINGS In C, a string can be a specially terminated char array or char pointer a char array, such as char str[ ]= high ; a char pointer, such as char *p = high ; If a is char array, the last element of the array must be equal to \0, signaling the end For example, the above str[ ] is really of length 5: str[0]= h str[1]= i str[2]= g str[3]= h str[4]= \0 The same array could ve been declared as: char str[5] = { h, i, g, h, \0 }; If you write char str[4] = { h, i, g, h };, then str is an array of chars but not a string. In char *p= high ; the system allocates memory of 5 characters long, stores high in the first 4, and \0 in the 5 th. 95

96 DECLARATION OF STRINGS The following instructions are all equivalent. They declare x to be an object of type string, and assign the string high school to it: string x( high school ); string x= high school ; string x; x= high school ; 96

97 THE STRING CLASS IN C++ C++ has a <string> library Include it in your programs when you wish to use strings: #include <string.h> In this library, a class string is defined and implemented It is very convenient and makes string processing easier than in C 97

98 AVAILABLE OPERATIONS Creating string objects. Reading string objects from keyboard. Displaying string objects to the screen. Finding a substring from a string. Modifying string objects. Adding string objects. Accessing characters in a string. Obtaining the size of string. And many more. 98

99 OPERATIONS ON STRINGS (CONCATENATION) Let x and y be two strings To concatenate x and y, write: x+y string x= high ; string y= school ; string z; z=x+y; cout<< z= <<z<<endl; z =z+ was fun ; cout<< z= <<z<<endl; Output: z=highschool z= highschool was fun 99

100 CONCATENATION OF MIXED-STYLE STRINGS In s=u+v+w; where s is of type string, u can be A string object, or a C-style string (a char array or a char pointer), a C-style char or a double-quoted string, or a single-quoted character. Same with v and w. At least u or v or w must be a string object 100

101 THE CONCAT-ASSIGN OPERATOR += Assume x is a string object. The statement x += y; is equivalent to x=x+y; where y can be a string object, a C-style string variable, a char variable, a double-quoted string, or a single-quoted char. 101

102 COMMONLY USED STRING FUNCTIONS String(); // For creating an empty string. String(const char *str); // For creating a string object from a null-terminated string. String(const string &str); // For creating a string object from other string object. 102

103 CREATING STRING OBJECTS string s1, s3; //creates two strings with no arguments. string s2( xyz ); // string with one-argument s1 = s2; // Assigning string objects s3 = abc + s2; // Concatenating strings cin >> s1; // Reading from keyboard (one word) cout << s2; // Display the content of s2 getline(cin, s1) // Reading from keyboard a line of text s3 += s1; // s3 = s3 + s1; s3 += abc ; // s3 = s3 + abc ; 103

104 MANIPULATING STRING OBJECTS insert() erase() replace() append() 104

105 MANIPULATING STRING OBJECTS string s1( ); string s2( abcde ); s1.insert(4, s2); // s1 = 1234abcde5 s1.erase(4, 5); // s1 = s2.replace(1, 3, s1); // s2 = a12345e 105

106 RELATIONAL OPERATIONS Operator Meaning == Equality!= Inequality < Less than <= Less than or equal > Greater than >= Greater than or equal string s1( ABC ); string s2( XYZ ); int x = s1.compare(s2); x == 0 if s1 == s2 x > 0 if s1 > s2 x < 0 if s1 < s2 106

107 STRING CHARACTERISTICS Function Task size() length() capacity() max_size() empty() resize() Number of elements currently stored Number of elements currently stored Total elements that can be stored Maximum size of a string object that a system can support Return true or 1 if the string is empty otherwise returns false or 0 Used to resize a string object (effects only size and length) 107

108 STRING CHARACTERISTICS void display(string &str) { } cout << Size = << str.size() << endl; cout << Length = << str.length() << endl; cout << Capacity = << str.capacity() << endl; cout << Max Size = << str.max_size() << endl; cout << Empty: << (str.empty()? yes : no ) << endl; cout << endl << endl; 108

109 ACCESSING CHARACTERS IN STRINGS Function at() substr() find() find_first_of( ) find_last_of( ) Task For accessing individual characters For retrieving a substring For finding a specific substring For finding the location of first occurrence of the specific character(s) For finding the location of last occurrence of the specific character(s) [ ] operator For accessing individual character. Makes the string object to look like an array. 109

110 POINTERS Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures 110

111 ADDRESSES AND POINTERS C++ allows two ways of accessing variables Name Address Symbol & gets the address of the variable that follows it Addresses/Pointers can be displayed by the cout statement Addresses displayed in HEXADECIMAL 111

112 EXAMPLE #include <iostream.h> value void main( ) { int data = 100; data float value = 56.47; cout << data << &data << endl; cout << value << &value << endl; } Output: 100 FFF FFF0 FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF

113 DECLARATION OF POINTER VARIABLES A pointer variable is declared by: datatype *pointervarname; The pointer variable pointervarname is used to point to a value of type datatype The * before the pointervarname indicates that this is a pointer variable, not a regular variable Example int *ptr1; float *ptr2; ptr1 is a pointer to an int ptr2 is a pointer to a float value 113

114 DECLARATION OF POINTER VARIABLES (CONT..) Whitespace doesn t matter and each of the following will declare ptr as a pointer (to a float) variable and data as a float variable float *ptr, data; float* ptr, data; float (*ptr), data; float data, *ptr; 114

115 ASSIGNMENT OF POINTER VARIABLES A pointer variable has to be assigned a valid memory address before it can be used in the program Example: float data = 50.8; float *ptr; ptr = &data; This will assign the address of the memory location allocated for the floating point variable data to the pointer variable ptr. 115

116 ASSIGNMENT OF POINTER VARIABLES (CONT..) FFF0 float data = 50.8; float *ptr; FFF1 FFF2 FFF3 ptr = &data; data FFF FFF5 FFF6 116

117 ASSIGNMENT OF POINTER VARIABLES (CONT..) ptr FFF0 float data = 50.8; float *ptr; FFF1 FFF2 FFF3 ptr = &data; data FFF FFF5 FFF6 117

118 ASSIGNMENT OF POINTER VARIABLES (CONT..) float data = 50.8; float *ptr; ptr FFF0 FFF1 FFF2 FFF3 FFF4 ptr = &data; data FFF FFF5 FFF6 118

119 INITIALIZING POINTERS A pointer can be initialized during declaration by assigning it the address of an existing variable float data = 50.8; float *ptr = &data; If a pointer is not initialized during declaration, it is wise to give it a NULL (0) value int *ip = 0; float *fp = NULL; 119

120 OPERATIONS ON POINTER VARIABLES Assignment the value of one pointer variable can be assigned to another pointer variable of the same type Relational operations - two pointer variables of the same type can be compared for equality, and so on Some limited arithmetic operations integer values can be added to and subtracted from a pointer variable value of one pointer variable can be subtracted from another pointer variable 120

121 POINTERS TO ARRAYS A pointer variable can be used to access the elements of an array of the same type. #include <iostream.h> int main() { //array int intarray[5] = { 31, 54, 77, 52, 93 }; for(int j=0; j<5; j++) //for each element, return 0; } cout << intarray[j] << endl; //print value 121

122 #include <iostream.h> #include<conio.h> void main() { //array int intarray[5] = { 31, 54, 77, 52, 93 }; for(int j=1; j<5; j++) cout << *(intarray) << endl; getch(); } O/p :

123 int gradelist[8] = {92,85,75,88,79,54,34,96}; int *mygrades = gradelist; cout << gradelist[1]; cout << *mygrades; cout << *(mygrades + 2); cout << mygrades[3]; Note that the array name gradelist acts like the pointer variable mygrades. O/P =

124 POINTERS AS ARGUMENTS TO FUNCTIONS Pointers can be passed to functions just like other types. Just as with any other argument, verify that the number and type of arguments in function invocation match the prototype (and function header). 124

125 EXAMPLE OF POINTER ARGUMENTS (PASS BY VALUE) void Swap(int *p1, int *p2); void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(&x,&y); // passes addresses of x and y explicitly cout << x << " " << y << endl; } void Swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } 125

126 EXAMPLE OF REFERENCE ARGUMENTS (PASS BY REFERENCE) void Swap(int &a, int &b); void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(x,y); //passes addresses of x and y implicitly cout << x << " " << y << endl; } void Swap(int &a, int &b) { int temp = a; a = b; b = temp; } 126

127 SAMPLE PROGRAMS ON POINTERS #include <iostream.h> #include<conio.h> void main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue <<'\n'; cout << "secondvalue is " << secondvalue << \n'; getch(); } firstvalue is 10 secondvalue is

128 FUNCTIONS IN C++ Experience has shown that the best way to develop and maintain large programs is to construct it from smaller pieces(modules) This technique Called Divide and Conquer Bad Development Approach main() { Return 0; } 128 Easer To Design Build Debug Extend Modify Understand Reuse Better Organization Wise Development Approach main() { } function f1() { } function f2() { }

129 FUNCTION DEFINITION Syntax format for function definition returned-value-type function-name (parameter-list) { Declarations of local variables and Statements } Parameter list Comma separated list of arguments Data type needed for each argument If no arguments, use void or leave blank Return-value-type Data type of result returned (use void if nothing returned) 129

130 FUNCTION DEFINITION Example function int square( int y ) { } return y * y; return keyword Returns data, and control goes to function s caller If no data to return, use return; Function ends when reaches right brace Control goes to caller Functions cannot be defined inside other functions 130

131 USER-DEFINED C++ FUNCTIONS C++ provides its users with a way to define their own functions (or user-defined function) For example, the <math.h> library does not include a standard function that allows users to round a real number to the i th digits, therefore, we must declare and implement this function ourselves 131

132 EXAMPLE OF USER-DEFINED C++ FUNCTION double computetax(double income) { if (income < ) return 0.0; double taxes = 0.07 * (income ); return taxes; } 132

133 EXAMPLE OF USER-DEFINED C++ FUNCTION Function header Function body double computetax(double income) { if (income < ) return 0.0; double taxes = 0.07 * (income ); return taxes; } 133

134 FUNCTION CALL METHODS Call by value A copy of the value is passed Call by reference The caller passes the address of the value Call by value A copy of the value (known) is passed from the callerfunction to the called-function Any change to the copy does not affect the original value in the caller function Advantages, prevents side effect, resulting in reliable software 134

135 Call By Reference reference-parameter is used to perform call by reference. The caller gives the called function the ability to directly access the caller s value, and to modify it. A reference parameter is an alias for it s corresponding argument, it is stated in c++ by flow the parameter s type in the function prototype by an ampersand(&) also in the function definition-header. Advantage: performance issue 135

136 void function_name (type &);// prototype main() { } void function_name(type &parameter_name) 136

137 PROGRAM TO FIND FACTORIAL #include<iostream.h> #include<conio.h> void main() { int num, factorial=1; cout<<" Enter Number To Find Its Factorial: "; cin>>num; for(int a=1;a<=num; a++) { factorial=factorial*a; } cout<<"factorial of Given Number is ="<<factorial<<endl; getch(); } 137

138 PROGRAM FOR PRIME NUMBER #include<iostream.h> #include<conio.h> void main() { int number,count=0; cout<<"enter number ; cin>>number; for(int a=1;a<=number;a++) { if(number%a==0) { count++; } } if(count==2) { cout<<" Prime number; } else { cout<<" Not a prime number \n"; } getch(); } 138

139 BUBBLE SORT #include<iostream.h> void main(){ //declaring array int array[5]; cout<<"enter 5 numbers randomly : "<<endl; for(int i=0; i<5; i++) { cin>>array[i]; } cout<<endl; cout<<"input array is: "<<end l; for(int j=0; j<5; j++) { //Displaying Array cout<<value at "<<j<<" Index: <<array[j]<<endl; } cout<<endl; // Bubble Sort Starts Here int temp; for(int i2=0; i2<=4; i2++) { for(int j=0; j<4; j++) { if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } 139

140 // Displaying Sorted array cout<<" Sorted Array is: "<<e ndl; for(int i3=0; i3<5; i3++) { cout<<"\t\t\tvalue at "<<i3< <" Index: "<<array[i3]<<endl; } getch(); } 140

141 RECURSION AND RECURSIVE FUNCTIONS Main calls another function..normal A function calls another function2.normal A function calls itself?! Possible?? YES A recursive function is one that call itself. 141

142 CONCEPT OF RECURSION A recursive function is called to solve a problem The function knows to solve only the simplest cases or socalled base-cases. Thus if the function called with a base-case, it simply returns a result. But if it is called with more complex problem, the function divides the problem into two conceptual pieces, one knows how to do, and another doesn't know what to do. The second case/piece must resemble the original problem, but be a slightly simpler/smaller version of the original problem 142

143 CONCEPT OF RECURSION (CONT.) Thus the function calls a fresh copy of itself to work on the smaller problem this is related as a Recursivecall/recursive step. The function keeps dividing each new sub problem into two conceptual pieces until eventually terminates after converging on the base-case. The function thus recognize the base-case and returns a result to the previous copy of the way up the line until original call of the function returns the final result to main. 143

144 FINDING FACTORIAL RECURSIVELY 5! 5! Final value=120 5*4! 5*4! 5!=5*24=120 returned 144 4*3! 3*2! 2*1! 1 4*3! 4!=4*6=24 returned 3!=3*2=6 returned 3*2! 2!=2*1=2 returned 2*1! 1 1

145 FINDING FACTORIAL RECURSIVELY //Recursive factorial Function #include<iostream.h> long factorial(long);//p rototype int main() { int num; cout<< enter a positive integer: ; cin>>num; cout<< factorial= <<factorial(num); return 0; } long factorial(long n) { if ( n <= 1) //the base case return 1; else } return n * factorial (n - 1); 145

146 RECURSIVE FUNCTION TO PRINT THE NUMBERS 1-10 TO THE SCREEN #include <iostream.h> int rec(int num); void main() { int n=10; cout << rec(n); } int rec(int num) { int val; if(num==10) return num; val = rec(num) - 1; return(val); } 146

147 FIBONACCI NUMBERS #include <iostream.h> int fib(int n) // 1, 1, 2, 3, 5, 8, 13, { if (n == 0 n == 1) return 1; return fib(n-1) + fib(n-2); } void main() { int n; cout << "Enter an integer: "; cin >> n; cout << "Fib = " << fib(n) << endl; return 0; } 147

148 FUNCTION OVERLOADING Function overloading Functions with same name and different parameters Should perform similar tasks i.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; } A call-time c++ complier selects the proper function by examining the number, type and order of the parameters 148

149 FUNCTION OVERLOADING Two or more functions can have the same name but different parameters Example: int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; } 149

150 SAMPLE PROGRAM #include <iostream> // abs is overloaded three ways int abs(int i); double abs(double d); long abs(long l); int main() { cout << abs(-10) << "\n"; cout << abs(-11.0) << "\n"; cout << abs(-9l) << "\n"; return 0; } int abs(int i) { cout << "Using integer abs()\n"; return i<0? -i : i; } double abs(double d) { cout << "Using double abs()\n"; return d<0.0? -d : d; } long abs(long l) { cout << "Using long abs()\n"; return l<0? -l : l; } 150

151 The output from this program is shown here. Using integer abs() 10 Using double abs() 11 Using long abs() 9 151

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

PROGRAMMING IN C++ COURSE CONTENT

PROGRAMMING IN C++ COURSE CONTENT PROGRAMMING IN C++ 1 COURSE CONTENT UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 2 1.1 Procedure oriented Programming 1.2 Object oriented programming paradigm 1.3 Basic concepts of Object Oriented

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

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

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

Pointers and Dynamic Memory Allocation

Pointers and Dynamic Memory Allocation Pointers and Dynamic Memory Allocation ALGORITHMS & DATA STRUCTURES 9 TH SEPTEMBER 2014 Last week Introduction This is not a course about programming: It s is about puzzling. well.. Donald Knuth Science

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Functions. Introduction :

Functions. Introduction : Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

CHAPTER 3 Expressions, Functions, Output

CHAPTER 3 Expressions, Functions, Output CHAPTER 3 Expressions, Functions, Output More Data Types: Integral Number Types short, long, int (all represent integer values with no fractional part). Computer Representation of integer numbers - Number

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

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

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 1 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 variables. Apply C++ syntax rules to declare variables, initialize

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016 Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

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

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them. 1. Why do you think C++ was not named ++C? C++ is a super set of language C. All the basic features of C are used in C++ in their original form C++ can be described as C+ some additional features. Therefore,

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Object Oriented Pragramming (22316)

Object Oriented Pragramming (22316) Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data

More information

Introduction to C Final Review Chapters 1-6 & 13

Introduction to C Final Review Chapters 1-6 & 13 Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

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

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

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

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3. Numeric Types, Expressions, and Output Chapter 3 Numeric Types, Expressions, and Output 1 Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

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

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O Overview of C Basic Data Types Constants Variables Identifiers Keywords Basic I/O NOTE: There are six classes of tokens: identifiers, keywords, constants, string literals, operators, and other separators.

More information

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010 IPCoreL Programming Language Reference Manual Phillip Duane Douglas, Jr. 11/3/2010 The IPCoreL Programming Language Reference Manual provides concise information about the grammar, syntax, semantics, and

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information