1 / 40

REVIEW OF C++

REVIEW OF C++. Contents. C++ Basics Data Handling Operators and Expressions Flow of Control Console I/o Operators. Arrays User defined Functions Standard Library Functions Structures. Indicates very important topics. C++ Character Set. C++ tokens. Keywords. Identifiers. Constants.

jory
Download Presentation

REVIEW OF C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. REVIEW OF C++ Dinesh Kumar Ram(PGT CS)

  2. Contents C++ Basics Data Handling Operators and Expressions Flow of Control Console I/o Operators Arrays User defined Functions Standard Library Functions Structures Indicates very important topics Dinesh Kumar Ram(PGT CS)

  3. C++ Character Set C++ tokens Keywords Identifiers Constants Dinesh Kumar Ram(PGT CS)

  4. DATA HANDLING Basic Data Types in C++ int char 2 bytes Eg. int a; 1 bytes Eg. char a; float double 4 bytes Eg. float a; 8 bytes Eg. double a; Dinesh Kumar Ram(PGT CS)

  5. DATA TYPE MODIFIERS 1. signed 2. unsigned 3. short 4. long Dinesh Kumar Ram(PGT CS)

  6. Derived Data Types Arrays- An array is a data structure which allows a collective name to be given to a group of elements which all have the same type. An individual element of an array is identified by its own unique index (or subscript). Eg: double balance[10]; Functions-A function is a group of statements that together perform a task. Every C++ program has at least one function which is main(), and all the most trivial programs can define additional functions. Pointer- pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is: type *var-name; Eg. int *t; Reference - A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. inti = 17; int& r = i; Dinesh Kumar Ram(PGT CS)

  7. User-Defined Derived Data Types - class Class represents a group of similar objects To define a class in c++, keyword class is used. It has two types of members. By default they are private. class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void) { return length * breadth * height; } }; Data members Members Function Dinesh Kumar Ram(PGT CS)

  8. 2. Structure 1. C++ arrays allow you to define variables that combine several data items of the same kind but 2. structure is another user defined data type which allows you to combine data items of different kinds. 3. Structures are used to represent a record, struct Books { char title[50]; char author[50]; char subject[100]; intbook_id; }book; 202 bytes allocated for book Members Stucture variable 50 50 100 2 Dinesh Kumar Ram(PGT CS)

  9. 3. Union 1. Aunion is a user-defined data or class type that, at any given time, contains only one object from its list of members (although that object can be an array or a class type). union Books { char title[50]; char author[50]; char subject[100]; intbook_id; }book; Members 100 bytes allocated for book Dinesh Kumar Ram(PGT CS)

  10. 4. Enumeration An enumeration is a user-defined type consisting of a set of named constants called enumerators. It is another way of defining integer constant Values of enumconstants enumMyEnumType { ALPHA, BETA, GAMMA }; ALPHA has a value of 0, BETA has a value of 1, and GAMMA has a value of 2. enumFooSize { SMALL = 10, MEDIUM = 100, LARGE = 1000 }; Dinesh Kumar Ram(PGT CS)

  11. OPERATORS AND EXPRESSIONS An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators Dinesh Kumar Ram(PGT CS)

  12. OPERATOR PRECEDENCE Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others Dinesh Kumar Ram(PGT CS)

  13. TYPE CONVERSION It is the process of converting one type into another. In other words converting an expression of a given type into another is called type casting Explicit or Type casting Explicit conversion is user-defined that forces an expression to be of specific type. Eg: cout<<7+(int)4.5; Implicit or Automatic type conversion Implicit type conversion is performed by the compiler without programmers intervention Eg: cout<<(7+4.5); Dinesh Kumar Ram(PGT CS)

  14. FLOW OF CONTROL By Default, the flow of control in a c++ program is sequential Looping statements Conditional statement while If do-while If..else for switch ?: Jump statements goto continue break exit() Dinesh Kumar Ram(PGT CS)

  15. Conditional statement - Examples If…else statements if(age>=18) cout<< “Major”; If(age< 8) cout<<“Minor”; if(age>=18) cout<< “Major”; else cout<<“Minor”; if(num>0) cout<< “+ve no”; else if(num<0) cout<<“-ve no”; else cout<<“zero”; Switch statement Using ?: operator Switch(week_day) { case 1: cout<<“Mon”; break; case 2: cout<<“tue”; break; case 3: cout<<“Wed”; break; case 4: cout<<“Thus”; break; case 5: cout<<“Fri”; break; case 6: cout<<“sat”; break; case 7: cout<<“sun”; break; default: cout<<“invalid i/p”; }; (age>=18)? cout<<“Major”: cout<<“Minor”; (num<0)? cout<<“+ve”: (num>0)? cout<<“-ve”:cout<<“zero”; Dinesh Kumar Ram(PGT CS)

  16. Looping statements - Examples while- Entry controlled loop do..while- Exit controlled loop num=10; While(num>=0) { cout<<num<<“:”; num--; } num=10; do { cout<<num<<“:”; num--; } while(num>=0); for – Entry controlled loop for(num=10;num>=0;num--) cout<<num<<“:”; Dinesh Kumar Ram(PGT CS)

  17. Jump statements- Examples Goto statement Unconditional jump stmt. Transfers the control to the label mentioned. Two types: forward goto and backward goto stmt. Forward goto skips the stmts. between the goto and label. Backward goto repeats the stmts. In between goto and label. Example of a backward goto EG: int a=10; L1: a++; cout<<a<<“:”; goto L1; 7. Example for a forward goto EG: int a=10; goto L1; a++; L1: cout<<a<<“;”; NOTE: CARE MUST BE TAKEN WHEN GOTO STMTS ARE USED IN A PROGRAM. AVOID GOTO STMTS. IN A PRGM. Dinesh Kumar Ram(PGT CS)

  18. Jump statements- break and continue break; stmt Unconditional jump stmt. Usually used in a loop or switch stmt. When cntl reaches break stmt. , the rest of the stmts. in the loop or switch is ignored and jumps over to the stmt following the loop. EG: for( inti=0;i<10;i++) { if(a==5) break; cout<<a<<“:”; } cout<<“End”; continue; stmt. Unconditional jump stmt. Usually found in a loop Continue skips the rest of the lines in a loop and moves to the next iteration. EG: for(inti=0;i<10;i++) { if(a==5) continue; cout<<a<<“:”; } cout<<“End”; Dinesh Kumar Ram(PGT CS)

  19. Lets revise some of programs based on looping statements Program to print the sum of n natural numbers Program to print following pattern: a) 1234 b) 1 123 12 12 123 1 1234 3. Program to find the following sum of series Dinesh Kumar Ram(PGT CS)

  20. Console I/O Operators Unformatted I/O Operations get()- used to read a single character from the i/p device. put()- used to print a single character on to the console. getline()- reads array of characters that ends with ‘\n’ by default, or until the limit is reached. write()- prints the array of characters on to the console. Formatted I/O Operations width()- specifies the required number of fields to be used while displaying the o/p. precision()- specifies the number of digits to be displayed after the decimal point. fill()- specifies a charater to be filled in the unused area of a field setf() sets the format flag that controls the o/p data. Dinesh Kumar Ram(PGT CS)

  21. ARRAYS ARRAYS - An array is a variable that holds multiple values of the same type. SYNTAX: data_typearray_name[size]; Array Initialization for One – Dimensional Arrays int a[ ]={10,20,30}; char a[ ] = “Hello”; or char a[ ]={‘H’,’e’,’l’,’l’,’o’,’/0’}; Array Initialization for 2 Dimensional Array int a[][]={ {1,2,3},{1,4,5},{1,6,7}; char name[][] ={ “apple”,”Mango”,”Orange”}; Dinesh Kumar Ram(PGT CS)

  22. Lets revise some of the programs in 1 D arrays Program to find the sum of n elements in array Program to add odd elements in array Program to swap elements at even position with the elements at odd position in 1- D array Program to search an element in 1 D array Program to add prime numbers in a 1 D array Program to count number of vowels and consonants in a sentence Program to count no of words in 1 D array Program to reverse a string and checking whether it is a palindromeor not Dinesh Kumar Ram(PGT CS)

  23. Programs in 2 D arrays Program to find the sum of diagonal elements in a matrix Program to find the row sum and column sum in a matrix Program to find the largest and second largest element in a matrix Program to add, subtract and multiply matrices Program to sort a array of names alphabetically Program to find the transpose of a matrix Dinesh Kumar Ram(PGT CS)

  24. FUNCTIONS A function is a group of statements that together perform a task. Every C++ program has at least one function which is main(), and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. To use a function, you will have to call or invoke that function. include <iostream> intmax(int num1, int num2); intmain () { inta = 100,b = 200,ret; ret = max(a, b); cout<< "Max value is : " << ret << endl; return 0; } intmax(int num1, int num2) { intresult; if (num1 > num2) result = num1; else result = num2; return result; } Dinesh Kumar Ram(PGT CS)

  25. Whenever function definition appears before the function call, there is no need of function prototype. include <iostream> intmax(int num1, int num2); intmain () { inta = 100,b = 200,ret; ret = max(a, b); cout<< "Max value is : " << ret << endl; return 0; } intmax(int num1, int num2) { intresult; if (num1 > num2) result = num1; else result = num2; return result; } Dinesh Kumar Ram(PGT CS)

  26. DIFFERENCE BETWEEN CALL BY VALUE AND CALL BY REFERENCE Call by Value In call by value, A separate copy of formal parameter is created. Values of actual parameter are copied on to the formal parameter. Any change made to the formal parameter will not effect the actual parameter Call by reference In call by reference, the address of the actual parameter are passed as argument during a call. No separate copy of formal parameter is created. Act as a alias name to the actual argument. Any change made to the formal parameter will reflect the original copy. void display(inta,int &b) { a=a+10; b=b+10; } void main() { int a=40,b=20; display(a,b); cout<<a<<“::”<<b; } Dinesh Kumar Ram(PGT CS)

  27. Default Arguments Default values for the arguments can be given to the functions By default, the number of actual parameters must match with the number of formal parameters. But while giving default values to the arguments, there is no such restrictions. The missing arguments will take up the default values. EXAMPLE: Consider the following prototype intmy_func(int a, int b, int c=12); The following are the valid function calls: result = my_func(1, 2, 3); result = my_func(1, 2); Dinesh Kumar Ram(PGT CS)

  28. Programs based on User – Defined Functions Write a program using function which accept two integers as an argument and return its sum. Call this function from main( ) and print the results in main( ).  Write a function that receives two numbers as an argument and display all prime numbers between these two numbers. Call this function from main( ). Write a function called zero_small() that has two integer arguments being passed by reference and sets the smaller of the two numbers to 0. Write the main program to access the function. Dinesh Kumar Ram(PGT CS)

  29. Standard library function stdio.h Operations on files: remove-Remove file (function ) Rename- Rename file (function ) Character input/output: fgetc-Get character from stream (function ) fgets-Get string from stream (function ) fputc-Write character to stream (function ) fputs- Write string to stream (function ) getc-Get character from stream (function ) getchar-Get character from stdin (function ) gets-Get string from stdin (function ) putc-Write character to stream (function ) putchar-Write character to stdout (function ) puts-Write string to stdout (function ) ungetc-Ungetcharacter from stream (function ) Dinesh Kumar Ram(PGT CS)

  30. string.h Functions Copying: memcpy-Copy block of memory (function ) memmove-Move block of memory (function ) strcpy-Copy string (function ) strncpy- Copy characters from string (function ) Concatenation: strcat-Concatenate strings (function ) strncat-Append characters from string (function ) Comparison: memcmp-Compare two blocks of memory (function ) strcmp-Compare two strings (function ) Searching: memchr-Locate character in block of memory strchr-Locate first occurrence of character in string strcspn-Get span until character in string Other: memset-Fill block of memory strerror-Get pointer to error message string strlen-Get string length (function ) Dinesh Kumar Ram(PGT CS)

  31. stdlib.h Pseudo-random sequence generation: rand- Generate random number (function ) srand-Initialize random number generator (function ) Dynamic memory management: calloc- Allocate space for array in memory free-Deallocatespace in memory malloc- Allocate memory block realloc-Reallocate memory block Functions String conversion: atof-Convert string to double atoi-Convert string to integer atol-Convert string to long integer atoll-Convert string to long long integer strtod-Convert string to double strtof-Convert string to float strtol-Convert string to long integer strtold-Convert string to long double Trigonometric functions: cos-Compute cosine sin-Compute sine tan-Compute tangent acos-Compute arc cosine asin-Compute arc sine atan-Compute arc tangent Exponential and logarithmic functions: exp-Compute exponential function log-Compute natural logarithm math.h Power functions pow-Raise to power sqrt-Compute square root Rounding, absolute value and remainder functions: ceil-Round up value fabs-Compute absolute value floor-Round down value fmod-Compute remainder of division Dinesh Kumar Ram(PGT CS)

  32. Programs- Standard Library Function Write a program which input principal, rate and time from user and calculate compound interest Write a program to compute area of triangle. Sides are input by user. Write a program to check character entered is alphabet, digit or special character using library functions. Write a program which display a number between 10 to 100 randomly. Write a program which accept a letter and display it in uppercase letter. Dinesh Kumar Ram(PGT CS)

  33. Structures A structure is a collection of variable which can be same or different types. The structure name becomes a user-defined data type and may be used the same way as other built-in data types, such as int, double, char. Defining a structure When dealing with the students in a school, many variables of different types are needed.  for example. structSTUDENT{introllno, age;        char name[80];        float marks;};STUDENT  is called the structure tag, and is your brand new data type, like int, double or char.rollno, name, age, and marks are structure members. Dinesh Kumar Ram(PGT CS)

  34. Alternate method of declaring variables of type struct: struct STUDENT{introllno, age;        char name[80];        float marks;} s1, s3; Accessing of data members The accessing of data members is done by using the following format:structure variable.member namefor examplecin>>s1.rollno>>s1.age>>s1.name>>s1.marks; Initialization of structure variable Initialization is done at the time of declaration of a variable. For exampleSTUDENTs2 = {100,17,”Aniket”,92}; Dinesh Kumar Ram(PGT CS)

  35. Structure variable in assignment statements3=s2; The statement assigns the value of each member of s2 to the corresponding member of s3. Note that one structure variable can be assigned to another only when they are of the same structure type, otherwise complier will give an error. Nested structure (Structure within structure) It is possible to use a structure to define another structure. This is called nesting of structure. Consider the following programstruct DAY{int month, date, year;};struct STUDENT{introllno, age;        char name[80];        day date_of_birth;        float marks;}; Dinesh Kumar Ram(PGT CS)

  36. Programs- structures Declare a structure to represent a complex number (a number having a real part and imaginary part). Write C++ functions to add, subtract, multiply and divide two complex numbers. An array stores details of 25 students (rollno, name, marks in three subject). Write a program to create such an array and print out a list of students who have failed in more than one subject. Dinesh Kumar Ram(PGT CS)

  37. typedef It is used to define new data type for an existing data type. It provides and alternative name for standard data type. It is used for self documenting the code by allowing descriptive name for the standard data type.The general format is:typedef existing datatype new datatype for example: typedeffloat real;Now, in a program one can use datatype real instead of float.Therefore, the following statement is valid: real amount; Enumerated data type The enumspecifier defines the set of names which are stored internally as integer constant. The first name was given the integer value 0, the second value 1 and so on. for example:enum months{jan, feb, mar, apr, may} ; It has the following features: It is user defined. It works if you know in advance a finite list of values that a data type can take. The list cannot be input by the user or output on the screen. Dinesh Kumar Ram(PGT CS)

  38. #define preprocessor directive The #define preprocessor allows to define symbolic names and constants e.g. #define pi 3.14159 This statement will translate every occurrence of PI in the program to 3.14159 Storage Class A storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes which can be used 1. auto 2. register 3. static 4. extern Dinesh Kumar Ram(PGT CS)

  39. The auto Storage Class The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e. local variables. The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. { register int miles; } The register should only be used for variables that require quick access such as counters. The static Storage Class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. static int a=10; extern Storage Class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. Dinesh Kumar Ram(PGT CS)

  40. ******END****** Dinesh Kumar Ram(PGT CS)

More Related