1.8k likes | 2.12k Views
Sharif University of Technology. C ++ Programming Languages. Lecturer: Omid Jafarinezhad Spring 2014 Lecture 1 c programming language overview. Department of Computer Engineering. Review Of Course Materials. Overview of the C-portions of C++
E N D
Sharif University of Technology C++ Programming Languages Lecturer: OmidJafarinezhad Spring 2014 Lecture 1 c programming language overview Department of Computer Engineering
Review Of Course Materials • Overview of the C-portions of C++ • e.g., loops, structs, arrays, basic data types, etc. • A quick tour through C++, focusing primarily on classes, templates, inheritance, and dynamic binding • An in-depth look at defining • abstract data types in C++ • focusing primarily on classes, templates, and exception handling • single and multiple inheritance • dynamic binding • pointer-to-member functions in C++ • dynamic memory management in C++ • container classes in C++ • Traps and pitfalls of using C++ and how to workaround them • Thread and Graphic (2D and 3D) programming, Refactoring, TDD, Qt, …
References • P. Deitel, H. Deitel, C++: How to Program, 9th Edition, Prentice Hall, 2011. • J. Soulie, C++ Language Tutorial, 2009. Available at http://www.cplusplus.com/doc/tutorial/ • M. Fowler, K. Beck, J. Brant, W. Opdyke, D. Roberts, Refactoring: Improving the Design of Existing Code, Addison Wesley, 1999.
Grading policy • Assignments : 4 pts • Projects: 4 pts • Quizzes: 2 pts • Midterm: 4 pts • Final Exam: 6 pts • Programming Contest: +1 pt (bonus)
C History • BCPL ,1967, Martin Richards • writing operating-systems software and compiler • B, 1969, Ken Thomson • based on BCPL • C, 1972, Dennis Ritchie • based on BCPL and B • at Bell Laboratories • originally implemented on a DEC PDP-11
C++ Programming Language • early 1980s, BjarneStroustrup • at Bell Labroratory • C++ a superset of C • object-oriented programming • Objects are essentially reusable software components that model items in the real world • filename.cpp
Simple C Program • Examples: // int is return data type // main is entrance function int main() { statement 1; statement 1; // …. return 0; } // Simplest c program int main() { return 0; } /* Objective: print on screen */ #include <stdio.h> // preprocessor statements have not ; int main() { printf("welcome to c!!!"); return 0; // indicate that program ended successfully } welcome to c!!!
Example • Header file • Constant • Main function • Variables • Input and output • Process #include <stdio.h> // (preprocessor ) #define PI 3.14 // PI constant (preprocessor ) // calculating area of circle int main() { /* variable definition */ float Radius; float Area = 0; // get radius of circle form user printf("Enter Radius :\n"); scanf("%f", &Radius); // calculating area of circle Area = PI * Radius * Radius; printf(“Area = %f", Area ); system("Pause"); return 0; }
Variable declaration • Before using a variable, you must declare it • Data_Type Identifier; • intwidth; // width of rectangle • float area; // result of calculating area stored in it • char separator;// word separator • Data_Type Identifier = Initial_Value; • intwidth = 10; // width of rectangle • floatarea = 255; // result of calculating area stored in it • charseperator = ‘,’; // word separator • Data_Type Identifier, Identifier, Identifier ,….; • intwidth, length, temporary; • float radius, area = 0;
Data types • Minimal set of basic data types • primitive data types • int • float • double • char • Void • The size and range of these data types may vary among processor types and compilers
Data type qualifiers • Modify the behavior of data type to which they are applied: • Sizequalifiers: alter the size of the basic data types: • short: multiply by 0.5 • long: multiply by 2 • short can be applied to: int • long can be applied to: intand double • Signqualifiers: can hold both positive and negative numbers, or only positive numbers.: • signed: + and - • unsigned: + • they can be applied to : intand char
Overflow and Underflow /* The # character indicate a pre-processor directive; it's an instruction to the compiler to make it do something The <> character tell C to look in the system area for the file stdio.h. If I had given the name #include "stdio.h" instead it would tell the compiler to look in the current directory /* #include <stdio.h> /* * Function main begins program execution * Semi-colon is statement terminator, so it is as a signal to the compiler for end of line */ intmain() { /* The 2 curly brackets { }, are used to specify the limits of the program block */ char letter = 'A'; // char variable to show ASCII code short shortVariable = 32769; // short variable for test overflow // printf command display string on the monitor printf("current value of shortVariable is = %d\n", shortVariable); printf("current value of letter is = %d", letter); printf("current value of letter is = %c", letter); system("PAUSE"); // pause the execution to show press any key … return 0; // indicate that program ended successfully } current value of shortVariable is = -32767 current value of letter is = 65 current value of letter is = A
Program Error • Compile-time or syntax • is caused when the compiler cannot recognize a statement • Run-time • E.g. division by zero • Logical • E.g. Overflow and Underflow
Integer constant value • Base 10: 1 915 +8 -90 • Base 8: 074 0123 084 • Base 16: 0x1 0X5 0x7fab • unsigned: 5000u 4U • long: 123456789l 56L • unsigned long: 536489ul • long long:5361254865LL 25lL • Example : • 0xABu 0123uL 017LL
floating-point constant value • A floating-point value contains a decimal point • 33.5 0.0 -657.983 .2 6. • For example, the value 150.4582 is represented in scientific notation as • 1.504582 X 102 • and is represented in exponential notation (by the computer) as • 1.504582E+02 • This notation indicates that 1.504582 is multiplied by 10 raised to the second power (E+02) • The E stands for “exponent”
Char and string constant value • Char char c; c = 'A'; // d = 65; • String printf("string is array of char!!!"); printf("example of escape sequence is \n");
Constant • Constants provide a way to define a variable which cannot be modified by any other part in the code • #define: without memory consume • const: memory consume • #define Identifier constant_value • #define PI 3.14 • #define ERROR "Disk error " • #define ERROR "multiline \ message" • #define ONE 1 #define TWO ONE + ONE
Constant • const [Data_Type] Identifier = constant_value; • const p = 3; // constint p = 3; • const p; p = 3.14; // compile error • const p = 3.14; // p = 3 because default is int • const float p = 3.14;
Operators • Arithmetic Operators • unary operators • operators that require only one operand • binary operators • operators that require two operands • Assignment Operators • Equality and Relational Operators • Logical Operators • Bitwise Operators • Conditional Operator • Comma Operator • sizeof Operator Width*High Operand
Arithmetic Operators • Unary Operator
Arithmetic Operators • Binary Operators
Division • The division of variables of type integer will always produce a variable of type integer as the result • Example int a = 7, b; float z; b = a / 2; z = a / 2.0; printf("b = %d, z = %f\n", b, z); Since b is declared as an integer, the result of a/2 is 3, not 3.5 • b = 3, z = 3.500000
Modulus • You could only use modulus (%) operation on integer variables (int, long, char) • z = a % 2.0; // error • z = a % 0; // error • Example int a = 7, b, c; b = a % 2; c = a / 2; printf("b = %d\n", b); printf("c = %d\n", c); Modulus will result in the remainder of a/2. - a/2 integral a%2 remainder
Assignment Operators • lvalue = rvalue; int i; float f; i = 2; // *&i = 2; 2 = i; // error: invalid lvalue in assignment f = 5.6; i = f; // i = 5; i = -5.9; // i = -5;
Assignment Operators • Assignment operators are used to combine the '=' operator with one of the binary arithmetic or bitwise operators • Example : • c = 9;
Equality and Relational Operators • Equality Operators: • Relational Operators:
Logical Operators • Logical operators are useful when we want to test multiple conditions • AND • OR • NOT • C has not bool data type, but: • 0: evaluate to false • If(0) printf("…"); • other: evaluate to true • If(1) printf(" …"); • If(-13) printf(" …");
&& - Logical AND • All the conditions must be true for the whole expression to be true • Example: if (a == 1 && b == 2 && c == 3) • means that the if statement is only true when a == 1 and b == 2 and c == 3 • If (a = 5) …
|| - Logical OR • The truth of one condition is enough to make the whole expression true • Example: if (a == 1 || b == 2|| c == 3) • means the if statement is true when either one of a, b or c has the right value
! - Logical NOT • Reverse the meaning of a condition • Example: if (!(radius > 90)) • Means if radius not bigger than 90.
Bitwise Operators • Apply to all kinds of int and char types: • signed and unsigned • char, short, int, long, long long
Bitwise Operators • Applicable for low level programming, e.g.: • Port manipulation • I/O programming • Usually: • &: set OFF one bit • |: set ON one bit • ^: reverse one bit
Conditional Operator • The conditional operator (?:) is used to simplify an if/else statement • Condition ? Expression1 : Expression2; • The statement above is equivalent to: if (Condition) Expression1; else Expression2; • Which are more readable?
Comma Operator • (Expression1 ,Expression2,…); • Example: • int x, y, z; • z = (x = 2, y = x + 1); • printf("z = %d", z); int x, y, z; x = 2; y = x + 1; z = y; printf("z = %d", z);
sizeof • The sizeof keyword returns the number of bytes of the given expression or type • returns an unsigned integer result • sizeofvariable_Identifier; • sizeof(variable_Identifier); • sizeof (Data_Taype); • Example: • int x; • printf("size of x = %d", sizeof x); • printf("size of long long= %d", sizeof(long long)); • printf("size of x = %d", sizeof (x));
Type Casting • Explicit Type cast: carried out by programmer using casting int k, i = 7; float f = 10.14; char c = 'B'; k = (i + f) % 3; // error k = (int)(i + f) % 3; • Implicit Type cast: carried out by compiler automatically f = 65.6; i = f; //f = (int)f; c = i; // c = (int)i;
Control Structures • Sequence • Decision selection statement • The if statement is called a single-selection statement because it selects or ignores a single action. • The if…else statement is called a double-selection statement because it selects between two different actions. • The switch statement is called a multiple-selection statement because it selects among many different actions • Repetition • while • do…while • for
Compound Statements • A statement is a specification of an action to be taken by the computer as the program executes • Compound Statements is a list of statements enclosed in braces, { }
NO YES NO YES x < y? Process A Process B Decision Structure • One of two possible actions is taken, depending on a condition • Selection structures are used to choose among alternative courses of action
NO YES x < y? Calculate a as x times 2. Calculate a as x plus y. Decision Structure • The flowchart segment below shows how a decision structure is expressed in C as an if/else statement Flowchart C programming language if (x < y) a = x * 2; else a = x + y;
NO YES x < y? Calculate a as x times 2. Decision Structure • The flowchart segment below shows a decision structure with only one action to perform Flowchart C programming language if (x < y) a = x * 2;
NO YES x > min? NO YES Display “x is outside the limits.” x < max? Display “x is outside the limits.” Display “x is within limits.” Combining Structures if (x > min) { if (x < max) printf("x is within the limits"); else printf("x is outside the limits"); } else printf("x is outside the limits");
Example if(x) { if(y) printf("Yes"); else printf("No"); } if(x) if(y) printf("Yes"); else printf("No"); if(x) { if(y) printf("Yes"); } else printf("No"); if (x < 0.25) count1++; else if (x >= 0.25 && x < 0.5) count2++; else if (x >= 0.5 && x < 0.75) count3++; else count4++; if (x < 0) sign = -1; else if (x == 0) sign = 0; else sign = 1;
Case Structure • One of several possible actions is taken, depending on the contents of a variable
CASEyears_employed 1 3 Other 2 bonus = 100 bonus = 400 bonus = 800 bonus = 200 Case Structure • indicates actions to perform depending on the value in years_employed If years_employed = 2, bonus is set to 200 If years_employed = 3, bonus is set to 400 If years_employed is any other value, bonus is set to 800 If years_employed = 1, bonus is set to 100
switch • A switch statement allows a single variable (integer or char) to be compared with several possible constants • A constant can not appear more than once, and there can only be one default expression
switch switch (variable) { caseconst: statements...; default: statements...; } switch (c = toupper(getch())) { case‘R’: printf("Red"); break; case‘G’: printf("Green"); break; default: printf("other"); }
CASEbetty? 1 2 3 Other betty = 1 Example switch(betty) { case 1: printf("betty = 1\n"); case 2: printf("betty=2\n"); break; case 3: printf("betty=3\n"); break; default: printf("Not sure\n"); } betty = 3 betty = 2 Not sure