review of c++
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
Dinesh Kumar Ram(PGT CS)
REVIEW OF C++
Dinesh Kumar Ram(PGT CS)
Contents
1.C++ Basics2.Data Handling3.Operators and
Expressions4.Flow of Control5.Console I/o
Operators
6.Arrays7.User defined
Functions8.Standard Library
Functions9.Structures
Indicates very important topics
Dinesh Kumar Ram(PGT CS)
C++ Character Set
C++ tokens
Keywords Identifiers Constants
Dinesh Kumar Ram(PGT CS)
DATA HANDLING
int
float
char
double
Basic Data Types in C++
1. 2 bytes 2. Eg. int a;
1. 4 bytes 2. Eg. float a;
1. 8 bytes 2. Eg. double a;
1. 1 bytes 2. Eg. char a;
Dinesh Kumar Ram(PGT CS)
DATA TYPE MODIFIERS
1. signed 2. unsigned 3. short 4. long
Type Typical Bit Widthchar 1byte
unsigned char 1bytesigned char 1byteint 2bytes
unsigned int 2bytessigned int 4bytes
short int 2bytesunsigned short int 2 bytes
signed short int 2 byteslong int 4bytes
signed long int 4bytesunsigned long int 4bytes
float 4bytes
double 8bytes
long double 10 bytes
Dinesh Kumar Ram(PGT CS)
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.int i = 17; int& r = i;
Dinesh Kumar Ram(PGT CS)
User-Defined Derived Data Types - class
1. Class represents a group of similar objects
2. To define a class in c++, keyword class is used.
3. 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)
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]; int book_id;}book;
202 bytes allocated for book
Members
Stucture variable
50 50 100 2
Dinesh Kumar Ram(PGT CS)
3. Union
1. A union 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]; int book_id;}book;
Members
100 bytes allocated for book
Dinesh Kumar Ram(PGT CS)
4. Enumeration
1. An enumeration is a user-defined type consisting of a set of named constants called enumerators.
2. It is another way of defining integer constant
Values of enum constants
enum MyEnumType { ALPHA, BETA, GAMMA }; ALPHA has a value of 0, BETA has a value of 1, and GAMMA has a value of 2.
enum FooSize { SMALL = 10, MEDIUM = 100, LARGE = 1000 };
Dinesh Kumar Ram(PGT CS)
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:1. Arithmetic Operators2. Relational Operators3. Logical Operators4. Bitwise Operators5. Assignment Operators6. Misc Operators
Dinesh Kumar Ram(PGT CS)
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
Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Dinesh Kumar Ram(PGT CS)
TYPE CONVERSION
Implicit or Automatic type conversion
Implicit type conversion is performed by the compiler without programmers intervention
Eg: cout<<(7+4.5);
Explicit or Type casting
Explicit conversion is user-defined that forces an expression to be of specific type.
Eg: cout<<7+(int)4.5;
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
Dinesh Kumar Ram(PGT CS)
FLOW OF CONTROLBy Default, the flow of control in a c++ program is sequential
Looping statements
Jump statements
Conditional statement
while
do-while
for
goto break continueexit()
If
If..else
switch
?:
Dinesh Kumar Ram(PGT CS)
Conditional statement - Examples
if(age>=18) cout<< “Major”;If(age< 8)
cout<<“Minor”;
if(age>=18)cout<< “Major”;
elsecout<<“Minor”;
if(num>0)cout<< “+ve no”;
else if(num<0)cout<<“-ve no”;
elsecout<<“zero”;
If…else statements
Switch statement Using ?: operatorSwitch(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”;
};
1. (age>=18)? cout<<“Major”: cout<<“Minor”;
2. (num<0)? cout<<“+ve”: (num>0)? cout<<“-
ve”:cout<<“zero”;
Dinesh Kumar Ram(PGT CS)
Looping statements - Examples
num=10;While(num>=0){
cout<<num<<“:”;num--;
}
num=10;do{
cout<<num<<“:”;num--;
}while(num>=0);
for(num=10;num>=0;num--)cout<<num<<“:”;
while- Entry controlled loop do..while- Exit controlled loop
for – Entry controlled loop
Dinesh Kumar Ram(PGT CS)
Jump statements- Examples
Goto statement1. Unconditional jump stmt. 2. Transfers the control to the label
mentioned.3. Two types: forward goto and
backward goto stmt.4. Forward goto skips the stmts.
between the goto and label.5. Backward goto repeats the
stmts. In between goto and label.
6. Example of a backward gotoEG:int a=10;L1: a++;cout<<a<<“:”;goto L1;
7. Example for a forward gotoEG: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)
Jump statements- break and continue
break; stmt1. Unconditional jump stmt.2. Usually used in a loop or switch
stmt.3. 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.
4. EG:for( int i=0;i<10;i++){
if(a==5)break;cout<<a<<“:”;
}cout<<“End”;
continue; stmt.1. Unconditional jump stmt.2. Usually found in a loop3. Continue skips the rest of the
lines in a loop and moves to the next iteration.
4. EG:for(int i=0;i<10;i++){
if(a==5)continue;cout<<a<<“:”;
}cout<<“End”;
Dinesh Kumar Ram(PGT CS)
Lets revise some of programs based on looping statements
1. Program to print the sum of n natural numbers
2. Program to print following pattern:a) 1234 b) 1
123 1212 1231 1234
3. Program to find the following sum of series
Dinesh Kumar Ram(PGT CS)
Console I/O Operators
Unformatted I/O Operations1. get()- used to read a single
character from the i/p device.2. put()- used to print a single
character on to the console.3. getline()- reads array of
characters that ends with ‘\n’ by default, or until the limit is reached.
4. write()- prints the array of characters on to the console.
Formatted I/O Operations1. width()- specifies the required
number of fields to be used while displaying the o/p.
2. precision()- specifies the number of digits to be displayed after the decimal point.
3. fill()- specifies a charater to be filled in the unused area of a field
4. setf() sets the format flag that controls the o/p data.
Dinesh Kumar Ram(PGT CS)
ARRAYSARRAYS - An array is a variable that holds multiple values of the same type. SYNTAX: data_type array_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)
Lets revise some of the programs in 1 D arrays
1. Program to find the sum of n elements in array
2. Program to add odd elements in array
3. Program to swap elements at even position with the elements at odd position
in 1- D array
4. Program to search an element in 1 D array
5. Program to add prime numbers in a 1 D array
6. Program to count number of vowels and consonants in a sentence
7. Program to count no of words in 1 D array
8. Program to reverse a string and checking whether it is a palindrome or not
Dinesh Kumar Ram(PGT CS)
Programs in 2 D arrays
1. Program to find the sum of diagonal elements in a matrix
2. Program to find the row sum and column sum in a matrix
3. Program to find the largest and second largest element in a matrix
4. Program to add, subtract and multiply matrices
5. Program to sort a array of names alphabetically
6. Program to find the transpose of a matrix
Dinesh Kumar Ram(PGT CS)
FUNCTIONSA 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> int max(int num1, int num2); int main () {int a = 100, b = 200,ret;
ret = max(a, b);
cout << "Max value is : " << ret << endl; return 0; }
int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
Dinesh Kumar Ram(PGT CS)
Whenever function definition appears before the function call, there is no need of function prototype.
include <iostream> int max(int num1, int num2); int main () {int a = 100, b = 200,ret;
ret = max(a, b);
cout << "Max value is : " << ret << endl; return 0; }
int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
Dinesh Kumar Ram(PGT CS)
DIFFERENCE BETWEEN CALL BY VALUE AND CALL BY REFERENCE
Call by Value1. In call by value, A separate copy of
formal parameter is created.2. Values of actual parameter are copied
on to the formal parameter.3. Any change made to the formal
parameter will not effect the actual parameter
Call by reference1. In call by reference, the address of
the actual parameter are passed as argument during a call.
2. No separate copy of formal parameter is created. Act as a alias name to the actual argument.
3. Any change made to the formal parameter will reflect the original copy.
void display(int a,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)
Default Arguments
1. Default values for the arguments can be given to the functions2. By default, the number of actual parameters must match with the number of
formal parameters.3. 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 prototypeint my_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)
Programs based on User – Defined Functions
1. 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( ).
2. Write a function that receives two numbers as an argument and display all
prime numbers between these two numbers. Call this function from main( ).
3. 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)
Standard library function
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-Unget character from stream (function )
stdio.h
Dinesh Kumar Ram(PGT CS)
FunctionsCopying: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 stringOther:memset-Fill block of memory strerror-Get pointer to error message string strlen-Get string length (function )
string.h
Dinesh Kumar Ram(PGT CS)
FunctionsString 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
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-Deallocate space in memory malloc- Allocate memory block realloc-Reallocate memory block
stdlib.h
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
Power functionspow-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
math.h
Dinesh Kumar Ram(PGT CS)
Programs- Standard Library Function
1. Write a program which input principal, rate and time from user and calculate
compound interest
2. Write a program to compute area of triangle. Sides are input by user.
3. Write a program to check character entered is alphabet, digit or special
character using library functions.
4. Write a program which display a number between 10 to 100 randomly.
5. Write a program which accept a letter and display it in uppercase letter.
Dinesh Kumar Ram(PGT CS)
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 structureWhen dealing with the students in a school, many variables of different types are needed. for example.struct STUDENT{ int rollno, 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)
Alternate method of declaring variables of type struct:struct STUDENT{ int rollno, age; char name[80]; float marks;} s1, s3;
Accessing of data membersThe 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 variableInitialization is done at the time of declaration of a variable. For exampleSTUDENT s2 = {100,17,”Aniket”,92};
Dinesh Kumar Ram(PGT CS)
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{ int rollno, age; char name[80]; day date_of_birth; float marks;};
Dinesh Kumar Ram(PGT CS)
Programs- structures
1. 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.
2. 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)
typedefIt 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:typedef float real;Now, in a program one can use datatype real instead of float.Therefore, the following statement is valid: real amount;
Enumerated data typeThe enum specifier 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)
#define preprocessor directiveThe #define preprocessor allows to define symbolic names and constants e.g. #define pi 3.14159This 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. auto2. register3. static4. extern
Dinesh Kumar Ram(PGT CS)
The auto Storage ClassThe 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 Classinstructs 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 Classis 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)
******END******