850 likes | 860 Views
Dive into the historical perspective, differences from C, program structure, variables, data types, and more in this beginner's guide to C++ programming. Includes hands-on examples to kickstart your learning journey.
E N D
Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari
Agenda Session 1 1. A Historical Perspective of C++ 2. Major Differences between C and C++ 3. Basics of C++ Structure of a program Variables and Data types Constants Operators Basic Input / output 4. Control Structures Structures Functions 5. Compound Data Types Arrays Characters Pointers Dynamic Memory 6. C++ and Object Oriented Programming Classes Objects Constructors Overloaded Constructors Destructor Copy Constructor Inheritance ( Public and Private) Function Overloading Operator Overloading Access Control Friendship Virtual Functions Polymorphism
C++ : Historical Perspective • What is C++ ? • Who invented C++ ? • Who are the users of C++ ?
C and C++ • C is a Procedural Language : “Decide which procedures you want; use the best algorithms you can find” • C++ is an Object Oriented Language: “Decide which modules you want; partition the program so that data is hidden within modules” • C was chosen to be the base of C++ because: 1.C is versatile and terse 2.C is adequate for most systems programming tasks 3.C runs everywhere and on everything
Basics of C++ • Structure of a C++ program • Variables and Data types • Constants • Operators • Basic Input / output
Our First C++ Program // my first program in C++ #include <iostream.h> Using namespace std; int main () { cout << “Hello Cs169 / Fall 2009 Students“; return 0; }
Comment Compilerdirectives Specifies standard related names Main portion of program.Contains C++ statements. Structure of a C++ Program /* greeting.cpp greets its user. * * Input: The name of the user * Output: A personalized greeting *********************************************************/ #include <iostream> // cin, cout, <<, >> #include <string> // string using namespace std; int main() { cout << "Please enter your first name: "; string firstName; cin >> firstName; cout << "\nWelcome to the world of C++, " << firstName << "!\n"; }
Variables and Data Types • Variable : a portion of memory to store a determined value. • How to distinguish variables ? Identifiers • Identifiers: • Combination of letters, digits, and underscores • Variable names should start with letter or digit • Important : C++ is a “case sensitive” language
More on Variables • Declaration – • int number1; • float number2; • Initialization – • int number1 = 0; • int number2 = 3.3; • Assignment- • number1=5; • number2=number1;
Scope of Variables • Global Variables – variables that are declared above main() can be accessed anywhere after the declaration • LocalVariables – variables declared in section of code {}. Only accessible in that region.
Initialization of Variables Two possibilities: • type identifier = initial_value ; • type identifier (initial_value) ;
Initialization of Variables // initialization of variables #include <iostream.h> Using namespace std; int main () { int x=5; int y(2); int result; x = x + 3; result = x - y cout << result; return 0; }
Characters and Strings • ‘X’ is a character • “hello Cs169-Fall2009” is a string • C++ library provides support for strings : string class string mystring = "This is a string"; string mystring ("This is a string");
Strings Example // my first string #include <iostream> #include <string> using namespace std; int main () { string mystring; mystring = “Hello Cs169, Fall 2009"; cout << mystring << endl; mystring = “Hello Cs169, I wish you a great semester"; cout << mystring << endl; return 0; } .
Defined Constants • #define identifier value #define PI 3.14159265 Example: Write a program that calculates the area and circumference of a Circle of Radius 10.
Declared Constants (const) • Use the “const” prefix you can declare constant with specific type Examples: • const int radius = 100; • const char tabulator = '\t';
Arithmetic Operators Assignment Operator ( = ) // assignment operator #include <iostream> using namespace std; int main () { int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0; }
Arithmetic Operators Compound assignment Increment & Decrement ( ++,--) Relational and equality operators ( ==, !=, >, <, >=, <= )
Arithmetic Operators Logical Operators ( !, &&, || )
Arithmetic Operators • + addition • - subraction • * multiplication • / division • % modulo or remainder
Basic C++ I/O • “iostream” C++ library • Cout cout << “Hello Cs169”; //Print Hello Cs169 cout << 120; // Print 120 on the screen cout << x; // print the content of x in the screen • Cin int age; cin >> age; cout << age cin >> a >> b; is equivalent to cin>>a; cin>>b;
Agenda Session 1 1. A Historical Perspective of C++ 2. Major Differences between C and C++ 3. Basics of C++ Structure of a program Variables and Data types Constants Operators Basic Input / output 4. Control Structures Structures Functions 5. Compound Data Types Arrays Characters Pointers Dynamic Memory 6. C++ and Object Oriented Programming Classes Friendship and Inheritance Polymorphism
Control structures • if (cond) state1 else if (cond2) state2 else state3 • while (expression) statement • do statement while (cond) • for (init; cond; increment) statement;
Switch Statement switch (x) { \ case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; }
Functions • We can use functions to achieve structured programming Int add(int a, int b){ a = a+b; return (a); } • ‘int’ is the return type, ‘a’ and ‘b’ are arguments • When we call the function we must pass it parameters matching the arguments
Passing Parameters • Call By Value • This is what we usually do, we pass a function the value of a variable • Call By Reference • Instead of the value we will pass a pointer to the variable. If we modify the passed variable the change will be seen by the caller • We use ‘&parm’ to show that we are passing the variable at the memory location of parm
Agenda Session 1 1. A Historical Perspective of C++ 2. Major Differences between C and C++ 3. Basics of C++ Structure of a program Variables and Data types Constants Operators Basic Input / output 4. Control Structures Structures Functions 5. Compound Data Types Arrays Characters Pointers Dynamic Memory 6. C++ and Object Oriented Programming Classes Friendship and Inheritance Polymorphism
Arrays • An Array is a set of elements of the same type located in contiguous memory locations. • An Array can be referenced using index
Arrays • Intialization • int numbers[5]={0,1,2,3,4,}; • Accessing • num2 =numbers[1]; • numbers[0]=99; • Passing arrays as parameters • Declaration: int add(int numarray[]) • Call: int array[]={1,2,3}; add(array);
Pointers • We used pointers in call by reference • A reference of a variable is the address that locates a variable in Memory • Pointer are Valuable in implementing data structures
Address Operator (&) • The ‘&’ operator returns the ‘address of’ its operand. • ‘&’ can be translated ‘address of’
Dereference Operator (*) (*) “Values pointed by” • Notice the difference: & is the reference operator and can be read as "address of" * is the dereference operator and can be read as "value pointed by”
Sizeof() • The Sizeof() function is used to determine how many bytes of a data type during compilation. • Ex: sizeof(float) equals 4 float array[10]; sizeof(array) equals 4*10 which is40
Dynamic Memory • Dynamic Memory allows us to determine and allocate memory to variables and data structures at ‘run time’. • C++ uses new and delete; • pointer = new type; • New returns a pointer to the allocated memory • delete pointer; • Frees up the memory that was allocated
Structs • Similar to records in Ada. struct person_t{ char fname[20]; char lname[20]; int age; }person1, person2; • Here we are declaring person1 and person2 as type person_t. • By convention we use the _t
Accessing the struct members • We use the ‘.’ to access members of a struct cout << person1.fname; person1.fname=“John”;
Pointers to Structs • We can point to a struct like other structures. Person_t* person1Ptr; person1Ptr = &person1; • We can no longer use the ‘.’ to access the members in the struct we are pointing to. • The ‘->’ is used Cout << person1Ptr->fname; • Element fname of structed pointed by person1Ptr • Same as *(person1Ptr.fname);
Agenda Session 1 1. A Historical Perspective of C++ 2. Major Differences between C and C++ 3. Basics of C++ Structure of a program Variables and Data types Constants Operators Basic Input / output 4. Control Structures Structures Functions 5. Compound Data Types Arrays Characters Pointers Dynamic Memory 6. C++ and Object Oriented Programming Classes Objects Constructors Overloaded Constructors Destructor Copy Constructor Inheritance ( Public and Private) Function Overloading Operator Overloading Access Control Friendship Polymorphism
C++ Classes • A Class is User-defined type • An Object is an instance of a Class • A Class has : • Members Variables • Member Functions • Constructor • Destructor
Constructors • A Constructor is a member function that initializes an Object of a Class • A Constructor has the same name as the class it belongs to • A Constructor can be overloaded • The compiler select the correct one for each use • Good Practices: • Always define a constructor and always initialize all data members • If you do not create a constructor one is automatically defined (not recommended • Warning: attempting to initialize a data member of a class explicitly without using a constructors is a syntax error. • .